compiler: look through aliases when looking for methods
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob3ee98844d3b8f34df18b2475513bd8f5e81c1166
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->named_type() != NULL)
601 return t1->named_type()->named_type_is_comparable(reason);
602 else if (t2->named_type() != NULL)
603 return t2->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 // The types are assignable if they have identical underlying types
682 // and either LHS or RHS is not a named type.
683 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
684 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
685 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
686 return true;
688 // The types are assignable if LHS is an interface type and RHS
689 // implements the required methods.
690 const Interface_type* lhs_interface_type = lhs->interface_type();
691 if (lhs_interface_type != NULL)
693 if (lhs_interface_type->implements_interface(rhs, reason))
694 return true;
695 const Interface_type* rhs_interface_type = rhs->interface_type();
696 if (rhs_interface_type != NULL
697 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
698 reason))
699 return true;
702 // The type are assignable if RHS is a bidirectional channel type,
703 // LHS is a channel type, they have identical element types, and
704 // either LHS or RHS is not a named type.
705 if (lhs->channel_type() != NULL
706 && rhs->channel_type() != NULL
707 && rhs->channel_type()->may_send()
708 && rhs->channel_type()->may_receive()
709 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
710 && Type::are_identical(lhs->channel_type()->element_type(),
711 rhs->channel_type()->element_type(),
712 true,
713 reason))
714 return true;
716 // The nil type may be assigned to a pointer, function, slice, map,
717 // channel, or interface type.
718 if (rhs->is_nil_type()
719 && (lhs->points_to() != NULL
720 || lhs->function_type() != NULL
721 || lhs->is_slice_type()
722 || lhs->map_type() != NULL
723 || lhs->channel_type() != NULL
724 || lhs->interface_type() != NULL))
725 return true;
727 // An untyped numeric constant may be assigned to a numeric type if
728 // it is representable in that type.
729 if ((rhs->is_abstract()
730 && (rhs->integer_type() != NULL
731 || rhs->float_type() != NULL
732 || rhs->complex_type() != NULL))
733 && (lhs->integer_type() != NULL
734 || lhs->float_type() != NULL
735 || lhs->complex_type() != NULL))
736 return true;
738 // Give some better error messages.
739 if (reason != NULL && reason->empty())
741 if (rhs->interface_type() != NULL)
742 reason->assign(_("need explicit conversion"));
743 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
745 size_t len = (lhs->named_type()->name().length()
746 + rhs->named_type()->name().length()
747 + 100);
748 char* buf = new char[len];
749 snprintf(buf, len, _("cannot use type %s as type %s"),
750 rhs->named_type()->message_name().c_str(),
751 lhs->named_type()->message_name().c_str());
752 reason->assign(buf);
753 delete[] buf;
757 return false;
760 // Return true if a value with type RHS may be converted to type LHS.
761 // If REASON is not NULL, set *REASON to the reason the types are not
762 // convertible.
764 bool
765 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
767 // The types are convertible if they are assignable.
768 if (Type::are_assignable(lhs, rhs, reason))
769 return true;
771 // A pointer to a regular type may not be converted to a pointer to
772 // a type that may not live in the heap, except when converting from
773 // unsafe.Pointer.
774 if (lhs->points_to() != NULL
775 && rhs->points_to() != NULL
776 && !lhs->points_to()->in_heap()
777 && rhs->points_to()->in_heap()
778 && !rhs->is_unsafe_pointer_type())
780 if (reason != NULL)
781 reason->assign(_("conversion from normal type to notinheap type"));
782 return false;
785 // The types are convertible if they have identical underlying
786 // types, ignoring struct field tags.
787 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
788 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
789 true, reason))
790 return true;
792 // The types are convertible if they are both unnamed pointer types
793 // and their pointer base types have identical underlying types,
794 // ignoring struct field tags.
795 if (lhs->named_type() == NULL
796 && rhs->named_type() == NULL
797 && lhs->points_to() != NULL
798 && rhs->points_to() != NULL
799 && (lhs->points_to()->named_type() != NULL
800 || rhs->points_to()->named_type() != NULL)
801 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
802 rhs->points_to()->base(),
803 IGNORE_TAGS,
804 true,
805 reason))
806 return true;
808 // Integer and floating point types are convertible to each other.
809 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
810 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
811 return true;
813 // Complex types are convertible to each other.
814 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
815 return true;
817 // An integer, or []byte, or []rune, may be converted to a string.
818 if (lhs->is_string_type())
820 if (rhs->integer_type() != NULL)
821 return true;
822 if (rhs->is_slice_type())
824 const Type* e = rhs->array_type()->element_type()->forwarded();
825 if (e->integer_type() != NULL
826 && (e->integer_type()->is_byte()
827 || e->integer_type()->is_rune()))
828 return true;
832 // A string may be converted to []byte or []rune.
833 if (rhs->is_string_type() && lhs->is_slice_type())
835 const Type* e = lhs->array_type()->element_type()->forwarded();
836 if (e->integer_type() != NULL
837 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
838 return true;
841 // An unsafe.Pointer type may be converted to any pointer type or to
842 // a type whose underlying type is uintptr, and vice-versa.
843 if (lhs->is_unsafe_pointer_type()
844 && (rhs->points_to() != NULL
845 || (rhs->integer_type() != NULL
846 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
847 return true;
848 if (rhs->is_unsafe_pointer_type()
849 && (lhs->points_to() != NULL
850 || (lhs->integer_type() != NULL
851 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
852 return true;
854 // Give a better error message.
855 if (reason != NULL)
857 if (reason->empty())
858 *reason = "invalid type conversion";
859 else
861 std::string s = "invalid type conversion (";
862 s += *reason;
863 s += ')';
864 *reason = s;
868 return false;
871 // Return a hash code for the type to be used for method lookup.
873 unsigned int
874 Type::hash_for_method(Gogo* gogo) const
876 if (this->named_type() != NULL && this->named_type()->is_alias())
877 return this->named_type()->real_type()->hash_for_method(gogo);
878 unsigned int ret = 0;
879 if (this->classification_ != TYPE_FORWARD)
880 ret += this->classification_;
881 return ret + this->do_hash_for_method(gogo);
884 // Default implementation of do_hash_for_method. This is appropriate
885 // for types with no subfields.
887 unsigned int
888 Type::do_hash_for_method(Gogo*) const
890 return 0;
893 // Return a hash code for a string, given a starting hash.
895 unsigned int
896 Type::hash_string(const std::string& s, unsigned int h)
898 const char* p = s.data();
899 size_t len = s.length();
900 for (; len > 0; --len)
902 h ^= *p++;
903 h*= 16777619;
905 return h;
908 // A hash table mapping unnamed types to the backend representation of
909 // those types.
911 Type::Type_btypes Type::type_btypes;
913 // Return the backend representation for this type.
915 Btype*
916 Type::get_backend(Gogo* gogo)
918 if (this->btype_ != NULL)
919 return this->btype_;
921 if (this->forward_declaration_type() != NULL
922 || this->named_type() != NULL)
923 return this->get_btype_without_hash(gogo);
925 if (this->is_error_type())
926 return gogo->backend()->error_type();
928 // To avoid confusing the backend, translate all identical Go types
929 // to the same backend representation. We use a hash table to do
930 // that. There is no need to use the hash table for named types, as
931 // named types are only identical to themselves.
933 std::pair<Type*, Type_btype_entry> val;
934 val.first = this;
935 val.second.btype = NULL;
936 val.second.is_placeholder = false;
937 std::pair<Type_btypes::iterator, bool> ins =
938 Type::type_btypes.insert(val);
939 if (!ins.second && ins.first->second.btype != NULL)
941 // Note that GOGO can be NULL here, but only when the GCC
942 // middle-end is asking for a frontend type. That will only
943 // happen for simple types, which should never require
944 // placeholders.
945 if (!ins.first->second.is_placeholder)
946 this->btype_ = ins.first->second.btype;
947 else if (gogo->named_types_are_converted())
949 this->finish_backend(gogo, ins.first->second.btype);
950 ins.first->second.is_placeholder = false;
953 return ins.first->second.btype;
956 Btype* bt = this->get_btype_without_hash(gogo);
958 if (ins.first->second.btype == NULL)
960 ins.first->second.btype = bt;
961 ins.first->second.is_placeholder = false;
963 else
965 // We have already created a backend representation for this
966 // type. This can happen when an unnamed type is defined using
967 // a named type which in turns uses an identical unnamed type.
968 // Use the representation we created earlier and ignore the one we just
969 // built.
970 if (this->btype_ == bt)
971 this->btype_ = ins.first->second.btype;
972 bt = ins.first->second.btype;
975 return bt;
978 // Return the backend representation for a type without looking in the
979 // hash table for identical types. This is used for named types,
980 // since a named type is never identical to any other type.
982 Btype*
983 Type::get_btype_without_hash(Gogo* gogo)
985 if (this->btype_ == NULL)
987 Btype* bt = this->do_get_backend(gogo);
989 // For a recursive function or pointer type, we will temporarily
990 // return a circular pointer type during the recursion. We
991 // don't want to record that for a forwarding type, as it may
992 // confuse us later.
993 if (this->forward_declaration_type() != NULL
994 && gogo->backend()->is_circular_pointer_type(bt))
995 return bt;
997 if (gogo == NULL || !gogo->named_types_are_converted())
998 return bt;
1000 this->btype_ = bt;
1002 return this->btype_;
1005 // Get the backend representation of a type without forcing the
1006 // creation of the backend representation of all supporting types.
1007 // This will return a backend type that has the correct size but may
1008 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1009 // and will not contain the final representation of the type to which
1010 // it points. This is used while converting all named types to the
1011 // backend representation, to avoid problems with indirect references
1012 // to types which are not yet complete. When this is called, the
1013 // sizes of all direct references (e.g., a struct field) should be
1014 // known, but the sizes of indirect references (e.g., the type to
1015 // which a pointer points) may not.
1017 Btype*
1018 Type::get_backend_placeholder(Gogo* gogo)
1020 if (gogo->named_types_are_converted())
1021 return this->get_backend(gogo);
1022 if (this->btype_ != NULL)
1023 return this->btype_;
1025 Btype* bt;
1026 switch (this->classification_)
1028 case TYPE_ERROR:
1029 case TYPE_VOID:
1030 case TYPE_BOOLEAN:
1031 case TYPE_INTEGER:
1032 case TYPE_FLOAT:
1033 case TYPE_COMPLEX:
1034 case TYPE_STRING:
1035 case TYPE_NIL:
1036 // These are simple types that can just be created directly.
1037 return this->get_backend(gogo);
1039 case TYPE_MAP:
1040 case TYPE_CHANNEL:
1041 // All maps and channels have the same backend representation.
1042 return this->get_backend(gogo);
1044 case TYPE_NAMED:
1045 case TYPE_FORWARD:
1046 // Named types keep track of their own dependencies and manage
1047 // their own placeholders.
1048 return this->get_backend(gogo);
1050 case TYPE_INTERFACE:
1051 if (this->interface_type()->is_empty())
1052 return Interface_type::get_backend_empty_interface_type(gogo);
1053 break;
1055 default:
1056 break;
1059 std::pair<Type*, Type_btype_entry> val;
1060 val.first = this;
1061 val.second.btype = NULL;
1062 val.second.is_placeholder = false;
1063 std::pair<Type_btypes::iterator, bool> ins =
1064 Type::type_btypes.insert(val);
1065 if (!ins.second && ins.first->second.btype != NULL)
1066 return ins.first->second.btype;
1068 switch (this->classification_)
1070 case TYPE_FUNCTION:
1072 // A Go function type is a pointer to a struct type.
1073 Location loc = this->function_type()->location();
1074 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1076 break;
1078 case TYPE_POINTER:
1080 Location loc = Linemap::unknown_location();
1081 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1082 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1083 Type::placeholder_pointers.push_back(pt);
1085 break;
1087 case TYPE_STRUCT:
1088 // We don't have to make the struct itself be a placeholder. We
1089 // are promised that we know the sizes of the struct fields.
1090 // But we may have to use a placeholder for any particular
1091 // struct field.
1093 std::vector<Backend::Btyped_identifier> bfields;
1094 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1095 true, &bfields);
1096 bt = gogo->backend()->struct_type(bfields);
1098 break;
1100 case TYPE_ARRAY:
1101 if (this->is_slice_type())
1103 std::vector<Backend::Btyped_identifier> bfields;
1104 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1105 bt = gogo->backend()->struct_type(bfields);
1107 else
1109 Btype* element = this->array_type()->get_backend_element(gogo, true);
1110 Bexpression* len = this->array_type()->get_backend_length(gogo);
1111 bt = gogo->backend()->array_type(element, len);
1113 break;
1115 case TYPE_INTERFACE:
1117 go_assert(!this->interface_type()->is_empty());
1118 std::vector<Backend::Btyped_identifier> bfields;
1119 get_backend_interface_fields(gogo, this->interface_type(), true,
1120 &bfields);
1121 bt = gogo->backend()->struct_type(bfields);
1123 break;
1125 case TYPE_SINK:
1126 case TYPE_CALL_MULTIPLE_RESULT:
1127 /* Note that various classifications were handled in the earlier
1128 switch. */
1129 default:
1130 go_unreachable();
1133 if (ins.first->second.btype == NULL)
1135 ins.first->second.btype = bt;
1136 ins.first->second.is_placeholder = true;
1138 else
1140 // A placeholder for this type got created along the way. Use
1141 // that one and ignore the one we just built.
1142 bt = ins.first->second.btype;
1145 return bt;
1148 // Complete the backend representation. This is called for a type
1149 // using a placeholder type.
1151 void
1152 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1154 switch (this->classification_)
1156 case TYPE_ERROR:
1157 case TYPE_VOID:
1158 case TYPE_BOOLEAN:
1159 case TYPE_INTEGER:
1160 case TYPE_FLOAT:
1161 case TYPE_COMPLEX:
1162 case TYPE_STRING:
1163 case TYPE_NIL:
1164 go_unreachable();
1166 case TYPE_FUNCTION:
1168 Btype* bt = this->do_get_backend(gogo);
1169 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1170 go_assert(saw_errors());
1172 break;
1174 case TYPE_POINTER:
1176 Btype* bt = this->do_get_backend(gogo);
1177 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1178 go_assert(saw_errors());
1180 break;
1182 case TYPE_STRUCT:
1183 // The struct type itself is done, but we have to make sure that
1184 // all the field types are converted.
1185 this->struct_type()->finish_backend_fields(gogo);
1186 break;
1188 case TYPE_ARRAY:
1189 // The array type itself is done, but make sure the element type
1190 // is converted.
1191 this->array_type()->finish_backend_element(gogo);
1192 break;
1194 case TYPE_MAP:
1195 case TYPE_CHANNEL:
1196 go_unreachable();
1198 case TYPE_INTERFACE:
1199 // The interface type itself is done, but make sure the method
1200 // types are converted.
1201 this->interface_type()->finish_backend_methods(gogo);
1202 break;
1204 case TYPE_NAMED:
1205 case TYPE_FORWARD:
1206 go_unreachable();
1208 case TYPE_SINK:
1209 case TYPE_CALL_MULTIPLE_RESULT:
1210 default:
1211 go_unreachable();
1214 this->btype_ = placeholder;
1217 // Return a pointer to the type descriptor for this type.
1219 Bexpression*
1220 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1222 Type* t = this->unalias();
1223 if (t->type_descriptor_var_ == NULL)
1225 t->make_type_descriptor_var(gogo);
1226 go_assert(t->type_descriptor_var_ != NULL);
1228 Bexpression* var_expr =
1229 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1230 Bexpression* var_addr =
1231 gogo->backend()->address_expression(var_expr, location);
1232 Type* td_type = Type::make_type_descriptor_type();
1233 Btype* td_btype = td_type->get_backend(gogo);
1234 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1235 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1238 // A mapping from unnamed types to type descriptor variables.
1240 Type::Type_descriptor_vars Type::type_descriptor_vars;
1242 // Build the type descriptor for this type.
1244 void
1245 Type::make_type_descriptor_var(Gogo* gogo)
1247 go_assert(this->type_descriptor_var_ == NULL);
1249 Named_type* nt = this->named_type();
1251 // We can have multiple instances of unnamed types, but we only want
1252 // to emit the type descriptor once. We use a hash table. This is
1253 // not necessary for named types, as they are unique, and we store
1254 // the type descriptor in the type itself.
1255 Bvariable** phash = NULL;
1256 if (nt == NULL)
1258 Bvariable* bvnull = NULL;
1259 std::pair<Type_descriptor_vars::iterator, bool> ins =
1260 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1261 if (!ins.second)
1263 // We've already built a type descriptor for this type.
1264 this->type_descriptor_var_ = ins.first->second;
1265 return;
1267 phash = &ins.first->second;
1270 // The type descriptor symbol for the unsafe.Pointer type is defined in
1271 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1272 // symbol if necessary.
1273 if (this->is_unsafe_pointer_type())
1275 Location bloc = Linemap::predeclared_location();
1277 Type* td_type = Type::make_type_descriptor_type();
1278 Btype* td_btype = td_type->get_backend(gogo);
1279 std::string name = gogo->type_descriptor_name(this, nt);
1280 std::string asm_name(go_selectively_encode_id(name));
1281 this->type_descriptor_var_ =
1282 gogo->backend()->immutable_struct_reference(name, asm_name,
1283 td_btype,
1284 bloc);
1286 if (phash != NULL)
1287 *phash = this->type_descriptor_var_;
1288 return;
1291 std::string var_name = gogo->type_descriptor_name(this, nt);
1293 // Build the contents of the type descriptor.
1294 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1296 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1298 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1300 const Package* dummy;
1301 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1303 std::string asm_name(go_selectively_encode_id(var_name));
1304 this->type_descriptor_var_ =
1305 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1306 initializer_btype,
1307 loc);
1308 if (phash != NULL)
1309 *phash = this->type_descriptor_var_;
1310 return;
1313 // See if this type descriptor can appear in multiple packages.
1314 bool is_common = false;
1315 if (nt != NULL)
1317 // We create the descriptor for a builtin type whenever we need
1318 // it.
1319 is_common = nt->is_builtin();
1321 else
1323 // This is an unnamed type. The descriptor could be defined in
1324 // any package where it is needed, and the linker will pick one
1325 // descriptor to keep.
1326 is_common = true;
1329 // We are going to build the type descriptor in this package. We
1330 // must create the variable before we convert the initializer to the
1331 // backend representation, because the initializer may refer to the
1332 // type descriptor of this type. By setting type_descriptor_var_ we
1333 // ensure that type_descriptor_pointer will work if called while
1334 // converting INITIALIZER.
1336 std::string asm_name(go_selectively_encode_id(var_name));
1337 this->type_descriptor_var_ =
1338 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1339 initializer_btype, loc);
1340 if (phash != NULL)
1341 *phash = this->type_descriptor_var_;
1343 Translate_context context(gogo, NULL, NULL, NULL);
1344 context.set_is_const();
1345 Bexpression* binitializer = initializer->get_backend(&context);
1347 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1348 var_name, false, is_common,
1349 initializer_btype, loc,
1350 binitializer);
1353 // Return true if this type descriptor is defined in a different
1354 // package. If this returns true it sets *PACKAGE to the package.
1356 bool
1357 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1358 const Package** package)
1360 if (nt != NULL)
1362 if (nt->named_object()->package() != NULL)
1364 // This is a named type defined in a different package. The
1365 // type descriptor should be defined in that package.
1366 *package = nt->named_object()->package();
1367 return true;
1370 else
1372 if (this->points_to() != NULL
1373 && this->points_to()->named_type() != NULL
1374 && this->points_to()->named_type()->named_object()->package() != NULL)
1376 // This is an unnamed pointer to a named type defined in a
1377 // different package. The descriptor should be defined in
1378 // that package.
1379 *package = this->points_to()->named_type()->named_object()->package();
1380 return true;
1383 return false;
1386 // Return a composite literal for a type descriptor.
1388 Expression*
1389 Type::type_descriptor(Gogo* gogo, Type* type)
1391 return type->do_type_descriptor(gogo, NULL);
1394 // Return a composite literal for a type descriptor with a name.
1396 Expression*
1397 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1399 go_assert(name != NULL && type->named_type() != name);
1400 return type->do_type_descriptor(gogo, name);
1403 // Make a builtin struct type from a list of fields. The fields are
1404 // pairs of a name and a type.
1406 Struct_type*
1407 Type::make_builtin_struct_type(int nfields, ...)
1409 va_list ap;
1410 va_start(ap, nfields);
1412 Location bloc = Linemap::predeclared_location();
1413 Struct_field_list* sfl = new Struct_field_list();
1414 for (int i = 0; i < nfields; i++)
1416 const char* field_name = va_arg(ap, const char *);
1417 Type* type = va_arg(ap, Type*);
1418 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1421 va_end(ap);
1423 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1424 ret->set_is_struct_incomparable();
1425 return ret;
1428 // A list of builtin named types.
1430 std::vector<Named_type*> Type::named_builtin_types;
1432 // Make a builtin named type.
1434 Named_type*
1435 Type::make_builtin_named_type(const char* name, Type* type)
1437 Location bloc = Linemap::predeclared_location();
1438 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1439 Named_type* ret = no->type_value();
1440 Type::named_builtin_types.push_back(ret);
1441 return ret;
1444 // Convert the named builtin types.
1446 void
1447 Type::convert_builtin_named_types(Gogo* gogo)
1449 for (std::vector<Named_type*>::const_iterator p =
1450 Type::named_builtin_types.begin();
1451 p != Type::named_builtin_types.end();
1452 ++p)
1454 bool r = (*p)->verify();
1455 go_assert(r);
1456 (*p)->convert(gogo);
1460 // Return the type of a type descriptor. We should really tie this to
1461 // runtime.Type rather than copying it. This must match the struct "_type"
1462 // declared in libgo/go/runtime/type.go.
1464 Type*
1465 Type::make_type_descriptor_type()
1467 static Type* ret;
1468 if (ret == NULL)
1470 Location bloc = Linemap::predeclared_location();
1472 Type* uint8_type = Type::lookup_integer_type("uint8");
1473 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1474 Type* uint32_type = Type::lookup_integer_type("uint32");
1475 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1476 Type* string_type = Type::lookup_string_type();
1477 Type* pointer_string_type = Type::make_pointer_type(string_type);
1479 // This is an unnamed version of unsafe.Pointer. Perhaps we
1480 // should use the named version instead, although that would
1481 // require us to create the unsafe package if it has not been
1482 // imported. It probably doesn't matter.
1483 Type* void_type = Type::make_void_type();
1484 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1486 Typed_identifier_list *params = new Typed_identifier_list();
1487 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1488 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1490 Typed_identifier_list* results = new Typed_identifier_list();
1491 results->push_back(Typed_identifier("", uintptr_type, bloc));
1493 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1494 bloc);
1496 params = new Typed_identifier_list();
1497 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1498 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1500 results = new Typed_identifier_list();
1501 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1503 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1504 bloc);
1506 // Forward declaration for the type descriptor type.
1507 Named_object* named_type_descriptor_type =
1508 Named_object::make_type_declaration("_type", NULL, bloc);
1509 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1510 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1512 // The type of a method on a concrete type.
1513 Struct_type* method_type =
1514 Type::make_builtin_struct_type(5,
1515 "name", pointer_string_type,
1516 "pkgPath", pointer_string_type,
1517 "mtyp", pointer_type_descriptor_type,
1518 "typ", pointer_type_descriptor_type,
1519 "tfn", unsafe_pointer_type);
1520 Named_type* named_method_type =
1521 Type::make_builtin_named_type("method", method_type);
1523 // Information for types with a name or methods.
1524 Type* slice_named_method_type =
1525 Type::make_array_type(named_method_type, NULL);
1526 Struct_type* uncommon_type =
1527 Type::make_builtin_struct_type(3,
1528 "name", pointer_string_type,
1529 "pkgPath", pointer_string_type,
1530 "methods", slice_named_method_type);
1531 Named_type* named_uncommon_type =
1532 Type::make_builtin_named_type("uncommonType", uncommon_type);
1534 Type* pointer_uncommon_type =
1535 Type::make_pointer_type(named_uncommon_type);
1537 // The type descriptor type.
1539 Struct_type* type_descriptor_type =
1540 Type::make_builtin_struct_type(12,
1541 "size", uintptr_type,
1542 "ptrdata", uintptr_type,
1543 "hash", uint32_type,
1544 "kind", uint8_type,
1545 "align", uint8_type,
1546 "fieldAlign", uint8_type,
1547 "hashfn", hash_fntype,
1548 "equalfn", equal_fntype,
1549 "gcdata", pointer_uint8_type,
1550 "string", pointer_string_type,
1551 "", pointer_uncommon_type,
1552 "ptrToThis",
1553 pointer_type_descriptor_type);
1555 Named_type* named = Type::make_builtin_named_type("_type",
1556 type_descriptor_type);
1558 named_type_descriptor_type->set_type_value(named);
1560 ret = named;
1563 return ret;
1566 // Make the type of a pointer to a type descriptor as represented in
1567 // Go.
1569 Type*
1570 Type::make_type_descriptor_ptr_type()
1572 static Type* ret;
1573 if (ret == NULL)
1574 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1575 return ret;
1578 // Return the alignment required by the memequalN function. N is a
1579 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1580 // in libgo/go/runtime/alg.go.
1582 int64_t
1583 Type::memequal_align(Gogo* gogo, int size)
1585 const char* tn;
1586 switch (size)
1588 case 16:
1589 tn = "int16";
1590 break;
1591 case 32:
1592 tn = "int32";
1593 break;
1594 case 64:
1595 tn = "int64";
1596 break;
1597 case 128:
1598 // The code uses [2]int64, which must have the same alignment as
1599 // int64.
1600 tn = "int64";
1601 break;
1602 default:
1603 go_unreachable();
1606 Type* t = Type::lookup_integer_type(tn);
1608 int64_t ret;
1609 if (!t->backend_type_align(gogo, &ret))
1610 go_unreachable();
1611 return ret;
1614 // Return whether this type needs specially built type functions.
1615 // This returns true for types that are comparable and either can not
1616 // use an identity comparison, or are a non-standard size.
1618 bool
1619 Type::needs_specific_type_functions(Gogo* gogo)
1621 Named_type* nt = this->named_type();
1622 if (nt != NULL && nt->is_alias())
1623 return false;
1624 if (!this->is_comparable())
1625 return false;
1626 if (!this->compare_is_identity(gogo))
1627 return true;
1629 // We create a few predeclared types for type descriptors; they are
1630 // really just for the backend and don't need hash or equality
1631 // functions.
1632 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1633 return false;
1635 int64_t size, align;
1636 if (!this->backend_type_size(gogo, &size)
1637 || !this->backend_type_align(gogo, &align))
1639 go_assert(saw_errors());
1640 return false;
1642 // This switch matches the one in Type::type_functions.
1643 switch (size)
1645 case 0:
1646 case 1:
1647 case 2:
1648 return align < Type::memequal_align(gogo, 16);
1649 case 4:
1650 return align < Type::memequal_align(gogo, 32);
1651 case 8:
1652 return align < Type::memequal_align(gogo, 64);
1653 case 16:
1654 return align < Type::memequal_align(gogo, 128);
1655 default:
1656 return true;
1660 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1661 // hash code for this type and which compare whether two values of
1662 // this type are equal. If NAME is not NULL it is the name of this
1663 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1664 // functions, for convenience; they may be NULL.
1666 void
1667 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1668 Function_type* equal_fntype, Named_object** hash_fn,
1669 Named_object** equal_fn)
1671 // If the unaliased type is not a named type, then the type does not
1672 // have a name after all.
1673 if (name != NULL)
1674 name = name->unalias()->named_type();
1676 if (!this->is_comparable())
1678 *hash_fn = NULL;
1679 *equal_fn = NULL;
1680 return;
1683 if (hash_fntype == NULL || equal_fntype == NULL)
1685 Location bloc = Linemap::predeclared_location();
1687 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1688 Type* void_type = Type::make_void_type();
1689 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1691 if (hash_fntype == NULL)
1693 Typed_identifier_list* params = new Typed_identifier_list();
1694 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1695 bloc));
1696 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1698 Typed_identifier_list* results = new Typed_identifier_list();
1699 results->push_back(Typed_identifier("", uintptr_type, bloc));
1701 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1703 if (equal_fntype == NULL)
1705 Typed_identifier_list* params = new Typed_identifier_list();
1706 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1707 bloc));
1708 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1709 bloc));
1711 Typed_identifier_list* results = new Typed_identifier_list();
1712 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1713 bloc));
1715 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1719 const char* hash_fnname;
1720 const char* equal_fnname;
1721 if (this->compare_is_identity(gogo))
1723 int64_t size, align;
1724 if (!this->backend_type_size(gogo, &size)
1725 || !this->backend_type_align(gogo, &align))
1727 go_assert(saw_errors());
1728 return;
1730 bool build_functions = false;
1731 // This switch matches the one in Type::needs_specific_type_functions.
1732 // The alignment tests are because of the memequal functions,
1733 // which assume that the values are aligned as required for an
1734 // integer of that size.
1735 switch (size)
1737 case 0:
1738 hash_fnname = "runtime.memhash0";
1739 equal_fnname = "runtime.memequal0";
1740 break;
1741 case 1:
1742 hash_fnname = "runtime.memhash8";
1743 equal_fnname = "runtime.memequal8";
1744 break;
1745 case 2:
1746 if (align < Type::memequal_align(gogo, 16))
1747 build_functions = true;
1748 else
1750 hash_fnname = "runtime.memhash16";
1751 equal_fnname = "runtime.memequal16";
1753 break;
1754 case 4:
1755 if (align < Type::memequal_align(gogo, 32))
1756 build_functions = true;
1757 else
1759 hash_fnname = "runtime.memhash32";
1760 equal_fnname = "runtime.memequal32";
1762 break;
1763 case 8:
1764 if (align < Type::memequal_align(gogo, 64))
1765 build_functions = true;
1766 else
1768 hash_fnname = "runtime.memhash64";
1769 equal_fnname = "runtime.memequal64";
1771 break;
1772 case 16:
1773 if (align < Type::memequal_align(gogo, 128))
1774 build_functions = true;
1775 else
1777 hash_fnname = "runtime.memhash128";
1778 equal_fnname = "runtime.memequal128";
1780 break;
1781 default:
1782 build_functions = true;
1783 break;
1785 if (build_functions)
1787 // We don't have a built-in function for a type of this size
1788 // and alignment. Build a function to use that calls the
1789 // generic hash/equality functions for identity, passing the size.
1790 this->specific_type_functions(gogo, name, size, hash_fntype,
1791 equal_fntype, hash_fn, equal_fn);
1792 return;
1795 else
1797 switch (this->base()->classification())
1799 case Type::TYPE_ERROR:
1800 case Type::TYPE_VOID:
1801 case Type::TYPE_NIL:
1802 case Type::TYPE_FUNCTION:
1803 case Type::TYPE_MAP:
1804 // For these types is_comparable should have returned false.
1805 go_unreachable();
1807 case Type::TYPE_BOOLEAN:
1808 case Type::TYPE_INTEGER:
1809 case Type::TYPE_POINTER:
1810 case Type::TYPE_CHANNEL:
1811 // For these types compare_is_identity should have returned true.
1812 go_unreachable();
1814 case Type::TYPE_FLOAT:
1815 switch (this->float_type()->bits())
1817 case 32:
1818 hash_fnname = "runtime.f32hash";
1819 equal_fnname = "runtime.f32equal";
1820 break;
1821 case 64:
1822 hash_fnname = "runtime.f64hash";
1823 equal_fnname = "runtime.f64equal";
1824 break;
1825 default:
1826 go_unreachable();
1828 break;
1830 case Type::TYPE_COMPLEX:
1831 switch (this->complex_type()->bits())
1833 case 64:
1834 hash_fnname = "runtime.c64hash";
1835 equal_fnname = "runtime.c64equal";
1836 break;
1837 case 128:
1838 hash_fnname = "runtime.c128hash";
1839 equal_fnname = "runtime.c128equal";
1840 break;
1841 default:
1842 go_unreachable();
1844 break;
1846 case Type::TYPE_STRING:
1847 hash_fnname = "runtime.strhash";
1848 equal_fnname = "runtime.strequal";
1849 break;
1851 case Type::TYPE_STRUCT:
1853 // This is a struct which can not be compared using a
1854 // simple identity function. We need to build a function
1855 // for comparison.
1856 this->specific_type_functions(gogo, name, -1, hash_fntype,
1857 equal_fntype, hash_fn, equal_fn);
1858 return;
1861 case Type::TYPE_ARRAY:
1862 if (this->is_slice_type())
1864 // Type::is_compatible_for_comparison should have
1865 // returned false.
1866 go_unreachable();
1868 else
1870 // This is an array which can not be compared using a
1871 // simple identity function. We need to build a
1872 // function for comparison.
1873 this->specific_type_functions(gogo, name, -1, hash_fntype,
1874 equal_fntype, hash_fn, equal_fn);
1875 return;
1877 break;
1879 case Type::TYPE_INTERFACE:
1880 if (this->interface_type()->is_empty())
1882 hash_fnname = "runtime.nilinterhash";
1883 equal_fnname = "runtime.nilinterequal";
1885 else
1887 hash_fnname = "runtime.interhash";
1888 equal_fnname = "runtime.interequal";
1890 break;
1892 case Type::TYPE_NAMED:
1893 case Type::TYPE_FORWARD:
1894 go_unreachable();
1896 default:
1897 go_unreachable();
1902 Location bloc = Linemap::predeclared_location();
1903 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1904 hash_fntype, bloc);
1905 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1906 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1907 equal_fntype, bloc);
1908 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1911 // A hash table mapping types to the specific hash functions.
1913 Type::Type_functions Type::type_functions_table;
1915 // Handle a type function which is specific to a type: if SIZE == -1,
1916 // this is a struct or array that can not use an identity comparison.
1917 // Otherwise, it is a type that uses an identity comparison but is not
1918 // one of the standard supported sizes.
1920 void
1921 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1922 Function_type* hash_fntype,
1923 Function_type* equal_fntype,
1924 Named_object** hash_fn,
1925 Named_object** equal_fn)
1927 Hash_equal_fn fnull(NULL, NULL);
1928 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1929 std::pair<Type_functions::iterator, bool> ins =
1930 Type::type_functions_table.insert(val);
1931 if (!ins.second)
1933 // We already have functions for this type
1934 *hash_fn = ins.first->second.first;
1935 *equal_fn = ins.first->second.second;
1936 return;
1939 std::string hash_name;
1940 std::string equal_name;
1941 gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
1943 Location bloc = Linemap::predeclared_location();
1945 const Package* package = NULL;
1946 bool is_defined_elsewhere =
1947 this->type_descriptor_defined_elsewhere(name, &package);
1948 if (is_defined_elsewhere)
1950 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1951 hash_fntype, bloc);
1952 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1953 equal_fntype, bloc);
1955 else
1957 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1958 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1959 bloc);
1962 ins.first->second.first = *hash_fn;
1963 ins.first->second.second = *equal_fn;
1965 if (!is_defined_elsewhere)
1967 if (gogo->in_global_scope())
1968 this->write_specific_type_functions(gogo, name, size, hash_name,
1969 hash_fntype, equal_name,
1970 equal_fntype);
1971 else
1972 gogo->queue_specific_type_function(this, name, size, hash_name,
1973 hash_fntype, equal_name,
1974 equal_fntype);
1978 // Write the hash and equality functions for a type which needs to be
1979 // written specially.
1981 void
1982 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1983 const std::string& hash_name,
1984 Function_type* hash_fntype,
1985 const std::string& equal_name,
1986 Function_type* equal_fntype)
1988 Location bloc = Linemap::predeclared_location();
1990 if (gogo->specific_type_functions_are_written())
1992 go_assert(saw_errors());
1993 return;
1996 go_assert(this->is_comparable());
1998 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1999 bloc);
2000 hash_fn->func_value()->set_is_type_specific_function();
2001 gogo->start_block(bloc);
2003 if (size != -1)
2004 this->write_identity_hash(gogo, size);
2005 else if (name != NULL && name->real_type()->named_type() != NULL)
2006 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2007 else if (this->struct_type() != NULL)
2008 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2009 equal_fntype);
2010 else if (this->array_type() != NULL)
2011 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2012 equal_fntype);
2013 else
2014 go_unreachable();
2016 Block* b = gogo->finish_block(bloc);
2017 gogo->add_block(b, bloc);
2018 gogo->lower_block(hash_fn, b);
2019 gogo->finish_function(bloc);
2021 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2022 false, bloc);
2023 equal_fn->func_value()->set_is_type_specific_function();
2024 gogo->start_block(bloc);
2026 if (size != -1)
2027 this->write_identity_equal(gogo, size);
2028 else if (name != NULL && name->real_type()->named_type() != NULL)
2029 this->write_named_equal(gogo, name);
2030 else if (this->struct_type() != NULL)
2031 this->struct_type()->write_equal_function(gogo, name);
2032 else if (this->array_type() != NULL)
2033 this->array_type()->write_equal_function(gogo, name);
2034 else
2035 go_unreachable();
2037 b = gogo->finish_block(bloc);
2038 gogo->add_block(b, bloc);
2039 gogo->lower_block(equal_fn, b);
2040 gogo->finish_function(bloc);
2042 // Build the function descriptors for the type descriptor to refer to.
2043 hash_fn->func_value()->descriptor(gogo, hash_fn);
2044 equal_fn->func_value()->descriptor(gogo, equal_fn);
2047 // Write a hash function for a type that can use an identity hash but
2048 // is not one of the standard supported sizes. For example, this
2049 // would be used for the type [3]byte. This builds a return statement
2050 // that returns a call to the memhash function, passing the key and
2051 // seed from the function arguments (already constructed before this
2052 // is called), and the constant size.
2054 void
2055 Type::write_identity_hash(Gogo* gogo, int64_t size)
2057 Location bloc = Linemap::predeclared_location();
2059 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2060 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2062 Typed_identifier_list* params = new Typed_identifier_list();
2063 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2064 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2065 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2067 Typed_identifier_list* results = new Typed_identifier_list();
2068 results->push_back(Typed_identifier("", uintptr_type, bloc));
2070 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2071 results, bloc);
2073 Named_object* memhash =
2074 Named_object::make_function_declaration("runtime.memhash", NULL,
2075 memhash_fntype, bloc);
2076 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2078 Named_object* key_arg = gogo->lookup("key", NULL);
2079 go_assert(key_arg != NULL);
2080 Named_object* seed_arg = gogo->lookup("seed", NULL);
2081 go_assert(seed_arg != NULL);
2083 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2084 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2085 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2086 bloc);
2087 Expression_list* args = new Expression_list();
2088 args->push_back(key_ref);
2089 args->push_back(seed_ref);
2090 args->push_back(size_arg);
2091 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2092 Expression* call = Expression::make_call(func, args, false, bloc);
2094 Expression_list* vals = new Expression_list();
2095 vals->push_back(call);
2096 Statement* s = Statement::make_return_statement(vals, bloc);
2097 gogo->add_statement(s);
2100 // Write an equality function for a type that can use an identity
2101 // equality comparison but is not one of the standard supported sizes.
2102 // For example, this would be used for the type [3]byte. This builds
2103 // a return statement that returns a call to the memequal function,
2104 // passing the two keys from the function arguments (already
2105 // constructed before this is called), and the constant size.
2107 void
2108 Type::write_identity_equal(Gogo* gogo, int64_t size)
2110 Location bloc = Linemap::predeclared_location();
2112 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2113 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2115 Typed_identifier_list* params = new Typed_identifier_list();
2116 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2117 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2118 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2120 Typed_identifier_list* results = new Typed_identifier_list();
2121 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2123 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2124 results, bloc);
2126 Named_object* memequal =
2127 Named_object::make_function_declaration("runtime.memequal", NULL,
2128 memequal_fntype, bloc);
2129 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2131 Named_object* key1_arg = gogo->lookup("key1", NULL);
2132 go_assert(key1_arg != NULL);
2133 Named_object* key2_arg = gogo->lookup("key2", NULL);
2134 go_assert(key2_arg != NULL);
2136 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2137 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2138 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2139 bloc);
2140 Expression_list* args = new Expression_list();
2141 args->push_back(key1_ref);
2142 args->push_back(key2_ref);
2143 args->push_back(size_arg);
2144 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2145 Expression* call = Expression::make_call(func, args, false, bloc);
2147 Expression_list* vals = new Expression_list();
2148 vals->push_back(call);
2149 Statement* s = Statement::make_return_statement(vals, bloc);
2150 gogo->add_statement(s);
2153 // Write a hash function that simply calls the hash function for a
2154 // named type. This is used when one named type is defined as
2155 // another. This ensures that this case works when the other named
2156 // type is defined in another package and relies on calling hash
2157 // functions defined only in that package.
2159 void
2160 Type::write_named_hash(Gogo* gogo, Named_type* name,
2161 Function_type* hash_fntype, Function_type* equal_fntype)
2163 Location bloc = Linemap::predeclared_location();
2165 Named_type* base_type = name->real_type()->named_type();
2166 while (base_type->is_alias())
2168 base_type = base_type->real_type()->named_type();
2169 go_assert(base_type != NULL);
2171 go_assert(base_type != NULL);
2173 // The pointer to the type we are going to hash. This is an
2174 // unsafe.Pointer.
2175 Named_object* key_arg = gogo->lookup("key", NULL);
2176 go_assert(key_arg != NULL);
2178 // The seed argument to the hash function.
2179 Named_object* seed_arg = gogo->lookup("seed", NULL);
2180 go_assert(seed_arg != NULL);
2182 Named_object* hash_fn;
2183 Named_object* equal_fn;
2184 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2185 &hash_fn, &equal_fn);
2187 // Call the hash function for the base type.
2188 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2189 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2190 Expression_list* args = new Expression_list();
2191 args->push_back(key_ref);
2192 args->push_back(seed_ref);
2193 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2194 Expression* call = Expression::make_call(func, args, false, bloc);
2196 // Return the hash of the base type.
2197 Expression_list* vals = new Expression_list();
2198 vals->push_back(call);
2199 Statement* s = Statement::make_return_statement(vals, bloc);
2200 gogo->add_statement(s);
2203 // Write an equality function that simply calls the equality function
2204 // for a named type. This is used when one named type is defined as
2205 // another. This ensures that this case works when the other named
2206 // type is defined in another package and relies on calling equality
2207 // functions defined only in that package.
2209 void
2210 Type::write_named_equal(Gogo* gogo, Named_type* name)
2212 Location bloc = Linemap::predeclared_location();
2214 // The pointers to the types we are going to compare. These have
2215 // type unsafe.Pointer.
2216 Named_object* key1_arg = gogo->lookup("key1", NULL);
2217 Named_object* key2_arg = gogo->lookup("key2", NULL);
2218 go_assert(key1_arg != NULL && key2_arg != NULL);
2220 Named_type* base_type = name->real_type()->named_type();
2221 go_assert(base_type != NULL);
2223 // Build temporaries with the base type.
2224 Type* pt = Type::make_pointer_type(base_type);
2226 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2227 ref = Expression::make_cast(pt, ref, bloc);
2228 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2229 gogo->add_statement(p1);
2231 ref = Expression::make_var_reference(key2_arg, bloc);
2232 ref = Expression::make_cast(pt, ref, bloc);
2233 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2234 gogo->add_statement(p2);
2236 // Compare the values for equality.
2237 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2238 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2240 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2241 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2243 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2245 // Return the equality comparison.
2246 Expression_list* vals = new Expression_list();
2247 vals->push_back(cond);
2248 Statement* s = Statement::make_return_statement(vals, bloc);
2249 gogo->add_statement(s);
2252 // Return a composite literal for the type descriptor for a plain type
2253 // of kind RUNTIME_TYPE_KIND named NAME.
2255 Expression*
2256 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2257 Named_type* name, const Methods* methods,
2258 bool only_value_methods)
2260 Location bloc = Linemap::predeclared_location();
2262 Type* td_type = Type::make_type_descriptor_type();
2263 const Struct_field_list* fields = td_type->struct_type()->fields();
2265 Expression_list* vals = new Expression_list();
2266 vals->reserve(12);
2268 if (!this->has_pointer())
2269 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2270 if (this->points_to() != NULL)
2271 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2272 int64_t ptrsize;
2273 int64_t ptrdata;
2274 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2275 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2277 Struct_field_list::const_iterator p = fields->begin();
2278 go_assert(p->is_field_name("size"));
2279 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2280 vals->push_back(Expression::make_type_info(this, type_info));
2282 ++p;
2283 go_assert(p->is_field_name("ptrdata"));
2284 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2285 vals->push_back(Expression::make_type_info(this, type_info));
2287 ++p;
2288 go_assert(p->is_field_name("hash"));
2289 unsigned int h;
2290 if (name != NULL)
2291 h = name->hash_for_method(gogo);
2292 else
2293 h = this->hash_for_method(gogo);
2294 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2296 ++p;
2297 go_assert(p->is_field_name("kind"));
2298 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2299 bloc));
2301 ++p;
2302 go_assert(p->is_field_name("align"));
2303 type_info = Expression::TYPE_INFO_ALIGNMENT;
2304 vals->push_back(Expression::make_type_info(this, type_info));
2306 ++p;
2307 go_assert(p->is_field_name("fieldAlign"));
2308 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2309 vals->push_back(Expression::make_type_info(this, type_info));
2311 ++p;
2312 go_assert(p->is_field_name("hashfn"));
2313 Function_type* hash_fntype = p->type()->function_type();
2315 ++p;
2316 go_assert(p->is_field_name("equalfn"));
2317 Function_type* equal_fntype = p->type()->function_type();
2319 Named_object* hash_fn;
2320 Named_object* equal_fn;
2321 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2322 &equal_fn);
2323 if (hash_fn == NULL)
2324 vals->push_back(Expression::make_cast(hash_fntype,
2325 Expression::make_nil(bloc),
2326 bloc));
2327 else
2328 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2329 if (equal_fn == NULL)
2330 vals->push_back(Expression::make_cast(equal_fntype,
2331 Expression::make_nil(bloc),
2332 bloc));
2333 else
2334 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2336 ++p;
2337 go_assert(p->is_field_name("gcdata"));
2338 vals->push_back(Expression::make_gc_symbol(this));
2340 ++p;
2341 go_assert(p->is_field_name("string"));
2342 Expression* s = Expression::make_string((name != NULL
2343 ? name->reflection(gogo)
2344 : this->reflection(gogo)),
2345 bloc);
2346 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2348 ++p;
2349 go_assert(p->is_field_name("uncommonType"));
2350 if (name == NULL && methods == NULL)
2351 vals->push_back(Expression::make_nil(bloc));
2352 else
2354 if (methods == NULL)
2355 methods = name->methods();
2356 vals->push_back(this->uncommon_type_constructor(gogo,
2357 p->type()->deref(),
2358 name, methods,
2359 only_value_methods));
2362 ++p;
2363 go_assert(p->is_field_name("ptrToThis"));
2364 if (name == NULL && methods == NULL)
2365 vals->push_back(Expression::make_nil(bloc));
2366 else
2368 Type* pt;
2369 if (name != NULL)
2370 pt = Type::make_pointer_type(name);
2371 else
2372 pt = Type::make_pointer_type(this);
2373 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2376 ++p;
2377 go_assert(p == fields->end());
2379 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2382 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2383 // length used by the gc toolchain, and also appears in
2384 // libgo/go/reflect/type.go.
2386 static const int64_t max_ptrmask_bytes = 2048;
2388 // Return a pointer to the Garbage Collection information for this type.
2390 Bexpression*
2391 Type::gc_symbol_pointer(Gogo* gogo)
2393 Type* t = this->unalias();
2395 if (!t->has_pointer())
2396 return gogo->backend()->nil_pointer_expression();
2398 if (t->gc_symbol_var_ == NULL)
2400 t->make_gc_symbol_var(gogo);
2401 go_assert(t->gc_symbol_var_ != NULL);
2403 Location bloc = Linemap::predeclared_location();
2404 Bexpression* var_expr =
2405 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2406 Bexpression* addr_expr =
2407 gogo->backend()->address_expression(var_expr, bloc);
2409 Type* uint8_type = Type::lookup_integer_type("uint8");
2410 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2411 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2412 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2415 // A mapping from unnamed types to GC symbol variables.
2417 Type::GC_symbol_vars Type::gc_symbol_vars;
2419 // Build the GC symbol for this type.
2421 void
2422 Type::make_gc_symbol_var(Gogo* gogo)
2424 go_assert(this->gc_symbol_var_ == NULL);
2426 Named_type* nt = this->named_type();
2428 // We can have multiple instances of unnamed types and similar to type
2429 // descriptors, we only want to the emit the GC data once, so we use a
2430 // hash table.
2431 Bvariable** phash = NULL;
2432 if (nt == NULL)
2434 Bvariable* bvnull = NULL;
2435 std::pair<GC_symbol_vars::iterator, bool> ins =
2436 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2437 if (!ins.second)
2439 // We've already built a gc symbol for this type.
2440 this->gc_symbol_var_ = ins.first->second;
2441 return;
2443 phash = &ins.first->second;
2446 int64_t ptrsize;
2447 int64_t ptrdata;
2448 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2450 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2451 if (phash != NULL)
2452 *phash = this->gc_symbol_var_;
2453 return;
2456 std::string sym_name = gogo->gc_symbol_name(this);
2458 // Build the contents of the gc symbol.
2459 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2460 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2462 // If the type descriptor for this type is defined somewhere else, so is the
2463 // GC symbol.
2464 const Package* dummy;
2465 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2467 std::string asm_name(go_selectively_encode_id(sym_name));
2468 this->gc_symbol_var_ =
2469 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2470 sym_btype);
2471 if (phash != NULL)
2472 *phash = this->gc_symbol_var_;
2473 return;
2476 // See if this gc symbol can appear in multiple packages.
2477 bool is_common = false;
2478 if (nt != NULL)
2480 // We create the symbol for a builtin type whenever we need
2481 // it.
2482 is_common = nt->is_builtin();
2484 else
2486 // This is an unnamed type. The descriptor could be defined in
2487 // any package where it is needed, and the linker will pick one
2488 // descriptor to keep.
2489 is_common = true;
2492 // Since we are building the GC symbol in this package, we must create the
2493 // variable before converting the initializer to its backend representation
2494 // because the initializer may refer to the GC symbol for this type.
2495 std::string asm_name(go_selectively_encode_id(sym_name));
2496 this->gc_symbol_var_ =
2497 gogo->backend()->implicit_variable(sym_name, asm_name,
2498 sym_btype, false, true, is_common, 0);
2499 if (phash != NULL)
2500 *phash = this->gc_symbol_var_;
2502 Translate_context context(gogo, NULL, NULL, NULL);
2503 context.set_is_const();
2504 Bexpression* sym_binit = sym_init->get_backend(&context);
2505 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2506 sym_btype, false, true, is_common,
2507 sym_binit);
2510 // Return whether this type needs a GC program, and set *PTRDATA to
2511 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2512 // pointer.
2514 bool
2515 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2517 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2518 if (!voidptr->backend_type_size(gogo, ptrsize))
2519 go_unreachable();
2521 if (!this->backend_type_ptrdata(gogo, ptrdata))
2523 go_assert(saw_errors());
2524 return false;
2527 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2530 // A simple class used to build a GC ptrmask for a type.
2532 class Ptrmask
2534 public:
2535 Ptrmask(size_t count)
2536 : bits_((count + 7) / 8, 0)
2539 void
2540 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2542 std::string
2543 symname() const;
2545 Expression*
2546 constructor(Gogo* gogo) const;
2548 private:
2549 void
2550 set(size_t index)
2551 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2553 // The actual bits.
2554 std::vector<unsigned char> bits_;
2557 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2558 // counts in bytes. PTRSIZE is the size of a pointer on the target
2559 // system.
2561 void
2562 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2564 switch (type->base()->classification())
2566 default:
2567 case Type::TYPE_NIL:
2568 case Type::TYPE_CALL_MULTIPLE_RESULT:
2569 case Type::TYPE_NAMED:
2570 case Type::TYPE_FORWARD:
2571 go_unreachable();
2573 case Type::TYPE_ERROR:
2574 case Type::TYPE_VOID:
2575 case Type::TYPE_BOOLEAN:
2576 case Type::TYPE_INTEGER:
2577 case Type::TYPE_FLOAT:
2578 case Type::TYPE_COMPLEX:
2579 case Type::TYPE_SINK:
2580 break;
2582 case Type::TYPE_FUNCTION:
2583 case Type::TYPE_POINTER:
2584 case Type::TYPE_MAP:
2585 case Type::TYPE_CHANNEL:
2586 // These types are all a single pointer.
2587 go_assert((offset % ptrsize) == 0);
2588 this->set(offset / ptrsize);
2589 break;
2591 case Type::TYPE_STRING:
2592 // A string starts with a single pointer.
2593 go_assert((offset % ptrsize) == 0);
2594 this->set(offset / ptrsize);
2595 break;
2597 case Type::TYPE_INTERFACE:
2598 // An interface is two pointers.
2599 go_assert((offset % ptrsize) == 0);
2600 this->set(offset / ptrsize);
2601 this->set((offset / ptrsize) + 1);
2602 break;
2604 case Type::TYPE_STRUCT:
2606 if (!type->has_pointer())
2607 return;
2609 const Struct_field_list* fields = type->struct_type()->fields();
2610 int64_t soffset = 0;
2611 for (Struct_field_list::const_iterator pf = fields->begin();
2612 pf != fields->end();
2613 ++pf)
2615 int64_t field_align;
2616 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2618 go_assert(saw_errors());
2619 return;
2621 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2623 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2625 int64_t field_size;
2626 if (!pf->type()->backend_type_size(gogo, &field_size))
2628 go_assert(saw_errors());
2629 return;
2631 soffset += field_size;
2634 break;
2636 case Type::TYPE_ARRAY:
2637 if (type->is_slice_type())
2639 // A slice starts with a single pointer.
2640 go_assert((offset % ptrsize) == 0);
2641 this->set(offset / ptrsize);
2642 break;
2644 else
2646 if (!type->has_pointer())
2647 return;
2649 int64_t len;
2650 if (!type->array_type()->int_length(&len))
2652 go_assert(saw_errors());
2653 return;
2656 Type* element_type = type->array_type()->element_type();
2657 int64_t ele_size;
2658 if (!element_type->backend_type_size(gogo, &ele_size))
2660 go_assert(saw_errors());
2661 return;
2664 int64_t eoffset = 0;
2665 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2666 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2667 break;
2672 // Return a symbol name for this ptrmask. This is used to coalesce
2673 // identical ptrmasks, which are common. The symbol name must use
2674 // only characters that are valid in symbols. It's nice if it's
2675 // short. We convert it to a string that uses only 32 characters,
2676 // avoiding digits and u and U.
2678 std::string
2679 Ptrmask::symname() const
2681 const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2682 go_assert(chars[32] == '\0');
2683 std::string ret;
2684 unsigned int b = 0;
2685 int remaining = 0;
2686 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2687 p != this->bits_.end();
2688 ++p)
2690 b |= *p << remaining;
2691 remaining += 8;
2692 while (remaining >= 5)
2694 ret += chars[b & 0x1f];
2695 b >>= 5;
2696 remaining -= 5;
2699 while (remaining > 0)
2701 ret += chars[b & 0x1f];
2702 b >>= 5;
2703 remaining -= 5;
2705 return ret;
2708 // Return a constructor for this ptrmask. This will be used to
2709 // initialize the runtime ptrmask value.
2711 Expression*
2712 Ptrmask::constructor(Gogo* gogo) const
2714 Location bloc = Linemap::predeclared_location();
2715 Type* byte_type = gogo->lookup_global("byte")->type_value();
2716 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2717 bloc);
2718 Array_type* at = Type::make_array_type(byte_type, len);
2719 Expression_list* vals = new Expression_list();
2720 vals->reserve(this->bits_.size());
2721 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2722 p != this->bits_.end();
2723 ++p)
2724 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2725 return Expression::make_array_composite_literal(at, vals, bloc);
2728 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2729 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2731 // Return a ptrmask variable for a type. For a type descriptor this
2732 // is only used for variables that are small enough to not need a
2733 // gcprog, but for a global variable this is used for a variable of
2734 // any size. PTRDATA is the number of bytes of the type that contain
2735 // pointer data. PTRSIZE is the size of a pointer on the target
2736 // system.
2738 Bvariable*
2739 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2741 Ptrmask ptrmask(ptrdata / ptrsize);
2742 if (ptrdata >= ptrsize)
2743 ptrmask.set_from(gogo, this, ptrsize, 0);
2744 else
2746 // This can happen in error cases. Just build an empty gcbits.
2747 go_assert(saw_errors());
2750 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2751 Bvariable* bvnull = NULL;
2752 std::pair<GC_gcbits_vars::iterator, bool> ins =
2753 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2754 if (!ins.second)
2756 // We've already built a GC symbol for this set of gcbits.
2757 return ins.first->second;
2760 Expression* val = ptrmask.constructor(gogo);
2761 Translate_context context(gogo, NULL, NULL, NULL);
2762 context.set_is_const();
2763 Bexpression* bval = val->get_backend(&context);
2765 std::string asm_name(go_selectively_encode_id(sym_name));
2766 Btype *btype = val->type()->get_backend(gogo);
2767 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2768 btype, false, true,
2769 true, 0);
2770 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2771 true, true, bval);
2772 ins.first->second = ret;
2773 return ret;
2776 // A GCProg is used to build a program for the garbage collector.
2777 // This is used for types with a lot of pointer data, to reduce the
2778 // size of the data in the compiled program. The program is expanded
2779 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2781 class GCProg
2783 public:
2784 GCProg()
2785 : bytes_(), index_(0), nb_(0)
2788 // The number of bits described so far.
2789 int64_t
2790 bit_index() const
2791 { return this->index_; }
2793 void
2794 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2796 void
2797 end();
2799 Expression*
2800 constructor(Gogo* gogo) const;
2802 private:
2803 void
2804 ptr(int64_t);
2806 bool
2807 should_repeat(int64_t, int64_t);
2809 void
2810 repeat(int64_t, int64_t);
2812 void
2813 zero_until(int64_t);
2815 void
2816 lit(unsigned char);
2818 void
2819 varint(int64_t);
2821 void
2822 flushlit();
2824 // Add a byte to the program.
2825 void
2826 byte(unsigned char x)
2827 { this->bytes_.push_back(x); }
2829 // The maximum number of bytes of literal bits.
2830 static const int max_literal = 127;
2832 // The program.
2833 std::vector<unsigned char> bytes_;
2834 // The index of the last bit described.
2835 int64_t index_;
2836 // The current set of literal bits.
2837 unsigned char b_[max_literal];
2838 // The current number of literal bits.
2839 int nb_;
2842 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2843 // counts in bytes. PTRSIZE is the size of a pointer on the target
2844 // system.
2846 void
2847 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2849 switch (type->base()->classification())
2851 default:
2852 case Type::TYPE_NIL:
2853 case Type::TYPE_CALL_MULTIPLE_RESULT:
2854 case Type::TYPE_NAMED:
2855 case Type::TYPE_FORWARD:
2856 go_unreachable();
2858 case Type::TYPE_ERROR:
2859 case Type::TYPE_VOID:
2860 case Type::TYPE_BOOLEAN:
2861 case Type::TYPE_INTEGER:
2862 case Type::TYPE_FLOAT:
2863 case Type::TYPE_COMPLEX:
2864 case Type::TYPE_SINK:
2865 break;
2867 case Type::TYPE_FUNCTION:
2868 case Type::TYPE_POINTER:
2869 case Type::TYPE_MAP:
2870 case Type::TYPE_CHANNEL:
2871 // These types are all a single pointer.
2872 go_assert((offset % ptrsize) == 0);
2873 this->ptr(offset / ptrsize);
2874 break;
2876 case Type::TYPE_STRING:
2877 // A string starts with a single pointer.
2878 go_assert((offset % ptrsize) == 0);
2879 this->ptr(offset / ptrsize);
2880 break;
2882 case Type::TYPE_INTERFACE:
2883 // An interface is two pointers.
2884 go_assert((offset % ptrsize) == 0);
2885 this->ptr(offset / ptrsize);
2886 this->ptr((offset / ptrsize) + 1);
2887 break;
2889 case Type::TYPE_STRUCT:
2891 if (!type->has_pointer())
2892 return;
2894 const Struct_field_list* fields = type->struct_type()->fields();
2895 int64_t soffset = 0;
2896 for (Struct_field_list::const_iterator pf = fields->begin();
2897 pf != fields->end();
2898 ++pf)
2900 int64_t field_align;
2901 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2903 go_assert(saw_errors());
2904 return;
2906 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2908 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2910 int64_t field_size;
2911 if (!pf->type()->backend_type_size(gogo, &field_size))
2913 go_assert(saw_errors());
2914 return;
2916 soffset += field_size;
2919 break;
2921 case Type::TYPE_ARRAY:
2922 if (type->is_slice_type())
2924 // A slice starts with a single pointer.
2925 go_assert((offset % ptrsize) == 0);
2926 this->ptr(offset / ptrsize);
2927 break;
2929 else
2931 if (!type->has_pointer())
2932 return;
2934 int64_t len;
2935 if (!type->array_type()->int_length(&len))
2937 go_assert(saw_errors());
2938 return;
2941 Type* element_type = type->array_type()->element_type();
2943 // Flatten array of array to a big array by multiplying counts.
2944 while (element_type->array_type() != NULL
2945 && !element_type->is_slice_type())
2947 int64_t ele_len;
2948 if (!element_type->array_type()->int_length(&ele_len))
2950 go_assert(saw_errors());
2951 return;
2954 len *= ele_len;
2955 element_type = element_type->array_type()->element_type();
2958 int64_t ele_size;
2959 if (!element_type->backend_type_size(gogo, &ele_size))
2961 go_assert(saw_errors());
2962 return;
2965 go_assert(len > 0 && ele_size > 0);
2967 if (!this->should_repeat(ele_size / ptrsize, len))
2969 // Cheaper to just emit the bits.
2970 int64_t eoffset = 0;
2971 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2972 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2974 else
2976 go_assert((offset % ptrsize) == 0);
2977 go_assert((ele_size % ptrsize) == 0);
2978 this->set_from(gogo, element_type, ptrsize, offset);
2979 this->zero_until((offset + ele_size) / ptrsize);
2980 this->repeat(ele_size / ptrsize, len - 1);
2983 break;
2988 // Emit a 1 into the bit stream of a GC program at the given bit index.
2990 void
2991 GCProg::ptr(int64_t index)
2993 go_assert(index >= this->index_);
2994 this->zero_until(index);
2995 this->lit(1);
2998 // Return whether it is worthwhile to use a repeat to describe c
2999 // elements of n bits each, compared to just emitting c copies of the
3000 // n-bit description.
3002 bool
3003 GCProg::should_repeat(int64_t n, int64_t c)
3005 // Repeat if there is more than 1 item and if the total data doesn't
3006 // fit into four bytes.
3007 return c > 1 && c * n > 4 * 8;
3010 // Emit an instruction to repeat the description of the last n words c
3011 // times (including the initial description, so c + 1 times in total).
3013 void
3014 GCProg::repeat(int64_t n, int64_t c)
3016 if (n == 0 || c == 0)
3017 return;
3018 this->flushlit();
3019 if (n < 128)
3020 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3021 else
3023 this->byte(0x80);
3024 this->varint(n);
3026 this->varint(c);
3027 this->index_ += n * c;
3030 // Add zeros to the bit stream up to the given index.
3032 void
3033 GCProg::zero_until(int64_t index)
3035 go_assert(index >= this->index_);
3036 int64_t skip = index - this->index_;
3037 if (skip == 0)
3038 return;
3039 if (skip < 4 * 8)
3041 for (int64_t i = 0; i < skip; ++i)
3042 this->lit(0);
3043 return;
3045 this->lit(0);
3046 this->flushlit();
3047 this->repeat(1, skip - 1);
3050 // Add a single literal bit to the program.
3052 void
3053 GCProg::lit(unsigned char x)
3055 if (this->nb_ == GCProg::max_literal)
3056 this->flushlit();
3057 this->b_[this->nb_] = x;
3058 ++this->nb_;
3059 ++this->index_;
3062 // Emit the varint encoding of x.
3064 void
3065 GCProg::varint(int64_t x)
3067 go_assert(x >= 0);
3068 while (x >= 0x80)
3070 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3071 x >>= 7;
3073 this->byte(static_cast<unsigned char>(x & 0x7f));
3076 // Flush any pending literal bits.
3078 void
3079 GCProg::flushlit()
3081 if (this->nb_ == 0)
3082 return;
3083 this->byte(static_cast<unsigned char>(this->nb_));
3084 unsigned char bits = 0;
3085 for (int i = 0; i < this->nb_; ++i)
3087 bits |= this->b_[i] << (i % 8);
3088 if ((i + 1) % 8 == 0)
3090 this->byte(bits);
3091 bits = 0;
3094 if (this->nb_ % 8 != 0)
3095 this->byte(bits);
3096 this->nb_ = 0;
3099 // Mark the end of a GC program.
3101 void
3102 GCProg::end()
3104 this->flushlit();
3105 this->byte(0);
3108 // Return an Expression for the bytes in a GC program.
3110 Expression*
3111 GCProg::constructor(Gogo* gogo) const
3113 Location bloc = Linemap::predeclared_location();
3115 // The first four bytes are the length of the program in target byte
3116 // order. Build a struct whose first type is uint32 to make this
3117 // work.
3119 Type* uint32_type = Type::lookup_integer_type("uint32");
3121 Type* byte_type = gogo->lookup_global("byte")->type_value();
3122 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3123 bloc);
3124 Array_type* at = Type::make_array_type(byte_type, len);
3126 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3127 "bytes", at);
3129 Expression_list* vals = new Expression_list();
3130 vals->reserve(this->bytes_.size());
3131 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3132 p != this->bytes_.end();
3133 ++p)
3134 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3135 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3137 vals = new Expression_list();
3138 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3139 bloc));
3140 vals->push_back(bytes);
3142 return Expression::make_struct_composite_literal(st, vals, bloc);
3145 // Return a composite literal for the garbage collection program for
3146 // this type. This is only used for types that are too large to use a
3147 // ptrmask.
3149 Expression*
3150 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3152 Location bloc = Linemap::predeclared_location();
3154 GCProg prog;
3155 prog.set_from(gogo, this, ptrsize, 0);
3156 int64_t offset = prog.bit_index() * ptrsize;
3157 prog.end();
3159 int64_t type_size;
3160 if (!this->backend_type_size(gogo, &type_size))
3162 go_assert(saw_errors());
3163 return Expression::make_error(bloc);
3166 go_assert(offset >= ptrdata && offset <= type_size);
3168 return prog.constructor(gogo);
3171 // Return a composite literal for the uncommon type information for
3172 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3173 // struct. If name is not NULL, it is the name of the type. If
3174 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3175 // is true if only value methods should be included. At least one of
3176 // NAME and METHODS must not be NULL.
3178 Expression*
3179 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3180 Named_type* name, const Methods* methods,
3181 bool only_value_methods) const
3183 Location bloc = Linemap::predeclared_location();
3185 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3187 Expression_list* vals = new Expression_list();
3188 vals->reserve(3);
3190 Struct_field_list::const_iterator p = fields->begin();
3191 go_assert(p->is_field_name("name"));
3193 ++p;
3194 go_assert(p->is_field_name("pkgPath"));
3196 if (name == NULL)
3198 vals->push_back(Expression::make_nil(bloc));
3199 vals->push_back(Expression::make_nil(bloc));
3201 else
3203 Named_object* no = name->named_object();
3204 std::string n = Gogo::unpack_hidden_name(no->name());
3205 Expression* s = Expression::make_string(n, bloc);
3206 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3208 if (name->is_builtin())
3209 vals->push_back(Expression::make_nil(bloc));
3210 else
3212 const Package* package = no->package();
3213 const std::string& pkgpath(package == NULL
3214 ? gogo->pkgpath()
3215 : package->pkgpath());
3216 s = Expression::make_string(pkgpath, bloc);
3217 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3221 ++p;
3222 go_assert(p->is_field_name("methods"));
3223 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3224 only_value_methods));
3226 ++p;
3227 go_assert(p == fields->end());
3229 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3230 vals, bloc);
3231 return Expression::make_unary(OPERATOR_AND, r, bloc);
3234 // Sort methods by name.
3236 class Sort_methods
3238 public:
3239 bool
3240 operator()(const std::pair<std::string, const Method*>& m1,
3241 const std::pair<std::string, const Method*>& m2) const
3243 return (Gogo::unpack_hidden_name(m1.first)
3244 < Gogo::unpack_hidden_name(m2.first));
3248 // Return a composite literal for the type method table for this type.
3249 // METHODS_TYPE is the type of the table, and is a slice type.
3250 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3251 // then only value methods are used.
3253 Expression*
3254 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3255 const Methods* methods,
3256 bool only_value_methods) const
3258 Location bloc = Linemap::predeclared_location();
3260 std::vector<std::pair<std::string, const Method*> > smethods;
3261 if (methods != NULL)
3263 smethods.reserve(methods->count());
3264 for (Methods::const_iterator p = methods->begin();
3265 p != methods->end();
3266 ++p)
3268 if (p->second->is_ambiguous())
3269 continue;
3270 if (only_value_methods && !p->second->is_value_method())
3271 continue;
3273 // This is where we implement the magic //go:nointerface
3274 // comment. If we saw that comment, we don't add this
3275 // method to the type descriptor.
3276 if (p->second->nointerface())
3277 continue;
3279 smethods.push_back(std::make_pair(p->first, p->second));
3283 if (smethods.empty())
3284 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3286 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3288 Type* method_type = methods_type->array_type()->element_type();
3290 Expression_list* vals = new Expression_list();
3291 vals->reserve(smethods.size());
3292 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3293 = smethods.begin();
3294 p != smethods.end();
3295 ++p)
3296 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3297 p->second, only_value_methods));
3299 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3302 // Return a composite literal for a single method. METHOD_TYPE is the
3303 // type of the entry. METHOD_NAME is the name of the method and M is
3304 // the method information.
3306 Expression*
3307 Type::method_constructor(Gogo*, Type* method_type,
3308 const std::string& method_name,
3309 const Method* m,
3310 bool only_value_methods) const
3312 Location bloc = Linemap::predeclared_location();
3314 const Struct_field_list* fields = method_type->struct_type()->fields();
3316 Expression_list* vals = new Expression_list();
3317 vals->reserve(5);
3319 Struct_field_list::const_iterator p = fields->begin();
3320 go_assert(p->is_field_name("name"));
3321 const std::string n = Gogo::unpack_hidden_name(method_name);
3322 Expression* s = Expression::make_string(n, bloc);
3323 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3325 ++p;
3326 go_assert(p->is_field_name("pkgPath"));
3327 if (!Gogo::is_hidden_name(method_name))
3328 vals->push_back(Expression::make_nil(bloc));
3329 else
3331 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3332 bloc);
3333 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3336 Named_object* no = (m->needs_stub_method()
3337 ? m->stub_object()
3338 : m->named_object());
3340 Function_type* mtype;
3341 if (no->is_function())
3342 mtype = no->func_value()->type();
3343 else
3344 mtype = no->func_declaration_value()->type();
3345 go_assert(mtype->is_method());
3346 Type* nonmethod_type = mtype->copy_without_receiver();
3348 ++p;
3349 go_assert(p->is_field_name("mtyp"));
3350 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3352 ++p;
3353 go_assert(p->is_field_name("typ"));
3354 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3355 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3356 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3358 ++p;
3359 go_assert(p->is_field_name("tfn"));
3360 vals->push_back(Expression::make_func_code_reference(no, bloc));
3362 ++p;
3363 go_assert(p == fields->end());
3365 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3368 // Return a composite literal for the type descriptor of a plain type.
3369 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3370 // NULL, it is the name to use as well as the list of methods.
3372 Expression*
3373 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3374 Named_type* name)
3376 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3377 name, NULL, true);
3380 // Return the type reflection string for this type.
3382 std::string
3383 Type::reflection(Gogo* gogo) const
3385 std::string ret;
3387 // The do_reflection virtual function should set RET to the
3388 // reflection string.
3389 this->do_reflection(gogo, &ret);
3391 return ret;
3394 // Return whether the backend size of the type is known.
3396 bool
3397 Type::is_backend_type_size_known(Gogo* gogo)
3399 switch (this->classification_)
3401 case TYPE_ERROR:
3402 case TYPE_VOID:
3403 case TYPE_BOOLEAN:
3404 case TYPE_INTEGER:
3405 case TYPE_FLOAT:
3406 case TYPE_COMPLEX:
3407 case TYPE_STRING:
3408 case TYPE_FUNCTION:
3409 case TYPE_POINTER:
3410 case TYPE_NIL:
3411 case TYPE_MAP:
3412 case TYPE_CHANNEL:
3413 case TYPE_INTERFACE:
3414 return true;
3416 case TYPE_STRUCT:
3418 const Struct_field_list* fields = this->struct_type()->fields();
3419 for (Struct_field_list::const_iterator pf = fields->begin();
3420 pf != fields->end();
3421 ++pf)
3422 if (!pf->type()->is_backend_type_size_known(gogo))
3423 return false;
3424 return true;
3427 case TYPE_ARRAY:
3429 const Array_type* at = this->array_type();
3430 if (at->length() == NULL)
3431 return true;
3432 else
3434 Numeric_constant nc;
3435 if (!at->length()->numeric_constant_value(&nc))
3436 return false;
3437 mpz_t ival;
3438 if (!nc.to_int(&ival))
3439 return false;
3440 mpz_clear(ival);
3441 return at->element_type()->is_backend_type_size_known(gogo);
3445 case TYPE_NAMED:
3446 this->named_type()->convert(gogo);
3447 return this->named_type()->is_named_backend_type_size_known();
3449 case TYPE_FORWARD:
3451 Forward_declaration_type* fdt = this->forward_declaration_type();
3452 return fdt->real_type()->is_backend_type_size_known(gogo);
3455 case TYPE_SINK:
3456 case TYPE_CALL_MULTIPLE_RESULT:
3457 go_unreachable();
3459 default:
3460 go_unreachable();
3464 // If the size of the type can be determined, set *PSIZE to the size
3465 // in bytes and return true. Otherwise, return false. This queries
3466 // the backend.
3468 bool
3469 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3471 if (!this->is_backend_type_size_known(gogo))
3472 return false;
3473 if (this->is_error_type())
3474 return false;
3475 Btype* bt = this->get_backend_placeholder(gogo);
3476 *psize = gogo->backend()->type_size(bt);
3477 if (*psize == -1)
3479 if (this->named_type() != NULL)
3480 go_error_at(this->named_type()->location(),
3481 "type %s larger than address space",
3482 Gogo::message_name(this->named_type()->name()).c_str());
3483 else
3484 go_error_at(Linemap::unknown_location(),
3485 "type %s larger than address space",
3486 this->reflection(gogo).c_str());
3488 // Make this an error type to avoid knock-on errors.
3489 this->classification_ = TYPE_ERROR;
3490 return false;
3492 return true;
3495 // If the alignment of the type can be determined, set *PALIGN to
3496 // the alignment in bytes and return true. Otherwise, return false.
3498 bool
3499 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3501 if (!this->is_backend_type_size_known(gogo))
3502 return false;
3503 Btype* bt = this->get_backend_placeholder(gogo);
3504 *palign = gogo->backend()->type_alignment(bt);
3505 return true;
3508 // Like backend_type_align, but return the alignment when used as a
3509 // field.
3511 bool
3512 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3514 if (!this->is_backend_type_size_known(gogo))
3515 return false;
3516 Btype* bt = this->get_backend_placeholder(gogo);
3517 *palign = gogo->backend()->type_field_alignment(bt);
3518 return true;
3521 // Get the ptrdata value for a type. This is the size of the prefix
3522 // of the type that contains all pointers. Store the ptrdata in
3523 // *PPTRDATA and return whether we found it.
3525 bool
3526 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3528 *pptrdata = 0;
3530 if (!this->has_pointer())
3531 return true;
3533 if (!this->is_backend_type_size_known(gogo))
3534 return false;
3536 switch (this->classification_)
3538 case TYPE_ERROR:
3539 return true;
3541 case TYPE_FUNCTION:
3542 case TYPE_POINTER:
3543 case TYPE_MAP:
3544 case TYPE_CHANNEL:
3545 // These types are nothing but a pointer.
3546 return this->backend_type_size(gogo, pptrdata);
3548 case TYPE_INTERFACE:
3549 // An interface is a struct of two pointers.
3550 return this->backend_type_size(gogo, pptrdata);
3552 case TYPE_STRING:
3554 // A string is a struct whose first field is a pointer, and
3555 // whose second field is not.
3556 Type* uint8_type = Type::lookup_integer_type("uint8");
3557 Type* ptr = Type::make_pointer_type(uint8_type);
3558 return ptr->backend_type_size(gogo, pptrdata);
3561 case TYPE_NAMED:
3562 case TYPE_FORWARD:
3563 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3565 case TYPE_STRUCT:
3567 const Struct_field_list* fields = this->struct_type()->fields();
3568 int64_t offset = 0;
3569 const Struct_field *ptr = NULL;
3570 int64_t ptr_offset = 0;
3571 for (Struct_field_list::const_iterator pf = fields->begin();
3572 pf != fields->end();
3573 ++pf)
3575 int64_t field_align;
3576 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3577 return false;
3578 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3580 if (pf->type()->has_pointer())
3582 ptr = &*pf;
3583 ptr_offset = offset;
3586 int64_t field_size;
3587 if (!pf->type()->backend_type_size(gogo, &field_size))
3588 return false;
3589 offset += field_size;
3592 if (ptr != NULL)
3594 int64_t ptr_ptrdata;
3595 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3596 return false;
3597 *pptrdata = ptr_offset + ptr_ptrdata;
3599 return true;
3602 case TYPE_ARRAY:
3603 if (this->is_slice_type())
3605 // A slice is a struct whose first field is a pointer, and
3606 // whose remaining fields are not.
3607 Type* element_type = this->array_type()->element_type();
3608 Type* ptr = Type::make_pointer_type(element_type);
3609 return ptr->backend_type_size(gogo, pptrdata);
3611 else
3613 Numeric_constant nc;
3614 if (!this->array_type()->length()->numeric_constant_value(&nc))
3615 return false;
3616 int64_t len;
3617 if (!nc.to_memory_size(&len))
3618 return false;
3620 Type* element_type = this->array_type()->element_type();
3621 int64_t ele_size;
3622 int64_t ele_ptrdata;
3623 if (!element_type->backend_type_size(gogo, &ele_size)
3624 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3625 return false;
3626 go_assert(ele_size > 0 && ele_ptrdata > 0);
3628 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3629 return true;
3632 default:
3633 case TYPE_VOID:
3634 case TYPE_BOOLEAN:
3635 case TYPE_INTEGER:
3636 case TYPE_FLOAT:
3637 case TYPE_COMPLEX:
3638 case TYPE_SINK:
3639 case TYPE_NIL:
3640 case TYPE_CALL_MULTIPLE_RESULT:
3641 go_unreachable();
3645 // Get the ptrdata value to store in a type descriptor. This is
3646 // normally the same as backend_type_ptrdata, but for a type that is
3647 // large enough to use a gcprog we may need to store a different value
3648 // if it ends with an array. If the gcprog uses a repeat descriptor
3649 // for the array, and if the array element ends with non-pointer data,
3650 // then the gcprog will produce a value that describes the complete
3651 // array where the backend ptrdata will omit the non-pointer elements
3652 // of the final array element. This is a subtle difference but the
3653 // run time code checks it to verify that it has expanded a gcprog as
3654 // expected.
3656 bool
3657 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3659 int64_t backend_ptrdata;
3660 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3661 return false;
3663 int64_t ptrsize;
3664 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3666 *pptrdata = backend_ptrdata;
3667 return true;
3670 GCProg prog;
3671 prog.set_from(gogo, this, ptrsize, 0);
3672 int64_t offset = prog.bit_index() * ptrsize;
3674 go_assert(offset >= backend_ptrdata);
3675 *pptrdata = offset;
3676 return true;
3679 // Default function to export a type.
3681 void
3682 Type::do_export(Export*) const
3684 go_unreachable();
3687 // Import a type.
3689 Type*
3690 Type::import_type(Import* imp)
3692 if (imp->match_c_string("("))
3693 return Function_type::do_import(imp);
3694 else if (imp->match_c_string("*"))
3695 return Pointer_type::do_import(imp);
3696 else if (imp->match_c_string("struct "))
3697 return Struct_type::do_import(imp);
3698 else if (imp->match_c_string("["))
3699 return Array_type::do_import(imp);
3700 else if (imp->match_c_string("map "))
3701 return Map_type::do_import(imp);
3702 else if (imp->match_c_string("chan "))
3703 return Channel_type::do_import(imp);
3704 else if (imp->match_c_string("interface"))
3705 return Interface_type::do_import(imp);
3706 else
3708 go_error_at(imp->location(), "import error: expected type");
3709 return Type::make_error_type();
3713 // Class Error_type.
3715 // Return the backend representation of an Error type.
3717 Btype*
3718 Error_type::do_get_backend(Gogo* gogo)
3720 return gogo->backend()->error_type();
3723 // Return an expression for the type descriptor for an error type.
3726 Expression*
3727 Error_type::do_type_descriptor(Gogo*, Named_type*)
3729 return Expression::make_error(Linemap::predeclared_location());
3732 // We should not be asked for the reflection string for an error type.
3734 void
3735 Error_type::do_reflection(Gogo*, std::string*) const
3737 go_assert(saw_errors());
3740 Type*
3741 Type::make_error_type()
3743 static Error_type singleton_error_type;
3744 return &singleton_error_type;
3747 // Class Void_type.
3749 // Get the backend representation of a void type.
3751 Btype*
3752 Void_type::do_get_backend(Gogo* gogo)
3754 return gogo->backend()->void_type();
3757 Type*
3758 Type::make_void_type()
3760 static Void_type singleton_void_type;
3761 return &singleton_void_type;
3764 // Class Boolean_type.
3766 // Return the backend representation of the boolean type.
3768 Btype*
3769 Boolean_type::do_get_backend(Gogo* gogo)
3771 return gogo->backend()->bool_type();
3774 // Make the type descriptor.
3776 Expression*
3777 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3779 if (name != NULL)
3780 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3781 else
3783 Named_object* no = gogo->lookup_global("bool");
3784 go_assert(no != NULL);
3785 return Type::type_descriptor(gogo, no->type_value());
3789 Type*
3790 Type::make_boolean_type()
3792 static Boolean_type boolean_type;
3793 return &boolean_type;
3796 // The named type "bool".
3798 static Named_type* named_bool_type;
3800 // Get the named type "bool".
3802 Named_type*
3803 Type::lookup_bool_type()
3805 return named_bool_type;
3808 // Make the named type "bool".
3810 Named_type*
3811 Type::make_named_bool_type()
3813 Type* bool_type = Type::make_boolean_type();
3814 Named_object* named_object =
3815 Named_object::make_type("bool", NULL, bool_type,
3816 Linemap::predeclared_location());
3817 Named_type* named_type = named_object->type_value();
3818 named_bool_type = named_type;
3819 return named_type;
3822 // Class Integer_type.
3824 Integer_type::Named_integer_types Integer_type::named_integer_types;
3826 // Create a new integer type. Non-abstract integer types always have
3827 // names.
3829 Named_type*
3830 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3831 int bits, int runtime_type_kind)
3833 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3834 runtime_type_kind);
3835 std::string sname(name);
3836 Named_object* named_object =
3837 Named_object::make_type(sname, NULL, integer_type,
3838 Linemap::predeclared_location());
3839 Named_type* named_type = named_object->type_value();
3840 std::pair<Named_integer_types::iterator, bool> ins =
3841 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3842 go_assert(ins.second);
3843 return named_type;
3846 // Look up an existing integer type.
3848 Named_type*
3849 Integer_type::lookup_integer_type(const char* name)
3851 Named_integer_types::const_iterator p =
3852 Integer_type::named_integer_types.find(name);
3853 go_assert(p != Integer_type::named_integer_types.end());
3854 return p->second;
3857 // Create a new abstract integer type.
3859 Integer_type*
3860 Integer_type::create_abstract_integer_type()
3862 static Integer_type* abstract_type;
3863 if (abstract_type == NULL)
3865 Type* int_type = Type::lookup_integer_type("int");
3866 abstract_type = new Integer_type(true, false,
3867 int_type->integer_type()->bits(),
3868 RUNTIME_TYPE_KIND_INT);
3870 return abstract_type;
3873 // Create a new abstract character type.
3875 Integer_type*
3876 Integer_type::create_abstract_character_type()
3878 static Integer_type* abstract_type;
3879 if (abstract_type == NULL)
3881 abstract_type = new Integer_type(true, false, 32,
3882 RUNTIME_TYPE_KIND_INT32);
3883 abstract_type->set_is_rune();
3885 return abstract_type;
3888 // Integer type compatibility.
3890 bool
3891 Integer_type::is_identical(const Integer_type* t) const
3893 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3894 return false;
3895 return this->is_abstract_ == t->is_abstract_;
3898 // Hash code.
3900 unsigned int
3901 Integer_type::do_hash_for_method(Gogo*) const
3903 return ((this->bits_ << 4)
3904 + ((this->is_unsigned_ ? 1 : 0) << 8)
3905 + ((this->is_abstract_ ? 1 : 0) << 9));
3908 // Convert an Integer_type to the backend representation.
3910 Btype*
3911 Integer_type::do_get_backend(Gogo* gogo)
3913 if (this->is_abstract_)
3915 go_assert(saw_errors());
3916 return gogo->backend()->error_type();
3918 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
3921 // The type descriptor for an integer type. Integer types are always
3922 // named.
3924 Expression*
3925 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3927 go_assert(name != NULL || saw_errors());
3928 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3931 // We should not be asked for the reflection string of a basic type.
3933 void
3934 Integer_type::do_reflection(Gogo*, std::string*) const
3936 go_assert(saw_errors());
3939 // Make an integer type.
3941 Named_type*
3942 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
3943 int runtime_type_kind)
3945 return Integer_type::create_integer_type(name, is_unsigned, bits,
3946 runtime_type_kind);
3949 // Make an abstract integer type.
3951 Integer_type*
3952 Type::make_abstract_integer_type()
3954 return Integer_type::create_abstract_integer_type();
3957 // Make an abstract character type.
3959 Integer_type*
3960 Type::make_abstract_character_type()
3962 return Integer_type::create_abstract_character_type();
3965 // Look up an integer type.
3967 Named_type*
3968 Type::lookup_integer_type(const char* name)
3970 return Integer_type::lookup_integer_type(name);
3973 // Class Float_type.
3975 Float_type::Named_float_types Float_type::named_float_types;
3977 // Create a new float type. Non-abstract float types always have
3978 // names.
3980 Named_type*
3981 Float_type::create_float_type(const char* name, int bits,
3982 int runtime_type_kind)
3984 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
3985 std::string sname(name);
3986 Named_object* named_object =
3987 Named_object::make_type(sname, NULL, float_type,
3988 Linemap::predeclared_location());
3989 Named_type* named_type = named_object->type_value();
3990 std::pair<Named_float_types::iterator, bool> ins =
3991 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
3992 go_assert(ins.second);
3993 return named_type;
3996 // Look up an existing float type.
3998 Named_type*
3999 Float_type::lookup_float_type(const char* name)
4001 Named_float_types::const_iterator p =
4002 Float_type::named_float_types.find(name);
4003 go_assert(p != Float_type::named_float_types.end());
4004 return p->second;
4007 // Create a new abstract float type.
4009 Float_type*
4010 Float_type::create_abstract_float_type()
4012 static Float_type* abstract_type;
4013 if (abstract_type == NULL)
4014 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4015 return abstract_type;
4018 // Whether this type is identical with T.
4020 bool
4021 Float_type::is_identical(const Float_type* t) const
4023 if (this->bits_ != t->bits_)
4024 return false;
4025 return this->is_abstract_ == t->is_abstract_;
4028 // Hash code.
4030 unsigned int
4031 Float_type::do_hash_for_method(Gogo*) const
4033 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4036 // Convert to the backend representation.
4038 Btype*
4039 Float_type::do_get_backend(Gogo* gogo)
4041 return gogo->backend()->float_type(this->bits_);
4044 // The type descriptor for a float type. Float types are always named.
4046 Expression*
4047 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4049 go_assert(name != NULL || saw_errors());
4050 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4053 // We should not be asked for the reflection string of a basic type.
4055 void
4056 Float_type::do_reflection(Gogo*, std::string*) const
4058 go_assert(saw_errors());
4061 // Make a floating point type.
4063 Named_type*
4064 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4066 return Float_type::create_float_type(name, bits, runtime_type_kind);
4069 // Make an abstract float type.
4071 Float_type*
4072 Type::make_abstract_float_type()
4074 return Float_type::create_abstract_float_type();
4077 // Look up a float type.
4079 Named_type*
4080 Type::lookup_float_type(const char* name)
4082 return Float_type::lookup_float_type(name);
4085 // Class Complex_type.
4087 Complex_type::Named_complex_types Complex_type::named_complex_types;
4089 // Create a new complex type. Non-abstract complex types always have
4090 // names.
4092 Named_type*
4093 Complex_type::create_complex_type(const char* name, int bits,
4094 int runtime_type_kind)
4096 Complex_type* complex_type = new Complex_type(false, bits,
4097 runtime_type_kind);
4098 std::string sname(name);
4099 Named_object* named_object =
4100 Named_object::make_type(sname, NULL, complex_type,
4101 Linemap::predeclared_location());
4102 Named_type* named_type = named_object->type_value();
4103 std::pair<Named_complex_types::iterator, bool> ins =
4104 Complex_type::named_complex_types.insert(std::make_pair(sname,
4105 named_type));
4106 go_assert(ins.second);
4107 return named_type;
4110 // Look up an existing complex type.
4112 Named_type*
4113 Complex_type::lookup_complex_type(const char* name)
4115 Named_complex_types::const_iterator p =
4116 Complex_type::named_complex_types.find(name);
4117 go_assert(p != Complex_type::named_complex_types.end());
4118 return p->second;
4121 // Create a new abstract complex type.
4123 Complex_type*
4124 Complex_type::create_abstract_complex_type()
4126 static Complex_type* abstract_type;
4127 if (abstract_type == NULL)
4128 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4129 return abstract_type;
4132 // Whether this type is identical with T.
4134 bool
4135 Complex_type::is_identical(const Complex_type *t) const
4137 if (this->bits_ != t->bits_)
4138 return false;
4139 return this->is_abstract_ == t->is_abstract_;
4142 // Hash code.
4144 unsigned int
4145 Complex_type::do_hash_for_method(Gogo*) const
4147 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4150 // Convert to the backend representation.
4152 Btype*
4153 Complex_type::do_get_backend(Gogo* gogo)
4155 return gogo->backend()->complex_type(this->bits_);
4158 // The type descriptor for a complex type. Complex types are always
4159 // named.
4161 Expression*
4162 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4164 go_assert(name != NULL || saw_errors());
4165 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4168 // We should not be asked for the reflection string of a basic type.
4170 void
4171 Complex_type::do_reflection(Gogo*, std::string*) const
4173 go_assert(saw_errors());
4176 // Make a complex type.
4178 Named_type*
4179 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4181 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4184 // Make an abstract complex type.
4186 Complex_type*
4187 Type::make_abstract_complex_type()
4189 return Complex_type::create_abstract_complex_type();
4192 // Look up a complex type.
4194 Named_type*
4195 Type::lookup_complex_type(const char* name)
4197 return Complex_type::lookup_complex_type(name);
4200 // Class String_type.
4202 // Convert String_type to the backend representation. A string is a
4203 // struct with two fields: a pointer to the characters and a length.
4205 Btype*
4206 String_type::do_get_backend(Gogo* gogo)
4208 static Btype* backend_string_type;
4209 if (backend_string_type == NULL)
4211 std::vector<Backend::Btyped_identifier> fields(2);
4213 Type* b = gogo->lookup_global("byte")->type_value();
4214 Type* pb = Type::make_pointer_type(b);
4216 // We aren't going to get back to this field to finish the
4217 // backend representation, so force it to be finished now.
4218 if (!gogo->named_types_are_converted())
4220 Btype* bt = pb->get_backend_placeholder(gogo);
4221 pb->finish_backend(gogo, bt);
4224 fields[0].name = "__data";
4225 fields[0].btype = pb->get_backend(gogo);
4226 fields[0].location = Linemap::predeclared_location();
4228 Type* int_type = Type::lookup_integer_type("int");
4229 fields[1].name = "__length";
4230 fields[1].btype = int_type->get_backend(gogo);
4231 fields[1].location = fields[0].location;
4233 backend_string_type = gogo->backend()->struct_type(fields);
4235 return backend_string_type;
4238 // The type descriptor for the string type.
4240 Expression*
4241 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4243 if (name != NULL)
4244 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4245 else
4247 Named_object* no = gogo->lookup_global("string");
4248 go_assert(no != NULL);
4249 return Type::type_descriptor(gogo, no->type_value());
4253 // We should not be asked for the reflection string of a basic type.
4255 void
4256 String_type::do_reflection(Gogo*, std::string* ret) const
4258 ret->append("string");
4261 // Make a string type.
4263 Type*
4264 Type::make_string_type()
4266 static String_type string_type;
4267 return &string_type;
4270 // The named type "string".
4272 static Named_type* named_string_type;
4274 // Get the named type "string".
4276 Named_type*
4277 Type::lookup_string_type()
4279 return named_string_type;
4282 // Make the named type string.
4284 Named_type*
4285 Type::make_named_string_type()
4287 Type* string_type = Type::make_string_type();
4288 Named_object* named_object =
4289 Named_object::make_type("string", NULL, string_type,
4290 Linemap::predeclared_location());
4291 Named_type* named_type = named_object->type_value();
4292 named_string_type = named_type;
4293 return named_type;
4296 // The sink type. This is the type of the blank identifier _. Any
4297 // type may be assigned to it.
4299 class Sink_type : public Type
4301 public:
4302 Sink_type()
4303 : Type(TYPE_SINK)
4306 protected:
4307 bool
4308 do_compare_is_identity(Gogo*)
4309 { return false; }
4311 Btype*
4312 do_get_backend(Gogo*)
4313 { go_unreachable(); }
4315 Expression*
4316 do_type_descriptor(Gogo*, Named_type*)
4317 { go_unreachable(); }
4319 void
4320 do_reflection(Gogo*, std::string*) const
4321 { go_unreachable(); }
4323 void
4324 do_mangled_name(Gogo*, std::string*) const
4325 { go_unreachable(); }
4328 // Make the sink type.
4330 Type*
4331 Type::make_sink_type()
4333 static Sink_type sink_type;
4334 return &sink_type;
4337 // Class Function_type.
4339 // Traversal.
4342 Function_type::do_traverse(Traverse* traverse)
4344 if (this->receiver_ != NULL
4345 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4346 return TRAVERSE_EXIT;
4347 if (this->parameters_ != NULL
4348 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4349 return TRAVERSE_EXIT;
4350 if (this->results_ != NULL
4351 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4352 return TRAVERSE_EXIT;
4353 return TRAVERSE_CONTINUE;
4356 // Returns whether T is a valid redeclaration of this type. If this
4357 // returns false, and REASON is not NULL, *REASON may be set to a
4358 // brief explanation of why it returned false.
4360 bool
4361 Function_type::is_valid_redeclaration(const Function_type* t,
4362 std::string* reason) const
4364 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4365 return false;
4367 // A redeclaration of a function is required to use the same names
4368 // for the receiver and parameters.
4369 if (this->receiver() != NULL
4370 && this->receiver()->name() != t->receiver()->name())
4372 if (reason != NULL)
4373 *reason = "receiver name changed";
4374 return false;
4377 const Typed_identifier_list* parms1 = this->parameters();
4378 const Typed_identifier_list* parms2 = t->parameters();
4379 if (parms1 != NULL)
4381 Typed_identifier_list::const_iterator p1 = parms1->begin();
4382 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4383 p2 != parms2->end();
4384 ++p2, ++p1)
4386 if (p1->name() != p2->name())
4388 if (reason != NULL)
4389 *reason = "parameter name changed";
4390 return false;
4393 // This is called at parse time, so we may have unknown
4394 // types.
4395 Type* t1 = p1->type()->forwarded();
4396 Type* t2 = p2->type()->forwarded();
4397 if (t1 != t2
4398 && t1->forward_declaration_type() != NULL
4399 && (t2->forward_declaration_type() == NULL
4400 || (t1->forward_declaration_type()->named_object()
4401 != t2->forward_declaration_type()->named_object())))
4402 return false;
4406 const Typed_identifier_list* results1 = this->results();
4407 const Typed_identifier_list* results2 = t->results();
4408 if (results1 != NULL)
4410 Typed_identifier_list::const_iterator res1 = results1->begin();
4411 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4412 res2 != results2->end();
4413 ++res2, ++res1)
4415 if (res1->name() != res2->name())
4417 if (reason != NULL)
4418 *reason = "result name changed";
4419 return false;
4422 // This is called at parse time, so we may have unknown
4423 // types.
4424 Type* t1 = res1->type()->forwarded();
4425 Type* t2 = res2->type()->forwarded();
4426 if (t1 != t2
4427 && t1->forward_declaration_type() != NULL
4428 && (t2->forward_declaration_type() == NULL
4429 || (t1->forward_declaration_type()->named_object()
4430 != t2->forward_declaration_type()->named_object())))
4431 return false;
4435 return true;
4438 // Check whether T is the same as this type.
4440 bool
4441 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4442 Cmp_tags cmp_tags, bool errors_are_identical,
4443 std::string* reason) const
4445 if (!ignore_receiver)
4447 const Typed_identifier* r1 = this->receiver();
4448 const Typed_identifier* r2 = t->receiver();
4449 if ((r1 != NULL) != (r2 != NULL))
4451 if (reason != NULL)
4452 *reason = _("different receiver types");
4453 return false;
4455 if (r1 != NULL)
4457 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4458 errors_are_identical, reason))
4460 if (reason != NULL && !reason->empty())
4461 *reason = "receiver: " + *reason;
4462 return false;
4467 const Typed_identifier_list* parms1 = this->parameters();
4468 if (parms1 != NULL && parms1->empty())
4469 parms1 = NULL;
4470 const Typed_identifier_list* parms2 = t->parameters();
4471 if (parms2 != NULL && parms2->empty())
4472 parms2 = NULL;
4473 if ((parms1 != NULL) != (parms2 != NULL))
4475 if (reason != NULL)
4476 *reason = _("different number of parameters");
4477 return false;
4479 if (parms1 != NULL)
4481 Typed_identifier_list::const_iterator p1 = parms1->begin();
4482 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4483 p2 != parms2->end();
4484 ++p2, ++p1)
4486 if (p1 == parms1->end())
4488 if (reason != NULL)
4489 *reason = _("different number of parameters");
4490 return false;
4493 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4494 errors_are_identical, NULL))
4496 if (reason != NULL)
4497 *reason = _("different parameter types");
4498 return false;
4501 if (p1 != parms1->end())
4503 if (reason != NULL)
4504 *reason = _("different number of parameters");
4505 return false;
4509 if (this->is_varargs() != t->is_varargs())
4511 if (reason != NULL)
4512 *reason = _("different varargs");
4513 return false;
4516 const Typed_identifier_list* results1 = this->results();
4517 if (results1 != NULL && results1->empty())
4518 results1 = NULL;
4519 const Typed_identifier_list* results2 = t->results();
4520 if (results2 != NULL && results2->empty())
4521 results2 = NULL;
4522 if ((results1 != NULL) != (results2 != NULL))
4524 if (reason != NULL)
4525 *reason = _("different number of results");
4526 return false;
4528 if (results1 != NULL)
4530 Typed_identifier_list::const_iterator res1 = results1->begin();
4531 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4532 res2 != results2->end();
4533 ++res2, ++res1)
4535 if (res1 == results1->end())
4537 if (reason != NULL)
4538 *reason = _("different number of results");
4539 return false;
4542 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4543 cmp_tags, errors_are_identical,
4544 NULL))
4546 if (reason != NULL)
4547 *reason = _("different result types");
4548 return false;
4551 if (res1 != results1->end())
4553 if (reason != NULL)
4554 *reason = _("different number of results");
4555 return false;
4559 return true;
4562 // Hash code.
4564 unsigned int
4565 Function_type::do_hash_for_method(Gogo* gogo) const
4567 unsigned int ret = 0;
4568 // We ignore the receiver type for hash codes, because we need to
4569 // get the same hash code for a method in an interface and a method
4570 // declared for a type. The former will not have a receiver.
4571 if (this->parameters_ != NULL)
4573 int shift = 1;
4574 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4575 p != this->parameters_->end();
4576 ++p, ++shift)
4577 ret += p->type()->hash_for_method(gogo) << shift;
4579 if (this->results_ != NULL)
4581 int shift = 2;
4582 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4583 p != this->results_->end();
4584 ++p, ++shift)
4585 ret += p->type()->hash_for_method(gogo) << shift;
4587 if (this->is_varargs_)
4588 ret += 1;
4589 ret <<= 4;
4590 return ret;
4593 // Hash result parameters.
4595 unsigned int
4596 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4598 unsigned int hash = 0;
4599 for (Typed_identifier_list::const_iterator p = t->begin();
4600 p != t->end();
4601 ++p)
4603 hash <<= 2;
4604 hash = Type::hash_string(p->name(), hash);
4605 hash += p->type()->hash_for_method(NULL);
4607 return hash;
4610 // Compare result parameters so that can map identical result
4611 // parameters to a single struct type.
4613 bool
4614 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4615 const Typed_identifier_list* b) const
4617 if (a->size() != b->size())
4618 return false;
4619 Typed_identifier_list::const_iterator pa = a->begin();
4620 for (Typed_identifier_list::const_iterator pb = b->begin();
4621 pb != b->end();
4622 ++pa, ++pb)
4624 if (pa->name() != pb->name()
4625 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4626 return false;
4628 return true;
4631 // Hash from results to a backend struct type.
4633 Function_type::Results_structs Function_type::results_structs;
4635 // Get the backend representation for a function type.
4637 Btype*
4638 Function_type::get_backend_fntype(Gogo* gogo)
4640 if (this->fnbtype_ == NULL)
4642 Backend::Btyped_identifier breceiver;
4643 if (this->receiver_ != NULL)
4645 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4647 // We always pass the address of the receiver parameter, in
4648 // order to make interface calls work with unknown types.
4649 Type* rtype = this->receiver_->type();
4650 if (rtype->points_to() == NULL)
4651 rtype = Type::make_pointer_type(rtype);
4652 breceiver.btype = rtype->get_backend(gogo);
4653 breceiver.location = this->receiver_->location();
4656 std::vector<Backend::Btyped_identifier> bparameters;
4657 if (this->parameters_ != NULL)
4659 bparameters.resize(this->parameters_->size());
4660 size_t i = 0;
4661 for (Typed_identifier_list::const_iterator p =
4662 this->parameters_->begin(); p != this->parameters_->end();
4663 ++p, ++i)
4665 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4666 bparameters[i].btype = p->type()->get_backend(gogo);
4667 bparameters[i].location = p->location();
4669 go_assert(i == bparameters.size());
4672 std::vector<Backend::Btyped_identifier> bresults;
4673 Btype* bresult_struct = NULL;
4674 if (this->results_ != NULL)
4676 bresults.resize(this->results_->size());
4677 size_t i = 0;
4678 for (Typed_identifier_list::const_iterator p =
4679 this->results_->begin();
4680 p != this->results_->end();
4681 ++p, ++i)
4683 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4684 bresults[i].btype = p->type()->get_backend(gogo);
4685 bresults[i].location = p->location();
4687 go_assert(i == bresults.size());
4689 if (this->results_->size() > 1)
4691 // Use the same results struct for all functions that
4692 // return the same set of results. This is useful to
4693 // unify calls to interface methods with other calls.
4694 std::pair<Typed_identifier_list*, Btype*> val;
4695 val.first = this->results_;
4696 val.second = NULL;
4697 std::pair<Results_structs::iterator, bool> ins =
4698 Function_type::results_structs.insert(val);
4699 if (ins.second)
4701 // Build a new struct type.
4702 Struct_field_list* sfl = new Struct_field_list;
4703 for (Typed_identifier_list::const_iterator p =
4704 this->results_->begin();
4705 p != this->results_->end();
4706 ++p)
4708 Typed_identifier tid = *p;
4709 if (tid.name().empty())
4710 tid = Typed_identifier("UNNAMED", tid.type(),
4711 tid.location());
4712 sfl->push_back(Struct_field(tid));
4714 Struct_type* st = Type::make_struct_type(sfl,
4715 this->location());
4716 st->set_is_struct_incomparable();
4717 ins.first->second = st->get_backend(gogo);
4719 bresult_struct = ins.first->second;
4723 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4724 bresults, bresult_struct,
4725 this->location());
4729 return this->fnbtype_;
4732 // Get the backend representation for a Go function type.
4734 Btype*
4735 Function_type::do_get_backend(Gogo* gogo)
4737 // When we do anything with a function value other than call it, it
4738 // is represented as a pointer to a struct whose first field is the
4739 // actual function. So that is what we return as the type of a Go
4740 // function.
4742 Location loc = this->location();
4743 Btype* struct_type =
4744 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4745 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4747 std::vector<Backend::Btyped_identifier> fields(1);
4748 fields[0].name = "code";
4749 fields[0].btype = this->get_backend_fntype(gogo);
4750 fields[0].location = loc;
4751 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4752 return gogo->backend()->error_type();
4753 return ptr_struct_type;
4756 // The type of a function type descriptor.
4758 Type*
4759 Function_type::make_function_type_descriptor_type()
4761 static Type* ret;
4762 if (ret == NULL)
4764 Type* tdt = Type::make_type_descriptor_type();
4765 Type* ptdt = Type::make_type_descriptor_ptr_type();
4767 Type* bool_type = Type::lookup_bool_type();
4769 Type* slice_type = Type::make_array_type(ptdt, NULL);
4771 Struct_type* s = Type::make_builtin_struct_type(4,
4772 "", tdt,
4773 "dotdotdot", bool_type,
4774 "in", slice_type,
4775 "out", slice_type);
4777 ret = Type::make_builtin_named_type("FuncType", s);
4780 return ret;
4783 // The type descriptor for a function type.
4785 Expression*
4786 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4788 Location bloc = Linemap::predeclared_location();
4790 Type* ftdt = Function_type::make_function_type_descriptor_type();
4792 const Struct_field_list* fields = ftdt->struct_type()->fields();
4794 Expression_list* vals = new Expression_list();
4795 vals->reserve(4);
4797 Struct_field_list::const_iterator p = fields->begin();
4798 go_assert(p->is_field_name("_type"));
4799 vals->push_back(this->type_descriptor_constructor(gogo,
4800 RUNTIME_TYPE_KIND_FUNC,
4801 name, NULL, true));
4803 ++p;
4804 go_assert(p->is_field_name("dotdotdot"));
4805 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4807 ++p;
4808 go_assert(p->is_field_name("in"));
4809 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4810 this->parameters()));
4812 ++p;
4813 go_assert(p->is_field_name("out"));
4814 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4815 this->results()));
4817 ++p;
4818 go_assert(p == fields->end());
4820 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4823 // Return a composite literal for the parameters or results of a type
4824 // descriptor.
4826 Expression*
4827 Function_type::type_descriptor_params(Type* params_type,
4828 const Typed_identifier* receiver,
4829 const Typed_identifier_list* params)
4831 Location bloc = Linemap::predeclared_location();
4833 if (receiver == NULL && params == NULL)
4834 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4836 Expression_list* vals = new Expression_list();
4837 vals->reserve((params == NULL ? 0 : params->size())
4838 + (receiver != NULL ? 1 : 0));
4840 if (receiver != NULL)
4841 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4843 if (params != NULL)
4845 for (Typed_identifier_list::const_iterator p = params->begin();
4846 p != params->end();
4847 ++p)
4848 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4851 return Expression::make_slice_composite_literal(params_type, vals, bloc);
4854 // The reflection string.
4856 void
4857 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4859 // FIXME: Turn this off until we straighten out the type of the
4860 // struct field used in a go statement which calls a method.
4861 // go_assert(this->receiver_ == NULL);
4863 ret->append("func");
4865 if (this->receiver_ != NULL)
4867 ret->push_back('(');
4868 this->append_reflection(this->receiver_->type(), gogo, ret);
4869 ret->push_back(')');
4872 ret->push_back('(');
4873 const Typed_identifier_list* params = this->parameters();
4874 if (params != NULL)
4876 bool is_varargs = this->is_varargs_;
4877 for (Typed_identifier_list::const_iterator p = params->begin();
4878 p != params->end();
4879 ++p)
4881 if (p != params->begin())
4882 ret->append(", ");
4883 if (!is_varargs || p + 1 != params->end())
4884 this->append_reflection(p->type(), gogo, ret);
4885 else
4887 ret->append("...");
4888 this->append_reflection(p->type()->array_type()->element_type(),
4889 gogo, ret);
4893 ret->push_back(')');
4895 const Typed_identifier_list* results = this->results();
4896 if (results != NULL && !results->empty())
4898 if (results->size() == 1)
4899 ret->push_back(' ');
4900 else
4901 ret->append(" (");
4902 for (Typed_identifier_list::const_iterator p = results->begin();
4903 p != results->end();
4904 ++p)
4906 if (p != results->begin())
4907 ret->append(", ");
4908 this->append_reflection(p->type(), gogo, ret);
4910 if (results->size() > 1)
4911 ret->push_back(')');
4915 // Export a function type.
4917 void
4918 Function_type::do_export(Export* exp) const
4920 // We don't write out the receiver. The only function types which
4921 // should have a receiver are the ones associated with explicitly
4922 // defined methods. For those the receiver type is written out by
4923 // Function::export_func.
4925 exp->write_c_string("(");
4926 bool first = true;
4927 if (this->parameters_ != NULL)
4929 bool is_varargs = this->is_varargs_;
4930 for (Typed_identifier_list::const_iterator p =
4931 this->parameters_->begin();
4932 p != this->parameters_->end();
4933 ++p)
4935 if (first)
4936 first = false;
4937 else
4938 exp->write_c_string(", ");
4939 exp->write_name(p->name());
4940 exp->write_c_string(" ");
4941 if (!is_varargs || p + 1 != this->parameters_->end())
4942 exp->write_type(p->type());
4943 else
4945 exp->write_c_string("...");
4946 exp->write_type(p->type()->array_type()->element_type());
4950 exp->write_c_string(")");
4952 const Typed_identifier_list* results = this->results_;
4953 if (results != NULL)
4955 exp->write_c_string(" ");
4956 if (results->size() == 1 && results->begin()->name().empty())
4957 exp->write_type(results->begin()->type());
4958 else
4960 first = true;
4961 exp->write_c_string("(");
4962 for (Typed_identifier_list::const_iterator p = results->begin();
4963 p != results->end();
4964 ++p)
4966 if (first)
4967 first = false;
4968 else
4969 exp->write_c_string(", ");
4970 exp->write_name(p->name());
4971 exp->write_c_string(" ");
4972 exp->write_type(p->type());
4974 exp->write_c_string(")");
4979 // Import a function type.
4981 Function_type*
4982 Function_type::do_import(Import* imp)
4984 imp->require_c_string("(");
4985 Typed_identifier_list* parameters;
4986 bool is_varargs = false;
4987 if (imp->peek_char() == ')')
4988 parameters = NULL;
4989 else
4991 parameters = new Typed_identifier_list();
4992 while (true)
4994 std::string name = imp->read_name();
4995 imp->require_c_string(" ");
4997 if (imp->match_c_string("..."))
4999 imp->advance(3);
5000 is_varargs = true;
5003 Type* ptype = imp->read_type();
5004 if (is_varargs)
5005 ptype = Type::make_array_type(ptype, NULL);
5006 parameters->push_back(Typed_identifier(name, ptype,
5007 imp->location()));
5008 if (imp->peek_char() != ',')
5009 break;
5010 go_assert(!is_varargs);
5011 imp->require_c_string(", ");
5014 imp->require_c_string(")");
5016 Typed_identifier_list* results;
5017 if (imp->peek_char() != ' ')
5018 results = NULL;
5019 else
5021 imp->advance(1);
5022 results = new Typed_identifier_list;
5023 if (imp->peek_char() != '(')
5025 Type* rtype = imp->read_type();
5026 results->push_back(Typed_identifier("", rtype, imp->location()));
5028 else
5030 imp->advance(1);
5031 while (true)
5033 std::string name = imp->read_name();
5034 imp->require_c_string(" ");
5035 Type* rtype = imp->read_type();
5036 results->push_back(Typed_identifier(name, rtype,
5037 imp->location()));
5038 if (imp->peek_char() != ',')
5039 break;
5040 imp->require_c_string(", ");
5042 imp->require_c_string(")");
5046 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5047 imp->location());
5048 if (is_varargs)
5049 ret->set_is_varargs();
5050 return ret;
5053 // Make a copy of a function type without a receiver.
5055 Function_type*
5056 Function_type::copy_without_receiver() const
5058 go_assert(this->is_method());
5059 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5060 this->results_,
5061 this->location_);
5062 if (this->is_varargs())
5063 ret->set_is_varargs();
5064 if (this->is_builtin())
5065 ret->set_is_builtin();
5066 return ret;
5069 // Make a copy of a function type with a receiver.
5071 Function_type*
5072 Function_type::copy_with_receiver(Type* receiver_type) const
5074 go_assert(!this->is_method());
5075 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5076 this->location_);
5077 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5078 this->results_,
5079 this->location_);
5080 if (this->is_varargs_)
5081 ret->set_is_varargs();
5082 return ret;
5085 // Make a copy of a function type with the receiver as the first
5086 // parameter.
5088 Function_type*
5089 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5091 go_assert(this->is_method());
5092 Typed_identifier_list* new_params = new Typed_identifier_list();
5093 Type* rtype = this->receiver_->type();
5094 if (want_pointer_receiver)
5095 rtype = Type::make_pointer_type(rtype);
5096 Typed_identifier receiver(this->receiver_->name(), rtype,
5097 this->receiver_->location());
5098 new_params->push_back(receiver);
5099 const Typed_identifier_list* orig_params = this->parameters_;
5100 if (orig_params != NULL && !orig_params->empty())
5102 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5103 p != orig_params->end();
5104 ++p)
5105 new_params->push_back(*p);
5107 return Type::make_function_type(NULL, new_params, this->results_,
5108 this->location_);
5111 // Make a copy of a function type ignoring any receiver and adding a
5112 // closure parameter.
5114 Function_type*
5115 Function_type::copy_with_names() const
5117 Typed_identifier_list* new_params = new Typed_identifier_list();
5118 const Typed_identifier_list* orig_params = this->parameters_;
5119 if (orig_params != NULL && !orig_params->empty())
5121 static int count;
5122 char buf[50];
5123 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5124 p != orig_params->end();
5125 ++p)
5127 snprintf(buf, sizeof buf, "pt.%u", count);
5128 ++count;
5129 new_params->push_back(Typed_identifier(buf, p->type(),
5130 p->location()));
5134 const Typed_identifier_list* orig_results = this->results_;
5135 Typed_identifier_list* new_results;
5136 if (orig_results == NULL || orig_results->empty())
5137 new_results = NULL;
5138 else
5140 new_results = new Typed_identifier_list();
5141 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5142 p != orig_results->end();
5143 ++p)
5144 new_results->push_back(Typed_identifier("", p->type(),
5145 p->location()));
5148 return Type::make_function_type(NULL, new_params, new_results,
5149 this->location());
5152 // Make a function type.
5154 Function_type*
5155 Type::make_function_type(Typed_identifier* receiver,
5156 Typed_identifier_list* parameters,
5157 Typed_identifier_list* results,
5158 Location location)
5160 return new Function_type(receiver, parameters, results, location);
5163 // Make a backend function type.
5165 Backend_function_type*
5166 Type::make_backend_function_type(Typed_identifier* receiver,
5167 Typed_identifier_list* parameters,
5168 Typed_identifier_list* results,
5169 Location location)
5171 return new Backend_function_type(receiver, parameters, results, location);
5174 // Class Pointer_type.
5176 // Traversal.
5179 Pointer_type::do_traverse(Traverse* traverse)
5181 return Type::traverse(this->to_type_, traverse);
5184 // Hash code.
5186 unsigned int
5187 Pointer_type::do_hash_for_method(Gogo* gogo) const
5189 return this->to_type_->hash_for_method(gogo) << 4;
5192 // Get the backend representation for a pointer type.
5194 Btype*
5195 Pointer_type::do_get_backend(Gogo* gogo)
5197 Btype* to_btype = this->to_type_->get_backend(gogo);
5198 return gogo->backend()->pointer_type(to_btype);
5201 // The type of a pointer type descriptor.
5203 Type*
5204 Pointer_type::make_pointer_type_descriptor_type()
5206 static Type* ret;
5207 if (ret == NULL)
5209 Type* tdt = Type::make_type_descriptor_type();
5210 Type* ptdt = Type::make_type_descriptor_ptr_type();
5212 Struct_type* s = Type::make_builtin_struct_type(2,
5213 "", tdt,
5214 "elem", ptdt);
5216 ret = Type::make_builtin_named_type("PtrType", s);
5219 return ret;
5222 // The type descriptor for a pointer type.
5224 Expression*
5225 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5227 if (this->is_unsafe_pointer_type())
5229 go_assert(name != NULL);
5230 return this->plain_type_descriptor(gogo,
5231 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5232 name);
5234 else
5236 Location bloc = Linemap::predeclared_location();
5238 const Methods* methods;
5239 Type* deref = this->points_to();
5240 if (deref->named_type() != NULL)
5241 methods = deref->named_type()->methods();
5242 else if (deref->struct_type() != NULL)
5243 methods = deref->struct_type()->methods();
5244 else
5245 methods = NULL;
5247 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5249 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5251 Expression_list* vals = new Expression_list();
5252 vals->reserve(2);
5254 Struct_field_list::const_iterator p = fields->begin();
5255 go_assert(p->is_field_name("_type"));
5256 vals->push_back(this->type_descriptor_constructor(gogo,
5257 RUNTIME_TYPE_KIND_PTR,
5258 name, methods, false));
5260 ++p;
5261 go_assert(p->is_field_name("elem"));
5262 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5264 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5268 // Reflection string.
5270 void
5271 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5273 ret->push_back('*');
5274 this->append_reflection(this->to_type_, gogo, ret);
5277 // Export.
5279 void
5280 Pointer_type::do_export(Export* exp) const
5282 exp->write_c_string("*");
5283 if (this->is_unsafe_pointer_type())
5284 exp->write_c_string("any");
5285 else
5286 exp->write_type(this->to_type_);
5289 // Import.
5291 Pointer_type*
5292 Pointer_type::do_import(Import* imp)
5294 imp->require_c_string("*");
5295 if (imp->match_c_string("any"))
5297 imp->advance(3);
5298 return Type::make_pointer_type(Type::make_void_type());
5300 Type* to = imp->read_type();
5301 return Type::make_pointer_type(to);
5304 // Cache of pointer types. Key is "to" type, value is pointer type
5305 // that points to key.
5307 Type::Pointer_type_table Type::pointer_types;
5309 // A list of placeholder pointer types. We keep this so we can ensure
5310 // they are finalized.
5312 std::vector<Pointer_type*> Type::placeholder_pointers;
5314 // Make a pointer type.
5316 Pointer_type*
5317 Type::make_pointer_type(Type* to_type)
5319 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5320 if (p != pointer_types.end())
5321 return p->second;
5322 Pointer_type* ret = new Pointer_type(to_type);
5323 pointer_types[to_type] = ret;
5324 return ret;
5327 // This helper is invoked immediately after named types have been
5328 // converted, to clean up any unresolved pointer types remaining in
5329 // the pointer type cache.
5331 // The motivation for this routine: occasionally the compiler creates
5332 // some specific pointer type as part of a lowering operation (ex:
5333 // pointer-to-void), then Type::backend_type_size() is invoked on the
5334 // type (which creates a Btype placeholder for it), that placeholder
5335 // passed somewhere along the line to the back end, but since there is
5336 // no reference to the type in user code, there is never a call to
5337 // Type::finish_backend for the type (hence the Btype remains as an
5338 // unresolved placeholder). Calling this routine will clean up such
5339 // instances.
5341 void
5342 Type::finish_pointer_types(Gogo* gogo)
5344 // We don't use begin() and end() because it is possible to add new
5345 // placeholder pointer types as we finalized existing ones.
5346 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5348 Pointer_type* pt = Type::placeholder_pointers[i];
5349 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5350 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5352 pt->finish_backend(gogo, tbti->second.btype);
5353 tbti->second.is_placeholder = false;
5358 // Class Nil_type.
5360 // Get the backend representation of a nil type. FIXME: Is this ever
5361 // actually called?
5363 Btype*
5364 Nil_type::do_get_backend(Gogo* gogo)
5366 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5369 // Make the nil type.
5371 Type*
5372 Type::make_nil_type()
5374 static Nil_type singleton_nil_type;
5375 return &singleton_nil_type;
5378 // The type of a function call which returns multiple values. This is
5379 // really a struct, but we don't want to confuse a function call which
5380 // returns a struct with a function call which returns multiple
5381 // values.
5383 class Call_multiple_result_type : public Type
5385 public:
5386 Call_multiple_result_type(Call_expression* call)
5387 : Type(TYPE_CALL_MULTIPLE_RESULT),
5388 call_(call)
5391 protected:
5392 bool
5393 do_has_pointer() const
5394 { return false; }
5396 bool
5397 do_compare_is_identity(Gogo*)
5398 { return false; }
5400 Btype*
5401 do_get_backend(Gogo* gogo)
5403 go_assert(saw_errors());
5404 return gogo->backend()->error_type();
5407 Expression*
5408 do_type_descriptor(Gogo*, Named_type*)
5410 go_assert(saw_errors());
5411 return Expression::make_error(Linemap::unknown_location());
5414 void
5415 do_reflection(Gogo*, std::string*) const
5416 { go_assert(saw_errors()); }
5418 void
5419 do_mangled_name(Gogo*, std::string*) const
5420 { go_assert(saw_errors()); }
5422 private:
5423 // The expression being called.
5424 Call_expression* call_;
5427 // Make a call result type.
5429 Type*
5430 Type::make_call_multiple_result_type(Call_expression* call)
5432 return new Call_multiple_result_type(call);
5435 // Class Struct_field.
5437 // Get the name of a field.
5439 const std::string&
5440 Struct_field::field_name() const
5442 const std::string& name(this->typed_identifier_.name());
5443 if (!name.empty())
5444 return name;
5445 else
5447 // This is called during parsing, before anything is lowered, so
5448 // we have to be pretty careful to avoid dereferencing an
5449 // unknown type name.
5450 Type* t = this->typed_identifier_.type();
5451 Type* dt = t;
5452 if (t->classification() == Type::TYPE_POINTER)
5454 // Very ugly.
5455 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5456 dt = ptype->points_to();
5458 if (dt->forward_declaration_type() != NULL)
5459 return dt->forward_declaration_type()->name();
5460 else if (dt->named_type() != NULL)
5462 // Note that this can be an alias name.
5463 return dt->named_type()->name();
5465 else if (t->is_error_type() || dt->is_error_type())
5467 static const std::string error_string = "*error*";
5468 return error_string;
5470 else
5472 // Avoid crashing in the erroneous case where T is named but
5473 // DT is not.
5474 go_assert(t != dt);
5475 if (t->forward_declaration_type() != NULL)
5476 return t->forward_declaration_type()->name();
5477 else if (t->named_type() != NULL)
5478 return t->named_type()->name();
5479 else
5480 go_unreachable();
5485 // Return whether this field is named NAME.
5487 bool
5488 Struct_field::is_field_name(const std::string& name) const
5490 const std::string& me(this->typed_identifier_.name());
5491 if (!me.empty())
5492 return me == name;
5493 else
5495 Type* t = this->typed_identifier_.type();
5496 if (t->points_to() != NULL)
5497 t = t->points_to();
5498 Named_type* nt = t->named_type();
5499 if (nt != NULL && nt->name() == name)
5500 return true;
5502 // This is a horrible hack caused by the fact that we don't pack
5503 // the names of builtin types. FIXME.
5504 if (!this->is_imported_
5505 && nt != NULL
5506 && nt->is_builtin()
5507 && nt->name() == Gogo::unpack_hidden_name(name))
5508 return true;
5510 return false;
5514 // Return whether this field is an unexported field named NAME.
5516 bool
5517 Struct_field::is_unexported_field_name(Gogo* gogo,
5518 const std::string& name) const
5520 const std::string& field_name(this->field_name());
5521 if (Gogo::is_hidden_name(field_name)
5522 && name == Gogo::unpack_hidden_name(field_name)
5523 && gogo->pack_hidden_name(name, false) != field_name)
5524 return true;
5526 // Check for the name of a builtin type. This is like the test in
5527 // is_field_name, only there we return false if this->is_imported_,
5528 // and here we return true.
5529 if (this->is_imported_ && this->is_anonymous())
5531 Type* t = this->typed_identifier_.type();
5532 if (t->points_to() != NULL)
5533 t = t->points_to();
5534 Named_type* nt = t->named_type();
5535 if (nt != NULL
5536 && nt->is_builtin()
5537 && nt->name() == Gogo::unpack_hidden_name(name))
5538 return true;
5541 return false;
5544 // Return whether this field is an embedded built-in type.
5546 bool
5547 Struct_field::is_embedded_builtin(Gogo* gogo) const
5549 const std::string& name(this->field_name());
5550 // We know that a field is an embedded type if it is anonymous.
5551 // We can decide if it is a built-in type by checking to see if it is
5552 // registered globally under the field's name.
5553 // This allows us to distinguish between embedded built-in types and
5554 // embedded types that are aliases to built-in types.
5555 return (this->is_anonymous()
5556 && !Gogo::is_hidden_name(name)
5557 && gogo->lookup_global(name.c_str()) != NULL);
5560 // Class Struct_type.
5562 // A hash table used to find identical unnamed structs so that they
5563 // share method tables.
5565 Struct_type::Identical_structs Struct_type::identical_structs;
5567 // A hash table used to merge method sets for identical unnamed
5568 // structs.
5570 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5572 // Traversal.
5575 Struct_type::do_traverse(Traverse* traverse)
5577 Struct_field_list* fields = this->fields_;
5578 if (fields != NULL)
5580 for (Struct_field_list::iterator p = fields->begin();
5581 p != fields->end();
5582 ++p)
5584 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5585 return TRAVERSE_EXIT;
5588 return TRAVERSE_CONTINUE;
5591 // Verify that the struct type is complete and valid.
5593 bool
5594 Struct_type::do_verify()
5596 Struct_field_list* fields = this->fields_;
5597 if (fields == NULL)
5598 return true;
5599 for (Struct_field_list::iterator p = fields->begin();
5600 p != fields->end();
5601 ++p)
5603 Type* t = p->type();
5604 if (p->is_anonymous())
5606 if ((t->named_type() != NULL && t->points_to() != NULL)
5607 || (t->named_type() == NULL && t->points_to() != NULL
5608 && t->points_to()->points_to() != NULL))
5610 go_error_at(p->location(), "embedded type may not be a pointer");
5611 p->set_type(Type::make_error_type());
5613 else if (t->points_to() != NULL
5614 && t->points_to()->interface_type() != NULL)
5616 go_error_at(p->location(),
5617 "embedded type may not be pointer to interface");
5618 p->set_type(Type::make_error_type());
5622 return true;
5625 // Whether this contains a pointer.
5627 bool
5628 Struct_type::do_has_pointer() const
5630 const Struct_field_list* fields = this->fields();
5631 if (fields == NULL)
5632 return false;
5633 for (Struct_field_list::const_iterator p = fields->begin();
5634 p != fields->end();
5635 ++p)
5637 if (p->type()->has_pointer())
5638 return true;
5640 return false;
5643 // Whether this type is identical to T.
5645 bool
5646 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5647 bool errors_are_identical) const
5649 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5650 return false;
5651 const Struct_field_list* fields1 = this->fields();
5652 const Struct_field_list* fields2 = t->fields();
5653 if (fields1 == NULL || fields2 == NULL)
5654 return fields1 == fields2;
5655 Struct_field_list::const_iterator pf2 = fields2->begin();
5656 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5657 pf1 != fields1->end();
5658 ++pf1, ++pf2)
5660 if (pf2 == fields2->end())
5661 return false;
5662 if (pf1->field_name() != pf2->field_name())
5663 return false;
5664 if (pf1->is_anonymous() != pf2->is_anonymous()
5665 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5666 errors_are_identical, NULL))
5667 return false;
5668 if (cmp_tags == COMPARE_TAGS)
5670 if (!pf1->has_tag())
5672 if (pf2->has_tag())
5673 return false;
5675 else
5677 if (!pf2->has_tag())
5678 return false;
5679 if (pf1->tag() != pf2->tag())
5680 return false;
5684 if (pf2 != fields2->end())
5685 return false;
5686 return true;
5689 // Whether comparisons of this struct type are simple identity
5690 // comparisons.
5692 bool
5693 Struct_type::do_compare_is_identity(Gogo* gogo)
5695 const Struct_field_list* fields = this->fields_;
5696 if (fields == NULL)
5697 return true;
5698 int64_t offset = 0;
5699 for (Struct_field_list::const_iterator pf = fields->begin();
5700 pf != fields->end();
5701 ++pf)
5703 if (Gogo::is_sink_name(pf->field_name()))
5704 return false;
5706 if (!pf->type()->compare_is_identity(gogo))
5707 return false;
5709 int64_t field_align;
5710 if (!pf->type()->backend_type_align(gogo, &field_align))
5711 return false;
5712 if ((offset & (field_align - 1)) != 0)
5714 // This struct has padding. We don't guarantee that that
5715 // padding is zero-initialized for a stack variable, so we
5716 // can't use memcmp to compare struct values.
5717 return false;
5720 int64_t field_size;
5721 if (!pf->type()->backend_type_size(gogo, &field_size))
5722 return false;
5723 offset += field_size;
5726 int64_t struct_size;
5727 if (!this->backend_type_size(gogo, &struct_size))
5728 return false;
5729 if (offset != struct_size)
5731 // Trailing padding may not be zero when on the stack.
5732 return false;
5735 return true;
5738 // Return whether this struct type is reflexive--whether a value of
5739 // this type is always equal to itself.
5741 bool
5742 Struct_type::do_is_reflexive()
5744 const Struct_field_list* fields = this->fields_;
5745 if (fields == NULL)
5746 return true;
5747 for (Struct_field_list::const_iterator pf = fields->begin();
5748 pf != fields->end();
5749 ++pf)
5751 if (!pf->type()->is_reflexive())
5752 return false;
5754 return true;
5757 // Return whether this struct type needs a key update when used as a
5758 // map key.
5760 bool
5761 Struct_type::do_needs_key_update()
5763 const Struct_field_list* fields = this->fields_;
5764 if (fields == NULL)
5765 return false;
5766 for (Struct_field_list::const_iterator pf = fields->begin();
5767 pf != fields->end();
5768 ++pf)
5770 if (pf->type()->needs_key_update())
5771 return true;
5773 return false;
5776 // Return whether this struct type is permitted to be in the heap.
5778 bool
5779 Struct_type::do_in_heap()
5781 const Struct_field_list* fields = this->fields_;
5782 if (fields == NULL)
5783 return true;
5784 for (Struct_field_list::const_iterator pf = fields->begin();
5785 pf != fields->end();
5786 ++pf)
5788 if (!pf->type()->in_heap())
5789 return false;
5791 return true;
5794 // Build identity and hash functions for this struct.
5796 // Hash code.
5798 unsigned int
5799 Struct_type::do_hash_for_method(Gogo* gogo) const
5801 unsigned int ret = 0;
5802 if (this->fields() != NULL)
5804 for (Struct_field_list::const_iterator pf = this->fields()->begin();
5805 pf != this->fields()->end();
5806 ++pf)
5807 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5809 ret <<= 2;
5810 if (this->is_struct_incomparable_)
5811 ret <<= 1;
5812 return ret;
5815 // Find the local field NAME.
5817 const Struct_field*
5818 Struct_type::find_local_field(const std::string& name,
5819 unsigned int *pindex) const
5821 const Struct_field_list* fields = this->fields_;
5822 if (fields == NULL)
5823 return NULL;
5824 unsigned int i = 0;
5825 for (Struct_field_list::const_iterator pf = fields->begin();
5826 pf != fields->end();
5827 ++pf, ++i)
5829 if (pf->is_field_name(name))
5831 if (pindex != NULL)
5832 *pindex = i;
5833 return &*pf;
5836 return NULL;
5839 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5841 Field_reference_expression*
5842 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5843 Location location) const
5845 unsigned int depth;
5846 return this->field_reference_depth(struct_expr, name, location, NULL,
5847 &depth);
5850 // Return an expression for a field, along with the depth at which it
5851 // was found.
5853 Field_reference_expression*
5854 Struct_type::field_reference_depth(Expression* struct_expr,
5855 const std::string& name,
5856 Location location,
5857 Saw_named_type* saw,
5858 unsigned int* depth) const
5860 const Struct_field_list* fields = this->fields_;
5861 if (fields == NULL)
5862 return NULL;
5864 // Look for a field with this name.
5865 unsigned int i = 0;
5866 for (Struct_field_list::const_iterator pf = fields->begin();
5867 pf != fields->end();
5868 ++pf, ++i)
5870 if (pf->is_field_name(name))
5872 *depth = 0;
5873 return Expression::make_field_reference(struct_expr, i, location);
5877 // Look for an anonymous field which contains a field with this
5878 // name.
5879 unsigned int found_depth = 0;
5880 Field_reference_expression* ret = NULL;
5881 i = 0;
5882 for (Struct_field_list::const_iterator pf = fields->begin();
5883 pf != fields->end();
5884 ++pf, ++i)
5886 if (!pf->is_anonymous())
5887 continue;
5889 Struct_type* st = pf->type()->deref()->struct_type();
5890 if (st == NULL)
5891 continue;
5893 Saw_named_type* hold_saw = saw;
5894 Saw_named_type saw_here;
5895 Named_type* nt = pf->type()->named_type();
5896 if (nt == NULL)
5897 nt = pf->type()->deref()->named_type();
5898 if (nt != NULL)
5900 Saw_named_type* q;
5901 for (q = saw; q != NULL; q = q->next)
5903 if (q->nt == nt)
5905 // If this is an error, it will be reported
5906 // elsewhere.
5907 break;
5910 if (q != NULL)
5911 continue;
5912 saw_here.next = saw;
5913 saw_here.nt = nt;
5914 saw = &saw_here;
5917 // Look for a reference using a NULL struct expression. If we
5918 // find one, fill in the struct expression with a reference to
5919 // this field.
5920 unsigned int subdepth;
5921 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5922 location,
5923 saw,
5924 &subdepth);
5926 saw = hold_saw;
5928 if (sub == NULL)
5929 continue;
5931 if (ret == NULL || subdepth < found_depth)
5933 if (ret != NULL)
5934 delete ret;
5935 ret = sub;
5936 found_depth = subdepth;
5937 Expression* here = Expression::make_field_reference(struct_expr, i,
5938 location);
5939 if (pf->type()->points_to() != NULL)
5940 here = Expression::make_dereference(here,
5941 Expression::NIL_CHECK_DEFAULT,
5942 location);
5943 while (sub->expr() != NULL)
5945 sub = sub->expr()->deref()->field_reference_expression();
5946 go_assert(sub != NULL);
5948 sub->set_struct_expression(here);
5949 sub->set_implicit(true);
5951 else if (subdepth > found_depth)
5952 delete sub;
5953 else
5955 // We do not handle ambiguity here--it should be handled by
5956 // Type::bind_field_or_method.
5957 delete sub;
5958 found_depth = 0;
5959 ret = NULL;
5963 if (ret != NULL)
5964 *depth = found_depth + 1;
5966 return ret;
5969 // Return the total number of fields, including embedded fields.
5971 unsigned int
5972 Struct_type::total_field_count() const
5974 if (this->fields_ == NULL)
5975 return 0;
5976 unsigned int ret = 0;
5977 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5978 pf != this->fields_->end();
5979 ++pf)
5981 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
5982 ++ret;
5983 else
5984 ret += pf->type()->struct_type()->total_field_count();
5986 return ret;
5989 // Return whether NAME is an unexported field, for better error reporting.
5991 bool
5992 Struct_type::is_unexported_local_field(Gogo* gogo,
5993 const std::string& name) const
5995 const Struct_field_list* fields = this->fields_;
5996 if (fields != NULL)
5998 for (Struct_field_list::const_iterator pf = fields->begin();
5999 pf != fields->end();
6000 ++pf)
6001 if (pf->is_unexported_field_name(gogo, name))
6002 return true;
6004 return false;
6007 // Finalize the methods of an unnamed struct.
6009 void
6010 Struct_type::finalize_methods(Gogo* gogo)
6012 if (this->all_methods_ != NULL)
6013 return;
6015 // It is possible to have multiple identical structs that have
6016 // methods. We want them to share method tables. Otherwise we will
6017 // emit identical methods more than once, which is bad since they
6018 // will even have the same names.
6019 std::pair<Identical_structs::iterator, bool> ins =
6020 Struct_type::identical_structs.insert(std::make_pair(this, this));
6021 if (!ins.second)
6023 // An identical struct was already entered into the hash table.
6024 // Note that finalize_methods is, fortunately, not recursive.
6025 this->all_methods_ = ins.first->second->all_methods_;
6026 return;
6029 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6032 // Return the method NAME, or NULL if there isn't one or if it is
6033 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6034 // ambiguous.
6036 Method*
6037 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6039 return Type::method_function(this->all_methods_, name, is_ambiguous);
6042 // Return a pointer to the interface method table for this type for
6043 // the interface INTERFACE. IS_POINTER is true if this is for a
6044 // pointer to THIS.
6046 Expression*
6047 Struct_type::interface_method_table(Interface_type* interface,
6048 bool is_pointer)
6050 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6051 val(this, NULL);
6052 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6053 Struct_type::struct_method_tables.insert(val);
6055 Struct_method_table_pair* smtp;
6056 if (!ins.second)
6057 smtp = ins.first->second;
6058 else
6060 smtp = new Struct_method_table_pair();
6061 smtp->first = NULL;
6062 smtp->second = NULL;
6063 ins.first->second = smtp;
6066 return Type::interface_method_table(this, interface, is_pointer,
6067 &smtp->first, &smtp->second);
6070 // Convert struct fields to the backend representation. This is not
6071 // declared in types.h so that types.h doesn't have to #include
6072 // backend.h.
6074 static void
6075 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6076 bool use_placeholder,
6077 std::vector<Backend::Btyped_identifier>* bfields)
6079 bfields->resize(fields->size());
6080 size_t i = 0;
6081 for (Struct_field_list::const_iterator p = fields->begin();
6082 p != fields->end();
6083 ++p, ++i)
6085 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6086 (*bfields)[i].btype = (use_placeholder
6087 ? p->type()->get_backend_placeholder(gogo)
6088 : p->type()->get_backend(gogo));
6089 (*bfields)[i].location = p->location();
6091 go_assert(i == fields->size());
6094 // Get the backend representation for a struct type.
6096 Btype*
6097 Struct_type::do_get_backend(Gogo* gogo)
6099 std::vector<Backend::Btyped_identifier> bfields;
6100 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6101 return gogo->backend()->struct_type(bfields);
6104 // Finish the backend representation of the fields of a struct.
6106 void
6107 Struct_type::finish_backend_fields(Gogo* gogo)
6109 const Struct_field_list* fields = this->fields_;
6110 if (fields != NULL)
6112 for (Struct_field_list::const_iterator p = fields->begin();
6113 p != fields->end();
6114 ++p)
6115 p->type()->get_backend(gogo);
6119 // The type of a struct type descriptor.
6121 Type*
6122 Struct_type::make_struct_type_descriptor_type()
6124 static Type* ret;
6125 if (ret == NULL)
6127 Type* tdt = Type::make_type_descriptor_type();
6128 Type* ptdt = Type::make_type_descriptor_ptr_type();
6130 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6131 Type* string_type = Type::lookup_string_type();
6132 Type* pointer_string_type = Type::make_pointer_type(string_type);
6134 Struct_type* sf =
6135 Type::make_builtin_struct_type(5,
6136 "name", pointer_string_type,
6137 "pkgPath", pointer_string_type,
6138 "typ", ptdt,
6139 "tag", pointer_string_type,
6140 "offsetAnon", uintptr_type);
6141 Type* nsf = Type::make_builtin_named_type("structField", sf);
6143 Type* slice_type = Type::make_array_type(nsf, NULL);
6145 Struct_type* s = Type::make_builtin_struct_type(2,
6146 "", tdt,
6147 "fields", slice_type);
6149 ret = Type::make_builtin_named_type("StructType", s);
6152 return ret;
6155 // Build a type descriptor for a struct type.
6157 Expression*
6158 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6160 Location bloc = Linemap::predeclared_location();
6162 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6164 const Struct_field_list* fields = stdt->struct_type()->fields();
6166 Expression_list* vals = new Expression_list();
6167 vals->reserve(2);
6169 const Methods* methods = this->methods();
6170 // A named struct should not have methods--the methods should attach
6171 // to the named type.
6172 go_assert(methods == NULL || name == NULL);
6174 Struct_field_list::const_iterator ps = fields->begin();
6175 go_assert(ps->is_field_name("_type"));
6176 vals->push_back(this->type_descriptor_constructor(gogo,
6177 RUNTIME_TYPE_KIND_STRUCT,
6178 name, methods, true));
6180 ++ps;
6181 go_assert(ps->is_field_name("fields"));
6183 Expression_list* elements = new Expression_list();
6184 elements->reserve(this->fields_->size());
6185 Type* element_type = ps->type()->array_type()->element_type();
6186 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6187 pf != this->fields_->end();
6188 ++pf)
6190 const Struct_field_list* f = element_type->struct_type()->fields();
6192 Expression_list* fvals = new Expression_list();
6193 fvals->reserve(5);
6195 Struct_field_list::const_iterator q = f->begin();
6196 go_assert(q->is_field_name("name"));
6197 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6198 Expression* s = Expression::make_string(n, bloc);
6199 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6201 ++q;
6202 go_assert(q->is_field_name("pkgPath"));
6203 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6204 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6205 fvals->push_back(Expression::make_nil(bloc));
6206 else
6208 std::string n;
6209 if (is_embedded_builtin)
6210 n = gogo->package_name();
6211 else
6212 n = Gogo::hidden_name_pkgpath(pf->field_name());
6213 Expression* s = Expression::make_string(n, bloc);
6214 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6217 ++q;
6218 go_assert(q->is_field_name("typ"));
6219 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6221 ++q;
6222 go_assert(q->is_field_name("tag"));
6223 if (!pf->has_tag())
6224 fvals->push_back(Expression::make_nil(bloc));
6225 else
6227 Expression* s = Expression::make_string(pf->tag(), bloc);
6228 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6231 ++q;
6232 go_assert(q->is_field_name("offsetAnon"));
6233 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6234 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6235 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6236 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6237 int av = pf->is_anonymous() ? 1 : 0;
6238 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6239 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6240 fvals->push_back(o);
6242 Expression* v = Expression::make_struct_composite_literal(element_type,
6243 fvals, bloc);
6244 elements->push_back(v);
6247 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6248 elements, bloc));
6250 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6253 // Write the hash function for a struct which can not use the identity
6254 // function.
6256 void
6257 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6258 Function_type* hash_fntype,
6259 Function_type* equal_fntype)
6261 Location bloc = Linemap::predeclared_location();
6263 // The pointer to the struct that we are going to hash. This is an
6264 // argument to the hash function we are implementing here.
6265 Named_object* key_arg = gogo->lookup("key", NULL);
6266 go_assert(key_arg != NULL);
6267 Type* key_arg_type = key_arg->var_value()->type();
6269 // The seed argument to the hash function.
6270 Named_object* seed_arg = gogo->lookup("seed", NULL);
6271 go_assert(seed_arg != NULL);
6273 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6275 // Make a temporary to hold the return value, initialized to the seed.
6276 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6277 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6278 bloc);
6279 gogo->add_statement(retval);
6281 // Make a temporary to hold the key as a uintptr.
6282 ref = Expression::make_var_reference(key_arg, bloc);
6283 ref = Expression::make_cast(uintptr_type, ref, bloc);
6284 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6285 bloc);
6286 gogo->add_statement(key);
6288 // Loop over the struct fields.
6289 const Struct_field_list* fields = this->fields_;
6290 for (Struct_field_list::const_iterator pf = fields->begin();
6291 pf != fields->end();
6292 ++pf)
6294 if (Gogo::is_sink_name(pf->field_name()))
6295 continue;
6297 // Get a pointer to the value of this field.
6298 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6299 ref = Expression::make_temporary_reference(key, bloc);
6300 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6301 bloc);
6302 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6304 // Get the hash function to use for the type of this field.
6305 Named_object* hash_fn;
6306 Named_object* equal_fn;
6307 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6308 equal_fntype, &hash_fn, &equal_fn);
6310 // Call the hash function for the field, passing retval as the seed.
6311 ref = Expression::make_temporary_reference(retval, bloc);
6312 Expression_list* args = new Expression_list();
6313 args->push_back(subkey);
6314 args->push_back(ref);
6315 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6316 Expression* call = Expression::make_call(func, args, false, bloc);
6318 // Set retval to the result.
6319 Temporary_reference_expression* tref =
6320 Expression::make_temporary_reference(retval, bloc);
6321 tref->set_is_lvalue();
6322 Statement* s = Statement::make_assignment(tref, call, bloc);
6323 gogo->add_statement(s);
6326 // Return retval to the caller of the hash function.
6327 Expression_list* vals = new Expression_list();
6328 ref = Expression::make_temporary_reference(retval, bloc);
6329 vals->push_back(ref);
6330 Statement* s = Statement::make_return_statement(vals, bloc);
6331 gogo->add_statement(s);
6334 // Write the equality function for a struct which can not use the
6335 // identity function.
6337 void
6338 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6340 Location bloc = Linemap::predeclared_location();
6342 // The pointers to the structs we are going to compare.
6343 Named_object* key1_arg = gogo->lookup("key1", NULL);
6344 Named_object* key2_arg = gogo->lookup("key2", NULL);
6345 go_assert(key1_arg != NULL && key2_arg != NULL);
6347 // Build temporaries with the right types.
6348 Type* pt = Type::make_pointer_type(name != NULL
6349 ? static_cast<Type*>(name)
6350 : static_cast<Type*>(this));
6352 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6353 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6354 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6355 gogo->add_statement(p1);
6357 ref = Expression::make_var_reference(key2_arg, bloc);
6358 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6359 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6360 gogo->add_statement(p2);
6362 const Struct_field_list* fields = this->fields_;
6363 unsigned int field_index = 0;
6364 for (Struct_field_list::const_iterator pf = fields->begin();
6365 pf != fields->end();
6366 ++pf, ++field_index)
6368 if (Gogo::is_sink_name(pf->field_name()))
6369 continue;
6371 // Compare one field in both P1 and P2.
6372 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6373 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6374 bloc);
6375 f1 = Expression::make_field_reference(f1, field_index, bloc);
6377 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6378 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6379 bloc);
6380 f2 = Expression::make_field_reference(f2, field_index, bloc);
6382 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6384 // If the values are not equal, return false.
6385 gogo->start_block(bloc);
6386 Expression_list* vals = new Expression_list();
6387 vals->push_back(Expression::make_boolean(false, bloc));
6388 Statement* s = Statement::make_return_statement(vals, bloc);
6389 gogo->add_statement(s);
6390 Block* then_block = gogo->finish_block(bloc);
6392 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6393 gogo->add_statement(s);
6396 // All the fields are equal, so return true.
6397 Expression_list* vals = new Expression_list();
6398 vals->push_back(Expression::make_boolean(true, bloc));
6399 Statement* s = Statement::make_return_statement(vals, bloc);
6400 gogo->add_statement(s);
6403 // Reflection string.
6405 void
6406 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6408 ret->append("struct {");
6410 for (Struct_field_list::const_iterator p = this->fields_->begin();
6411 p != this->fields_->end();
6412 ++p)
6414 if (p != this->fields_->begin())
6415 ret->push_back(';');
6416 ret->push_back(' ');
6417 if (p->is_anonymous())
6418 ret->push_back('?');
6419 else
6420 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6421 ret->push_back(' ');
6422 if (p->is_anonymous()
6423 && p->type()->named_type() != NULL
6424 && p->type()->named_type()->is_alias())
6425 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6426 else
6427 this->append_reflection(p->type(), gogo, ret);
6429 if (p->has_tag())
6431 const std::string& tag(p->tag());
6432 ret->append(" \"");
6433 for (std::string::const_iterator p = tag.begin();
6434 p != tag.end();
6435 ++p)
6437 if (*p == '\0')
6438 ret->append("\\x00");
6439 else if (*p == '\n')
6440 ret->append("\\n");
6441 else if (*p == '\t')
6442 ret->append("\\t");
6443 else if (*p == '"')
6444 ret->append("\\\"");
6445 else if (*p == '\\')
6446 ret->append("\\\\");
6447 else
6448 ret->push_back(*p);
6450 ret->push_back('"');
6454 if (!this->fields_->empty())
6455 ret->push_back(' ');
6457 ret->push_back('}');
6460 // If the offset of field INDEX in the backend implementation can be
6461 // determined, set *POFFSET to the offset in bytes and return true.
6462 // Otherwise, return false.
6464 bool
6465 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6466 int64_t* poffset)
6468 if (!this->is_backend_type_size_known(gogo))
6469 return false;
6470 Btype* bt = this->get_backend_placeholder(gogo);
6471 *poffset = gogo->backend()->type_field_offset(bt, index);
6472 return true;
6475 // Export.
6477 void
6478 Struct_type::do_export(Export* exp) const
6480 exp->write_c_string("struct { ");
6481 const Struct_field_list* fields = this->fields_;
6482 go_assert(fields != NULL);
6483 for (Struct_field_list::const_iterator p = fields->begin();
6484 p != fields->end();
6485 ++p)
6487 if (p->is_anonymous())
6488 exp->write_string("? ");
6489 else
6491 exp->write_string(p->field_name());
6492 exp->write_c_string(" ");
6494 exp->write_type(p->type());
6496 if (p->has_tag())
6498 exp->write_c_string(" ");
6499 Expression* expr =
6500 Expression::make_string(p->tag(), Linemap::predeclared_location());
6501 expr->export_expression(exp);
6502 delete expr;
6505 exp->write_c_string("; ");
6507 exp->write_c_string("}");
6510 // Import.
6512 Struct_type*
6513 Struct_type::do_import(Import* imp)
6515 imp->require_c_string("struct { ");
6516 Struct_field_list* fields = new Struct_field_list;
6517 if (imp->peek_char() != '}')
6519 while (true)
6521 std::string name;
6522 if (imp->match_c_string("? "))
6523 imp->advance(2);
6524 else
6526 name = imp->read_identifier();
6527 imp->require_c_string(" ");
6529 Type* ftype = imp->read_type();
6531 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6532 sf.set_is_imported();
6534 if (imp->peek_char() == ' ')
6536 imp->advance(1);
6537 Expression* expr = Expression::import_expression(imp);
6538 String_expression* sexpr = expr->string_expression();
6539 go_assert(sexpr != NULL);
6540 sf.set_tag(sexpr->val());
6541 delete sexpr;
6544 imp->require_c_string("; ");
6545 fields->push_back(sf);
6546 if (imp->peek_char() == '}')
6547 break;
6550 imp->require_c_string("}");
6552 return Type::make_struct_type(fields, imp->location());
6555 // Whether we can write this struct type to a C header file.
6556 // We can't if any of the fields are structs defined in a different package.
6558 bool
6559 Struct_type::can_write_to_c_header(
6560 std::vector<const Named_object*>* requires,
6561 std::vector<const Named_object*>* declare) const
6563 const Struct_field_list* fields = this->fields_;
6564 if (fields == NULL || fields->empty())
6565 return false;
6566 int sinks = 0;
6567 for (Struct_field_list::const_iterator p = fields->begin();
6568 p != fields->end();
6569 ++p)
6571 if (p->is_anonymous())
6572 return false;
6573 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6574 return false;
6575 if (Gogo::message_name(p->field_name()) == "_")
6576 sinks++;
6578 if (sinks > 1)
6579 return false;
6580 return true;
6583 // Whether we can write the type T to a C header file.
6585 bool
6586 Struct_type::can_write_type_to_c_header(
6587 const Type* t,
6588 std::vector<const Named_object*>* requires,
6589 std::vector<const Named_object*>* declare) const
6591 t = t->forwarded();
6592 switch (t->classification())
6594 case TYPE_ERROR:
6595 case TYPE_FORWARD:
6596 return false;
6598 case TYPE_VOID:
6599 case TYPE_BOOLEAN:
6600 case TYPE_INTEGER:
6601 case TYPE_FLOAT:
6602 case TYPE_COMPLEX:
6603 case TYPE_STRING:
6604 case TYPE_FUNCTION:
6605 case TYPE_MAP:
6606 case TYPE_CHANNEL:
6607 case TYPE_INTERFACE:
6608 return true;
6610 case TYPE_POINTER:
6611 // Don't try to handle a pointer to an array.
6612 if (t->points_to()->array_type() != NULL
6613 && !t->points_to()->is_slice_type())
6614 return false;
6616 if (t->points_to()->named_type() != NULL
6617 && t->points_to()->struct_type() != NULL)
6618 declare->push_back(t->points_to()->named_type()->named_object());
6619 return true;
6621 case TYPE_STRUCT:
6622 return t->struct_type()->can_write_to_c_header(requires, declare);
6624 case TYPE_ARRAY:
6625 if (t->is_slice_type())
6626 return true;
6627 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6628 requires, declare);
6630 case TYPE_NAMED:
6632 const Named_object* no = t->named_type()->named_object();
6633 if (no->package() != NULL)
6635 if (t->is_unsafe_pointer_type())
6636 return true;
6637 return false;
6639 if (t->struct_type() != NULL)
6641 requires->push_back(no);
6642 return t->struct_type()->can_write_to_c_header(requires, declare);
6644 return this->can_write_type_to_c_header(t->base(), requires, declare);
6647 case TYPE_CALL_MULTIPLE_RESULT:
6648 case TYPE_NIL:
6649 case TYPE_SINK:
6650 default:
6651 go_unreachable();
6655 // Write this struct to a C header file.
6657 void
6658 Struct_type::write_to_c_header(std::ostream& os) const
6660 const Struct_field_list* fields = this->fields_;
6661 for (Struct_field_list::const_iterator p = fields->begin();
6662 p != fields->end();
6663 ++p)
6665 os << '\t';
6666 this->write_field_to_c_header(os, p->field_name(), p->type());
6667 os << ';' << std::endl;
6671 // Write the type of a struct field to a C header file.
6673 void
6674 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6675 const Type *t) const
6677 bool print_name = true;
6678 t = t->forwarded();
6679 switch (t->classification())
6681 case TYPE_VOID:
6682 os << "void";
6683 break;
6685 case TYPE_BOOLEAN:
6686 os << "_Bool";
6687 break;
6689 case TYPE_INTEGER:
6691 const Integer_type* it = t->integer_type();
6692 if (it->is_unsigned())
6693 os << 'u';
6694 os << "int" << it->bits() << "_t";
6696 break;
6698 case TYPE_FLOAT:
6699 switch (t->float_type()->bits())
6701 case 32:
6702 os << "float";
6703 break;
6704 case 64:
6705 os << "double";
6706 break;
6707 default:
6708 go_unreachable();
6710 break;
6712 case TYPE_COMPLEX:
6713 switch (t->complex_type()->bits())
6715 case 64:
6716 os << "float _Complex";
6717 break;
6718 case 128:
6719 os << "double _Complex";
6720 break;
6721 default:
6722 go_unreachable();
6724 break;
6726 case TYPE_STRING:
6727 os << "String";
6728 break;
6730 case TYPE_FUNCTION:
6731 os << "FuncVal*";
6732 break;
6734 case TYPE_POINTER:
6736 std::vector<const Named_object*> requires;
6737 std::vector<const Named_object*> declare;
6738 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6739 &declare))
6740 os << "void*";
6741 else
6743 this->write_field_to_c_header(os, "", t->points_to());
6744 os << '*';
6747 break;
6749 case TYPE_MAP:
6750 os << "Map*";
6751 break;
6753 case TYPE_CHANNEL:
6754 os << "Chan*";
6755 break;
6757 case TYPE_INTERFACE:
6758 if (t->interface_type()->is_empty())
6759 os << "Eface";
6760 else
6761 os << "Iface";
6762 break;
6764 case TYPE_STRUCT:
6765 os << "struct {" << std::endl;
6766 t->struct_type()->write_to_c_header(os);
6767 os << "\t}";
6768 break;
6770 case TYPE_ARRAY:
6771 if (t->is_slice_type())
6772 os << "Slice";
6773 else
6775 const Type *ele = t;
6776 std::vector<const Type*> array_types;
6777 while (ele->array_type() != NULL && !ele->is_slice_type())
6779 array_types.push_back(ele);
6780 ele = ele->array_type()->element_type();
6782 this->write_field_to_c_header(os, "", ele);
6783 os << ' ' << Gogo::message_name(name);
6784 print_name = false;
6785 while (!array_types.empty())
6787 ele = array_types.back();
6788 array_types.pop_back();
6789 os << '[';
6790 Numeric_constant nc;
6791 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6792 go_unreachable();
6793 mpz_t val;
6794 if (!nc.to_int(&val))
6795 go_unreachable();
6796 char* s = mpz_get_str(NULL, 10, val);
6797 os << s;
6798 free(s);
6799 mpz_clear(val);
6800 os << ']';
6803 break;
6805 case TYPE_NAMED:
6807 const Named_object* no = t->named_type()->named_object();
6808 if (t->struct_type() != NULL)
6809 os << "struct " << no->message_name();
6810 else if (t->is_unsafe_pointer_type())
6811 os << "void*";
6812 else if (t == Type::lookup_integer_type("uintptr"))
6813 os << "uintptr_t";
6814 else
6816 this->write_field_to_c_header(os, name, t->base());
6817 print_name = false;
6820 break;
6822 case TYPE_ERROR:
6823 case TYPE_FORWARD:
6824 case TYPE_CALL_MULTIPLE_RESULT:
6825 case TYPE_NIL:
6826 case TYPE_SINK:
6827 default:
6828 go_unreachable();
6831 if (print_name && !name.empty())
6832 os << ' ' << Gogo::message_name(name);
6835 // Make a struct type.
6837 Struct_type*
6838 Type::make_struct_type(Struct_field_list* fields,
6839 Location location)
6841 return new Struct_type(fields, location);
6844 // Class Array_type.
6846 // Store the length of an array as an int64_t into *PLEN. Return
6847 // false if the length can not be determined. This will assert if
6848 // called for a slice.
6850 bool
6851 Array_type::int_length(int64_t* plen)
6853 go_assert(this->length_ != NULL);
6854 Numeric_constant nc;
6855 if (!this->length_->numeric_constant_value(&nc))
6856 return false;
6857 return nc.to_memory_size(plen);
6860 // Whether two array types are identical.
6862 bool
6863 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6864 bool errors_are_identical) const
6866 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6867 cmp_tags, errors_are_identical, NULL))
6868 return false;
6870 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6871 return false;
6873 Expression* l1 = this->length();
6874 Expression* l2 = t->length();
6876 // Slices of the same element type are identical.
6877 if (l1 == NULL && l2 == NULL)
6878 return true;
6880 // Arrays of the same element type are identical if they have the
6881 // same length.
6882 if (l1 != NULL && l2 != NULL)
6884 if (l1 == l2)
6885 return true;
6887 // Try to determine the lengths. If we can't, assume the arrays
6888 // are not identical.
6889 bool ret = false;
6890 Numeric_constant nc1, nc2;
6891 if (l1->numeric_constant_value(&nc1)
6892 && l2->numeric_constant_value(&nc2))
6894 mpz_t v1;
6895 if (nc1.to_int(&v1))
6897 mpz_t v2;
6898 if (nc2.to_int(&v2))
6900 ret = mpz_cmp(v1, v2) == 0;
6901 mpz_clear(v2);
6903 mpz_clear(v1);
6906 return ret;
6909 // Otherwise the arrays are not identical.
6910 return false;
6913 // Traversal.
6916 Array_type::do_traverse(Traverse* traverse)
6918 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6919 return TRAVERSE_EXIT;
6920 if (this->length_ != NULL
6921 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6922 return TRAVERSE_EXIT;
6923 return TRAVERSE_CONTINUE;
6926 // Check that the length is valid.
6928 bool
6929 Array_type::verify_length()
6931 if (this->length_ == NULL)
6932 return true;
6934 Type_context context(Type::lookup_integer_type("int"), false);
6935 this->length_->determine_type(&context);
6937 if (!this->length_->is_constant())
6939 go_error_at(this->length_->location(), "array bound is not constant");
6940 return false;
6943 Numeric_constant nc;
6944 if (!this->length_->numeric_constant_value(&nc))
6946 if (this->length_->type()->integer_type() != NULL
6947 || this->length_->type()->float_type() != NULL)
6948 go_error_at(this->length_->location(), "array bound is not constant");
6949 else
6950 go_error_at(this->length_->location(), "array bound is not numeric");
6951 return false;
6954 Type* int_type = Type::lookup_integer_type("int");
6955 unsigned int tbits = int_type->integer_type()->bits();
6956 unsigned long val;
6957 switch (nc.to_unsigned_long(&val))
6959 case Numeric_constant::NC_UL_VALID:
6960 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
6962 go_error_at(this->length_->location(), "array bound overflows");
6963 return false;
6965 break;
6966 case Numeric_constant::NC_UL_NOTINT:
6967 go_error_at(this->length_->location(), "array bound truncated to integer");
6968 return false;
6969 case Numeric_constant::NC_UL_NEGATIVE:
6970 go_error_at(this->length_->location(), "negative array bound");
6971 return false;
6972 case Numeric_constant::NC_UL_BIG:
6974 mpz_t val;
6975 if (!nc.to_int(&val))
6976 go_unreachable();
6977 unsigned int bits = mpz_sizeinbase(val, 2);
6978 mpz_clear(val);
6979 if (bits >= tbits)
6981 go_error_at(this->length_->location(), "array bound overflows");
6982 return false;
6985 break;
6986 default:
6987 go_unreachable();
6990 return true;
6993 // Verify the type.
6995 bool
6996 Array_type::do_verify()
6998 if (this->element_type()->is_error_type())
6999 return false;
7000 if (!this->verify_length())
7001 this->length_ = Expression::make_error(this->length_->location());
7002 return true;
7005 // Whether the type contains pointers. This is always true for a
7006 // slice. For an array it is true if the element type has pointers
7007 // and the length is greater than zero.
7009 bool
7010 Array_type::do_has_pointer() const
7012 if (this->length_ == NULL)
7013 return true;
7014 if (!this->element_type_->has_pointer())
7015 return false;
7017 Numeric_constant nc;
7018 if (!this->length_->numeric_constant_value(&nc))
7020 // Error reported elsewhere.
7021 return false;
7024 unsigned long val;
7025 switch (nc.to_unsigned_long(&val))
7027 case Numeric_constant::NC_UL_VALID:
7028 return val > 0;
7029 case Numeric_constant::NC_UL_BIG:
7030 return true;
7031 default:
7032 // Error reported elsewhere.
7033 return false;
7037 // Whether we can use memcmp to compare this array.
7039 bool
7040 Array_type::do_compare_is_identity(Gogo* gogo)
7042 if (this->length_ == NULL)
7043 return false;
7045 // Check for [...], which indicates that this is not a real type.
7046 if (this->length_->is_nil_expression())
7047 return false;
7049 if (!this->element_type_->compare_is_identity(gogo))
7050 return false;
7052 // If there is any padding, then we can't use memcmp.
7053 int64_t size;
7054 int64_t align;
7055 if (!this->element_type_->backend_type_size(gogo, &size)
7056 || !this->element_type_->backend_type_align(gogo, &align))
7057 return false;
7058 if ((size & (align - 1)) != 0)
7059 return false;
7061 return true;
7064 // Array type hash code.
7066 unsigned int
7067 Array_type::do_hash_for_method(Gogo* gogo) const
7069 unsigned int ret;
7071 // There is no very convenient way to get a hash code for the
7072 // length.
7073 ret = this->element_type_->hash_for_method(gogo) + 1;
7074 if (this->is_array_incomparable_)
7075 ret <<= 1;
7076 return ret;
7079 // Write the hash function for an array which can not use the identify
7080 // function.
7082 void
7083 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7084 Function_type* hash_fntype,
7085 Function_type* equal_fntype)
7087 Location bloc = Linemap::predeclared_location();
7089 // The pointer to the array that we are going to hash. This is an
7090 // argument to the hash function we are implementing here.
7091 Named_object* key_arg = gogo->lookup("key", NULL);
7092 go_assert(key_arg != NULL);
7093 Type* key_arg_type = key_arg->var_value()->type();
7095 // The seed argument to the hash function.
7096 Named_object* seed_arg = gogo->lookup("seed", NULL);
7097 go_assert(seed_arg != NULL);
7099 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7101 // Make a temporary to hold the return value, initialized to the seed.
7102 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7103 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7104 bloc);
7105 gogo->add_statement(retval);
7107 // Make a temporary to hold the key as a uintptr.
7108 ref = Expression::make_var_reference(key_arg, bloc);
7109 ref = Expression::make_cast(uintptr_type, ref, bloc);
7110 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7111 bloc);
7112 gogo->add_statement(key);
7114 // Loop over the array elements.
7115 // for i = range a
7116 Type* int_type = Type::lookup_integer_type("int");
7117 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7118 gogo->add_statement(index);
7120 Expression* iref = Expression::make_temporary_reference(index, bloc);
7121 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7122 Type* pt = Type::make_pointer_type(name != NULL
7123 ? static_cast<Type*>(name)
7124 : static_cast<Type*>(this));
7125 aref = Expression::make_cast(pt, aref, bloc);
7126 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7127 NULL,
7128 aref,
7129 bloc);
7131 gogo->start_block(bloc);
7133 // Get the hash function for the element type.
7134 Named_object* hash_fn;
7135 Named_object* equal_fn;
7136 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7137 hash_fntype, equal_fntype, &hash_fn,
7138 &equal_fn);
7140 // Get a pointer to this element in the loop.
7141 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7142 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7144 // Get the size of each element.
7145 Expression* ele_size = Expression::make_type_info(this->element_type_,
7146 Expression::TYPE_INFO_SIZE);
7148 // Get the hash of this element, passing retval as the seed.
7149 ref = Expression::make_temporary_reference(retval, bloc);
7150 Expression_list* args = new Expression_list();
7151 args->push_back(subkey);
7152 args->push_back(ref);
7153 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7154 Expression* call = Expression::make_call(func, args, false, bloc);
7156 // Set retval to the result.
7157 Temporary_reference_expression* tref =
7158 Expression::make_temporary_reference(retval, bloc);
7159 tref->set_is_lvalue();
7160 Statement* s = Statement::make_assignment(tref, call, bloc);
7161 gogo->add_statement(s);
7163 // Increase the element pointer.
7164 tref = Expression::make_temporary_reference(key, bloc);
7165 tref->set_is_lvalue();
7166 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7167 bloc);
7168 Block* statements = gogo->finish_block(bloc);
7170 for_range->add_statements(statements);
7171 gogo->add_statement(for_range);
7173 // Return retval to the caller of the hash function.
7174 Expression_list* vals = new Expression_list();
7175 ref = Expression::make_temporary_reference(retval, bloc);
7176 vals->push_back(ref);
7177 s = Statement::make_return_statement(vals, bloc);
7178 gogo->add_statement(s);
7181 // Write the equality function for an array which can not use the
7182 // identity function.
7184 void
7185 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7187 Location bloc = Linemap::predeclared_location();
7189 // The pointers to the arrays we are going to compare.
7190 Named_object* key1_arg = gogo->lookup("key1", NULL);
7191 Named_object* key2_arg = gogo->lookup("key2", NULL);
7192 go_assert(key1_arg != NULL && key2_arg != NULL);
7194 // Build temporaries for the keys with the right types.
7195 Type* pt = Type::make_pointer_type(name != NULL
7196 ? static_cast<Type*>(name)
7197 : static_cast<Type*>(this));
7199 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7200 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7201 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7202 gogo->add_statement(p1);
7204 ref = Expression::make_var_reference(key2_arg, bloc);
7205 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7206 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7207 gogo->add_statement(p2);
7209 // Loop over the array elements.
7210 // for i = range a
7211 Type* int_type = Type::lookup_integer_type("int");
7212 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7213 gogo->add_statement(index);
7215 Expression* iref = Expression::make_temporary_reference(index, bloc);
7216 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7217 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7218 NULL,
7219 aref,
7220 bloc);
7222 gogo->start_block(bloc);
7224 // Compare element in P1 and P2.
7225 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7226 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7227 ref = Expression::make_temporary_reference(index, bloc);
7228 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7230 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7231 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7232 ref = Expression::make_temporary_reference(index, bloc);
7233 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7235 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7237 // If the elements are not equal, return false.
7238 gogo->start_block(bloc);
7239 Expression_list* vals = new Expression_list();
7240 vals->push_back(Expression::make_boolean(false, bloc));
7241 Statement* s = Statement::make_return_statement(vals, bloc);
7242 gogo->add_statement(s);
7243 Block* then_block = gogo->finish_block(bloc);
7245 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7246 gogo->add_statement(s);
7248 Block* statements = gogo->finish_block(bloc);
7250 for_range->add_statements(statements);
7251 gogo->add_statement(for_range);
7253 // All the elements are equal, so return true.
7254 vals = new Expression_list();
7255 vals->push_back(Expression::make_boolean(true, bloc));
7256 s = Statement::make_return_statement(vals, bloc);
7257 gogo->add_statement(s);
7260 // Get the backend representation of the fields of a slice. This is
7261 // not declared in types.h so that types.h doesn't have to #include
7262 // backend.h.
7264 // We use int for the count and capacity fields. This matches 6g.
7265 // The language more or less assumes that we can't allocate space of a
7266 // size which does not fit in int.
7268 static void
7269 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7270 std::vector<Backend::Btyped_identifier>* bfields)
7272 bfields->resize(3);
7274 Type* pet = Type::make_pointer_type(type->element_type());
7275 Btype* pbet = (use_placeholder
7276 ? pet->get_backend_placeholder(gogo)
7277 : pet->get_backend(gogo));
7278 Location ploc = Linemap::predeclared_location();
7280 Backend::Btyped_identifier* p = &(*bfields)[0];
7281 p->name = "__values";
7282 p->btype = pbet;
7283 p->location = ploc;
7285 Type* int_type = Type::lookup_integer_type("int");
7287 p = &(*bfields)[1];
7288 p->name = "__count";
7289 p->btype = int_type->get_backend(gogo);
7290 p->location = ploc;
7292 p = &(*bfields)[2];
7293 p->name = "__capacity";
7294 p->btype = int_type->get_backend(gogo);
7295 p->location = ploc;
7298 // Get the backend representation for the type of this array. A fixed array is
7299 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7300 // just like an array in C. An open array is a struct with three
7301 // fields: a data pointer, the length, and the capacity.
7303 Btype*
7304 Array_type::do_get_backend(Gogo* gogo)
7306 if (this->length_ == NULL)
7308 std::vector<Backend::Btyped_identifier> bfields;
7309 get_backend_slice_fields(gogo, this, false, &bfields);
7310 return gogo->backend()->struct_type(bfields);
7312 else
7314 Btype* element = this->get_backend_element(gogo, false);
7315 Bexpression* len = this->get_backend_length(gogo);
7316 return gogo->backend()->array_type(element, len);
7320 // Return the backend representation of the element type.
7322 Btype*
7323 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7325 if (use_placeholder)
7326 return this->element_type_->get_backend_placeholder(gogo);
7327 else
7328 return this->element_type_->get_backend(gogo);
7331 // Return the backend representation of the length. The length may be
7332 // computed using a function call, so we must only evaluate it once.
7334 Bexpression*
7335 Array_type::get_backend_length(Gogo* gogo)
7337 go_assert(this->length_ != NULL);
7338 if (this->blength_ == NULL)
7340 if (this->length_->is_error_expression())
7342 this->blength_ = gogo->backend()->error_expression();
7343 return this->blength_;
7345 Numeric_constant nc;
7346 mpz_t val;
7347 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7349 if (mpz_sgn(val) < 0)
7351 this->blength_ = gogo->backend()->error_expression();
7352 return this->blength_;
7354 Type* t = nc.type();
7355 if (t == NULL)
7356 t = Type::lookup_integer_type("int");
7357 else if (t->is_abstract())
7358 t = t->make_non_abstract_type();
7359 Btype* btype = t->get_backend(gogo);
7360 this->blength_ =
7361 gogo->backend()->integer_constant_expression(btype, val);
7362 mpz_clear(val);
7364 else
7366 // Make up a translation context for the array length
7367 // expression. FIXME: This won't work in general.
7368 Translate_context context(gogo, NULL, NULL, NULL);
7369 this->blength_ = this->length_->get_backend(&context);
7371 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7372 this->blength_ =
7373 gogo->backend()->convert_expression(ibtype, this->blength_,
7374 this->length_->location());
7377 return this->blength_;
7380 // Finish backend representation of the array.
7382 void
7383 Array_type::finish_backend_element(Gogo* gogo)
7385 Type* et = this->array_type()->element_type();
7386 et->get_backend(gogo);
7387 if (this->is_slice_type())
7389 // This relies on the fact that we always use the same
7390 // structure for a pointer to any given type.
7391 Type* pet = Type::make_pointer_type(et);
7392 pet->get_backend(gogo);
7396 // Return an expression for a pointer to the values in ARRAY.
7398 Expression*
7399 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7401 if (this->length() != NULL)
7403 // Fixed array.
7404 go_assert(array->type()->array_type() != NULL);
7405 Type* etype = array->type()->array_type()->element_type();
7406 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7407 return Expression::make_cast(Type::make_pointer_type(etype), array,
7408 array->location());
7411 // Slice.
7413 if (is_lvalue)
7415 Temporary_reference_expression* tref =
7416 array->temporary_reference_expression();
7417 Var_expression* ve = array->var_expression();
7418 if (tref != NULL)
7420 tref = tref->copy()->temporary_reference_expression();
7421 tref->set_is_lvalue();
7422 array = tref;
7424 else if (ve != NULL)
7426 ve = new Var_expression(ve->named_object(), ve->location());
7427 array = ve;
7431 return Expression::make_slice_info(array,
7432 Expression::SLICE_INFO_VALUE_POINTER,
7433 array->location());
7436 // Return an expression for the length of the array ARRAY which has this
7437 // type.
7439 Expression*
7440 Array_type::get_length(Gogo*, Expression* array) const
7442 if (this->length_ != NULL)
7443 return this->length_;
7445 // This is a slice. We need to read the length field.
7446 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7447 array->location());
7450 // Return an expression for the capacity of the array ARRAY which has this
7451 // type.
7453 Expression*
7454 Array_type::get_capacity(Gogo*, Expression* array) const
7456 if (this->length_ != NULL)
7457 return this->length_;
7459 // This is a slice. We need to read the capacity field.
7460 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7461 array->location());
7464 // Export.
7466 void
7467 Array_type::do_export(Export* exp) const
7469 exp->write_c_string("[");
7470 if (this->length_ != NULL)
7471 this->length_->export_expression(exp);
7472 exp->write_c_string("] ");
7473 exp->write_type(this->element_type_);
7476 // Import.
7478 Array_type*
7479 Array_type::do_import(Import* imp)
7481 imp->require_c_string("[");
7482 Expression* length;
7483 if (imp->peek_char() == ']')
7484 length = NULL;
7485 else
7486 length = Expression::import_expression(imp);
7487 imp->require_c_string("] ");
7488 Type* element_type = imp->read_type();
7489 return Type::make_array_type(element_type, length);
7492 // The type of an array type descriptor.
7494 Type*
7495 Array_type::make_array_type_descriptor_type()
7497 static Type* ret;
7498 if (ret == NULL)
7500 Type* tdt = Type::make_type_descriptor_type();
7501 Type* ptdt = Type::make_type_descriptor_ptr_type();
7503 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7505 Struct_type* sf =
7506 Type::make_builtin_struct_type(4,
7507 "", tdt,
7508 "elem", ptdt,
7509 "slice", ptdt,
7510 "len", uintptr_type);
7512 ret = Type::make_builtin_named_type("ArrayType", sf);
7515 return ret;
7518 // The type of an slice type descriptor.
7520 Type*
7521 Array_type::make_slice_type_descriptor_type()
7523 static Type* ret;
7524 if (ret == NULL)
7526 Type* tdt = Type::make_type_descriptor_type();
7527 Type* ptdt = Type::make_type_descriptor_ptr_type();
7529 Struct_type* sf =
7530 Type::make_builtin_struct_type(2,
7531 "", tdt,
7532 "elem", ptdt);
7534 ret = Type::make_builtin_named_type("SliceType", sf);
7537 return ret;
7540 // Build a type descriptor for an array/slice type.
7542 Expression*
7543 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7545 if (this->length_ != NULL)
7546 return this->array_type_descriptor(gogo, name);
7547 else
7548 return this->slice_type_descriptor(gogo, name);
7551 // Build a type descriptor for an array type.
7553 Expression*
7554 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7556 Location bloc = Linemap::predeclared_location();
7558 Type* atdt = Array_type::make_array_type_descriptor_type();
7560 const Struct_field_list* fields = atdt->struct_type()->fields();
7562 Expression_list* vals = new Expression_list();
7563 vals->reserve(3);
7565 Struct_field_list::const_iterator p = fields->begin();
7566 go_assert(p->is_field_name("_type"));
7567 vals->push_back(this->type_descriptor_constructor(gogo,
7568 RUNTIME_TYPE_KIND_ARRAY,
7569 name, NULL, true));
7571 ++p;
7572 go_assert(p->is_field_name("elem"));
7573 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7575 ++p;
7576 go_assert(p->is_field_name("slice"));
7577 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7578 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7580 ++p;
7581 go_assert(p->is_field_name("len"));
7582 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7584 ++p;
7585 go_assert(p == fields->end());
7587 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7590 // Build a type descriptor for a slice type.
7592 Expression*
7593 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7595 Location bloc = Linemap::predeclared_location();
7597 Type* stdt = Array_type::make_slice_type_descriptor_type();
7599 const Struct_field_list* fields = stdt->struct_type()->fields();
7601 Expression_list* vals = new Expression_list();
7602 vals->reserve(2);
7604 Struct_field_list::const_iterator p = fields->begin();
7605 go_assert(p->is_field_name("_type"));
7606 vals->push_back(this->type_descriptor_constructor(gogo,
7607 RUNTIME_TYPE_KIND_SLICE,
7608 name, NULL, true));
7610 ++p;
7611 go_assert(p->is_field_name("elem"));
7612 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7614 ++p;
7615 go_assert(p == fields->end());
7617 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7620 // Reflection string.
7622 void
7623 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7625 ret->push_back('[');
7626 if (this->length_ != NULL)
7628 Numeric_constant nc;
7629 if (!this->length_->numeric_constant_value(&nc))
7631 go_assert(saw_errors());
7632 return;
7634 mpz_t val;
7635 if (!nc.to_int(&val))
7637 go_assert(saw_errors());
7638 return;
7640 char* s = mpz_get_str(NULL, 10, val);
7641 ret->append(s);
7642 free(s);
7643 mpz_clear(val);
7645 ret->push_back(']');
7647 this->append_reflection(this->element_type_, gogo, ret);
7650 // Make an array type.
7652 Array_type*
7653 Type::make_array_type(Type* element_type, Expression* length)
7655 return new Array_type(element_type, length);
7658 // Class Map_type.
7660 Named_object* Map_type::zero_value;
7661 int64_t Map_type::zero_value_size;
7662 int64_t Map_type::zero_value_align;
7664 // If this map requires the "fat" functions, return the pointer to
7665 // pass as the zero value to those functions. Otherwise, in the
7666 // normal case, return NULL. The map requires the "fat" functions if
7667 // the value size is larger than max_zero_size bytes. max_zero_size
7668 // must match maxZero in libgo/go/runtime/hashmap.go.
7670 Expression*
7671 Map_type::fat_zero_value(Gogo* gogo)
7673 int64_t valsize;
7674 if (!this->val_type_->backend_type_size(gogo, &valsize))
7676 go_assert(saw_errors());
7677 return NULL;
7679 if (valsize <= Map_type::max_zero_size)
7680 return NULL;
7682 if (Map_type::zero_value_size < valsize)
7683 Map_type::zero_value_size = valsize;
7685 int64_t valalign;
7686 if (!this->val_type_->backend_type_align(gogo, &valalign))
7688 go_assert(saw_errors());
7689 return NULL;
7692 if (Map_type::zero_value_align < valalign)
7693 Map_type::zero_value_align = valalign;
7695 Location bloc = Linemap::predeclared_location();
7697 if (Map_type::zero_value == NULL)
7699 // The final type will be set in backend_zero_value.
7700 Type* uint8_type = Type::lookup_integer_type("uint8");
7701 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7702 Array_type* array_type = Type::make_array_type(uint8_type, size);
7703 array_type->set_is_array_incomparable();
7704 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7705 std::string name = gogo->map_zero_value_name();
7706 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7709 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7710 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7711 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7712 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7713 return z;
7716 // Return whether VAR is the map zero value.
7718 bool
7719 Map_type::is_zero_value(Variable* var)
7721 return (Map_type::zero_value != NULL
7722 && Map_type::zero_value->var_value() == var);
7725 // Return the backend representation for the zero value.
7727 Bvariable*
7728 Map_type::backend_zero_value(Gogo* gogo)
7730 Location bloc = Linemap::predeclared_location();
7732 go_assert(Map_type::zero_value != NULL);
7734 Type* uint8_type = Type::lookup_integer_type("uint8");
7735 Btype* buint8_type = uint8_type->get_backend(gogo);
7737 Type* int_type = Type::lookup_integer_type("int");
7739 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7740 int_type, bloc);
7741 Translate_context context(gogo, NULL, NULL, NULL);
7742 Bexpression* blength = e->get_backend(&context);
7744 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7746 std::string zname = Map_type::zero_value->name();
7747 std::string asm_name(go_selectively_encode_id(zname));
7748 Bvariable* zvar =
7749 gogo->backend()->implicit_variable(zname, asm_name,
7750 barray_type, false, false, true,
7751 Map_type::zero_value_align);
7752 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7753 false, false, true, NULL);
7754 return zvar;
7757 // Traversal.
7760 Map_type::do_traverse(Traverse* traverse)
7762 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7763 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7764 return TRAVERSE_EXIT;
7765 return TRAVERSE_CONTINUE;
7768 // Check that the map type is OK.
7770 bool
7771 Map_type::do_verify()
7773 // The runtime support uses "map[void]void".
7774 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7775 go_error_at(this->location_, "invalid map key type");
7776 if (!this->key_type_->in_heap())
7777 go_error_at(this->location_, "go:notinheap map key not allowed");
7778 if (!this->val_type_->in_heap())
7779 go_error_at(this->location_, "go:notinheap map value not allowed");
7780 return true;
7783 // Whether two map types are identical.
7785 bool
7786 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7787 bool errors_are_identical) const
7789 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7790 cmp_tags, errors_are_identical, NULL)
7791 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7792 cmp_tags, errors_are_identical,
7793 NULL));
7796 // Hash code.
7798 unsigned int
7799 Map_type::do_hash_for_method(Gogo* gogo) const
7801 return (this->key_type_->hash_for_method(gogo)
7802 + this->val_type_->hash_for_method(gogo)
7803 + 2);
7806 // Get the backend representation for a map type. A map type is
7807 // represented as a pointer to a struct. The struct is hmap in
7808 // runtime/hashmap.go.
7810 Btype*
7811 Map_type::do_get_backend(Gogo* gogo)
7813 static Btype* backend_map_type;
7814 if (backend_map_type == NULL)
7816 std::vector<Backend::Btyped_identifier> bfields(9);
7818 Location bloc = Linemap::predeclared_location();
7820 Type* int_type = Type::lookup_integer_type("int");
7821 bfields[0].name = "count";
7822 bfields[0].btype = int_type->get_backend(gogo);
7823 bfields[0].location = bloc;
7825 Type* uint8_type = Type::lookup_integer_type("uint8");
7826 bfields[1].name = "flags";
7827 bfields[1].btype = uint8_type->get_backend(gogo);
7828 bfields[1].location = bloc;
7830 bfields[2].name = "B";
7831 bfields[2].btype = bfields[1].btype;
7832 bfields[2].location = bloc;
7834 Type* uint16_type = Type::lookup_integer_type("uint16");
7835 bfields[3].name = "noverflow";
7836 bfields[3].btype = uint16_type->get_backend(gogo);
7837 bfields[3].location = bloc;
7839 Type* uint32_type = Type::lookup_integer_type("uint32");
7840 bfields[4].name = "hash0";
7841 bfields[4].btype = uint32_type->get_backend(gogo);
7842 bfields[4].location = bloc;
7844 Btype* bvt = gogo->backend()->void_type();
7845 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7846 bfields[5].name = "buckets";
7847 bfields[5].btype = bpvt;
7848 bfields[5].location = bloc;
7850 bfields[6].name = "oldbuckets";
7851 bfields[6].btype = bpvt;
7852 bfields[6].location = bloc;
7854 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7855 bfields[7].name = "nevacuate";
7856 bfields[7].btype = uintptr_type->get_backend(gogo);
7857 bfields[7].location = bloc;
7859 bfields[8].name = "extra";
7860 bfields[8].btype = bpvt;
7861 bfields[8].location = bloc;
7863 Btype *bt = gogo->backend()->struct_type(bfields);
7864 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7865 backend_map_type = gogo->backend()->pointer_type(bt);
7867 return backend_map_type;
7870 // The type of a map type descriptor.
7872 Type*
7873 Map_type::make_map_type_descriptor_type()
7875 static Type* ret;
7876 if (ret == NULL)
7878 Type* tdt = Type::make_type_descriptor_type();
7879 Type* ptdt = Type::make_type_descriptor_ptr_type();
7880 Type* uint8_type = Type::lookup_integer_type("uint8");
7881 Type* uint16_type = Type::lookup_integer_type("uint16");
7882 Type* bool_type = Type::lookup_bool_type();
7884 Struct_type* sf =
7885 Type::make_builtin_struct_type(12,
7886 "", tdt,
7887 "key", ptdt,
7888 "elem", ptdt,
7889 "bucket", ptdt,
7890 "hmap", ptdt,
7891 "keysize", uint8_type,
7892 "indirectkey", bool_type,
7893 "valuesize", uint8_type,
7894 "indirectvalue", bool_type,
7895 "bucketsize", uint16_type,
7896 "reflexivekey", bool_type,
7897 "needkeyupdate", bool_type);
7899 ret = Type::make_builtin_named_type("MapType", sf);
7902 return ret;
7905 // Build a type descriptor for a map type.
7907 Expression*
7908 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7910 Location bloc = Linemap::predeclared_location();
7912 Type* mtdt = Map_type::make_map_type_descriptor_type();
7913 Type* uint8_type = Type::lookup_integer_type("uint8");
7914 Type* uint16_type = Type::lookup_integer_type("uint16");
7916 int64_t keysize;
7917 if (!this->key_type_->backend_type_size(gogo, &keysize))
7919 go_error_at(this->location_, "error determining map key type size");
7920 return Expression::make_error(this->location_);
7923 int64_t valsize;
7924 if (!this->val_type_->backend_type_size(gogo, &valsize))
7926 go_error_at(this->location_, "error determining map value type size");
7927 return Expression::make_error(this->location_);
7930 int64_t ptrsize;
7931 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
7933 go_assert(saw_errors());
7934 return Expression::make_error(this->location_);
7937 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
7938 if (bucket_type == NULL)
7940 go_assert(saw_errors());
7941 return Expression::make_error(this->location_);
7944 int64_t bucketsize;
7945 if (!bucket_type->backend_type_size(gogo, &bucketsize))
7947 go_assert(saw_errors());
7948 return Expression::make_error(this->location_);
7951 const Struct_field_list* fields = mtdt->struct_type()->fields();
7953 Expression_list* vals = new Expression_list();
7954 vals->reserve(12);
7956 Struct_field_list::const_iterator p = fields->begin();
7957 go_assert(p->is_field_name("_type"));
7958 vals->push_back(this->type_descriptor_constructor(gogo,
7959 RUNTIME_TYPE_KIND_MAP,
7960 name, NULL, true));
7962 ++p;
7963 go_assert(p->is_field_name("key"));
7964 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
7966 ++p;
7967 go_assert(p->is_field_name("elem"));
7968 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
7970 ++p;
7971 go_assert(p->is_field_name("bucket"));
7972 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
7974 ++p;
7975 go_assert(p->is_field_name("hmap"));
7976 Type* hmap_type = this->hmap_type(bucket_type);
7977 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
7979 ++p;
7980 go_assert(p->is_field_name("keysize"));
7981 if (keysize > Map_type::max_key_size)
7982 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
7983 else
7984 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
7986 ++p;
7987 go_assert(p->is_field_name("indirectkey"));
7988 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
7989 bloc));
7991 ++p;
7992 go_assert(p->is_field_name("valuesize"));
7993 if (valsize > Map_type::max_val_size)
7994 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
7995 else
7996 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
7998 ++p;
7999 go_assert(p->is_field_name("indirectvalue"));
8000 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8001 bloc));
8003 ++p;
8004 go_assert(p->is_field_name("bucketsize"));
8005 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8006 bloc));
8008 ++p;
8009 go_assert(p->is_field_name("reflexivekey"));
8010 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8011 bloc));
8013 ++p;
8014 go_assert(p->is_field_name("needkeyupdate"));
8015 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8016 bloc));
8018 ++p;
8019 go_assert(p == fields->end());
8021 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8024 // Return the bucket type to use for a map type. This must correspond
8025 // to libgo/go/runtime/hashmap.go.
8027 Type*
8028 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8030 if (this->bucket_type_ != NULL)
8031 return this->bucket_type_;
8033 Type* key_type = this->key_type_;
8034 if (keysize > Map_type::max_key_size)
8035 key_type = Type::make_pointer_type(key_type);
8037 Type* val_type = this->val_type_;
8038 if (valsize > Map_type::max_val_size)
8039 val_type = Type::make_pointer_type(val_type);
8041 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8042 NULL, this->location_);
8044 Type* uint8_type = Type::lookup_integer_type("uint8");
8045 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8046 topbits_type->set_is_array_incomparable();
8047 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8048 keys_type->set_is_array_incomparable();
8049 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8050 values_type->set_is_array_incomparable();
8052 // If keys and values have no pointers, the map implementation can
8053 // keep a list of overflow pointers on the side so that buckets can
8054 // be marked as having no pointers. Arrange for the bucket to have
8055 // no pointers by changing the type of the overflow field to uintptr
8056 // in this case. See comment on the hmap.overflow field in
8057 // libgo/go/runtime/hashmap.go.
8058 Type* overflow_type;
8059 if (!key_type->has_pointer() && !val_type->has_pointer())
8060 overflow_type = Type::lookup_integer_type("uintptr");
8061 else
8063 // This should really be a pointer to the bucket type itself,
8064 // but that would require us to construct a Named_type for it to
8065 // give it a way to refer to itself. Since nothing really cares
8066 // (except perhaps for someone using a debugger) just use an
8067 // unsafe pointer.
8068 overflow_type = Type::make_pointer_type(Type::make_void_type());
8071 // Make sure the overflow pointer is the last memory in the struct,
8072 // because the runtime assumes it can use size-ptrSize as the offset
8073 // of the overflow pointer. We double-check that property below
8074 // once the offsets and size are computed.
8076 int64_t topbits_field_size, topbits_field_align;
8077 int64_t keys_field_size, keys_field_align;
8078 int64_t values_field_size, values_field_align;
8079 int64_t overflow_field_size, overflow_field_align;
8080 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8081 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8082 || !keys_type->backend_type_size(gogo, &keys_field_size)
8083 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8084 || !values_type->backend_type_size(gogo, &values_field_size)
8085 || !values_type->backend_type_field_align(gogo, &values_field_align)
8086 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8087 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8089 go_assert(saw_errors());
8090 return NULL;
8093 Struct_type* ret;
8094 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8095 values_field_align);
8096 if (max_align <= overflow_field_align)
8097 ret = make_builtin_struct_type(4,
8098 "topbits", topbits_type,
8099 "keys", keys_type,
8100 "values", values_type,
8101 "overflow", overflow_type);
8102 else
8104 size_t off = topbits_field_size;
8105 off = ((off + keys_field_align - 1)
8106 &~ static_cast<size_t>(keys_field_align - 1));
8107 off += keys_field_size;
8108 off = ((off + values_field_align - 1)
8109 &~ static_cast<size_t>(values_field_align - 1));
8110 off += values_field_size;
8112 int64_t padded_overflow_field_size =
8113 ((overflow_field_size + max_align - 1)
8114 &~ static_cast<size_t>(max_align - 1));
8116 size_t ovoff = off;
8117 ovoff = ((ovoff + max_align - 1)
8118 &~ static_cast<size_t>(max_align - 1));
8119 size_t pad = (ovoff - off
8120 + padded_overflow_field_size - overflow_field_size);
8122 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8123 this->location_);
8124 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8125 pad_type->set_is_array_incomparable();
8127 ret = make_builtin_struct_type(5,
8128 "topbits", topbits_type,
8129 "keys", keys_type,
8130 "values", values_type,
8131 "pad", pad_type,
8132 "overflow", overflow_type);
8135 // Verify that the overflow field is just before the end of the
8136 // bucket type.
8138 Btype* btype = ret->get_backend(gogo);
8139 int64_t offset = gogo->backend()->type_field_offset(btype,
8140 ret->field_count() - 1);
8141 int64_t size;
8142 if (!ret->backend_type_size(gogo, &size))
8144 go_assert(saw_errors());
8145 return NULL;
8148 int64_t ptr_size;
8149 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8151 go_assert(saw_errors());
8152 return NULL;
8155 go_assert(offset + ptr_size == size);
8157 ret->set_is_struct_incomparable();
8159 this->bucket_type_ = ret;
8160 return ret;
8163 // Return the hashmap type for a map type.
8165 Type*
8166 Map_type::hmap_type(Type* bucket_type)
8168 if (this->hmap_type_ != NULL)
8169 return this->hmap_type_;
8171 Type* int_type = Type::lookup_integer_type("int");
8172 Type* uint8_type = Type::lookup_integer_type("uint8");
8173 Type* uint16_type = Type::lookup_integer_type("uint16");
8174 Type* uint32_type = Type::lookup_integer_type("uint32");
8175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8176 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8178 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8180 Struct_type* ret = make_builtin_struct_type(9,
8181 "count", int_type,
8182 "flags", uint8_type,
8183 "B", uint8_type,
8184 "noverflow", uint16_type,
8185 "hash0", uint32_type,
8186 "buckets", ptr_bucket_type,
8187 "oldbuckets", ptr_bucket_type,
8188 "nevacuate", uintptr_type,
8189 "extra", void_ptr_type);
8190 ret->set_is_struct_incomparable();
8191 this->hmap_type_ = ret;
8192 return ret;
8195 // Return the iterator type for a map type. This is the type of the
8196 // value used when doing a range over a map.
8198 Type*
8199 Map_type::hiter_type(Gogo* gogo)
8201 if (this->hiter_type_ != NULL)
8202 return this->hiter_type_;
8204 int64_t keysize, valsize;
8205 if (!this->key_type_->backend_type_size(gogo, &keysize)
8206 || !this->val_type_->backend_type_size(gogo, &valsize))
8208 go_assert(saw_errors());
8209 return NULL;
8212 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8213 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8214 Type* uint8_type = Type::lookup_integer_type("uint8");
8215 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8216 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8217 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8218 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8219 Type* hmap_type = this->hmap_type(bucket_type);
8220 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8221 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8222 Type* bool_type = Type::lookup_bool_type();
8224 Struct_type* ret = make_builtin_struct_type(15,
8225 "key", key_ptr_type,
8226 "val", val_ptr_type,
8227 "t", uint8_ptr_type,
8228 "h", hmap_ptr_type,
8229 "buckets", bucket_ptr_type,
8230 "bptr", bucket_ptr_type,
8231 "overflow", void_ptr_type,
8232 "oldoverflow", void_ptr_type,
8233 "startBucket", uintptr_type,
8234 "offset", uint8_type,
8235 "wrapped", bool_type,
8236 "B", uint8_type,
8237 "i", uint8_type,
8238 "bucket", uintptr_type,
8239 "checkBucket", uintptr_type);
8240 ret->set_is_struct_incomparable();
8241 this->hiter_type_ = ret;
8242 return ret;
8245 // Reflection string for a map.
8247 void
8248 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8250 ret->append("map[");
8251 this->append_reflection(this->key_type_, gogo, ret);
8252 ret->append("]");
8253 this->append_reflection(this->val_type_, gogo, ret);
8256 // Export a map type.
8258 void
8259 Map_type::do_export(Export* exp) const
8261 exp->write_c_string("map [");
8262 exp->write_type(this->key_type_);
8263 exp->write_c_string("] ");
8264 exp->write_type(this->val_type_);
8267 // Import a map type.
8269 Map_type*
8270 Map_type::do_import(Import* imp)
8272 imp->require_c_string("map [");
8273 Type* key_type = imp->read_type();
8274 imp->require_c_string("] ");
8275 Type* val_type = imp->read_type();
8276 return Type::make_map_type(key_type, val_type, imp->location());
8279 // Make a map type.
8281 Map_type*
8282 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8284 return new Map_type(key_type, val_type, location);
8287 // Class Channel_type.
8289 // Verify.
8291 bool
8292 Channel_type::do_verify()
8294 // We have no location for this error, but this is not something the
8295 // ordinary user will see.
8296 if (!this->element_type_->in_heap())
8297 go_error_at(Linemap::unknown_location(),
8298 "chan of go:notinheap type not allowed");
8299 return true;
8302 // Hash code.
8304 unsigned int
8305 Channel_type::do_hash_for_method(Gogo* gogo) const
8307 unsigned int ret = 0;
8308 if (this->may_send_)
8309 ret += 1;
8310 if (this->may_receive_)
8311 ret += 2;
8312 if (this->element_type_ != NULL)
8313 ret += this->element_type_->hash_for_method(gogo) << 2;
8314 return ret << 3;
8317 // Whether this type is the same as T.
8319 bool
8320 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8321 bool errors_are_identical) const
8323 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8324 cmp_tags, errors_are_identical, NULL))
8325 return false;
8326 return (this->may_send_ == t->may_send_
8327 && this->may_receive_ == t->may_receive_);
8330 // Return the backend representation for a channel type. A channel is a pointer
8331 // to a __go_channel struct. The __go_channel struct is defined in
8332 // libgo/runtime/channel.h.
8334 Btype*
8335 Channel_type::do_get_backend(Gogo* gogo)
8337 static Btype* backend_channel_type;
8338 if (backend_channel_type == NULL)
8340 std::vector<Backend::Btyped_identifier> bfields;
8341 Btype* bt = gogo->backend()->struct_type(bfields);
8342 bt = gogo->backend()->named_type("__go_channel", bt,
8343 Linemap::predeclared_location());
8344 backend_channel_type = gogo->backend()->pointer_type(bt);
8346 return backend_channel_type;
8349 // Build a type descriptor for a channel type.
8351 Type*
8352 Channel_type::make_chan_type_descriptor_type()
8354 static Type* ret;
8355 if (ret == NULL)
8357 Type* tdt = Type::make_type_descriptor_type();
8358 Type* ptdt = Type::make_type_descriptor_ptr_type();
8360 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8362 Struct_type* sf =
8363 Type::make_builtin_struct_type(3,
8364 "", tdt,
8365 "elem", ptdt,
8366 "dir", uintptr_type);
8368 ret = Type::make_builtin_named_type("ChanType", sf);
8371 return ret;
8374 // Build a type descriptor for a map type.
8376 Expression*
8377 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8379 Location bloc = Linemap::predeclared_location();
8381 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8383 const Struct_field_list* fields = ctdt->struct_type()->fields();
8385 Expression_list* vals = new Expression_list();
8386 vals->reserve(3);
8388 Struct_field_list::const_iterator p = fields->begin();
8389 go_assert(p->is_field_name("_type"));
8390 vals->push_back(this->type_descriptor_constructor(gogo,
8391 RUNTIME_TYPE_KIND_CHAN,
8392 name, NULL, true));
8394 ++p;
8395 go_assert(p->is_field_name("elem"));
8396 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8398 ++p;
8399 go_assert(p->is_field_name("dir"));
8400 // These bits must match the ones in libgo/runtime/go-type.h.
8401 int val = 0;
8402 if (this->may_receive_)
8403 val |= 1;
8404 if (this->may_send_)
8405 val |= 2;
8406 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8408 ++p;
8409 go_assert(p == fields->end());
8411 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8414 // Reflection string.
8416 void
8417 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8419 if (!this->may_send_)
8420 ret->append("<-");
8421 ret->append("chan");
8422 if (!this->may_receive_)
8423 ret->append("<-");
8424 ret->push_back(' ');
8425 this->append_reflection(this->element_type_, gogo, ret);
8428 // Export.
8430 void
8431 Channel_type::do_export(Export* exp) const
8433 exp->write_c_string("chan ");
8434 if (this->may_send_ && !this->may_receive_)
8435 exp->write_c_string("-< ");
8436 else if (this->may_receive_ && !this->may_send_)
8437 exp->write_c_string("<- ");
8438 exp->write_type(this->element_type_);
8441 // Import.
8443 Channel_type*
8444 Channel_type::do_import(Import* imp)
8446 imp->require_c_string("chan ");
8448 bool may_send;
8449 bool may_receive;
8450 if (imp->match_c_string("-< "))
8452 imp->advance(3);
8453 may_send = true;
8454 may_receive = false;
8456 else if (imp->match_c_string("<- "))
8458 imp->advance(3);
8459 may_receive = true;
8460 may_send = false;
8462 else
8464 may_send = true;
8465 may_receive = true;
8468 Type* element_type = imp->read_type();
8470 return Type::make_channel_type(may_send, may_receive, element_type);
8473 // Return the type to manage a select statement with ncases case
8474 // statements. A value of this type is allocated on the stack. This
8475 // must match the type hselect in libgo/go/runtime/select.go.
8477 Type*
8478 Channel_type::select_type(int ncases)
8480 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8481 Type* uint16_type = Type::lookup_integer_type("uint16");
8483 static Struct_type* scase_type;
8484 if (scase_type == NULL)
8486 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8487 Type* uint64_type = Type::lookup_integer_type("uint64");
8488 scase_type =
8489 Type::make_builtin_struct_type(7,
8490 "elem", unsafe_pointer_type,
8491 "chan", unsafe_pointer_type,
8492 "pc", uintptr_type,
8493 "kind", uint16_type,
8494 "index", uint16_type,
8495 "receivedp", unsafe_pointer_type,
8496 "releasetime", uint64_type);
8497 scase_type->set_is_struct_incomparable();
8500 Expression* ncases_expr =
8501 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8502 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8503 scases->set_is_array_incomparable();
8504 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8505 order->set_is_array_incomparable();
8507 Struct_type* ret =
8508 Type::make_builtin_struct_type(7,
8509 "tcase", uint16_type,
8510 "ncase", uint16_type,
8511 "pollorder", unsafe_pointer_type,
8512 "lockorder", unsafe_pointer_type,
8513 "scase", scases,
8514 "lockorderarr", order,
8515 "pollorderarr", order);
8516 ret->set_is_struct_incomparable();
8517 return ret;
8520 // Make a new channel type.
8522 Channel_type*
8523 Type::make_channel_type(bool send, bool receive, Type* element_type)
8525 return new Channel_type(send, receive, element_type);
8528 // Class Interface_type.
8530 // Return the list of methods.
8532 const Typed_identifier_list*
8533 Interface_type::methods() const
8535 go_assert(this->methods_are_finalized_ || saw_errors());
8536 return this->all_methods_;
8539 // Return the number of methods.
8541 size_t
8542 Interface_type::method_count() const
8544 go_assert(this->methods_are_finalized_ || saw_errors());
8545 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8548 // Traversal.
8551 Interface_type::do_traverse(Traverse* traverse)
8553 Typed_identifier_list* methods = (this->methods_are_finalized_
8554 ? this->all_methods_
8555 : this->parse_methods_);
8556 if (methods == NULL)
8557 return TRAVERSE_CONTINUE;
8558 return methods->traverse(traverse);
8561 // Finalize the methods. This handles interface inheritance.
8563 void
8564 Interface_type::finalize_methods()
8566 if (this->methods_are_finalized_)
8567 return;
8568 this->methods_are_finalized_ = true;
8569 if (this->parse_methods_ == NULL)
8570 return;
8572 this->all_methods_ = new Typed_identifier_list();
8573 this->all_methods_->reserve(this->parse_methods_->size());
8574 Typed_identifier_list inherit;
8575 for (Typed_identifier_list::const_iterator pm =
8576 this->parse_methods_->begin();
8577 pm != this->parse_methods_->end();
8578 ++pm)
8580 const Typed_identifier* p = &*pm;
8581 if (p->name().empty())
8582 inherit.push_back(*p);
8583 else if (this->find_method(p->name()) == NULL)
8584 this->all_methods_->push_back(*p);
8585 else
8586 go_error_at(p->location(), "duplicate method %qs",
8587 Gogo::message_name(p->name()).c_str());
8590 std::vector<Named_type*> seen;
8591 seen.reserve(inherit.size());
8592 bool issued_recursive_error = false;
8593 while (!inherit.empty())
8595 Type* t = inherit.back().type();
8596 Location tl = inherit.back().location();
8597 inherit.pop_back();
8599 Interface_type* it = t->interface_type();
8600 if (it == NULL)
8602 if (!t->is_error())
8603 go_error_at(tl, "interface contains embedded non-interface");
8604 continue;
8606 if (it == this)
8608 if (!issued_recursive_error)
8610 go_error_at(tl, "invalid recursive interface");
8611 issued_recursive_error = true;
8613 continue;
8616 Named_type* nt = t->named_type();
8617 if (nt != NULL && it->parse_methods_ != NULL)
8619 std::vector<Named_type*>::const_iterator q;
8620 for (q = seen.begin(); q != seen.end(); ++q)
8622 if (*q == nt)
8624 go_error_at(tl, "inherited interface loop");
8625 break;
8628 if (q != seen.end())
8629 continue;
8630 seen.push_back(nt);
8633 const Typed_identifier_list* imethods = it->parse_methods_;
8634 if (imethods == NULL)
8635 continue;
8636 for (Typed_identifier_list::const_iterator q = imethods->begin();
8637 q != imethods->end();
8638 ++q)
8640 if (q->name().empty())
8641 inherit.push_back(*q);
8642 else if (this->find_method(q->name()) == NULL)
8643 this->all_methods_->push_back(Typed_identifier(q->name(),
8644 q->type(), tl));
8645 else
8646 go_error_at(tl, "inherited method %qs is ambiguous",
8647 Gogo::message_name(q->name()).c_str());
8651 if (!this->all_methods_->empty())
8652 this->all_methods_->sort_by_name();
8653 else
8655 delete this->all_methods_;
8656 this->all_methods_ = NULL;
8660 // Return the method NAME, or NULL.
8662 const Typed_identifier*
8663 Interface_type::find_method(const std::string& name) const
8665 go_assert(this->methods_are_finalized_);
8666 if (this->all_methods_ == NULL)
8667 return NULL;
8668 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8669 p != this->all_methods_->end();
8670 ++p)
8671 if (p->name() == name)
8672 return &*p;
8673 return NULL;
8676 // Return the method index.
8678 size_t
8679 Interface_type::method_index(const std::string& name) const
8681 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8682 size_t ret = 0;
8683 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8684 p != this->all_methods_->end();
8685 ++p, ++ret)
8686 if (p->name() == name)
8687 return ret;
8688 go_unreachable();
8691 // Return whether NAME is an unexported method, for better error
8692 // reporting.
8694 bool
8695 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8697 go_assert(this->methods_are_finalized_);
8698 if (this->all_methods_ == NULL)
8699 return false;
8700 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8701 p != this->all_methods_->end();
8702 ++p)
8704 const std::string& method_name(p->name());
8705 if (Gogo::is_hidden_name(method_name)
8706 && name == Gogo::unpack_hidden_name(method_name)
8707 && gogo->pack_hidden_name(name, false) != method_name)
8708 return true;
8710 return false;
8713 // Whether this type is identical with T.
8715 bool
8716 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
8717 bool errors_are_identical) const
8719 // If methods have not been finalized, then we are asking whether
8720 // func redeclarations are the same. This is an error, so for
8721 // simplicity we say they are never the same.
8722 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8723 return false;
8725 // We require the same methods with the same types. The methods
8726 // have already been sorted.
8727 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8728 return this->all_methods_ == t->all_methods_;
8730 if (this->assume_identical(this, t) || t->assume_identical(t, this))
8731 return true;
8733 Assume_identical* hold_ai = this->assume_identical_;
8734 Assume_identical ai;
8735 ai.t1 = this;
8736 ai.t2 = t;
8737 ai.next = hold_ai;
8738 this->assume_identical_ = &ai;
8740 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8741 Typed_identifier_list::const_iterator p2;
8742 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8744 if (p1 == this->all_methods_->end())
8745 break;
8746 if (p1->name() != p2->name()
8747 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
8748 errors_are_identical, NULL))
8749 break;
8752 this->assume_identical_ = hold_ai;
8754 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8757 // Return true if T1 and T2 are assumed to be identical during a type
8758 // comparison.
8760 bool
8761 Interface_type::assume_identical(const Interface_type* t1,
8762 const Interface_type* t2) const
8764 for (Assume_identical* p = this->assume_identical_;
8765 p != NULL;
8766 p = p->next)
8767 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8768 return true;
8769 return false;
8772 // Whether we can assign the interface type T to this type. The types
8773 // are known to not be identical. An interface assignment is only
8774 // permitted if T is known to implement all methods in THIS.
8775 // Otherwise a type guard is required.
8777 bool
8778 Interface_type::is_compatible_for_assign(const Interface_type* t,
8779 std::string* reason) const
8781 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8782 if (this->all_methods_ == NULL)
8783 return true;
8784 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8785 p != this->all_methods_->end();
8786 ++p)
8788 const Typed_identifier* m = t->find_method(p->name());
8789 if (m == NULL)
8791 if (reason != NULL)
8793 char buf[200];
8794 snprintf(buf, sizeof buf,
8795 _("need explicit conversion; missing method %s%s%s"),
8796 go_open_quote(), Gogo::message_name(p->name()).c_str(),
8797 go_close_quote());
8798 reason->assign(buf);
8800 return false;
8803 std::string subreason;
8804 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8806 if (reason != NULL)
8808 std::string n = Gogo::message_name(p->name());
8809 size_t len = 100 + n.length() + subreason.length();
8810 char* buf = new char[len];
8811 if (subreason.empty())
8812 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8813 go_open_quote(), n.c_str(), go_close_quote());
8814 else
8815 snprintf(buf, len,
8816 _("incompatible type for method %s%s%s (%s)"),
8817 go_open_quote(), n.c_str(), go_close_quote(),
8818 subreason.c_str());
8819 reason->assign(buf);
8820 delete[] buf;
8822 return false;
8826 return true;
8829 // Hash code.
8831 unsigned int
8832 Interface_type::do_hash_for_method(Gogo*) const
8834 go_assert(this->methods_are_finalized_);
8835 unsigned int ret = 0;
8836 if (this->all_methods_ != NULL)
8838 for (Typed_identifier_list::const_iterator p =
8839 this->all_methods_->begin();
8840 p != this->all_methods_->end();
8841 ++p)
8843 ret = Type::hash_string(p->name(), ret);
8844 // We don't use the method type in the hash, to avoid
8845 // infinite recursion if an interface method uses a type
8846 // which is an interface which inherits from the interface
8847 // itself.
8848 // type T interface { F() interface {T}}
8849 ret <<= 1;
8852 return ret;
8855 // Return true if T implements the interface. If it does not, and
8856 // REASON is not NULL, set *REASON to a useful error message.
8858 bool
8859 Interface_type::implements_interface(const Type* t, std::string* reason) const
8861 go_assert(this->methods_are_finalized_);
8862 if (this->all_methods_ == NULL)
8863 return true;
8865 bool is_pointer = false;
8866 const Named_type* nt = t->named_type();
8867 const Struct_type* st = t->struct_type();
8868 // If we start with a named type, we don't dereference it to find
8869 // methods.
8870 if (nt == NULL)
8872 const Type* pt = t->points_to();
8873 if (pt != NULL)
8875 // If T is a pointer to a named type, then we need to look at
8876 // the type to which it points.
8877 is_pointer = true;
8878 nt = pt->named_type();
8879 st = pt->struct_type();
8883 // If we have a named type, get the methods from it rather than from
8884 // any struct type.
8885 if (nt != NULL)
8886 st = NULL;
8888 // Only named and struct types have methods.
8889 if (nt == NULL && st == NULL)
8891 if (reason != NULL)
8893 if (t->points_to() != NULL
8894 && t->points_to()->interface_type() != NULL)
8895 reason->assign(_("pointer to interface type has no methods"));
8896 else
8897 reason->assign(_("type has no methods"));
8899 return false;
8902 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8904 if (reason != NULL)
8906 if (t->points_to() != NULL
8907 && t->points_to()->interface_type() != NULL)
8908 reason->assign(_("pointer to interface type has no methods"));
8909 else
8910 reason->assign(_("type has no methods"));
8912 return false;
8915 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8916 p != this->all_methods_->end();
8917 ++p)
8919 bool is_ambiguous = false;
8920 Method* m = (nt != NULL
8921 ? nt->method_function(p->name(), &is_ambiguous)
8922 : st->method_function(p->name(), &is_ambiguous));
8923 if (m == NULL)
8925 if (reason != NULL)
8927 std::string n = Gogo::message_name(p->name());
8928 size_t len = n.length() + 100;
8929 char* buf = new char[len];
8930 if (is_ambiguous)
8931 snprintf(buf, len, _("ambiguous method %s%s%s"),
8932 go_open_quote(), n.c_str(), go_close_quote());
8933 else
8934 snprintf(buf, len, _("missing method %s%s%s"),
8935 go_open_quote(), n.c_str(), go_close_quote());
8936 reason->assign(buf);
8937 delete[] buf;
8939 return false;
8942 Function_type *p_fn_type = p->type()->function_type();
8943 Function_type* m_fn_type = m->type()->function_type();
8944 go_assert(p_fn_type != NULL && m_fn_type != NULL);
8945 std::string subreason;
8946 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
8947 &subreason))
8949 if (reason != NULL)
8951 std::string n = Gogo::message_name(p->name());
8952 size_t len = 100 + n.length() + subreason.length();
8953 char* buf = new char[len];
8954 if (subreason.empty())
8955 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8956 go_open_quote(), n.c_str(), go_close_quote());
8957 else
8958 snprintf(buf, len,
8959 _("incompatible type for method %s%s%s (%s)"),
8960 go_open_quote(), n.c_str(), go_close_quote(),
8961 subreason.c_str());
8962 reason->assign(buf);
8963 delete[] buf;
8965 return false;
8968 if (!is_pointer && !m->is_value_method())
8970 if (reason != NULL)
8972 std::string n = Gogo::message_name(p->name());
8973 size_t len = 100 + n.length();
8974 char* buf = new char[len];
8975 snprintf(buf, len,
8976 _("method %s%s%s requires a pointer receiver"),
8977 go_open_quote(), n.c_str(), go_close_quote());
8978 reason->assign(buf);
8979 delete[] buf;
8981 return false;
8984 // If the magic //go:nointerface comment was used, the method
8985 // may not be used to implement interfaces.
8986 if (m->nointerface())
8988 if (reason != NULL)
8990 std::string n = Gogo::message_name(p->name());
8991 size_t len = 100 + n.length();
8992 char* buf = new char[len];
8993 snprintf(buf, len,
8994 _("method %s%s%s is marked go:nointerface"),
8995 go_open_quote(), n.c_str(), go_close_quote());
8996 reason->assign(buf);
8997 delete[] buf;
8999 return false;
9003 return true;
9006 // Return the backend representation of the empty interface type. We
9007 // use the same struct for all empty interfaces.
9009 Btype*
9010 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9012 static Btype* empty_interface_type;
9013 if (empty_interface_type == NULL)
9015 std::vector<Backend::Btyped_identifier> bfields(2);
9017 Location bloc = Linemap::predeclared_location();
9019 Type* pdt = Type::make_type_descriptor_ptr_type();
9020 bfields[0].name = "__type_descriptor";
9021 bfields[0].btype = pdt->get_backend(gogo);
9022 bfields[0].location = bloc;
9024 Type* vt = Type::make_pointer_type(Type::make_void_type());
9025 bfields[1].name = "__object";
9026 bfields[1].btype = vt->get_backend(gogo);
9027 bfields[1].location = bloc;
9029 empty_interface_type = gogo->backend()->struct_type(bfields);
9031 return empty_interface_type;
9034 // Return a pointer to the backend representation of the method table.
9036 Btype*
9037 Interface_type::get_backend_methods(Gogo* gogo)
9039 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9040 return this->bmethods_;
9042 Location loc = this->location();
9044 std::vector<Backend::Btyped_identifier>
9045 mfields(this->all_methods_->size() + 1);
9047 Type* pdt = Type::make_type_descriptor_ptr_type();
9048 mfields[0].name = "__type_descriptor";
9049 mfields[0].btype = pdt->get_backend(gogo);
9050 mfields[0].location = loc;
9052 std::string last_name = "";
9053 size_t i = 1;
9054 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9055 p != this->all_methods_->end();
9056 ++p, ++i)
9058 // The type of the method in Go only includes the parameters.
9059 // The actual method also has a receiver, which is always a
9060 // pointer. We need to add that pointer type here in order to
9061 // generate the correct type for the backend.
9062 Function_type* ft = p->type()->function_type();
9063 go_assert(ft->receiver() == NULL);
9065 const Typed_identifier_list* params = ft->parameters();
9066 Typed_identifier_list* mparams = new Typed_identifier_list();
9067 if (params != NULL)
9068 mparams->reserve(params->size() + 1);
9069 Type* vt = Type::make_pointer_type(Type::make_void_type());
9070 mparams->push_back(Typed_identifier("", vt, ft->location()));
9071 if (params != NULL)
9073 for (Typed_identifier_list::const_iterator pp = params->begin();
9074 pp != params->end();
9075 ++pp)
9076 mparams->push_back(*pp);
9079 Typed_identifier_list* mresults = (ft->results() == NULL
9080 ? NULL
9081 : ft->results()->copy());
9082 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9083 ft->location());
9085 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9086 mfields[i].btype = mft->get_backend_fntype(gogo);
9087 mfields[i].location = loc;
9089 // Sanity check: the names should be sorted.
9090 go_assert(Gogo::unpack_hidden_name(p->name())
9091 > Gogo::unpack_hidden_name(last_name));
9092 last_name = p->name();
9095 Btype* st = gogo->backend()->struct_type(mfields);
9096 Btype* ret = gogo->backend()->pointer_type(st);
9098 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
9099 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
9100 this->bmethods_ = ret;
9101 this->bmethods_is_placeholder_ = false;
9102 return ret;
9105 // Return a placeholder for the pointer to the backend methods table.
9107 Btype*
9108 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9110 if (this->bmethods_ == NULL)
9112 Location loc = this->location();
9113 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
9114 false);
9115 this->bmethods_is_placeholder_ = true;
9117 return this->bmethods_;
9120 // Return the fields of a non-empty interface type. This is not
9121 // declared in types.h so that types.h doesn't have to #include
9122 // backend.h.
9124 static void
9125 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9126 bool use_placeholder,
9127 std::vector<Backend::Btyped_identifier>* bfields)
9129 Location loc = type->location();
9131 bfields->resize(2);
9133 (*bfields)[0].name = "__methods";
9134 (*bfields)[0].btype = (use_placeholder
9135 ? type->get_backend_methods_placeholder(gogo)
9136 : type->get_backend_methods(gogo));
9137 (*bfields)[0].location = loc;
9139 Type* vt = Type::make_pointer_type(Type::make_void_type());
9140 (*bfields)[1].name = "__object";
9141 (*bfields)[1].btype = vt->get_backend(gogo);
9142 (*bfields)[1].location = Linemap::predeclared_location();
9145 // Return the backend representation for an interface type. An interface is a
9146 // pointer to a struct. The struct has three fields. The first field is a
9147 // pointer to the type descriptor for the dynamic type of the object.
9148 // The second field is a pointer to a table of methods for the
9149 // interface to be used with the object. The third field is the value
9150 // of the object itself.
9152 Btype*
9153 Interface_type::do_get_backend(Gogo* gogo)
9155 if (this->is_empty())
9156 return Interface_type::get_backend_empty_interface_type(gogo);
9157 else
9159 if (this->interface_btype_ != NULL)
9160 return this->interface_btype_;
9161 this->interface_btype_ =
9162 gogo->backend()->placeholder_struct_type("", this->location_);
9163 std::vector<Backend::Btyped_identifier> bfields;
9164 get_backend_interface_fields(gogo, this, false, &bfields);
9165 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9166 bfields))
9167 this->interface_btype_ = gogo->backend()->error_type();
9168 return this->interface_btype_;
9172 // Finish the backend representation of the methods.
9174 void
9175 Interface_type::finish_backend_methods(Gogo* gogo)
9177 if (!this->is_empty())
9179 const Typed_identifier_list* methods = this->methods();
9180 if (methods != NULL)
9182 for (Typed_identifier_list::const_iterator p = methods->begin();
9183 p != methods->end();
9184 ++p)
9185 p->type()->get_backend(gogo);
9188 // Getting the backend methods now will set the placeholder
9189 // pointer.
9190 this->get_backend_methods(gogo);
9194 // The type of an interface type descriptor.
9196 Type*
9197 Interface_type::make_interface_type_descriptor_type()
9199 static Type* ret;
9200 if (ret == NULL)
9202 Type* tdt = Type::make_type_descriptor_type();
9203 Type* ptdt = Type::make_type_descriptor_ptr_type();
9205 Type* string_type = Type::lookup_string_type();
9206 Type* pointer_string_type = Type::make_pointer_type(string_type);
9208 Struct_type* sm =
9209 Type::make_builtin_struct_type(3,
9210 "name", pointer_string_type,
9211 "pkgPath", pointer_string_type,
9212 "typ", ptdt);
9214 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9216 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9218 Struct_type* s = Type::make_builtin_struct_type(2,
9219 "", tdt,
9220 "methods", slice_nsm);
9222 ret = Type::make_builtin_named_type("InterfaceType", s);
9225 return ret;
9228 // Build a type descriptor for an interface type.
9230 Expression*
9231 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9233 Location bloc = Linemap::predeclared_location();
9235 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9237 const Struct_field_list* ifields = itdt->struct_type()->fields();
9239 Expression_list* ivals = new Expression_list();
9240 ivals->reserve(2);
9242 Struct_field_list::const_iterator pif = ifields->begin();
9243 go_assert(pif->is_field_name("_type"));
9244 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9245 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9246 true));
9248 ++pif;
9249 go_assert(pif->is_field_name("methods"));
9251 Expression_list* methods = new Expression_list();
9252 if (this->all_methods_ != NULL)
9254 Type* elemtype = pif->type()->array_type()->element_type();
9256 methods->reserve(this->all_methods_->size());
9257 for (Typed_identifier_list::const_iterator pm =
9258 this->all_methods_->begin();
9259 pm != this->all_methods_->end();
9260 ++pm)
9262 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9264 Expression_list* mvals = new Expression_list();
9265 mvals->reserve(3);
9267 Struct_field_list::const_iterator pmf = mfields->begin();
9268 go_assert(pmf->is_field_name("name"));
9269 std::string s = Gogo::unpack_hidden_name(pm->name());
9270 Expression* e = Expression::make_string(s, bloc);
9271 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9273 ++pmf;
9274 go_assert(pmf->is_field_name("pkgPath"));
9275 if (!Gogo::is_hidden_name(pm->name()))
9276 mvals->push_back(Expression::make_nil(bloc));
9277 else
9279 s = Gogo::hidden_name_pkgpath(pm->name());
9280 e = Expression::make_string(s, bloc);
9281 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9284 ++pmf;
9285 go_assert(pmf->is_field_name("typ"));
9286 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9288 ++pmf;
9289 go_assert(pmf == mfields->end());
9291 e = Expression::make_struct_composite_literal(elemtype, mvals,
9292 bloc);
9293 methods->push_back(e);
9297 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9298 methods, bloc));
9300 ++pif;
9301 go_assert(pif == ifields->end());
9303 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9306 // Reflection string.
9308 void
9309 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9311 ret->append("interface {");
9312 const Typed_identifier_list* methods = this->parse_methods_;
9313 if (methods != NULL)
9315 ret->push_back(' ');
9316 for (Typed_identifier_list::const_iterator p = methods->begin();
9317 p != methods->end();
9318 ++p)
9320 if (p != methods->begin())
9321 ret->append("; ");
9322 if (p->name().empty())
9323 this->append_reflection(p->type(), gogo, ret);
9324 else
9326 if (!Gogo::is_hidden_name(p->name()))
9327 ret->append(p->name());
9328 else if (gogo->pkgpath_from_option())
9329 ret->append(p->name().substr(1));
9330 else
9332 // If no -fgo-pkgpath option, backward compatibility
9333 // for how this used to work before -fgo-pkgpath was
9334 // introduced.
9335 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9336 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9337 ret->push_back('.');
9338 ret->append(Gogo::unpack_hidden_name(p->name()));
9340 std::string sub = p->type()->reflection(gogo);
9341 go_assert(sub.compare(0, 4, "func") == 0);
9342 sub = sub.substr(4);
9343 ret->append(sub);
9346 ret->push_back(' ');
9348 ret->append("}");
9351 // Export.
9353 void
9354 Interface_type::do_export(Export* exp) const
9356 exp->write_c_string("interface { ");
9358 const Typed_identifier_list* methods = this->parse_methods_;
9359 if (methods != NULL)
9361 for (Typed_identifier_list::const_iterator pm = methods->begin();
9362 pm != methods->end();
9363 ++pm)
9365 if (pm->name().empty())
9367 exp->write_c_string("? ");
9368 exp->write_type(pm->type());
9370 else
9372 exp->write_string(pm->name());
9373 exp->write_c_string(" (");
9375 const Function_type* fntype = pm->type()->function_type();
9377 bool first = true;
9378 const Typed_identifier_list* parameters = fntype->parameters();
9379 if (parameters != NULL)
9381 bool is_varargs = fntype->is_varargs();
9382 for (Typed_identifier_list::const_iterator pp =
9383 parameters->begin();
9384 pp != parameters->end();
9385 ++pp)
9387 if (first)
9388 first = false;
9389 else
9390 exp->write_c_string(", ");
9391 exp->write_name(pp->name());
9392 exp->write_c_string(" ");
9393 if (!is_varargs || pp + 1 != parameters->end())
9394 exp->write_type(pp->type());
9395 else
9397 exp->write_c_string("...");
9398 Type *pptype = pp->type();
9399 exp->write_type(pptype->array_type()->element_type());
9404 exp->write_c_string(")");
9406 const Typed_identifier_list* results = fntype->results();
9407 if (results != NULL)
9409 exp->write_c_string(" ");
9410 if (results->size() == 1 && results->begin()->name().empty())
9411 exp->write_type(results->begin()->type());
9412 else
9414 first = true;
9415 exp->write_c_string("(");
9416 for (Typed_identifier_list::const_iterator p =
9417 results->begin();
9418 p != results->end();
9419 ++p)
9421 if (first)
9422 first = false;
9423 else
9424 exp->write_c_string(", ");
9425 exp->write_name(p->name());
9426 exp->write_c_string(" ");
9427 exp->write_type(p->type());
9429 exp->write_c_string(")");
9434 exp->write_c_string("; ");
9438 exp->write_c_string("}");
9441 // Import an interface type.
9443 Interface_type*
9444 Interface_type::do_import(Import* imp)
9446 imp->require_c_string("interface { ");
9448 Typed_identifier_list* methods = new Typed_identifier_list;
9449 while (imp->peek_char() != '}')
9451 std::string name = imp->read_identifier();
9453 if (name == "?")
9455 imp->require_c_string(" ");
9456 Type* t = imp->read_type();
9457 methods->push_back(Typed_identifier("", t, imp->location()));
9458 imp->require_c_string("; ");
9459 continue;
9462 imp->require_c_string(" (");
9464 Typed_identifier_list* parameters;
9465 bool is_varargs = false;
9466 if (imp->peek_char() == ')')
9467 parameters = NULL;
9468 else
9470 parameters = new Typed_identifier_list;
9471 while (true)
9473 std::string name = imp->read_name();
9474 imp->require_c_string(" ");
9476 if (imp->match_c_string("..."))
9478 imp->advance(3);
9479 is_varargs = true;
9482 Type* ptype = imp->read_type();
9483 if (is_varargs)
9484 ptype = Type::make_array_type(ptype, NULL);
9485 parameters->push_back(Typed_identifier(name, ptype,
9486 imp->location()));
9487 if (imp->peek_char() != ',')
9488 break;
9489 go_assert(!is_varargs);
9490 imp->require_c_string(", ");
9493 imp->require_c_string(")");
9495 Typed_identifier_list* results;
9496 if (imp->peek_char() != ' ')
9497 results = NULL;
9498 else
9500 results = new Typed_identifier_list;
9501 imp->advance(1);
9502 if (imp->peek_char() != '(')
9504 Type* rtype = imp->read_type();
9505 results->push_back(Typed_identifier("", rtype, imp->location()));
9507 else
9509 imp->advance(1);
9510 while (true)
9512 std::string name = imp->read_name();
9513 imp->require_c_string(" ");
9514 Type* rtype = imp->read_type();
9515 results->push_back(Typed_identifier(name, rtype,
9516 imp->location()));
9517 if (imp->peek_char() != ',')
9518 break;
9519 imp->require_c_string(", ");
9521 imp->require_c_string(")");
9525 Function_type* fntype = Type::make_function_type(NULL, parameters,
9526 results,
9527 imp->location());
9528 if (is_varargs)
9529 fntype->set_is_varargs();
9530 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9532 imp->require_c_string("; ");
9535 imp->require_c_string("}");
9537 if (methods->empty())
9539 delete methods;
9540 methods = NULL;
9543 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9544 ret->package_ = imp->package();
9545 return ret;
9548 // Make an interface type.
9550 Interface_type*
9551 Type::make_interface_type(Typed_identifier_list* methods,
9552 Location location)
9554 return new Interface_type(methods, location);
9557 // Make an empty interface type.
9559 Interface_type*
9560 Type::make_empty_interface_type(Location location)
9562 Interface_type* ret = new Interface_type(NULL, location);
9563 ret->finalize_methods();
9564 return ret;
9567 // Class Method.
9569 // Bind a method to an object.
9571 Expression*
9572 Method::bind_method(Expression* expr, Location location) const
9574 if (this->stub_ == NULL)
9576 // When there is no stub object, the binding is determined by
9577 // the child class.
9578 return this->do_bind_method(expr, location);
9580 return Expression::make_bound_method(expr, this, this->stub_, location);
9583 // Return the named object associated with a method. This may only be
9584 // called after methods are finalized.
9586 Named_object*
9587 Method::named_object() const
9589 if (this->stub_ != NULL)
9590 return this->stub_;
9591 return this->do_named_object();
9594 // Class Named_method.
9596 // The type of the method.
9598 Function_type*
9599 Named_method::do_type() const
9601 if (this->named_object_->is_function())
9602 return this->named_object_->func_value()->type();
9603 else if (this->named_object_->is_function_declaration())
9604 return this->named_object_->func_declaration_value()->type();
9605 else
9606 go_unreachable();
9609 // Return the location of the method receiver.
9611 Location
9612 Named_method::do_receiver_location() const
9614 return this->do_type()->receiver()->location();
9617 // Bind a method to an object.
9619 Expression*
9620 Named_method::do_bind_method(Expression* expr, Location location) const
9622 Named_object* no = this->named_object_;
9623 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9624 no, location);
9625 // If this is not a local method, and it does not use a stub, then
9626 // the real method expects a different type. We need to cast the
9627 // first argument.
9628 if (this->depth() > 0 && !this->needs_stub_method())
9630 Function_type* ftype = this->do_type();
9631 go_assert(ftype->is_method());
9632 Type* frtype = ftype->receiver()->type();
9633 bme->set_first_argument_type(frtype);
9635 return bme;
9638 // Return whether this method should not participate in interfaces.
9640 bool
9641 Named_method::do_nointerface() const
9643 Named_object* no = this->named_object_;
9644 return no->is_function() && no->func_value()->nointerface();
9647 // Class Interface_method.
9649 // Bind a method to an object.
9651 Expression*
9652 Interface_method::do_bind_method(Expression* expr,
9653 Location location) const
9655 return Expression::make_interface_field_reference(expr, this->name_,
9656 location);
9659 // Class Methods.
9661 // Insert a new method. Return true if it was inserted, false
9662 // otherwise.
9664 bool
9665 Methods::insert(const std::string& name, Method* m)
9667 std::pair<Method_map::iterator, bool> ins =
9668 this->methods_.insert(std::make_pair(name, m));
9669 if (ins.second)
9670 return true;
9671 else
9673 Method* old_method = ins.first->second;
9674 if (m->depth() < old_method->depth())
9676 delete old_method;
9677 ins.first->second = m;
9678 return true;
9680 else
9682 if (m->depth() == old_method->depth())
9683 old_method->set_is_ambiguous();
9684 return false;
9689 // Return the number of unambiguous methods.
9691 size_t
9692 Methods::count() const
9694 size_t ret = 0;
9695 for (Method_map::const_iterator p = this->methods_.begin();
9696 p != this->methods_.end();
9697 ++p)
9698 if (!p->second->is_ambiguous())
9699 ++ret;
9700 return ret;
9703 // Class Named_type.
9705 // Return the name of the type.
9707 const std::string&
9708 Named_type::name() const
9710 return this->named_object_->name();
9713 // Return the name of the type to use in an error message.
9715 std::string
9716 Named_type::message_name() const
9718 return this->named_object_->message_name();
9721 // Return the base type for this type. We have to be careful about
9722 // circular type definitions, which are invalid but may be seen here.
9724 Type*
9725 Named_type::named_base()
9727 if (this->seen_)
9728 return this;
9729 this->seen_ = true;
9730 Type* ret = this->type_->base();
9731 this->seen_ = false;
9732 return ret;
9735 const Type*
9736 Named_type::named_base() const
9738 if (this->seen_)
9739 return this;
9740 this->seen_ = true;
9741 const Type* ret = this->type_->base();
9742 this->seen_ = false;
9743 return ret;
9746 // Return whether this is an error type. We have to be careful about
9747 // circular type definitions, which are invalid but may be seen here.
9749 bool
9750 Named_type::is_named_error_type() const
9752 if (this->seen_)
9753 return false;
9754 this->seen_ = true;
9755 bool ret = this->type_->is_error_type();
9756 this->seen_ = false;
9757 return ret;
9760 // Whether this type is comparable. We have to be careful about
9761 // circular type definitions.
9763 bool
9764 Named_type::named_type_is_comparable(std::string* reason) const
9766 if (this->seen_)
9767 return false;
9768 this->seen_ = true;
9769 bool ret = Type::are_compatible_for_comparison(true, this->type_,
9770 this->type_, reason);
9771 this->seen_ = false;
9772 return ret;
9775 // Add a method to this type.
9777 Named_object*
9778 Named_type::add_method(const std::string& name, Function* function)
9780 go_assert(!this->is_alias_);
9781 if (this->local_methods_ == NULL)
9782 this->local_methods_ = new Bindings(NULL);
9783 return this->local_methods_->add_function(name, NULL, function);
9786 // Add a method declaration to this type.
9788 Named_object*
9789 Named_type::add_method_declaration(const std::string& name, Package* package,
9790 Function_type* type,
9791 Location location)
9793 go_assert(!this->is_alias_);
9794 if (this->local_methods_ == NULL)
9795 this->local_methods_ = new Bindings(NULL);
9796 return this->local_methods_->add_function_declaration(name, package, type,
9797 location);
9800 // Add an existing method to this type.
9802 void
9803 Named_type::add_existing_method(Named_object* no)
9805 go_assert(!this->is_alias_);
9806 if (this->local_methods_ == NULL)
9807 this->local_methods_ = new Bindings(NULL);
9808 this->local_methods_->add_named_object(no);
9811 // Look for a local method NAME, and returns its named object, or NULL
9812 // if not there.
9814 Named_object*
9815 Named_type::find_local_method(const std::string& name) const
9817 if (this->is_error_)
9818 return NULL;
9819 if (this->is_alias_)
9821 Named_type* nt = this->type_->named_type();
9822 if (nt != NULL)
9824 if (this->seen_alias_)
9825 return NULL;
9826 this->seen_alias_ = true;
9827 Named_object* ret = nt->find_local_method(name);
9828 this->seen_alias_ = false;
9829 return ret;
9831 return NULL;
9833 if (this->local_methods_ == NULL)
9834 return NULL;
9835 return this->local_methods_->lookup(name);
9838 // Return the list of local methods.
9840 const Bindings*
9841 Named_type::local_methods() const
9843 if (this->is_error_)
9844 return NULL;
9845 if (this->is_alias_)
9847 Named_type* nt = this->type_->named_type();
9848 if (nt != NULL)
9850 if (this->seen_alias_)
9851 return NULL;
9852 this->seen_alias_ = true;
9853 const Bindings* ret = nt->local_methods();
9854 this->seen_alias_ = false;
9855 return ret;
9857 return NULL;
9859 return this->local_methods_;
9862 // Return whether NAME is an unexported field or method, for better
9863 // error reporting.
9865 bool
9866 Named_type::is_unexported_local_method(Gogo* gogo,
9867 const std::string& name) const
9869 if (this->is_error_)
9870 return false;
9871 if (this->is_alias_)
9873 Named_type* nt = this->type_->named_type();
9874 if (nt != NULL)
9876 if (this->seen_alias_)
9877 return false;
9878 this->seen_alias_ = true;
9879 bool ret = nt->is_unexported_local_method(gogo, name);
9880 this->seen_alias_ = false;
9881 return ret;
9883 return false;
9885 Bindings* methods = this->local_methods_;
9886 if (methods != NULL)
9888 for (Bindings::const_declarations_iterator p =
9889 methods->begin_declarations();
9890 p != methods->end_declarations();
9891 ++p)
9893 if (Gogo::is_hidden_name(p->first)
9894 && name == Gogo::unpack_hidden_name(p->first)
9895 && gogo->pack_hidden_name(name, false) != p->first)
9896 return true;
9899 return false;
9902 // Build the complete list of methods for this type, which means
9903 // recursively including all methods for anonymous fields. Create all
9904 // stub methods.
9906 void
9907 Named_type::finalize_methods(Gogo* gogo)
9909 if (this->is_alias_)
9910 return;
9911 if (this->all_methods_ != NULL)
9912 return;
9914 if (this->local_methods_ != NULL
9915 && (this->points_to() != NULL || this->interface_type() != NULL))
9917 const Bindings* lm = this->local_methods_;
9918 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
9919 p != lm->end_declarations();
9920 ++p)
9921 go_error_at(p->second->location(),
9922 "invalid pointer or interface receiver type");
9923 delete this->local_methods_;
9924 this->local_methods_ = NULL;
9925 return;
9928 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
9931 // Return whether this type has any methods.
9933 bool
9934 Named_type::has_any_methods() const
9936 if (this->is_error_)
9937 return false;
9938 if (this->is_alias_)
9940 if (this->type_->named_type() != NULL)
9942 if (this->seen_alias_)
9943 return false;
9944 this->seen_alias_ = true;
9945 bool ret = this->type_->named_type()->has_any_methods();
9946 this->seen_alias_ = false;
9947 return ret;
9949 if (this->type_->struct_type() != NULL)
9950 return this->type_->struct_type()->has_any_methods();
9951 return false;
9953 return this->all_methods_ != NULL;
9956 // Return the methods for this type.
9958 const Methods*
9959 Named_type::methods() const
9961 if (this->is_error_)
9962 return NULL;
9963 if (this->is_alias_)
9965 if (this->type_->named_type() != NULL)
9967 if (this->seen_alias_)
9968 return NULL;
9969 this->seen_alias_ = true;
9970 const Methods* ret = this->type_->named_type()->methods();
9971 this->seen_alias_ = false;
9972 return ret;
9974 if (this->type_->struct_type() != NULL)
9975 return this->type_->struct_type()->methods();
9976 return NULL;
9978 return this->all_methods_;
9981 // Return the method NAME, or NULL if there isn't one or if it is
9982 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
9983 // ambiguous.
9985 Method*
9986 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
9988 if (this->is_error_)
9989 return NULL;
9990 if (this->is_alias_)
9992 if (is_ambiguous != NULL)
9993 *is_ambiguous = false;
9994 if (this->type_->named_type() != NULL)
9996 if (this->seen_alias_)
9997 return NULL;
9998 this->seen_alias_ = true;
9999 Named_type* nt = this->type_->named_type();
10000 Method* ret = nt->method_function(name, is_ambiguous);
10001 this->seen_alias_ = false;
10002 return ret;
10004 if (this->type_->struct_type() != NULL)
10005 return this->type_->struct_type()->method_function(name, is_ambiguous);
10006 return NULL;
10008 return Type::method_function(this->all_methods_, name, is_ambiguous);
10011 // Return a pointer to the interface method table for this type for
10012 // the interface INTERFACE. IS_POINTER is true if this is for a
10013 // pointer to THIS.
10015 Expression*
10016 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10018 if (this->is_error_)
10019 return Expression::make_error(this->location_);
10020 if (this->is_alias_)
10022 if (this->type_->named_type() != NULL)
10024 if (this->seen_alias_)
10025 return Expression::make_error(this->location_);
10026 this->seen_alias_ = true;
10027 Named_type* nt = this->type_->named_type();
10028 Expression* ret = nt->interface_method_table(interface, is_pointer);
10029 this->seen_alias_ = false;
10030 return ret;
10032 if (this->type_->struct_type() != NULL)
10033 return this->type_->struct_type()->interface_method_table(interface,
10034 is_pointer);
10035 go_unreachable();
10037 return Type::interface_method_table(this, interface, is_pointer,
10038 &this->interface_method_tables_,
10039 &this->pointer_interface_method_tables_);
10042 // Look for a use of a complete type within another type. This is
10043 // used to check that we don't try to use a type within itself.
10045 class Find_type_use : public Traverse
10047 public:
10048 Find_type_use(Named_type* find_type)
10049 : Traverse(traverse_types),
10050 find_type_(find_type), found_(false)
10053 // Whether we found the type.
10054 bool
10055 found() const
10056 { return this->found_; }
10058 protected:
10060 type(Type*);
10062 private:
10063 // The type we are looking for.
10064 Named_type* find_type_;
10065 // Whether we found the type.
10066 bool found_;
10069 // Check for FIND_TYPE in TYPE.
10072 Find_type_use::type(Type* type)
10074 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10076 this->found_ = true;
10077 return TRAVERSE_EXIT;
10080 // It's OK if we see a reference to the type in any type which is
10081 // essentially a pointer: a pointer, a slice, a function, a map, or
10082 // a channel.
10083 if (type->points_to() != NULL
10084 || type->is_slice_type()
10085 || type->function_type() != NULL
10086 || type->map_type() != NULL
10087 || type->channel_type() != NULL)
10088 return TRAVERSE_SKIP_COMPONENTS;
10090 // For an interface, a reference to the type in a method type should
10091 // be ignored, but we have to consider direct inheritance. When
10092 // this is called, there may be cases of direct inheritance
10093 // represented as a method with no name.
10094 if (type->interface_type() != NULL)
10096 const Typed_identifier_list* methods = type->interface_type()->methods();
10097 if (methods != NULL)
10099 for (Typed_identifier_list::const_iterator p = methods->begin();
10100 p != methods->end();
10101 ++p)
10103 if (p->name().empty())
10105 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10106 return TRAVERSE_EXIT;
10110 return TRAVERSE_SKIP_COMPONENTS;
10113 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10114 // to convert TYPE to the backend representation before we convert
10115 // FIND_TYPE_.
10116 if (type->named_type() != NULL)
10118 switch (type->base()->classification())
10120 case Type::TYPE_ERROR:
10121 case Type::TYPE_BOOLEAN:
10122 case Type::TYPE_INTEGER:
10123 case Type::TYPE_FLOAT:
10124 case Type::TYPE_COMPLEX:
10125 case Type::TYPE_STRING:
10126 case Type::TYPE_NIL:
10127 break;
10129 case Type::TYPE_ARRAY:
10130 case Type::TYPE_STRUCT:
10131 this->find_type_->add_dependency(type->named_type());
10132 break;
10134 case Type::TYPE_NAMED:
10135 case Type::TYPE_FORWARD:
10136 go_assert(saw_errors());
10137 break;
10139 case Type::TYPE_VOID:
10140 case Type::TYPE_SINK:
10141 case Type::TYPE_FUNCTION:
10142 case Type::TYPE_POINTER:
10143 case Type::TYPE_CALL_MULTIPLE_RESULT:
10144 case Type::TYPE_MAP:
10145 case Type::TYPE_CHANNEL:
10146 case Type::TYPE_INTERFACE:
10147 default:
10148 go_unreachable();
10152 return TRAVERSE_CONTINUE;
10155 // Look for a circular reference of an alias.
10157 class Find_alias : public Traverse
10159 public:
10160 Find_alias(Named_type* find_type)
10161 : Traverse(traverse_types),
10162 find_type_(find_type), found_(false)
10165 // Whether we found the type.
10166 bool
10167 found() const
10168 { return this->found_; }
10170 protected:
10172 type(Type*);
10174 private:
10175 // The type we are looking for.
10176 Named_type* find_type_;
10177 // Whether we found the type.
10178 bool found_;
10182 Find_alias::type(Type* type)
10184 Named_type* nt = type->named_type();
10185 if (nt != NULL)
10187 if (nt == this->find_type_)
10189 this->found_ = true;
10190 return TRAVERSE_EXIT;
10193 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10194 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10195 // an alias itself, it's OK if whatever T2 is defined as refers
10196 // to T1.
10197 if (!nt->is_alias())
10198 return TRAVERSE_SKIP_COMPONENTS;
10201 return TRAVERSE_CONTINUE;
10204 // Verify that a named type does not refer to itself.
10206 bool
10207 Named_type::do_verify()
10209 if (this->is_verified_)
10210 return true;
10211 this->is_verified_ = true;
10213 if (this->is_error_)
10214 return false;
10216 if (this->is_alias_)
10218 Find_alias find(this);
10219 Type::traverse(this->type_, &find);
10220 if (find.found())
10222 go_error_at(this->location_, "invalid recursive alias %qs",
10223 this->message_name().c_str());
10224 this->is_error_ = true;
10225 return false;
10229 Find_type_use find(this);
10230 Type::traverse(this->type_, &find);
10231 if (find.found())
10233 go_error_at(this->location_, "invalid recursive type %qs",
10234 this->message_name().c_str());
10235 this->is_error_ = true;
10236 return false;
10239 // Check whether any of the local methods overloads an existing
10240 // struct field or interface method. We don't need to check the
10241 // list of methods against itself: that is handled by the Bindings
10242 // code.
10243 if (this->local_methods_ != NULL)
10245 Struct_type* st = this->type_->struct_type();
10246 if (st != NULL)
10248 for (Bindings::const_declarations_iterator p =
10249 this->local_methods_->begin_declarations();
10250 p != this->local_methods_->end_declarations();
10251 ++p)
10253 const std::string& name(p->first);
10254 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10256 go_error_at(p->second->location(),
10257 "method %qs redeclares struct field name",
10258 Gogo::message_name(name).c_str());
10264 return true;
10267 // Return whether this type is or contains a pointer.
10269 bool
10270 Named_type::do_has_pointer() const
10272 if (this->seen_)
10273 return false;
10274 this->seen_ = true;
10275 bool ret = this->type_->has_pointer();
10276 this->seen_ = false;
10277 return ret;
10280 // Return whether comparisons for this type can use the identity
10281 // function.
10283 bool
10284 Named_type::do_compare_is_identity(Gogo* gogo)
10286 // We don't use this->seen_ here because compare_is_identity may
10287 // call base() later, and that will mess up if seen_ is set here.
10288 if (this->seen_in_compare_is_identity_)
10289 return false;
10290 this->seen_in_compare_is_identity_ = true;
10291 bool ret = this->type_->compare_is_identity(gogo);
10292 this->seen_in_compare_is_identity_ = false;
10293 return ret;
10296 // Return whether this type is reflexive--whether it is always equal
10297 // to itself.
10299 bool
10300 Named_type::do_is_reflexive()
10302 if (this->seen_in_compare_is_identity_)
10303 return false;
10304 this->seen_in_compare_is_identity_ = true;
10305 bool ret = this->type_->is_reflexive();
10306 this->seen_in_compare_is_identity_ = false;
10307 return ret;
10310 // Return whether this type needs a key update when used as a map key.
10312 bool
10313 Named_type::do_needs_key_update()
10315 if (this->seen_in_compare_is_identity_)
10316 return true;
10317 this->seen_in_compare_is_identity_ = true;
10318 bool ret = this->type_->needs_key_update();
10319 this->seen_in_compare_is_identity_ = false;
10320 return ret;
10323 // Return a hash code. This is used for method lookup. We simply
10324 // hash on the name itself.
10326 unsigned int
10327 Named_type::do_hash_for_method(Gogo* gogo) const
10329 if (this->is_error_)
10330 return 0;
10332 // Aliases are handled in Type::hash_for_method.
10333 go_assert(!this->is_alias_);
10335 const std::string& name(this->named_object()->name());
10336 unsigned int ret = Type::hash_string(name, 0);
10338 // GOGO will be NULL here when called from Type_hash_identical.
10339 // That is OK because that is only used for internal hash tables
10340 // where we are going to be comparing named types for equality. In
10341 // other cases, which are cases where the runtime is going to
10342 // compare hash codes to see if the types are the same, we need to
10343 // include the pkgpath in the hash.
10344 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10346 const Package* package = this->named_object()->package();
10347 if (package == NULL)
10348 ret = Type::hash_string(gogo->pkgpath(), ret);
10349 else
10350 ret = Type::hash_string(package->pkgpath(), ret);
10353 return ret;
10356 // Convert a named type to the backend representation. In order to
10357 // get dependencies right, we fill in a dummy structure for this type,
10358 // then convert all the dependencies, then complete this type. When
10359 // this function is complete, the size of the type is known.
10361 void
10362 Named_type::convert(Gogo* gogo)
10364 if (this->is_error_ || this->is_converted_)
10365 return;
10367 this->create_placeholder(gogo);
10369 // If we are called to turn unsafe.Sizeof into a constant, we may
10370 // not have verified the type yet. We have to make sure it is
10371 // verified, since that sets the list of dependencies.
10372 this->verify();
10374 // Convert all the dependencies. If they refer indirectly back to
10375 // this type, they will pick up the intermediate representation we just
10376 // created.
10377 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10378 p != this->dependencies_.end();
10379 ++p)
10380 (*p)->convert(gogo);
10382 // Complete this type.
10383 Btype* bt = this->named_btype_;
10384 Type* base = this->type_->base();
10385 switch (base->classification())
10387 case TYPE_VOID:
10388 case TYPE_BOOLEAN:
10389 case TYPE_INTEGER:
10390 case TYPE_FLOAT:
10391 case TYPE_COMPLEX:
10392 case TYPE_STRING:
10393 case TYPE_NIL:
10394 break;
10396 case TYPE_MAP:
10397 case TYPE_CHANNEL:
10398 break;
10400 case TYPE_FUNCTION:
10401 case TYPE_POINTER:
10402 // The size of these types is already correct. We don't worry
10403 // about filling them in until later, when we also track
10404 // circular references.
10405 break;
10407 case TYPE_STRUCT:
10409 std::vector<Backend::Btyped_identifier> bfields;
10410 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10411 true, &bfields);
10412 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10413 bt = gogo->backend()->error_type();
10415 break;
10417 case TYPE_ARRAY:
10418 // Slice types were completed in create_placeholder.
10419 if (!base->is_slice_type())
10421 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10422 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10423 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10424 bt = gogo->backend()->error_type();
10426 break;
10428 case TYPE_INTERFACE:
10429 // Interface types were completed in create_placeholder.
10430 break;
10432 case TYPE_ERROR:
10433 return;
10435 default:
10436 case TYPE_SINK:
10437 case TYPE_CALL_MULTIPLE_RESULT:
10438 case TYPE_NAMED:
10439 case TYPE_FORWARD:
10440 go_unreachable();
10443 this->named_btype_ = bt;
10444 this->is_converted_ = true;
10445 this->is_placeholder_ = false;
10448 // Create the placeholder for a named type. This is the first step in
10449 // converting to the backend representation.
10451 void
10452 Named_type::create_placeholder(Gogo* gogo)
10454 if (this->is_error_)
10455 this->named_btype_ = gogo->backend()->error_type();
10457 if (this->named_btype_ != NULL)
10458 return;
10460 // Create the structure for this type. Note that because we call
10461 // base() here, we don't attempt to represent a named type defined
10462 // as another named type. Instead both named types will point to
10463 // different base representations.
10464 Type* base = this->type_->base();
10465 Btype* bt;
10466 bool set_name = true;
10467 switch (base->classification())
10469 case TYPE_ERROR:
10470 this->is_error_ = true;
10471 this->named_btype_ = gogo->backend()->error_type();
10472 return;
10474 case TYPE_VOID:
10475 case TYPE_BOOLEAN:
10476 case TYPE_INTEGER:
10477 case TYPE_FLOAT:
10478 case TYPE_COMPLEX:
10479 case TYPE_STRING:
10480 case TYPE_NIL:
10481 // These are simple basic types, we can just create them
10482 // directly.
10483 bt = Type::get_named_base_btype(gogo, base);
10484 break;
10486 case TYPE_MAP:
10487 case TYPE_CHANNEL:
10488 // All maps and channels have the same backend representation.
10489 bt = Type::get_named_base_btype(gogo, base);
10490 break;
10492 case TYPE_FUNCTION:
10493 case TYPE_POINTER:
10495 bool for_function = base->classification() == TYPE_FUNCTION;
10496 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10497 this->location_,
10498 for_function);
10499 set_name = false;
10501 break;
10503 case TYPE_STRUCT:
10504 bt = gogo->backend()->placeholder_struct_type(this->name(),
10505 this->location_);
10506 this->is_placeholder_ = true;
10507 set_name = false;
10508 break;
10510 case TYPE_ARRAY:
10511 if (base->is_slice_type())
10512 bt = gogo->backend()->placeholder_struct_type(this->name(),
10513 this->location_);
10514 else
10516 bt = gogo->backend()->placeholder_array_type(this->name(),
10517 this->location_);
10518 this->is_placeholder_ = true;
10520 set_name = false;
10521 break;
10523 case TYPE_INTERFACE:
10524 if (base->interface_type()->is_empty())
10525 bt = Interface_type::get_backend_empty_interface_type(gogo);
10526 else
10528 bt = gogo->backend()->placeholder_struct_type(this->name(),
10529 this->location_);
10530 set_name = false;
10532 break;
10534 default:
10535 case TYPE_SINK:
10536 case TYPE_CALL_MULTIPLE_RESULT:
10537 case TYPE_NAMED:
10538 case TYPE_FORWARD:
10539 go_unreachable();
10542 if (set_name)
10543 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10545 this->named_btype_ = bt;
10547 if (base->is_slice_type())
10549 // We do not record slices as dependencies of other types,
10550 // because we can fill them in completely here with the final
10551 // size.
10552 std::vector<Backend::Btyped_identifier> bfields;
10553 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10554 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10555 this->named_btype_ = gogo->backend()->error_type();
10557 else if (base->interface_type() != NULL
10558 && !base->interface_type()->is_empty())
10560 // We do not record interfaces as dependencies of other types,
10561 // because we can fill them in completely here with the final
10562 // size.
10563 std::vector<Backend::Btyped_identifier> bfields;
10564 get_backend_interface_fields(gogo, base->interface_type(), true,
10565 &bfields);
10566 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10567 this->named_btype_ = gogo->backend()->error_type();
10571 // Get the backend representation for a named type.
10573 Btype*
10574 Named_type::do_get_backend(Gogo* gogo)
10576 if (this->is_error_)
10577 return gogo->backend()->error_type();
10579 Btype* bt = this->named_btype_;
10581 if (!gogo->named_types_are_converted())
10583 // We have not completed converting named types. NAMED_BTYPE_
10584 // is a placeholder and we shouldn't do anything further.
10585 if (bt != NULL)
10586 return bt;
10588 // We don't build dependencies for types whose sizes do not
10589 // change or are not relevant, so we may see them here while
10590 // converting types.
10591 this->create_placeholder(gogo);
10592 bt = this->named_btype_;
10593 go_assert(bt != NULL);
10594 return bt;
10597 // We are not converting types. This should only be called if the
10598 // type has already been converted.
10599 if (!this->is_converted_)
10601 go_assert(saw_errors());
10602 return gogo->backend()->error_type();
10605 go_assert(bt != NULL);
10607 // Complete the backend representation.
10608 Type* base = this->type_->base();
10609 Btype* bt1;
10610 switch (base->classification())
10612 case TYPE_ERROR:
10613 return gogo->backend()->error_type();
10615 case TYPE_VOID:
10616 case TYPE_BOOLEAN:
10617 case TYPE_INTEGER:
10618 case TYPE_FLOAT:
10619 case TYPE_COMPLEX:
10620 case TYPE_STRING:
10621 case TYPE_NIL:
10622 case TYPE_MAP:
10623 case TYPE_CHANNEL:
10624 return bt;
10626 case TYPE_STRUCT:
10627 if (!this->seen_in_get_backend_)
10629 this->seen_in_get_backend_ = true;
10630 base->struct_type()->finish_backend_fields(gogo);
10631 this->seen_in_get_backend_ = false;
10633 return bt;
10635 case TYPE_ARRAY:
10636 if (!this->seen_in_get_backend_)
10638 this->seen_in_get_backend_ = true;
10639 base->array_type()->finish_backend_element(gogo);
10640 this->seen_in_get_backend_ = false;
10642 return bt;
10644 case TYPE_INTERFACE:
10645 if (!this->seen_in_get_backend_)
10647 this->seen_in_get_backend_ = true;
10648 base->interface_type()->finish_backend_methods(gogo);
10649 this->seen_in_get_backend_ = false;
10651 return bt;
10653 case TYPE_FUNCTION:
10654 // Don't build a circular data structure. GENERIC can't handle
10655 // it.
10656 if (this->seen_in_get_backend_)
10658 this->is_circular_ = true;
10659 return gogo->backend()->circular_pointer_type(bt, true);
10661 this->seen_in_get_backend_ = true;
10662 bt1 = Type::get_named_base_btype(gogo, base);
10663 this->seen_in_get_backend_ = false;
10664 if (this->is_circular_)
10665 bt1 = gogo->backend()->circular_pointer_type(bt, true);
10666 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10667 bt = gogo->backend()->error_type();
10668 return bt;
10670 case TYPE_POINTER:
10671 // Don't build a circular data structure. GENERIC can't handle
10672 // it.
10673 if (this->seen_in_get_backend_)
10675 this->is_circular_ = true;
10676 return gogo->backend()->circular_pointer_type(bt, false);
10678 this->seen_in_get_backend_ = true;
10679 bt1 = Type::get_named_base_btype(gogo, base);
10680 this->seen_in_get_backend_ = false;
10681 if (this->is_circular_)
10682 bt1 = gogo->backend()->circular_pointer_type(bt, false);
10683 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10684 bt = gogo->backend()->error_type();
10685 return bt;
10687 default:
10688 case TYPE_SINK:
10689 case TYPE_CALL_MULTIPLE_RESULT:
10690 case TYPE_NAMED:
10691 case TYPE_FORWARD:
10692 go_unreachable();
10695 go_unreachable();
10698 // Build a type descriptor for a named type.
10700 Expression*
10701 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10703 if (this->is_error_)
10704 return Expression::make_error(this->location_);
10705 if (name == NULL && this->is_alias_)
10707 if (this->seen_alias_)
10708 return Expression::make_error(this->location_);
10709 this->seen_alias_ = true;
10710 Expression* ret = this->type_->type_descriptor(gogo, NULL);
10711 this->seen_alias_ = false;
10712 return ret;
10715 // If NAME is not NULL, then we don't really want the type
10716 // descriptor for this type; we want the descriptor for the
10717 // underlying type, giving it the name NAME.
10718 return this->named_type_descriptor(gogo, this->type_,
10719 name == NULL ? this : name);
10722 // Add to the reflection string. This is used mostly for the name of
10723 // the type used in a type descriptor, not for actual reflection
10724 // strings.
10726 void
10727 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10729 this->append_reflection_type_name(gogo, false, ret);
10732 // Add to the reflection string. For an alias we normally use the
10733 // real name, but if USE_ALIAS is true we use the alias name itself.
10735 void
10736 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10737 std::string* ret) const
10739 if (this->is_error_)
10740 return;
10741 if (this->is_alias_ && !use_alias)
10743 if (this->seen_alias_)
10744 return;
10745 this->seen_alias_ = true;
10746 this->append_reflection(this->type_, gogo, ret);
10747 this->seen_alias_ = false;
10748 return;
10750 if (!this->is_builtin())
10752 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10753 // make a unique reflection string, so that the type
10754 // canonicalization in the reflect package will work. In order
10755 // to be compatible with the gc compiler, we put tabs into the
10756 // package path, so that the reflect methods can discard it.
10757 const Package* package = this->named_object_->package();
10758 ret->push_back('\t');
10759 ret->append(package != NULL
10760 ? package->pkgpath_symbol()
10761 : gogo->pkgpath_symbol());
10762 ret->push_back('\t');
10763 ret->append(package != NULL
10764 ? package->package_name()
10765 : gogo->package_name());
10766 ret->push_back('.');
10768 if (this->in_function_ != NULL)
10770 ret->push_back('\t');
10771 const Typed_identifier* rcvr =
10772 this->in_function_->func_value()->type()->receiver();
10773 if (rcvr != NULL)
10775 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10776 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10777 ret->push_back('.');
10779 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10780 ret->push_back('$');
10781 if (this->in_function_index_ > 0)
10783 char buf[30];
10784 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10785 ret->append(buf);
10786 ret->push_back('$');
10788 ret->push_back('\t');
10790 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10793 // Export the type. This is called to export a global type.
10795 void
10796 Named_type::export_named_type(Export* exp, const std::string&) const
10798 // We don't need to write the name of the type here, because it will
10799 // be written by Export::write_type anyhow.
10800 exp->write_c_string("type ");
10801 exp->write_type(this);
10802 exp->write_c_string(";\n");
10805 // Import a named type.
10807 void
10808 Named_type::import_named_type(Import* imp, Named_type** ptype)
10810 imp->require_c_string("type ");
10811 Type *type = imp->read_type();
10812 *ptype = type->named_type();
10813 go_assert(*ptype != NULL);
10814 imp->require_c_string(";\n");
10817 // Export the type when it is referenced by another type. In this
10818 // case Export::export_type will already have issued the name.
10820 void
10821 Named_type::do_export(Export* exp) const
10823 exp->write_type(this->type_);
10825 // To save space, we only export the methods directly attached to
10826 // this type.
10827 Bindings* methods = this->local_methods_;
10828 if (methods == NULL)
10829 return;
10831 exp->write_c_string("\n");
10832 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10833 p != methods->end_definitions();
10834 ++p)
10836 exp->write_c_string(" ");
10837 (*p)->export_named_object(exp);
10840 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10841 p != methods->end_declarations();
10842 ++p)
10844 if (p->second->is_function_declaration())
10846 exp->write_c_string(" ");
10847 p->second->export_named_object(exp);
10852 // Make a named type.
10854 Named_type*
10855 Type::make_named_type(Named_object* named_object, Type* type,
10856 Location location)
10858 return new Named_type(named_object, type, location);
10861 // Finalize the methods for TYPE. It will be a named type or a struct
10862 // type. This sets *ALL_METHODS to the list of methods, and builds
10863 // all required stubs.
10865 void
10866 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10867 Methods** all_methods)
10869 *all_methods = new Methods();
10870 std::vector<const Named_type*> seen;
10871 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10872 if ((*all_methods)->empty())
10874 delete *all_methods;
10875 *all_methods = NULL;
10877 Type::build_stub_methods(gogo, type, *all_methods, location);
10880 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
10881 // build up the struct field indexes as we go. DEPTH is the depth of
10882 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
10883 // adding these methods for an anonymous field with pointer type.
10884 // NEEDS_STUB_METHOD is true if we need to use a stub method which
10885 // calls the real method. TYPES_SEEN is used to avoid infinite
10886 // recursion.
10888 void
10889 Type::add_methods_for_type(const Type* type,
10890 const Method::Field_indexes* field_indexes,
10891 unsigned int depth,
10892 bool is_embedded_pointer,
10893 bool needs_stub_method,
10894 std::vector<const Named_type*>* seen,
10895 Methods* methods)
10897 // Pointer types may not have methods.
10898 if (type->points_to() != NULL)
10899 return;
10901 const Named_type* nt = type->named_type();
10902 if (nt != NULL)
10904 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10905 p != seen->end();
10906 ++p)
10908 if (*p == nt)
10909 return;
10912 seen->push_back(nt);
10914 Type::add_local_methods_for_type(nt, field_indexes, depth,
10915 is_embedded_pointer, needs_stub_method,
10916 methods);
10919 Type::add_embedded_methods_for_type(type, field_indexes, depth,
10920 is_embedded_pointer, needs_stub_method,
10921 seen, methods);
10923 // If we are called with depth > 0, then we are looking at an
10924 // anonymous field of a struct. If such a field has interface type,
10925 // then we need to add the interface methods. We don't want to add
10926 // them when depth == 0, because we will already handle them
10927 // following the usual rules for an interface type.
10928 if (depth > 0)
10929 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
10931 if (nt != NULL)
10932 seen->pop_back();
10935 // Add the local methods for the named type NT to *METHODS. The
10936 // parameters are as for add_methods_to_type.
10938 void
10939 Type::add_local_methods_for_type(const Named_type* nt,
10940 const Method::Field_indexes* field_indexes,
10941 unsigned int depth,
10942 bool is_embedded_pointer,
10943 bool needs_stub_method,
10944 Methods* methods)
10946 const Bindings* local_methods = nt->local_methods();
10947 if (local_methods == NULL)
10948 return;
10950 for (Bindings::const_declarations_iterator p =
10951 local_methods->begin_declarations();
10952 p != local_methods->end_declarations();
10953 ++p)
10955 Named_object* no = p->second;
10956 bool is_value_method = (is_embedded_pointer
10957 || !Type::method_expects_pointer(no));
10958 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
10959 (needs_stub_method || depth > 0));
10960 if (!methods->insert(no->name(), m))
10961 delete m;
10965 // Add the embedded methods for TYPE to *METHODS. These are the
10966 // methods attached to anonymous fields. The parameters are as for
10967 // add_methods_to_type.
10969 void
10970 Type::add_embedded_methods_for_type(const Type* type,
10971 const Method::Field_indexes* field_indexes,
10972 unsigned int depth,
10973 bool is_embedded_pointer,
10974 bool needs_stub_method,
10975 std::vector<const Named_type*>* seen,
10976 Methods* methods)
10978 // Look for anonymous fields in TYPE. TYPE has fields if it is a
10979 // struct.
10980 const Struct_type* st = type->struct_type();
10981 if (st == NULL)
10982 return;
10984 const Struct_field_list* fields = st->fields();
10985 if (fields == NULL)
10986 return;
10988 unsigned int i = 0;
10989 for (Struct_field_list::const_iterator pf = fields->begin();
10990 pf != fields->end();
10991 ++pf, ++i)
10993 if (!pf->is_anonymous())
10994 continue;
10996 Type* ftype = pf->type();
10997 bool is_pointer = false;
10998 if (ftype->points_to() != NULL)
11000 ftype = ftype->points_to();
11001 is_pointer = true;
11003 Named_type* fnt = ftype->named_type();
11004 if (fnt == NULL)
11006 // This is an error, but it will be diagnosed elsewhere.
11007 continue;
11010 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11011 sub_field_indexes->next = field_indexes;
11012 sub_field_indexes->field_index = i;
11014 Methods tmp_methods;
11015 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11016 (is_embedded_pointer || is_pointer),
11017 (needs_stub_method
11018 || is_pointer
11019 || i > 0),
11020 seen,
11021 &tmp_methods);
11022 // Check if there are promoted methods that conflict with field names and
11023 // don't add them to the method map.
11024 for (Methods::const_iterator p = tmp_methods.begin();
11025 p != tmp_methods.end();
11026 ++p)
11028 bool found = false;
11029 for (Struct_field_list::const_iterator fp = fields->begin();
11030 fp != fields->end();
11031 ++fp)
11033 if (fp->field_name() == p->first)
11035 found = true;
11036 break;
11039 if (!found &&
11040 !methods->insert(p->first, p->second))
11041 delete p->second;
11046 // If TYPE is an interface type, then add its method to *METHODS.
11047 // This is for interface methods attached to an anonymous field. The
11048 // parameters are as for add_methods_for_type.
11050 void
11051 Type::add_interface_methods_for_type(const Type* type,
11052 const Method::Field_indexes* field_indexes,
11053 unsigned int depth,
11054 Methods* methods)
11056 const Interface_type* it = type->interface_type();
11057 if (it == NULL)
11058 return;
11060 const Typed_identifier_list* imethods = it->methods();
11061 if (imethods == NULL)
11062 return;
11064 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11065 pm != imethods->end();
11066 ++pm)
11068 Function_type* fntype = pm->type()->function_type();
11069 if (fntype == NULL)
11071 // This is an error, but it should be reported elsewhere
11072 // when we look at the methods for IT.
11073 continue;
11075 go_assert(!fntype->is_method());
11076 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11077 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11078 field_indexes, depth);
11079 if (!methods->insert(pm->name(), m))
11080 delete m;
11084 // Build stub methods for TYPE as needed. METHODS is the set of
11085 // methods for the type. A stub method may be needed when a type
11086 // inherits a method from an anonymous field. When we need the
11087 // address of the method, as in a type descriptor, we need to build a
11088 // little stub which does the required field dereferences and jumps to
11089 // the real method. LOCATION is the location of the type definition.
11091 void
11092 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11093 Location location)
11095 if (methods == NULL)
11096 return;
11097 for (Methods::const_iterator p = methods->begin();
11098 p != methods->end();
11099 ++p)
11101 Method* m = p->second;
11102 if (m->is_ambiguous() || !m->needs_stub_method())
11103 continue;
11105 const std::string& name(p->first);
11107 // Build a stub method.
11109 const Function_type* fntype = m->type();
11111 static unsigned int counter;
11112 char buf[100];
11113 snprintf(buf, sizeof buf, "$this%u", counter);
11114 ++counter;
11116 Type* receiver_type = const_cast<Type*>(type);
11117 if (!m->is_value_method())
11118 receiver_type = Type::make_pointer_type(receiver_type);
11119 Location receiver_location = m->receiver_location();
11120 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11121 receiver_location);
11123 const Typed_identifier_list* fnparams = fntype->parameters();
11124 Typed_identifier_list* stub_params;
11125 if (fnparams == NULL || fnparams->empty())
11126 stub_params = NULL;
11127 else
11129 // We give each stub parameter a unique name.
11130 stub_params = new Typed_identifier_list();
11131 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11132 pp != fnparams->end();
11133 ++pp)
11135 char pbuf[100];
11136 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11137 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11138 pp->location()));
11139 ++counter;
11143 const Typed_identifier_list* fnresults = fntype->results();
11144 Typed_identifier_list* stub_results;
11145 if (fnresults == NULL || fnresults->empty())
11146 stub_results = NULL;
11147 else
11149 // We create the result parameters without any names, since
11150 // we won't refer to them.
11151 stub_results = new Typed_identifier_list();
11152 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11153 pr != fnresults->end();
11154 ++pr)
11155 stub_results->push_back(Typed_identifier("", pr->type(),
11156 pr->location()));
11159 Function_type* stub_type = Type::make_function_type(receiver,
11160 stub_params,
11161 stub_results,
11162 fntype->location());
11163 if (fntype->is_varargs())
11164 stub_type->set_is_varargs();
11166 // We only create the function in the package which creates the
11167 // type.
11168 const Package* package;
11169 if (type->named_type() == NULL)
11170 package = NULL;
11171 else
11172 package = type->named_type()->named_object()->package();
11173 std::string stub_name = gogo->stub_method_name(package, name);
11174 Named_object* stub;
11175 if (package != NULL)
11176 stub = Named_object::make_function_declaration(stub_name, package,
11177 stub_type, location);
11178 else
11180 stub = gogo->start_function(stub_name, stub_type, false,
11181 fntype->location());
11182 Type::build_one_stub_method(gogo, m, buf, stub_params,
11183 fntype->is_varargs(), location);
11184 gogo->finish_function(fntype->location());
11186 if (type->named_type() == NULL && stub->is_function())
11187 stub->func_value()->set_is_unnamed_type_stub_method();
11188 if (m->nointerface() && stub->is_function())
11189 stub->func_value()->set_nointerface();
11192 m->set_stub_object(stub);
11196 // Build a stub method which adjusts the receiver as required to call
11197 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11198 // PARAMS is the list of function parameters.
11200 void
11201 Type::build_one_stub_method(Gogo* gogo, Method* method,
11202 const char* receiver_name,
11203 const Typed_identifier_list* params,
11204 bool is_varargs,
11205 Location location)
11207 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11208 go_assert(receiver_object != NULL);
11210 Expression* expr = Expression::make_var_reference(receiver_object, location);
11211 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11212 if (expr->type()->points_to() == NULL)
11213 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11215 Expression_list* arguments;
11216 if (params == NULL || params->empty())
11217 arguments = NULL;
11218 else
11220 arguments = new Expression_list();
11221 for (Typed_identifier_list::const_iterator p = params->begin();
11222 p != params->end();
11223 ++p)
11225 Named_object* param = gogo->lookup(p->name(), NULL);
11226 go_assert(param != NULL);
11227 Expression* param_ref = Expression::make_var_reference(param,
11228 location);
11229 arguments->push_back(param_ref);
11233 Expression* func = method->bind_method(expr, location);
11234 go_assert(func != NULL);
11235 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11236 location);
11238 gogo->add_statement(Statement::make_return_from_call(call, location));
11241 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11242 // in reverse order.
11244 Expression*
11245 Type::apply_field_indexes(Expression* expr,
11246 const Method::Field_indexes* field_indexes,
11247 Location location)
11249 if (field_indexes == NULL)
11250 return expr;
11251 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11252 Struct_type* stype = expr->type()->deref()->struct_type();
11253 go_assert(stype != NULL
11254 && field_indexes->field_index < stype->field_count());
11255 if (expr->type()->struct_type() == NULL)
11257 go_assert(expr->type()->points_to() != NULL);
11258 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11259 location);
11260 go_assert(expr->type()->struct_type() == stype);
11262 return Expression::make_field_reference(expr, field_indexes->field_index,
11263 location);
11266 // Return whether NO is a method for which the receiver is a pointer.
11268 bool
11269 Type::method_expects_pointer(const Named_object* no)
11271 const Function_type *fntype;
11272 if (no->is_function())
11273 fntype = no->func_value()->type();
11274 else if (no->is_function_declaration())
11275 fntype = no->func_declaration_value()->type();
11276 else
11277 go_unreachable();
11278 return fntype->receiver()->type()->points_to() != NULL;
11281 // Given a set of methods for a type, METHODS, return the method NAME,
11282 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11283 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11284 // but is ambiguous (and return NULL).
11286 Method*
11287 Type::method_function(const Methods* methods, const std::string& name,
11288 bool* is_ambiguous)
11290 if (is_ambiguous != NULL)
11291 *is_ambiguous = false;
11292 if (methods == NULL)
11293 return NULL;
11294 Methods::const_iterator p = methods->find(name);
11295 if (p == methods->end())
11296 return NULL;
11297 Method* m = p->second;
11298 if (m->is_ambiguous())
11300 if (is_ambiguous != NULL)
11301 *is_ambiguous = true;
11302 return NULL;
11304 return m;
11307 // Return a pointer to the interface method table for TYPE for the
11308 // interface INTERFACE.
11310 Expression*
11311 Type::interface_method_table(Type* type,
11312 Interface_type *interface,
11313 bool is_pointer,
11314 Interface_method_tables** method_tables,
11315 Interface_method_tables** pointer_tables)
11317 go_assert(!interface->is_empty());
11319 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11321 if (*pimt == NULL)
11322 *pimt = new Interface_method_tables(5);
11324 std::pair<Interface_type*, Expression*> val(interface, NULL);
11325 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11327 Location loc = Linemap::predeclared_location();
11328 if (ins.second)
11330 // This is a new entry in the hash table.
11331 go_assert(ins.first->second == NULL);
11332 ins.first->second =
11333 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11335 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11338 // Look for field or method NAME for TYPE. Return an Expression for
11339 // the field or method bound to EXPR. If there is no such field or
11340 // method, give an appropriate error and return an error expression.
11342 Expression*
11343 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11344 const std::string& name,
11345 Location location)
11347 if (type->deref()->is_error_type())
11348 return Expression::make_error(location);
11350 const Named_type* nt = type->deref()->named_type();
11351 const Struct_type* st = type->deref()->struct_type();
11352 const Interface_type* it = type->interface_type();
11354 // If this is a pointer to a pointer, then it is possible that the
11355 // pointed-to type has methods.
11356 bool dereferenced = false;
11357 if (nt == NULL
11358 && st == NULL
11359 && it == NULL
11360 && type->points_to() != NULL
11361 && type->points_to()->points_to() != NULL)
11363 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11364 location);
11365 type = type->points_to();
11366 if (type->deref()->is_error_type())
11367 return Expression::make_error(location);
11368 nt = type->points_to()->named_type();
11369 st = type->points_to()->struct_type();
11370 dereferenced = true;
11373 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11374 || expr->is_addressable());
11375 std::vector<const Named_type*> seen;
11376 bool is_method = false;
11377 bool found_pointer_method = false;
11378 std::string ambig1;
11379 std::string ambig2;
11380 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11381 &seen, NULL, &is_method,
11382 &found_pointer_method, &ambig1, &ambig2))
11384 Expression* ret;
11385 if (!is_method)
11387 go_assert(st != NULL);
11388 if (type->struct_type() == NULL)
11390 if (dereferenced)
11392 go_error_at(location, "pointer type has no field %qs",
11393 Gogo::message_name(name).c_str());
11394 return Expression::make_error(location);
11396 go_assert(type->points_to() != NULL);
11397 expr = Expression::make_dereference(expr,
11398 Expression::NIL_CHECK_DEFAULT,
11399 location);
11400 go_assert(expr->type()->struct_type() == st);
11402 ret = st->field_reference(expr, name, location);
11403 if (ret == NULL)
11405 go_error_at(location, "type has no field %qs",
11406 Gogo::message_name(name).c_str());
11407 return Expression::make_error(location);
11410 else if (it != NULL && it->find_method(name) != NULL)
11411 ret = Expression::make_interface_field_reference(expr, name,
11412 location);
11413 else
11415 Method* m;
11416 if (nt != NULL)
11417 m = nt->method_function(name, NULL);
11418 else if (st != NULL)
11419 m = st->method_function(name, NULL);
11420 else
11421 go_unreachable();
11422 go_assert(m != NULL);
11423 if (dereferenced)
11425 go_error_at(location,
11426 "calling method %qs requires explicit dereference",
11427 Gogo::message_name(name).c_str());
11428 return Expression::make_error(location);
11430 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11431 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11432 ret = m->bind_method(expr, location);
11434 go_assert(ret != NULL);
11435 return ret;
11437 else
11439 if (Gogo::is_erroneous_name(name))
11441 // An error was already reported.
11443 else if (!ambig1.empty())
11444 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11445 Gogo::message_name(name).c_str(), ambig1.c_str(),
11446 ambig2.c_str());
11447 else if (found_pointer_method)
11448 go_error_at(location, "method requires a pointer receiver");
11449 else if (nt == NULL && st == NULL && it == NULL)
11450 go_error_at(location,
11451 ("reference to field %qs in object which "
11452 "has no fields or methods"),
11453 Gogo::message_name(name).c_str());
11454 else
11456 bool is_unexported;
11457 // The test for 'a' and 'z' is to handle builtin names,
11458 // which are not hidden.
11459 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11460 is_unexported = false;
11461 else
11463 std::string unpacked = Gogo::unpack_hidden_name(name);
11464 seen.clear();
11465 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11466 unpacked,
11467 &seen);
11469 if (is_unexported)
11470 go_error_at(location, "reference to unexported field or method %qs",
11471 Gogo::message_name(name).c_str());
11472 else
11473 go_error_at(location, "reference to undefined field or method %qs",
11474 Gogo::message_name(name).c_str());
11476 return Expression::make_error(location);
11480 // Look in TYPE for a field or method named NAME, return true if one
11481 // is found. This looks through embedded anonymous fields and handles
11482 // ambiguity. If a method is found, sets *IS_METHOD to true;
11483 // otherwise, if a field is found, set it to false. If
11484 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11485 // whose address can not be taken. SEEN is used to avoid infinite
11486 // recursion on invalid types.
11488 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11489 // method we couldn't use because it requires a pointer. LEVEL is
11490 // used for recursive calls, and can be NULL for a non-recursive call.
11491 // When this function returns false because it finds that the name is
11492 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11493 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11494 // will be unchanged.
11496 // This function just returns whether or not there is a field or
11497 // method, and whether it is a field or method. It doesn't build an
11498 // expression to refer to it. If it is a method, we then look in the
11499 // list of all methods for the type. If it is a field, the search has
11500 // to be done again, looking only for fields, and building up the
11501 // expression as we go.
11503 bool
11504 Type::find_field_or_method(const Type* type,
11505 const std::string& name,
11506 bool receiver_can_be_pointer,
11507 std::vector<const Named_type*>* seen,
11508 int* level,
11509 bool* is_method,
11510 bool* found_pointer_method,
11511 std::string* ambig1,
11512 std::string* ambig2)
11514 // Named types can have locally defined methods.
11515 const Named_type* nt = type->unalias()->named_type();
11516 if (nt == NULL && type->points_to() != NULL)
11517 nt = type->points_to()->unalias()->named_type();
11518 if (nt != NULL)
11520 Named_object* no = nt->find_local_method(name);
11521 if (no != NULL)
11523 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11525 *is_method = true;
11526 return true;
11529 // Record that we have found a pointer method in order to
11530 // give a better error message if we don't find anything
11531 // else.
11532 *found_pointer_method = true;
11535 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11536 p != seen->end();
11537 ++p)
11539 if (*p == nt)
11541 // We've already seen this type when searching for methods.
11542 return false;
11547 // Interface types can have methods.
11548 const Interface_type* it = type->interface_type();
11549 if (it != NULL && it->find_method(name) != NULL)
11551 *is_method = true;
11552 return true;
11555 // Struct types can have fields. They can also inherit fields and
11556 // methods from anonymous fields.
11557 const Struct_type* st = type->deref()->struct_type();
11558 if (st == NULL)
11559 return false;
11560 const Struct_field_list* fields = st->fields();
11561 if (fields == NULL)
11562 return false;
11564 if (nt != NULL)
11565 seen->push_back(nt);
11567 int found_level = 0;
11568 bool found_is_method = false;
11569 std::string found_ambig1;
11570 std::string found_ambig2;
11571 const Struct_field* found_parent = NULL;
11572 for (Struct_field_list::const_iterator pf = fields->begin();
11573 pf != fields->end();
11574 ++pf)
11576 if (pf->is_field_name(name))
11578 *is_method = false;
11579 if (nt != NULL)
11580 seen->pop_back();
11581 return true;
11584 if (!pf->is_anonymous())
11585 continue;
11587 if (pf->type()->deref()->is_error_type()
11588 || pf->type()->deref()->is_undefined())
11589 continue;
11591 Named_type* fnt = pf->type()->named_type();
11592 if (fnt == NULL)
11593 fnt = pf->type()->deref()->named_type();
11594 go_assert(fnt != NULL);
11596 // Methods with pointer receivers on embedded field are
11597 // inherited by the pointer to struct, and also by the struct
11598 // type if the field itself is a pointer.
11599 bool can_be_pointer = (receiver_can_be_pointer
11600 || pf->type()->points_to() != NULL);
11601 int sublevel = level == NULL ? 1 : *level + 1;
11602 bool sub_is_method;
11603 std::string subambig1;
11604 std::string subambig2;
11605 bool subfound = Type::find_field_or_method(fnt,
11606 name,
11607 can_be_pointer,
11608 seen,
11609 &sublevel,
11610 &sub_is_method,
11611 found_pointer_method,
11612 &subambig1,
11613 &subambig2);
11614 if (!subfound)
11616 if (!subambig1.empty())
11618 // The name was found via this field, but is ambiguous.
11619 // if the ambiguity is lower or at the same level as
11620 // anything else we have already found, then we want to
11621 // pass the ambiguity back to the caller.
11622 if (found_level == 0 || sublevel <= found_level)
11624 found_ambig1 = (Gogo::message_name(pf->field_name())
11625 + '.' + subambig1);
11626 found_ambig2 = (Gogo::message_name(pf->field_name())
11627 + '.' + subambig2);
11628 found_level = sublevel;
11632 else
11634 // The name was found via this field. Use the level to see
11635 // if we want to use this one, or whether it introduces an
11636 // ambiguity.
11637 if (found_level == 0 || sublevel < found_level)
11639 found_level = sublevel;
11640 found_is_method = sub_is_method;
11641 found_ambig1.clear();
11642 found_ambig2.clear();
11643 found_parent = &*pf;
11645 else if (sublevel > found_level)
11647 else if (found_ambig1.empty())
11649 // We found an ambiguity.
11650 go_assert(found_parent != NULL);
11651 found_ambig1 = Gogo::message_name(found_parent->field_name());
11652 found_ambig2 = Gogo::message_name(pf->field_name());
11654 else
11656 // We found an ambiguity, but we already know of one.
11657 // Just report the earlier one.
11662 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
11663 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11664 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
11665 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11667 if (nt != NULL)
11668 seen->pop_back();
11670 if (found_level == 0)
11671 return false;
11672 else if (found_is_method
11673 && type->named_type() != NULL
11674 && type->points_to() != NULL)
11676 // If this is a method inherited from a struct field in a named pointer
11677 // type, it is invalid to automatically dereference the pointer to the
11678 // struct to find this method.
11679 if (level != NULL)
11680 *level = found_level;
11681 *is_method = true;
11682 return false;
11684 else if (!found_ambig1.empty())
11686 go_assert(!found_ambig1.empty());
11687 ambig1->assign(found_ambig1);
11688 ambig2->assign(found_ambig2);
11689 if (level != NULL)
11690 *level = found_level;
11691 return false;
11693 else
11695 if (level != NULL)
11696 *level = found_level;
11697 *is_method = found_is_method;
11698 return true;
11702 // Return whether NAME is an unexported field or method for TYPE.
11704 bool
11705 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11706 const std::string& name,
11707 std::vector<const Named_type*>* seen)
11709 const Named_type* nt = type->named_type();
11710 if (nt == NULL)
11711 nt = type->deref()->named_type();
11712 if (nt != NULL)
11714 if (nt->is_unexported_local_method(gogo, name))
11715 return true;
11717 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11718 p != seen->end();
11719 ++p)
11721 if (*p == nt)
11723 // We've already seen this type.
11724 return false;
11729 const Interface_type* it = type->interface_type();
11730 if (it != NULL && it->is_unexported_method(gogo, name))
11731 return true;
11733 type = type->deref();
11735 const Struct_type* st = type->struct_type();
11736 if (st != NULL && st->is_unexported_local_field(gogo, name))
11737 return true;
11739 if (st == NULL)
11740 return false;
11742 const Struct_field_list* fields = st->fields();
11743 if (fields == NULL)
11744 return false;
11746 if (nt != NULL)
11747 seen->push_back(nt);
11749 for (Struct_field_list::const_iterator pf = fields->begin();
11750 pf != fields->end();
11751 ++pf)
11753 if (pf->is_anonymous()
11754 && !pf->type()->deref()->is_error_type()
11755 && !pf->type()->deref()->is_undefined())
11757 Named_type* subtype = pf->type()->named_type();
11758 if (subtype == NULL)
11759 subtype = pf->type()->deref()->named_type();
11760 if (subtype == NULL)
11762 // This is an error, but it will be diagnosed elsewhere.
11763 continue;
11765 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11767 if (nt != NULL)
11768 seen->pop_back();
11769 return true;
11774 if (nt != NULL)
11775 seen->pop_back();
11777 return false;
11780 // Class Forward_declaration.
11782 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11783 : Type(TYPE_FORWARD),
11784 named_object_(named_object->resolve()), warned_(false)
11786 go_assert(this->named_object_->is_unknown()
11787 || this->named_object_->is_type_declaration());
11790 // Return the named object.
11792 Named_object*
11793 Forward_declaration_type::named_object()
11795 return this->named_object_->resolve();
11798 const Named_object*
11799 Forward_declaration_type::named_object() const
11801 return this->named_object_->resolve();
11804 // Return the name of the forward declared type.
11806 const std::string&
11807 Forward_declaration_type::name() const
11809 return this->named_object()->name();
11812 // Warn about a use of a type which has been declared but not defined.
11814 void
11815 Forward_declaration_type::warn() const
11817 Named_object* no = this->named_object_->resolve();
11818 if (no->is_unknown())
11820 // The name was not defined anywhere.
11821 if (!this->warned_)
11823 go_error_at(this->named_object_->location(),
11824 "use of undefined type %qs",
11825 no->message_name().c_str());
11826 this->warned_ = true;
11829 else if (no->is_type_declaration())
11831 // The name was seen as a type, but the type was never defined.
11832 if (no->type_declaration_value()->using_type())
11834 go_error_at(this->named_object_->location(),
11835 "use of undefined type %qs",
11836 no->message_name().c_str());
11837 this->warned_ = true;
11840 else
11842 // The name was defined, but not as a type.
11843 if (!this->warned_)
11845 go_error_at(this->named_object_->location(), "expected type");
11846 this->warned_ = true;
11851 // Get the base type of a declaration. This gives an error if the
11852 // type has not yet been defined.
11854 Type*
11855 Forward_declaration_type::real_type()
11857 if (this->is_defined())
11859 Named_type* nt = this->named_object()->type_value();
11860 if (!nt->is_valid())
11861 return Type::make_error_type();
11862 return this->named_object()->type_value();
11864 else
11866 this->warn();
11867 return Type::make_error_type();
11871 const Type*
11872 Forward_declaration_type::real_type() const
11874 if (this->is_defined())
11876 const Named_type* nt = this->named_object()->type_value();
11877 if (!nt->is_valid())
11878 return Type::make_error_type();
11879 return this->named_object()->type_value();
11881 else
11883 this->warn();
11884 return Type::make_error_type();
11888 // Return whether the base type is defined.
11890 bool
11891 Forward_declaration_type::is_defined() const
11893 return this->named_object()->is_type();
11896 // Add a method. This is used when methods are defined before the
11897 // type.
11899 Named_object*
11900 Forward_declaration_type::add_method(const std::string& name,
11901 Function* function)
11903 Named_object* no = this->named_object();
11904 if (no->is_unknown())
11905 no->declare_as_type();
11906 return no->type_declaration_value()->add_method(name, function);
11909 // Add a method declaration. This is used when methods are declared
11910 // before the type.
11912 Named_object*
11913 Forward_declaration_type::add_method_declaration(const std::string& name,
11914 Package* package,
11915 Function_type* type,
11916 Location location)
11918 Named_object* no = this->named_object();
11919 if (no->is_unknown())
11920 no->declare_as_type();
11921 Type_declaration* td = no->type_declaration_value();
11922 return td->add_method_declaration(name, package, type, location);
11925 // Add an already created object as a method.
11927 void
11928 Forward_declaration_type::add_existing_method(Named_object* nom)
11930 Named_object* no = this->named_object();
11931 if (no->is_unknown())
11932 no->declare_as_type();
11933 no->type_declaration_value()->add_existing_method(nom);
11936 // Traversal.
11939 Forward_declaration_type::do_traverse(Traverse* traverse)
11941 if (this->is_defined()
11942 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
11943 return TRAVERSE_EXIT;
11944 return TRAVERSE_CONTINUE;
11947 // Verify the type.
11949 bool
11950 Forward_declaration_type::do_verify()
11952 if (!this->is_defined() && !this->is_nil_constant_as_type())
11954 this->warn();
11955 return false;
11957 return true;
11960 // Get the backend representation for the type.
11962 Btype*
11963 Forward_declaration_type::do_get_backend(Gogo* gogo)
11965 if (this->is_defined())
11966 return Type::get_named_base_btype(gogo, this->real_type());
11968 if (this->warned_)
11969 return gogo->backend()->error_type();
11971 // We represent an undefined type as a struct with no fields. That
11972 // should work fine for the backend, since the same case can arise
11973 // in C.
11974 std::vector<Backend::Btyped_identifier> fields;
11975 Btype* bt = gogo->backend()->struct_type(fields);
11976 return gogo->backend()->named_type(this->name(), bt,
11977 this->named_object()->location());
11980 // Build a type descriptor for a forwarded type.
11982 Expression*
11983 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11985 Location ploc = Linemap::predeclared_location();
11986 if (!this->is_defined())
11987 return Expression::make_error(ploc);
11988 else
11990 Type* t = this->real_type();
11991 if (name != NULL)
11992 return this->named_type_descriptor(gogo, t, name);
11993 else
11994 return Expression::make_error(this->named_object_->location());
11998 // The reflection string.
12000 void
12001 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12003 this->append_reflection(this->real_type(), gogo, ret);
12006 // Export a forward declaration. This can happen when a defined type
12007 // refers to a type which is only declared (and is presumably defined
12008 // in some other file in the same package).
12010 void
12011 Forward_declaration_type::do_export(Export*) const
12013 // If there is a base type, that should be exported instead of this.
12014 go_assert(!this->is_defined());
12016 // We don't output anything.
12019 // Make a forward declaration.
12021 Type*
12022 Type::make_forward_declaration(Named_object* named_object)
12024 return new Forward_declaration_type(named_object);
12027 // Class Typed_identifier_list.
12029 // Sort the entries by name.
12031 struct Typed_identifier_list_sort
12033 public:
12034 bool
12035 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12037 return (Gogo::unpack_hidden_name(t1.name())
12038 < Gogo::unpack_hidden_name(t2.name()));
12042 void
12043 Typed_identifier_list::sort_by_name()
12045 std::sort(this->entries_.begin(), this->entries_.end(),
12046 Typed_identifier_list_sort());
12049 // Traverse types.
12052 Typed_identifier_list::traverse(Traverse* traverse)
12054 for (Typed_identifier_list::const_iterator p = this->begin();
12055 p != this->end();
12056 ++p)
12058 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12059 return TRAVERSE_EXIT;
12061 return TRAVERSE_CONTINUE;
12064 // Copy the list.
12066 Typed_identifier_list*
12067 Typed_identifier_list::copy() const
12069 Typed_identifier_list* ret = new Typed_identifier_list();
12070 for (Typed_identifier_list::const_iterator p = this->begin();
12071 p != this->end();
12072 ++p)
12073 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12074 return ret;