Require target lra in gcc.dg/pr108095.c
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob7f471eab428116cd21f7593469e0805f73b37770
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 "go-sha1.h"
16 #include "operator.h"
17 #include "expressions.h"
18 #include "statements.h"
19 #include "export.h"
20 #include "import.h"
21 #include "backend.h"
22 #include "types.h"
24 // Forward declarations so that we don't have to make types.h #include
25 // backend.h.
27 static void
28 get_backend_struct_fields(Gogo* gogo, Struct_type* type, 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 // Note that this type is an error. This is called by children when
265 // they discover an error during the verify_types pass.
267 void
268 Type::set_is_error()
270 this->classification_ = TYPE_ERROR;
273 // If this is a pointer type, return the type to which it points.
274 // Otherwise, return NULL.
276 Type*
277 Type::points_to() const
279 const Pointer_type* ptype = this->convert<const Pointer_type,
280 TYPE_POINTER>();
281 return ptype == NULL ? NULL : ptype->points_to();
284 // Return whether this is a slice type.
286 bool
287 Type::is_slice_type() const
289 return this->array_type() != NULL && this->array_type()->length() == NULL;
292 // Return whether this is the predeclared constant nil being used as a
293 // type.
295 bool
296 Type::is_nil_constant_as_type() const
298 const Type* t = this->forwarded();
299 if (t->forward_declaration_type() != NULL)
301 const Named_object* no = t->forward_declaration_type()->named_object();
302 if (no->is_unknown())
303 no = no->unknown_value()->real_named_object();
304 if (no != NULL
305 && no->is_const()
306 && no->const_value()->expr()->is_nil_expression())
307 return true;
309 return false;
312 // Traverse a type.
315 Type::traverse(Type* type, Traverse* traverse)
317 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
318 || (traverse->traverse_mask()
319 & Traverse::traverse_expressions) != 0);
320 if (traverse->remember_type(type))
322 // We have already traversed this type.
323 return TRAVERSE_CONTINUE;
325 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
327 int t = traverse->type(type);
328 if (t == TRAVERSE_EXIT)
329 return TRAVERSE_EXIT;
330 else if (t == TRAVERSE_SKIP_COMPONENTS)
331 return TRAVERSE_CONTINUE;
333 // An array type has an expression which we need to traverse if
334 // traverse_expressions is set.
335 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
336 return TRAVERSE_EXIT;
337 return TRAVERSE_CONTINUE;
340 // Default implementation for do_traverse for child class.
343 Type::do_traverse(Traverse*)
345 return TRAVERSE_CONTINUE;
348 // Return whether two types are identical. If REASON is not NULL,
349 // optionally set *REASON to the reason the types are not identical.
351 bool
352 Type::are_identical(const Type* t1, const Type* t2, int flags,
353 std::string* reason)
355 if (t1 == NULL || t2 == NULL)
357 // Something is wrong.
358 return (flags & COMPARE_ERRORS) == 0 ? true : t1 == t2;
361 // Skip defined forward declarations.
362 t1 = t1->forwarded();
363 t2 = t2->forwarded();
365 if ((flags & COMPARE_ALIASES) == 0)
367 // Ignore aliases.
368 t1 = t1->unalias();
369 t2 = t2->unalias();
372 if (t1 == t2)
373 return true;
375 // An undefined forward declaration is an error.
376 if (t1->forward_declaration_type() != NULL
377 || t2->forward_declaration_type() != NULL)
378 return (flags & COMPARE_ERRORS) == 0;
380 // Avoid cascading errors with error types.
381 if (t1->is_error_type() || t2->is_error_type())
383 if ((flags & COMPARE_ERRORS) == 0)
384 return true;
385 return t1->is_error_type() && t2->is_error_type();
388 // Get a good reason for the sink type. Note that the sink type on
389 // the left hand side of an assignment is handled in are_assignable.
390 if (t1->is_sink_type() || t2->is_sink_type())
392 if (reason != NULL)
393 *reason = "invalid use of _";
394 return false;
397 // A named type is only identical to itself.
398 if (t1->named_type() != NULL || t2->named_type() != NULL)
399 return false;
401 // Check type shapes.
402 if (t1->classification() != t2->classification())
403 return false;
405 switch (t1->classification())
407 case TYPE_VOID:
408 case TYPE_BOOLEAN:
409 case TYPE_STRING:
410 case TYPE_NIL:
411 // These types are always identical.
412 return true;
414 case TYPE_INTEGER:
415 return t1->integer_type()->is_identical(t2->integer_type());
417 case TYPE_FLOAT:
418 return t1->float_type()->is_identical(t2->float_type());
420 case TYPE_COMPLEX:
421 return t1->complex_type()->is_identical(t2->complex_type());
423 case TYPE_FUNCTION:
424 return t1->function_type()->is_identical(t2->function_type(),
425 false, flags, reason);
427 case TYPE_POINTER:
428 return Type::are_identical(t1->points_to(), t2->points_to(), flags,
429 reason);
431 case TYPE_STRUCT:
432 return t1->struct_type()->is_identical(t2->struct_type(), flags);
434 case TYPE_ARRAY:
435 return t1->array_type()->is_identical(t2->array_type(), flags);
437 case TYPE_MAP:
438 return t1->map_type()->is_identical(t2->map_type(), flags);
440 case TYPE_CHANNEL:
441 return t1->channel_type()->is_identical(t2->channel_type(), flags);
443 case TYPE_INTERFACE:
444 return t1->interface_type()->is_identical(t2->interface_type(), flags);
446 case TYPE_CALL_MULTIPLE_RESULT:
447 if (reason != NULL)
448 *reason = "invalid use of multiple-value function call";
449 return false;
451 default:
452 go_unreachable();
456 // Return true if it's OK to have a binary operation with types LHS
457 // and RHS. This is not used for shifts or comparisons.
459 bool
460 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
462 if (Type::are_identical(lhs, rhs, Type::COMPARE_TAGS, NULL))
463 return true;
465 // A constant of abstract bool type may be mixed with any bool type.
466 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
467 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
468 return true;
470 // A constant of abstract string type may be mixed with any string
471 // type.
472 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
473 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
474 return true;
476 lhs = lhs->base();
477 rhs = rhs->base();
479 // A constant of abstract integer, float, or complex type may be
480 // mixed with an integer, float, or complex type.
481 if ((rhs->is_abstract()
482 && (rhs->integer_type() != NULL
483 || rhs->float_type() != NULL
484 || rhs->complex_type() != NULL)
485 && (lhs->integer_type() != NULL
486 || lhs->float_type() != NULL
487 || lhs->complex_type() != NULL))
488 || (lhs->is_abstract()
489 && (lhs->integer_type() != NULL
490 || lhs->float_type() != NULL
491 || lhs->complex_type() != NULL)
492 && (rhs->integer_type() != NULL
493 || rhs->float_type() != NULL
494 || rhs->complex_type() != NULL)))
495 return true;
497 // The nil type may be compared to a pointer, an interface type, a
498 // slice type, a channel type, a map type, or a function type.
499 if (lhs->is_nil_type()
500 && (rhs->points_to() != NULL
501 || rhs->interface_type() != NULL
502 || rhs->is_slice_type()
503 || rhs->map_type() != NULL
504 || rhs->channel_type() != NULL
505 || rhs->function_type() != NULL))
506 return true;
507 if (rhs->is_nil_type()
508 && (lhs->points_to() != NULL
509 || lhs->interface_type() != NULL
510 || lhs->is_slice_type()
511 || lhs->map_type() != NULL
512 || lhs->channel_type() != NULL
513 || lhs->function_type() != NULL))
514 return true;
516 return false;
519 // Return true if a value with type T1 may be compared with a value of
520 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
522 bool
523 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
524 const Type *t2, std::string *reason)
526 if (t1 != t2
527 && !Type::are_assignable(t1, t2, NULL)
528 && !Type::are_assignable(t2, t1, NULL))
530 if (reason != NULL)
531 *reason = "incompatible types in binary expression";
532 return false;
535 if (!is_equality_op)
537 if (t1->integer_type() == NULL
538 && t1->float_type() == NULL
539 && !t1->is_string_type())
541 if (reason != NULL)
542 *reason = _("invalid comparison of non-ordered type");
543 return false;
546 else if (t1->is_slice_type()
547 || t1->map_type() != NULL
548 || t1->function_type() != NULL
549 || t2->is_slice_type()
550 || t2->map_type() != NULL
551 || t2->function_type() != NULL)
553 if (!t1->is_nil_type() && !t2->is_nil_type())
555 if (reason != NULL)
557 if (t1->is_slice_type() || t2->is_slice_type())
558 *reason = _("slice can only be compared to nil");
559 else if (t1->map_type() != NULL || t2->map_type() != NULL)
560 *reason = _("map can only be compared to nil");
561 else
562 *reason = _("func can only be compared to nil");
564 // Match 6g error messages.
565 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
567 char buf[200];
568 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
569 reason->c_str());
570 *reason = buf;
573 return false;
576 else
578 if (!t1->is_boolean_type()
579 && t1->integer_type() == NULL
580 && t1->float_type() == NULL
581 && t1->complex_type() == NULL
582 && !t1->is_string_type()
583 && t1->points_to() == NULL
584 && t1->channel_type() == NULL
585 && t1->interface_type() == NULL
586 && t1->struct_type() == NULL
587 && t1->array_type() == NULL
588 && !t1->is_nil_type())
590 if (reason != NULL)
591 *reason = _("invalid comparison of non-comparable type");
592 return false;
595 if (t1->unalias()->named_type() != NULL)
596 return t1->unalias()->named_type()->named_type_is_comparable(reason);
597 else if (t2->unalias()->named_type() != NULL)
598 return t2->unalias()->named_type()->named_type_is_comparable(reason);
599 else if (t1->struct_type() != NULL)
601 if (t1->struct_type()->is_struct_incomparable())
603 if (reason != NULL)
604 *reason = _("invalid comparison of generated struct");
605 return false;
607 const Struct_field_list* fields = t1->struct_type()->fields();
608 for (Struct_field_list::const_iterator p = fields->begin();
609 p != fields->end();
610 ++p)
612 if (!p->type()->is_comparable())
614 if (reason != NULL)
615 *reason = _("invalid comparison of non-comparable struct");
616 return false;
620 else if (t1->array_type() != NULL)
622 if (t1->array_type()->is_array_incomparable())
624 if (reason != NULL)
625 *reason = _("invalid comparison of generated array");
626 return false;
628 if (t1->array_type()->length()->is_nil_expression()
629 || !t1->array_type()->element_type()->is_comparable())
631 if (reason != NULL)
632 *reason = _("invalid comparison of non-comparable array");
633 return false;
638 return true;
641 // Return true if a value with type RHS may be assigned to a variable
642 // with type LHS. If REASON is not NULL, set *REASON to the reason
643 // the types are not assignable.
645 bool
646 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
648 // Do some checks first. Make sure the types are defined.
649 if (rhs != NULL && !rhs->is_undefined())
651 if (rhs->is_void_type())
653 if (reason != NULL)
654 *reason = "non-value used as value";
655 return false;
657 if (rhs->is_call_multiple_result_type())
659 if (reason != NULL)
660 reason->assign(_("multiple-value function call in "
661 "single-value context"));
662 return false;
666 // Any value may be assigned to the blank identifier.
667 if (lhs != NULL
668 && !lhs->is_undefined()
669 && lhs->is_sink_type())
670 return true;
672 // Identical types are assignable.
673 if (Type::are_identical(lhs, rhs, Type::COMPARE_TAGS, reason))
674 return true;
676 // Ignore aliases, except for error messages.
677 const Type* lhs_orig = lhs;
678 const Type* rhs_orig = rhs;
679 lhs = lhs->unalias();
680 rhs = rhs->unalias();
682 // The types are assignable if they have identical underlying types
683 // and either LHS or RHS is not a named type.
684 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
685 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
686 && Type::are_identical(lhs->base(), rhs->base(), Type::COMPARE_TAGS,
687 reason))
688 return true;
690 // The types are assignable if LHS is an interface type and RHS
691 // implements the required methods.
692 const Interface_type* lhs_interface_type = lhs->interface_type();
693 if (lhs_interface_type != NULL)
695 if (lhs_interface_type->implements_interface(rhs, reason))
696 return true;
697 const Interface_type* rhs_interface_type = rhs->interface_type();
698 if (rhs_interface_type != NULL
699 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
700 reason))
701 return true;
704 // The type are assignable if RHS is a bidirectional channel type,
705 // LHS is a channel type, they have identical element types, and
706 // either LHS or RHS is not a named type.
707 if (lhs->channel_type() != NULL
708 && rhs->channel_type() != NULL
709 && rhs->channel_type()->may_send()
710 && rhs->channel_type()->may_receive()
711 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
712 && Type::are_identical(lhs->channel_type()->element_type(),
713 rhs->channel_type()->element_type(),
714 Type::COMPARE_TAGS,
715 reason))
716 return true;
718 // The nil type may be assigned to a pointer, function, slice, map,
719 // channel, or interface type.
720 if (rhs->is_nil_type()
721 && (lhs->points_to() != NULL
722 || lhs->function_type() != NULL
723 || lhs->is_slice_type()
724 || lhs->map_type() != NULL
725 || lhs->channel_type() != NULL
726 || lhs->interface_type() != NULL))
727 return true;
729 // An untyped numeric constant may be assigned to a numeric type if
730 // it is representable in that type.
731 if ((rhs->is_abstract()
732 && (rhs->integer_type() != NULL
733 || rhs->float_type() != NULL
734 || rhs->complex_type() != NULL))
735 && (lhs->integer_type() != NULL
736 || lhs->float_type() != NULL
737 || lhs->complex_type() != NULL))
738 return true;
740 // Give some better error messages.
741 if (reason != NULL && reason->empty())
743 if (rhs->interface_type() != NULL)
744 reason->assign(_("need explicit conversion"));
745 else if (lhs_orig->named_type() != NULL
746 && rhs_orig->named_type() != NULL)
748 size_t len = (lhs_orig->named_type()->name().length()
749 + rhs_orig->named_type()->name().length()
750 + 100);
751 char* buf = new char[len];
752 snprintf(buf, len, _("cannot use type %s as type %s"),
753 rhs_orig->named_type()->message_name().c_str(),
754 lhs_orig->named_type()->message_name().c_str());
755 reason->assign(buf);
756 delete[] buf;
760 return false;
763 // Return true if a value with type RHS may be converted to type LHS.
764 // If REASON is not NULL, set *REASON to the reason the types are not
765 // convertible.
767 bool
768 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
770 // The types are convertible if they are assignable.
771 if (Type::are_assignable(lhs, rhs, reason))
772 return true;
774 // Ignore aliases.
775 lhs = lhs->unalias();
776 rhs = rhs->unalias();
778 // A pointer to a regular type may not be converted to a pointer to
779 // a type that may not live in the heap, except when converting from
780 // unsafe.Pointer.
781 if (lhs->points_to() != NULL
782 && rhs->points_to() != NULL
783 && !lhs->points_to()->in_heap()
784 && rhs->points_to()->in_heap()
785 && !rhs->is_unsafe_pointer_type())
787 if (reason != NULL)
788 reason->assign(_("conversion from normal type to notinheap type"));
789 return false;
792 // The types are convertible if they have identical underlying
793 // types, ignoring struct field tags.
794 if (Type::are_identical(lhs->base(), rhs->base(), 0, reason))
795 return true;
797 // The types are convertible if they are both unnamed pointer types
798 // and their pointer base types have identical underlying types,
799 // ignoring struct field tags.
800 if (lhs->named_type() == NULL
801 && rhs->named_type() == NULL
802 && lhs->points_to() != NULL
803 && rhs->points_to() != NULL
804 && (lhs->points_to()->named_type() != NULL
805 || rhs->points_to()->named_type() != NULL)
806 && Type::are_identical(lhs->points_to()->base(),
807 rhs->points_to()->base(),
808 0, reason))
809 return true;
811 // Integer and floating point types are convertible to each other.
812 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
813 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
814 return true;
816 // Complex types are convertible to each other.
817 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
818 return true;
820 // An integer, or []byte, or []rune, may be converted to a string.
821 if (lhs->is_string_type())
823 if (rhs->integer_type() != NULL)
824 return true;
825 if (rhs->is_slice_type())
827 const Type* e = rhs->array_type()->element_type()->forwarded();
828 if (e->integer_type() != NULL
829 && (e->integer_type()->is_byte()
830 || e->integer_type()->is_rune()))
831 return true;
835 // A string may be converted to []byte or []rune.
836 if (rhs->is_string_type() && lhs->is_slice_type())
838 const Type* e = lhs->array_type()->element_type()->forwarded();
839 if (e->integer_type() != NULL
840 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
841 return true;
844 // A slice may be converted to a pointer-to-array.
845 if (rhs->is_slice_type()
846 && lhs->points_to() != NULL
847 && lhs->points_to()->array_type() != NULL
848 && !lhs->points_to()->is_slice_type()
849 && Type::are_identical(lhs->points_to()->array_type()->element_type(),
850 rhs->array_type()->element_type(), 0, reason))
851 return true;
853 // An unsafe.Pointer type may be converted to any pointer type or to
854 // a type whose underlying type is uintptr, and vice-versa.
855 if (lhs->is_unsafe_pointer_type()
856 && (rhs->points_to() != NULL
857 || (rhs->integer_type() != NULL
858 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
859 return true;
860 if (rhs->is_unsafe_pointer_type()
861 && (lhs->points_to() != NULL
862 || (lhs->integer_type() != NULL
863 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
864 return true;
866 // Give a better error message.
867 if (reason != NULL)
869 if (reason->empty())
870 *reason = "invalid type conversion";
871 else
873 std::string s = "invalid type conversion (";
874 s += *reason;
875 s += ')';
876 *reason = s;
880 return false;
883 // Copy expressions if it may change the size.
885 // The only type that has an expression is an array type. The only
886 // types whose size can be changed by the size of an array type are an
887 // array type itself, or a struct type with an array field.
888 Type*
889 Type::copy_expressions()
891 // This is run during parsing, so types may not be valid yet.
892 // We only have to worry about array type literals.
893 switch (this->classification_)
895 default:
896 return this;
898 case TYPE_ARRAY:
900 Array_type* at = this->array_type();
901 if (at->length() == NULL)
902 return this;
903 Expression* len = at->length()->copy();
904 if (at->length() == len)
905 return this;
906 return Type::make_array_type(at->element_type(), len);
909 case TYPE_STRUCT:
911 Struct_type* st = this->struct_type();
912 const Struct_field_list* sfl = st->fields();
913 if (sfl == NULL)
914 return this;
915 bool changed = false;
916 Struct_field_list *nsfl = new Struct_field_list();
917 for (Struct_field_list::const_iterator pf = sfl->begin();
918 pf != sfl->end();
919 ++pf)
921 Type* ft = pf->type()->copy_expressions();
922 Struct_field nf(Typed_identifier((pf->is_anonymous()
923 ? ""
924 : pf->field_name()),
926 pf->location()));
927 if (pf->has_tag())
928 nf.set_tag(pf->tag());
929 nsfl->push_back(nf);
930 if (ft != pf->type())
931 changed = true;
933 if (!changed)
935 delete(nsfl);
936 return this;
938 return Type::make_struct_type(nsfl, st->location());
942 go_unreachable();
945 // Return a hash code for the type to be used for method lookup.
947 unsigned int
948 Type::hash_for_method(Gogo* gogo, int flags) const
950 const Type* t = this->forwarded();
951 if (t->named_type() != NULL && t->named_type()->is_alias())
953 unsigned int r =
954 t->named_type()->real_type()->hash_for_method(gogo, flags);
955 if ((flags & Type::COMPARE_ALIASES) != 0)
956 r += TYPE_FORWARD;
957 return r;
959 unsigned int ret = t->classification_;
960 return ret + t->do_hash_for_method(gogo, flags);
963 // Default implementation of do_hash_for_method. This is appropriate
964 // for types with no subfields.
966 unsigned int
967 Type::do_hash_for_method(Gogo*, int) const
969 return 0;
972 // A hash table mapping unnamed types to the backend representation of
973 // those types.
975 Type::Type_btypes Type::type_btypes;
977 // Return the backend representation for this type.
979 Btype*
980 Type::get_backend(Gogo* gogo)
982 if (this->btype_ != NULL)
983 return this->btype_;
985 if (this->named_type() != NULL && this->named_type()->is_alias())
987 Btype* bt = this->unalias()->get_backend(gogo);
988 if (gogo != NULL && gogo->named_types_are_converted())
989 this->btype_ = bt;
990 return bt;
993 if (this->forward_declaration_type() != NULL
994 || this->named_type() != NULL)
995 return this->get_btype_without_hash(gogo);
997 if (this->is_error_type())
998 return gogo->backend()->error_type();
1000 // To avoid confusing the backend, translate all identical Go types
1001 // to the same backend representation. We use a hash table to do
1002 // that. There is no need to use the hash table for named types, as
1003 // named types are only identical to themselves.
1005 std::pair<Type*, Type_btype_entry> val;
1006 val.first = this;
1007 val.second.btype = NULL;
1008 val.second.is_placeholder = false;
1009 std::pair<Type_btypes::iterator, bool> ins =
1010 Type::type_btypes.insert(val);
1011 if (!ins.second && ins.first->second.btype != NULL)
1013 // Note that GOGO can be NULL here, but only when the GCC
1014 // middle-end is asking for a frontend type. That will only
1015 // happen for simple types, which should never require
1016 // placeholders.
1017 if (!ins.first->second.is_placeholder)
1018 this->btype_ = ins.first->second.btype;
1019 else if (gogo->named_types_are_converted())
1021 this->finish_backend(gogo, ins.first->second.btype);
1022 ins.first->second.is_placeholder = false;
1025 // We set the has_padding field of a Struct_type when we convert
1026 // to the backend type, so if we have multiple Struct_type's
1027 // mapping to the same backend type we need to copy the
1028 // has_padding field. FIXME: This is awkward. We shouldn't
1029 // really change the type when setting the backend type, but
1030 // there isn't any other good time to add the padding field.
1031 if (ins.first->first->struct_type() != NULL
1032 && ins.first->first->struct_type()->has_padding())
1033 this->struct_type()->set_has_padding();
1035 return ins.first->second.btype;
1038 Btype* bt = this->get_btype_without_hash(gogo);
1040 if (ins.first->second.btype == NULL)
1042 ins.first->second.btype = bt;
1043 ins.first->second.is_placeholder = false;
1045 else
1047 // We have already created a backend representation for this
1048 // type. This can happen when an unnamed type is defined using
1049 // a named type which in turns uses an identical unnamed type.
1050 // Use the representation we created earlier and ignore the one we just
1051 // built.
1052 if (this->btype_ == bt)
1053 this->btype_ = ins.first->second.btype;
1054 bt = ins.first->second.btype;
1057 return bt;
1060 // Return the backend representation for a type without looking in the
1061 // hash table for identical types. This is used for named types,
1062 // since a named type is never identical to any other type.
1064 Btype*
1065 Type::get_btype_without_hash(Gogo* gogo)
1067 if (this->btype_ == NULL)
1069 Btype* bt = this->do_get_backend(gogo);
1071 // For a recursive function or pointer type, we will temporarily
1072 // return a circular pointer type during the recursion. We
1073 // don't want to record that for a forwarding type, as it may
1074 // confuse us later.
1075 if (this->forward_declaration_type() != NULL
1076 && gogo->backend()->is_circular_pointer_type(bt))
1077 return bt;
1079 if (gogo == NULL || !gogo->named_types_are_converted())
1080 return bt;
1082 this->btype_ = bt;
1084 return this->btype_;
1087 // Get the backend representation of a type without forcing the
1088 // creation of the backend representation of all supporting types.
1089 // This will return a backend type that has the correct size but may
1090 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1091 // and will not contain the final representation of the type to which
1092 // it points. This is used while converting all named types to the
1093 // backend representation, to avoid problems with indirect references
1094 // to types which are not yet complete. When this is called, the
1095 // sizes of all direct references (e.g., a struct field) should be
1096 // known, but the sizes of indirect references (e.g., the type to
1097 // which a pointer points) may not.
1099 Btype*
1100 Type::get_backend_placeholder(Gogo* gogo)
1102 if (gogo->named_types_are_converted())
1103 return this->get_backend(gogo);
1104 if (this->btype_ != NULL)
1105 return this->btype_;
1107 Btype* bt;
1108 switch (this->classification_)
1110 case TYPE_ERROR:
1111 case TYPE_VOID:
1112 case TYPE_BOOLEAN:
1113 case TYPE_INTEGER:
1114 case TYPE_FLOAT:
1115 case TYPE_COMPLEX:
1116 case TYPE_STRING:
1117 case TYPE_NIL:
1118 // These are simple types that can just be created directly.
1119 return this->get_backend(gogo);
1121 case TYPE_MAP:
1122 case TYPE_CHANNEL:
1123 // All maps and channels have the same backend representation.
1124 return this->get_backend(gogo);
1126 case TYPE_NAMED:
1127 case TYPE_FORWARD:
1128 // Named types keep track of their own dependencies and manage
1129 // their own placeholders.
1130 if (this->named_type() != NULL && this->named_type()->is_alias())
1131 return this->unalias()->get_backend_placeholder(gogo);
1132 return this->get_backend(gogo);
1134 case TYPE_INTERFACE:
1135 if (this->interface_type()->is_empty())
1136 return Interface_type::get_backend_empty_interface_type(gogo);
1137 break;
1139 default:
1140 break;
1143 std::pair<Type*, Type_btype_entry> val;
1144 val.first = this;
1145 val.second.btype = NULL;
1146 val.second.is_placeholder = false;
1147 std::pair<Type_btypes::iterator, bool> ins =
1148 Type::type_btypes.insert(val);
1149 if (!ins.second && ins.first->second.btype != NULL)
1150 return ins.first->second.btype;
1152 switch (this->classification_)
1154 case TYPE_FUNCTION:
1156 // A Go function type is a pointer to a struct type.
1157 Location loc = this->function_type()->location();
1158 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1159 Type::placeholder_pointers.push_back(this);
1161 break;
1163 case TYPE_POINTER:
1165 Location loc = Linemap::unknown_location();
1166 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1167 Type::placeholder_pointers.push_back(this);
1169 break;
1171 case TYPE_STRUCT:
1172 // We don't have to make the struct itself be a placeholder. We
1173 // are promised that we know the sizes of the struct fields.
1174 // But we may have to use a placeholder for any particular
1175 // struct field.
1177 std::vector<Backend::Btyped_identifier> bfields;
1178 get_backend_struct_fields(gogo, this->struct_type(), true, &bfields);
1179 bt = gogo->backend()->struct_type(bfields);
1181 break;
1183 case TYPE_ARRAY:
1184 if (this->is_slice_type())
1186 std::vector<Backend::Btyped_identifier> bfields;
1187 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1188 bt = gogo->backend()->struct_type(bfields);
1190 else
1192 Btype* element = this->array_type()->get_backend_element(gogo, true);
1193 Bexpression* len = this->array_type()->get_backend_length(gogo);
1194 bt = gogo->backend()->array_type(element, len);
1196 break;
1198 case TYPE_INTERFACE:
1200 go_assert(!this->interface_type()->is_empty());
1201 std::vector<Backend::Btyped_identifier> bfields;
1202 get_backend_interface_fields(gogo, this->interface_type(), true,
1203 &bfields);
1204 bt = gogo->backend()->struct_type(bfields);
1206 break;
1208 case TYPE_SINK:
1209 case TYPE_CALL_MULTIPLE_RESULT:
1210 /* Note that various classifications were handled in the earlier
1211 switch. */
1212 default:
1213 go_unreachable();
1216 if (ins.first->second.btype == NULL)
1218 ins.first->second.btype = bt;
1219 ins.first->second.is_placeholder = true;
1221 else
1223 // A placeholder for this type got created along the way. Use
1224 // that one and ignore the one we just built.
1225 bt = ins.first->second.btype;
1228 return bt;
1231 // Complete the backend representation. This is called for a type
1232 // using a placeholder type.
1234 void
1235 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1237 switch (this->classification_)
1239 case TYPE_ERROR:
1240 case TYPE_VOID:
1241 case TYPE_BOOLEAN:
1242 case TYPE_INTEGER:
1243 case TYPE_FLOAT:
1244 case TYPE_COMPLEX:
1245 case TYPE_STRING:
1246 case TYPE_NIL:
1247 go_unreachable();
1249 case TYPE_FUNCTION:
1251 Btype* bt = this->do_get_backend(gogo);
1252 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1253 go_assert(saw_errors());
1255 break;
1257 case TYPE_POINTER:
1259 Btype* bt = this->do_get_backend(gogo);
1260 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1261 go_assert(saw_errors());
1263 break;
1265 case TYPE_STRUCT:
1266 // The struct type itself is done, but we have to make sure that
1267 // all the field types are converted.
1268 this->struct_type()->finish_backend_fields(gogo);
1269 break;
1271 case TYPE_ARRAY:
1272 // The array type itself is done, but make sure the element type
1273 // is converted.
1274 this->array_type()->finish_backend_element(gogo);
1275 break;
1277 case TYPE_MAP:
1278 case TYPE_CHANNEL:
1279 go_unreachable();
1281 case TYPE_INTERFACE:
1282 // The interface type itself is done, but make sure the method
1283 // types are converted.
1284 this->interface_type()->finish_backend_methods(gogo);
1285 break;
1287 case TYPE_NAMED:
1288 case TYPE_FORWARD:
1289 go_unreachable();
1291 case TYPE_SINK:
1292 case TYPE_CALL_MULTIPLE_RESULT:
1293 default:
1294 go_unreachable();
1297 this->btype_ = placeholder;
1300 // Return a pointer to the type descriptor for this type.
1302 Bexpression*
1303 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1305 Type* t = this->unalias();
1306 if (t->type_descriptor_var_ == NULL)
1308 t->make_type_descriptor_var(gogo);
1309 go_assert(t->type_descriptor_var_ != NULL);
1311 Bexpression* var_expr =
1312 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1313 Bexpression* var_addr =
1314 gogo->backend()->address_expression(var_expr, location);
1315 Type* td_type = Type::make_type_descriptor_type();
1316 Btype* td_btype = td_type->get_backend(gogo);
1317 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1318 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1321 // A mapping from unnamed types to type descriptor variables.
1323 Type::Type_descriptor_vars Type::type_descriptor_vars;
1325 // Build the type descriptor for this type.
1327 void
1328 Type::make_type_descriptor_var(Gogo* gogo)
1330 go_assert(this->type_descriptor_var_ == NULL);
1332 Named_type* nt = this->named_type();
1334 // We can have multiple instances of unnamed types, but we only want
1335 // to emit the type descriptor once. We use a hash table. This is
1336 // not necessary for named types, as they are unique, and we store
1337 // the type descriptor in the type itself.
1338 Bvariable** phash = NULL;
1339 if (nt == NULL)
1341 Bvariable* bvnull = NULL;
1342 std::pair<Type_descriptor_vars::iterator, bool> ins =
1343 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1344 if (!ins.second)
1346 // We've already built a type descriptor for this type.
1347 this->type_descriptor_var_ = ins.first->second;
1348 return;
1350 phash = &ins.first->second;
1353 // The type descriptor symbol for the unsafe.Pointer type is defined in
1354 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1355 // symbol if necessary.
1356 if (this->is_unsafe_pointer_type())
1358 Location bloc = Linemap::predeclared_location();
1360 Type* td_type = Type::make_type_descriptor_type();
1361 Btype* td_btype = td_type->get_backend(gogo);
1362 Backend_name bname;
1363 gogo->type_descriptor_backend_name(this, nt, &bname);
1364 this->type_descriptor_var_ =
1365 gogo->backend()->immutable_struct_reference(bname.name(),
1366 bname.optional_asm_name(),
1367 td_btype,
1368 bloc);
1370 if (phash != NULL)
1371 *phash = this->type_descriptor_var_;
1372 return;
1375 Backend_name bname;
1376 gogo->type_descriptor_backend_name(this, nt, &bname);
1378 // Build the contents of the type descriptor.
1379 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1381 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1383 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1385 const Package* dummy;
1386 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1388 this->type_descriptor_var_ =
1389 gogo->backend()->immutable_struct_reference(bname.name(),
1390 bname.optional_asm_name(),
1391 initializer_btype,
1392 loc);
1393 if (phash != NULL)
1394 *phash = this->type_descriptor_var_;
1395 return;
1398 // See if this type descriptor can appear in multiple packages.
1399 bool is_common = false;
1400 if (nt != NULL)
1402 // We create the descriptor for a builtin type whenever we need
1403 // it.
1404 is_common = nt->is_builtin();
1406 else
1408 // This is an unnamed type. The descriptor could be defined in
1409 // any package where it is needed, and the linker will pick one
1410 // descriptor to keep.
1411 is_common = true;
1414 // We are going to build the type descriptor in this package. We
1415 // must create the variable before we convert the initializer to the
1416 // backend representation, because the initializer may refer to the
1417 // type descriptor of this type. By setting type_descriptor_var_ we
1418 // ensure that type_descriptor_pointer will work if called while
1419 // converting INITIALIZER.
1421 unsigned int flags = 0;
1422 if (is_common)
1423 flags |= Backend::variable_is_common;
1424 this->type_descriptor_var_ =
1425 gogo->backend()->immutable_struct(bname.name(), bname.optional_asm_name(),
1426 flags, initializer_btype, loc);
1427 if (phash != NULL)
1428 *phash = this->type_descriptor_var_;
1430 Translate_context context(gogo, NULL, NULL, NULL);
1431 context.set_is_const();
1432 Bexpression* binitializer = initializer->get_backend(&context);
1434 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1435 bname.name(), flags,
1436 initializer_btype, loc,
1437 binitializer);
1439 // For types that may be created by reflection, add it to the
1440 // list of which we will register the type descriptor to the
1441 // runtime.
1442 // Do not add generated incomparable array/struct types, see
1443 // issue #22605.
1444 if (is_common
1445 && (this->points_to() != NULL
1446 || this->channel_type() != NULL
1447 || this->map_type() != NULL
1448 || this->function_type() != NULL
1449 || this->is_slice_type()
1450 || (this->struct_type() != NULL
1451 && !this->struct_type()->is_struct_incomparable())
1452 || (this->array_type() != NULL
1453 && !this->array_type()->is_array_incomparable())))
1454 gogo->add_type_descriptor(this);
1457 // Return true if this type descriptor is defined in a different
1458 // package. If this returns true it sets *PACKAGE to the package.
1460 bool
1461 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1462 const Package** package)
1464 if (nt != NULL)
1466 if (nt->named_object()->package() != NULL)
1468 // This is a named type defined in a different package. The
1469 // type descriptor should be defined in that package.
1470 *package = nt->named_object()->package();
1471 return true;
1474 else
1476 if (this->points_to() != NULL
1477 && this->points_to()->unalias()->named_type() != NULL
1478 && this->points_to()->unalias()->named_type()->named_object()->package() != NULL)
1480 // This is an unnamed pointer to a named type defined in a
1481 // different package. The descriptor should be defined in
1482 // that package.
1483 *package = this->points_to()->unalias()->named_type()->named_object()->package();
1484 return true;
1487 return false;
1490 // Return a composite literal for a type descriptor.
1492 Expression*
1493 Type::type_descriptor(Gogo* gogo, Type* type)
1495 return type->do_type_descriptor(gogo, NULL);
1498 // Return a composite literal for a type descriptor with a name.
1500 Expression*
1501 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1503 go_assert(name != NULL && type->named_type() != name);
1504 return type->do_type_descriptor(gogo, name);
1507 // Make a builtin struct type from a list of fields. The fields are
1508 // pairs of a name and a type.
1510 Struct_type*
1511 Type::make_builtin_struct_type(int nfields, ...)
1513 va_list ap;
1514 va_start(ap, nfields);
1516 Location bloc = Linemap::predeclared_location();
1517 Struct_field_list* sfl = new Struct_field_list();
1518 for (int i = 0; i < nfields; i++)
1520 const char* field_name = va_arg(ap, const char *);
1521 Type* type = va_arg(ap, Type*);
1522 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1525 va_end(ap);
1527 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1528 ret->set_is_struct_incomparable();
1529 return ret;
1532 // A list of builtin named types.
1534 std::vector<Named_type*> Type::named_builtin_types;
1536 // Make a builtin named type.
1538 Named_type*
1539 Type::make_builtin_named_type(const char* name, Type* type)
1541 Location bloc = Linemap::predeclared_location();
1542 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1543 Named_type* ret = no->type_value();
1544 Type::named_builtin_types.push_back(ret);
1545 return ret;
1548 // Convert the named builtin types.
1550 void
1551 Type::convert_builtin_named_types(Gogo* gogo)
1553 for (std::vector<Named_type*>::const_iterator p =
1554 Type::named_builtin_types.begin();
1555 p != Type::named_builtin_types.end();
1556 ++p)
1558 bool r = (*p)->verify();
1559 go_assert(r);
1560 (*p)->convert(gogo);
1564 // Values to store in the tflag field of a type descriptor. This must
1565 // match the definitions in libgo/go/runtime/type.go.
1567 const int TFLAG_REGULAR_MEMORY = 1 << 3;
1569 // Return the type of a type descriptor. We should really tie this to
1570 // runtime.Type rather than copying it. This must match the struct "_type"
1571 // declared in libgo/go/runtime/type.go.
1573 Type*
1574 Type::make_type_descriptor_type()
1576 static Type* ret;
1577 if (ret == NULL)
1579 Location bloc = Linemap::predeclared_location();
1581 Type* uint8_type = Type::lookup_integer_type("uint8");
1582 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1583 Type* uint32_type = Type::lookup_integer_type("uint32");
1584 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1585 Type* string_type = Type::lookup_string_type();
1586 Type* pointer_string_type = Type::make_pointer_type(string_type);
1588 // This is an unnamed version of unsafe.Pointer. Perhaps we
1589 // should use the named version instead, although that would
1590 // require us to create the unsafe package if it has not been
1591 // imported. It probably doesn't matter.
1592 Type* void_type = Type::make_void_type();
1593 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1595 Typed_identifier_list* params = new Typed_identifier_list();
1596 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1597 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1599 Typed_identifier_list* results = new Typed_identifier_list();
1600 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1602 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1603 bloc);
1605 // Forward declaration for the type descriptor type.
1606 Named_object* named_type_descriptor_type =
1607 Named_object::make_type_declaration("_type", NULL, bloc);
1608 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1609 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1611 // The type of a method on a concrete type.
1612 Struct_type* method_type =
1613 Type::make_builtin_struct_type(5,
1614 "name", pointer_string_type,
1615 "pkgPath", pointer_string_type,
1616 "mtyp", pointer_type_descriptor_type,
1617 "typ", pointer_type_descriptor_type,
1618 "tfn", unsafe_pointer_type);
1619 Named_type* named_method_type =
1620 Type::make_builtin_named_type("method", method_type);
1622 // Information for types with a name or methods.
1623 Type* slice_named_method_type =
1624 Type::make_array_type(named_method_type, NULL);
1625 Struct_type* uncommon_type =
1626 Type::make_builtin_struct_type(3,
1627 "name", pointer_string_type,
1628 "pkgPath", pointer_string_type,
1629 "methods", slice_named_method_type);
1630 Named_type* named_uncommon_type =
1631 Type::make_builtin_named_type("uncommonType", uncommon_type);
1633 Type* pointer_uncommon_type =
1634 Type::make_pointer_type(named_uncommon_type);
1636 // The type descriptor type.
1638 Struct_type* type_descriptor_type =
1639 Type::make_builtin_struct_type(12,
1640 "size", uintptr_type,
1641 "ptrdata", uintptr_type,
1642 "hash", uint32_type,
1643 "tflag", uint8_type,
1644 "align", uint8_type,
1645 "fieldAlign", uint8_type,
1646 "kind", uint8_type,
1647 "equal", equal_fntype,
1648 "gcdata", pointer_uint8_type,
1649 "string", pointer_string_type,
1650 "", pointer_uncommon_type,
1651 "ptrToThis",
1652 pointer_type_descriptor_type);
1654 Named_type* named = Type::make_builtin_named_type("_type",
1655 type_descriptor_type);
1657 named_type_descriptor_type->set_type_value(named);
1659 ret = named;
1662 return ret;
1665 // Make the type of a pointer to a type descriptor as represented in
1666 // Go.
1668 Type*
1669 Type::make_type_descriptor_ptr_type()
1671 static Type* ret;
1672 if (ret == NULL)
1673 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1674 return ret;
1677 // Return the alignment required by the memequalN function. N is a
1678 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1679 // in libgo/go/runtime/alg.go.
1681 int64_t
1682 Type::memequal_align(Gogo* gogo, int size)
1684 const char* tn;
1685 switch (size)
1687 case 16:
1688 tn = "int16";
1689 break;
1690 case 32:
1691 tn = "int32";
1692 break;
1693 case 64:
1694 tn = "int64";
1695 break;
1696 case 128:
1697 // The code uses [2]int64, which must have the same alignment as
1698 // int64.
1699 tn = "int64";
1700 break;
1701 default:
1702 go_unreachable();
1705 Type* t = Type::lookup_integer_type(tn);
1707 int64_t ret;
1708 if (!t->backend_type_align(gogo, &ret))
1709 go_unreachable();
1710 return ret;
1713 // Return whether this type needs specially built type functions.
1714 // This returns true for types that are comparable and either can not
1715 // use an identity comparison, or are a non-standard size.
1717 bool
1718 Type::needs_specific_type_functions(Gogo* gogo)
1720 Named_type* nt = this->named_type();
1721 if (nt != NULL && nt->is_alias())
1722 return false;
1723 if (!this->is_comparable())
1724 return false;
1725 if (!this->compare_is_identity(gogo))
1726 return true;
1728 // We create a few predeclared types for type descriptors; they are
1729 // really just for the backend and don't need hash or equality
1730 // functions.
1731 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1732 return false;
1734 int64_t size, align;
1735 if (!this->backend_type_size(gogo, &size)
1736 || !this->backend_type_align(gogo, &align))
1738 go_assert(saw_errors());
1739 return false;
1741 // This switch matches the one in Type::equal_function.
1742 switch (size)
1744 case 0:
1745 case 1:
1746 case 2:
1747 return align < Type::memequal_align(gogo, 16);
1748 case 4:
1749 return align < Type::memequal_align(gogo, 32);
1750 case 8:
1751 return align < Type::memequal_align(gogo, 64);
1752 case 16:
1753 return align < Type::memequal_align(gogo, 128);
1754 default:
1755 return true;
1759 // Return the runtime function that computes the hash of this type.
1760 // HASH_FNTYPE is the type of the hash function function, for
1761 // convenience; it may be NULL. This returns NULL if the type is not
1762 // comparable.
1764 Named_object*
1765 Type::hash_function(Gogo* gogo, Function_type* hash_fntype)
1767 if (this->named_type() != NULL)
1768 go_assert(!this->named_type()->is_alias());
1770 if (!this->is_comparable())
1771 return NULL;
1773 if (hash_fntype == NULL)
1775 Location bloc = Linemap::predeclared_location();
1776 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1777 Type* void_type = Type::make_void_type();
1778 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1779 Typed_identifier_list* params = new Typed_identifier_list();
1780 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1781 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1782 Typed_identifier_list* results = new Typed_identifier_list();
1783 results->push_back(Typed_identifier("", uintptr_type, bloc));
1784 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1787 const char* hash_fnname;
1788 if (this->compare_is_identity(gogo))
1790 int64_t size;
1791 if (!this->backend_type_size(gogo, &size))
1793 go_assert(saw_errors());
1794 return NULL;
1796 switch (size)
1798 case 0:
1799 hash_fnname = "runtime.memhash0";
1800 break;
1801 case 1:
1802 hash_fnname = "runtime.memhash8";
1803 break;
1804 case 2:
1805 hash_fnname = "runtime.memhash16";
1806 break;
1807 case 4:
1808 hash_fnname = "runtime.memhash32";
1809 break;
1810 case 8:
1811 hash_fnname = "runtime.memhash64";
1812 break;
1813 case 16:
1814 hash_fnname = "runtime.memhash128";
1815 break;
1816 default:
1817 // We don't have a built-in function for a type of this
1818 // size. Build a function to use that calls the generic
1819 // hash functions for identity, passing the size.
1820 return this->build_hash_function(gogo, size, hash_fntype);
1823 else
1825 switch (this->base()->classification())
1827 case Type::TYPE_ERROR:
1828 case Type::TYPE_VOID:
1829 case Type::TYPE_NIL:
1830 case Type::TYPE_FUNCTION:
1831 case Type::TYPE_MAP:
1832 // For these types is_comparable should have returned false.
1833 go_unreachable();
1835 case Type::TYPE_BOOLEAN:
1836 case Type::TYPE_INTEGER:
1837 case Type::TYPE_POINTER:
1838 case Type::TYPE_CHANNEL:
1839 // For these types compare_is_identity should have returned true.
1840 go_unreachable();
1842 case Type::TYPE_FLOAT:
1843 switch (this->float_type()->bits())
1845 case 32:
1846 hash_fnname = "runtime.f32hash";
1847 break;
1848 case 64:
1849 hash_fnname = "runtime.f64hash";
1850 break;
1851 default:
1852 go_unreachable();
1854 break;
1856 case Type::TYPE_COMPLEX:
1857 switch (this->complex_type()->bits())
1859 case 64:
1860 hash_fnname = "runtime.c64hash";
1861 break;
1862 case 128:
1863 hash_fnname = "runtime.c128hash";
1864 break;
1865 default:
1866 go_unreachable();
1868 break;
1870 case Type::TYPE_STRING:
1871 hash_fnname = "runtime.strhash";
1872 break;
1874 case Type::TYPE_STRUCT:
1875 // This is a struct which can not be compared using a simple
1876 // identity function. We need to build a function to
1877 // compute the hash.
1878 return this->build_hash_function(gogo, -1, hash_fntype);
1880 case Type::TYPE_ARRAY:
1881 if (this->is_slice_type())
1883 // Type::is_compatible_for_comparison should have
1884 // returned false.
1885 go_unreachable();
1887 else
1889 // This is an array which can not be compared using a
1890 // simple identity function. We need to build a
1891 // function to compute the hash.
1892 return this->build_hash_function(gogo, -1, hash_fntype);
1894 break;
1896 case Type::TYPE_INTERFACE:
1897 if (this->interface_type()->is_empty())
1898 hash_fnname = "runtime.nilinterhash";
1899 else
1900 hash_fnname = "runtime.interhash";
1901 break;
1903 case Type::TYPE_NAMED:
1904 case Type::TYPE_FORWARD:
1905 go_unreachable();
1907 default:
1908 go_unreachable();
1912 Location bloc = Linemap::predeclared_location();
1913 Named_object *hash_fn = Named_object::make_function_declaration(hash_fnname,
1914 NULL,
1915 hash_fntype,
1916 bloc);
1917 hash_fn->func_declaration_value()->set_asm_name(hash_fnname);
1918 return hash_fn;
1921 // A hash table mapping types to the specific hash functions.
1923 Type::Type_function Type::type_hash_functions_table;
1925 // Build a hash function that is specific to a type: if SIZE == -1,
1926 // this is a struct or array type that cannot use an identity
1927 // comparison. Otherwise, it is a type that uses an identity
1928 // comparison but is not one of the standard supported sizes.
1930 // Unlike an equality function, hash functions are not in type
1931 // descriptors, so we can't assume that a named type has defined a
1932 // hash function in the package that defines the type. So hash
1933 // functions are always defined locally. FIXME: It would be better to
1934 // define hash functions with comdat linkage so that duplicate hash
1935 // functions can be coalesced at link time.
1937 Named_object*
1938 Type::build_hash_function(Gogo* gogo, int64_t size, Function_type* hash_fntype)
1940 Type* type = this->base();
1942 std::pair<Type*, Named_object*> val(type, NULL);
1943 std::pair<Type_function::iterator, bool> ins =
1944 Type::type_hash_functions_table.insert(val);
1945 if (!ins.second)
1947 // We already have a function for this type.
1948 return ins.first->second;
1951 Backend_name bname;
1952 gogo->hash_function_name(type, &bname);
1954 Location bloc = Linemap::predeclared_location();
1956 Named_object* hash_fn = gogo->declare_package_function(bname.name(),
1957 hash_fntype, bloc);
1959 ins.first->second = hash_fn;
1961 if (gogo->in_global_scope())
1962 type->write_hash_function(gogo, size, &bname, hash_fntype);
1963 else
1964 gogo->queue_hash_function(type, size, &bname, hash_fntype);
1966 return hash_fn;
1969 // Write the hash function for a type that needs it written specially.
1971 void
1972 Type::write_hash_function(Gogo* gogo, int64_t size, const Backend_name* bname,
1973 Function_type* hash_fntype)
1975 Location bloc = Linemap::predeclared_location();
1977 if (gogo->specific_type_functions_are_written())
1979 go_assert(saw_errors());
1980 return;
1983 go_assert(this->is_comparable());
1985 Named_object* hash_fn = gogo->start_function(bname->name(), hash_fntype,
1986 false, bloc);
1987 hash_fn->func_value()->set_asm_name(bname->asm_name());
1988 hash_fn->func_value()->set_is_type_specific_function();
1989 gogo->start_block(bloc);
1991 if (size != -1)
1992 this->write_identity_hash(gogo, size);
1993 else if (this->struct_type() != NULL)
1994 this->struct_type()->write_hash_function(gogo, hash_fntype);
1995 else if (this->array_type() != NULL)
1996 this->array_type()->write_hash_function(gogo, hash_fntype);
1997 else
1998 go_unreachable();
2000 Block* b = gogo->finish_block(bloc);
2001 gogo->add_block(b, bloc);
2002 gogo->lower_block(hash_fn, b);
2003 gogo->order_block(b);
2004 gogo->remove_shortcuts_in_block(b);
2005 gogo->finish_function(bloc);
2007 // Build the function descriptor for the type descriptor to refer to.
2008 hash_fn->func_value()->descriptor(gogo, hash_fn);
2011 // Write a hash function for a type that can use an identity hash but
2012 // is not one of the standard supported sizes. For example, this
2013 // would be used for the type [3]byte. This builds a return statement
2014 // that returns a call to the memhash function, passing the key and
2015 // seed from the function arguments (already constructed before this
2016 // is called), and the constant size.
2018 void
2019 Type::write_identity_hash(Gogo* gogo, int64_t size)
2021 Location bloc = Linemap::predeclared_location();
2023 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2024 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2026 Typed_identifier_list* params = new Typed_identifier_list();
2027 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2028 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2029 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2031 Typed_identifier_list* results = new Typed_identifier_list();
2032 results->push_back(Typed_identifier("", uintptr_type, bloc));
2034 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2035 results, bloc);
2037 Named_object* memhash =
2038 Named_object::make_function_declaration("runtime.memhash", NULL,
2039 memhash_fntype, bloc);
2040 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2042 Named_object* key_arg = gogo->lookup("key", NULL);
2043 go_assert(key_arg != NULL);
2044 Named_object* seed_arg = gogo->lookup("seed", NULL);
2045 go_assert(seed_arg != NULL);
2047 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2048 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2049 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2050 bloc);
2051 Expression_list* args = new Expression_list();
2052 args->push_back(key_ref);
2053 args->push_back(seed_ref);
2054 args->push_back(size_arg);
2055 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2056 Expression* call = Expression::make_call(func, args, false, bloc);
2058 Expression_list* vals = new Expression_list();
2059 vals->push_back(call);
2060 Statement* s = Statement::make_return_statement(vals, bloc);
2061 gogo->add_statement(s);
2064 // Return the runtime function that compares whether two values of
2065 // this type are equal. If NAME is not NULL it is the name of this
2066 // type. EQUAL_FNTYPE is the type of the equality function, for
2067 // convenience; it may be NULL. This returns NULL if the type is not
2068 // comparable.
2070 Named_object*
2071 Type::equal_function(Gogo* gogo, Named_type* name, Function_type* equal_fntype)
2073 if (this->named_type() != NULL)
2074 go_assert(!this->named_type()->is_alias());
2076 // If the unaliased type is not a named type, then the type does not
2077 // have a name after all.
2078 if (name != NULL)
2079 name = name->unalias()->named_type();
2081 if (!this->is_comparable())
2082 return NULL;
2084 if (equal_fntype == NULL)
2086 Location bloc = Linemap::predeclared_location();
2087 Type* void_type = Type::make_void_type();
2088 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
2089 Typed_identifier_list* params = new Typed_identifier_list();
2090 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2091 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2092 Typed_identifier_list* results = new Typed_identifier_list();
2093 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2094 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
2097 const char* equal_fnname;
2098 if (this->compare_is_identity(gogo))
2100 int64_t size, align;
2101 if (!this->backend_type_size(gogo, &size)
2102 || !this->backend_type_align(gogo, &align))
2104 go_assert(saw_errors());
2105 return NULL;
2107 bool build_function = false;
2108 // This switch matches the one in Type::needs_specific_type_functions.
2109 // The alignment tests are because of the memequal functions,
2110 // which assume that the values are aligned as required for an
2111 // integer of that size.
2112 switch (size)
2114 case 0:
2115 equal_fnname = "runtime.memequal0";
2116 break;
2117 case 1:
2118 equal_fnname = "runtime.memequal8";
2119 break;
2120 case 2:
2121 if (align < Type::memequal_align(gogo, 16))
2122 build_function = true;
2123 else
2124 equal_fnname = "runtime.memequal16";
2125 break;
2126 case 4:
2127 if (align < Type::memequal_align(gogo, 32))
2128 build_function = true;
2129 else
2130 equal_fnname = "runtime.memequal32";
2131 break;
2132 case 8:
2133 if (align < Type::memequal_align(gogo, 64))
2134 build_function = true;
2135 else
2136 equal_fnname = "runtime.memequal64";
2137 break;
2138 case 16:
2139 if (align < Type::memequal_align(gogo, 128))
2140 build_function = true;
2141 else
2142 equal_fnname = "runtime.memequal128";
2143 break;
2144 default:
2145 build_function = true;
2146 break;
2148 if (build_function)
2150 // We don't have a built-in function for a type of this size
2151 // and alignment. Build a function to use that calls the
2152 // generic equality functions for identity, passing the size.
2153 return this->build_equal_function(gogo, name, size, equal_fntype);
2156 else
2158 switch (this->base()->classification())
2160 case Type::TYPE_ERROR:
2161 case Type::TYPE_VOID:
2162 case Type::TYPE_NIL:
2163 case Type::TYPE_FUNCTION:
2164 case Type::TYPE_MAP:
2165 // For these types is_comparable should have returned false.
2166 go_unreachable();
2168 case Type::TYPE_BOOLEAN:
2169 case Type::TYPE_INTEGER:
2170 case Type::TYPE_POINTER:
2171 case Type::TYPE_CHANNEL:
2172 // For these types compare_is_identity should have returned true.
2173 go_unreachable();
2175 case Type::TYPE_FLOAT:
2176 switch (this->float_type()->bits())
2178 case 32:
2179 equal_fnname = "runtime.f32equal";
2180 break;
2181 case 64:
2182 equal_fnname = "runtime.f64equal";
2183 break;
2184 default:
2185 go_unreachable();
2187 break;
2189 case Type::TYPE_COMPLEX:
2190 switch (this->complex_type()->bits())
2192 case 64:
2193 equal_fnname = "runtime.c64equal";
2194 break;
2195 case 128:
2196 equal_fnname = "runtime.c128equal";
2197 break;
2198 default:
2199 go_unreachable();
2201 break;
2203 case Type::TYPE_STRING:
2204 equal_fnname = "runtime.strequal";
2205 break;
2207 case Type::TYPE_STRUCT:
2208 // This is a struct which can not be compared using a simple
2209 // identity function. We need to build a function for
2210 // comparison.
2211 return this->build_equal_function(gogo, name, -1, equal_fntype);
2213 case Type::TYPE_ARRAY:
2214 if (this->is_slice_type())
2216 // Type::is_compatible_for_comparison should have
2217 // returned false.
2218 go_unreachable();
2220 else
2222 // This is an array which can not be compared using a
2223 // simple identity function. We need to build a
2224 // function for comparison.
2225 return this->build_equal_function(gogo, name, -1, equal_fntype);
2227 break;
2229 case Type::TYPE_INTERFACE:
2230 if (this->interface_type()->is_empty())
2231 equal_fnname = "runtime.nilinterequal";
2232 else
2233 equal_fnname = "runtime.interequal";
2234 break;
2236 case Type::TYPE_NAMED:
2237 case Type::TYPE_FORWARD:
2238 go_unreachable();
2240 default:
2241 go_unreachable();
2245 Location bloc = Linemap::predeclared_location();
2246 Named_object* equal_fn =
2247 Named_object::make_function_declaration(equal_fnname, NULL, equal_fntype,
2248 bloc);
2249 equal_fn->func_declaration_value()->set_asm_name(equal_fnname);
2250 return equal_fn;
2253 // A hash table mapping types to the specific equal functions.
2255 Type::Type_function Type::type_equal_functions_table;
2257 // Build an equality function that is specific to a type: if SIZE ==
2258 // -1, this is a struct or array type that cannot use an identity
2259 // comparison. Otherwise, it is a type that uses an identity
2260 // comparison but is not one of the standard supported sizes or it is
2261 // not aligned as needed.
2263 Named_object*
2264 Type::build_equal_function(Gogo* gogo, Named_type* name, int64_t size,
2265 Function_type* equal_fntype)
2267 std::pair<Type*, Named_object*> val(name != NULL ? name : this, nullptr);
2268 std::pair<Type_function::iterator, bool> ins =
2269 Type::type_equal_functions_table.insert(val);
2270 if (!ins.second)
2272 // We already have a function for this type.
2273 return ins.first->second;
2276 Backend_name bname;
2277 gogo->equal_function_name(this, name, &bname);
2279 Location bloc = Linemap::predeclared_location();
2281 const Package* package = NULL;
2282 bool is_defined_elsewhere =
2283 this->type_descriptor_defined_elsewhere(name, &package);
2285 Named_object* equal_fn;
2286 if (is_defined_elsewhere)
2287 equal_fn = Named_object::make_function_declaration(bname.name(), package,
2288 equal_fntype, bloc);
2289 else
2290 equal_fn = gogo->declare_package_function(bname.name(), equal_fntype, bloc);
2292 ins.first->second = equal_fn;
2294 if (is_defined_elsewhere)
2295 equal_fn->func_declaration_value()->set_asm_name(bname.asm_name());
2296 else
2298 if (gogo->in_global_scope())
2299 this->write_equal_function(gogo, name, size, &bname, equal_fntype);
2300 else
2301 gogo->queue_equal_function(this, name, size, &bname, equal_fntype);
2304 return equal_fn;
2307 // Write the equal function for a type that needs it written
2308 // specially.
2310 void
2311 Type::write_equal_function(Gogo* gogo, Named_type* name, int64_t size,
2312 const Backend_name* bname,
2313 Function_type* equal_fntype)
2315 Location bloc = Linemap::predeclared_location();
2317 if (gogo->specific_type_functions_are_written())
2319 go_assert(saw_errors());
2320 return;
2323 go_assert(this->is_comparable());
2325 Named_object* equal_fn = gogo->start_function(bname->name(), equal_fntype,
2326 false, bloc);
2327 equal_fn->func_value()->set_asm_name(bname->asm_name());
2328 equal_fn->func_value()->set_is_type_specific_function();
2329 gogo->start_block(bloc);
2331 if (size != -1)
2332 this->write_identity_equal(gogo, size);
2333 else if (name != NULL && name->real_type()->named_type() != NULL)
2334 this->write_named_equal(gogo, name);
2335 else if (this->struct_type() != NULL)
2336 this->struct_type()->write_equal_function(gogo, name);
2337 else if (this->array_type() != NULL)
2338 this->array_type()->write_equal_function(gogo, name);
2339 else
2340 go_unreachable();
2342 Block* b = gogo->finish_block(bloc);
2343 gogo->add_block(b, bloc);
2344 gogo->lower_block(equal_fn, b);
2345 gogo->order_block(b);
2346 gogo->remove_shortcuts_in_block(b);
2347 gogo->finish_function(bloc);
2349 // Build the function descriptor for the type descriptor to refer to.
2350 equal_fn->func_value()->descriptor(gogo, equal_fn);
2353 // Write an equality function for a type that can use an identity
2354 // equality comparison but is not one of the standard supported sizes.
2355 // For example, this would be used for the type [3]byte. This builds
2356 // a return statement that returns a call to the memequal function,
2357 // passing the two keys from the function arguments (already
2358 // constructed before this is called), and the constant size.
2360 void
2361 Type::write_identity_equal(Gogo* gogo, int64_t size)
2363 Location bloc = Linemap::predeclared_location();
2365 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2366 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2368 Typed_identifier_list* params = new Typed_identifier_list();
2369 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2370 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2371 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2373 Typed_identifier_list* results = new Typed_identifier_list();
2374 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2376 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2377 results, bloc);
2379 Named_object* memequal =
2380 Named_object::make_function_declaration("runtime.memequal", NULL,
2381 memequal_fntype, bloc);
2382 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2384 Named_object* key1_arg = gogo->lookup("key1", NULL);
2385 go_assert(key1_arg != NULL);
2386 Named_object* key2_arg = gogo->lookup("key2", NULL);
2387 go_assert(key2_arg != NULL);
2389 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2390 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2391 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2392 bloc);
2393 Expression_list* args = new Expression_list();
2394 args->push_back(key1_ref);
2395 args->push_back(key2_ref);
2396 args->push_back(size_arg);
2397 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2398 Expression* call = Expression::make_call(func, args, false, bloc);
2400 Expression_list* vals = new Expression_list();
2401 vals->push_back(call);
2402 Statement* s = Statement::make_return_statement(vals, bloc);
2403 gogo->add_statement(s);
2406 // Write an equality function that simply calls the equality function
2407 // for a named type. This is used when one named type is defined as
2408 // another. This ensures that this case works when the other named
2409 // type is defined in another package and relies on calling equality
2410 // functions defined only in that package.
2412 void
2413 Type::write_named_equal(Gogo* gogo, Named_type* name)
2415 Location bloc = Linemap::predeclared_location();
2417 // The pointers to the types we are going to compare. These have
2418 // type unsafe.Pointer.
2419 Named_object* key1_arg = gogo->lookup("key1", NULL);
2420 Named_object* key2_arg = gogo->lookup("key2", NULL);
2421 go_assert(key1_arg != NULL && key2_arg != NULL);
2423 Named_type* base_type = name->real_type()->named_type();
2424 go_assert(base_type != NULL);
2426 // Build temporaries with the base type.
2427 Type* pt = Type::make_pointer_type(base_type);
2429 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2430 ref = Expression::make_cast(pt, ref, bloc);
2431 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2432 gogo->add_statement(p1);
2434 ref = Expression::make_var_reference(key2_arg, bloc);
2435 ref = Expression::make_cast(pt, ref, bloc);
2436 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2437 gogo->add_statement(p2);
2439 // Compare the values for equality.
2440 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2441 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2443 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2444 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2446 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2448 // Return the equality comparison.
2449 Expression_list* vals = new Expression_list();
2450 vals->push_back(cond);
2451 Statement* s = Statement::make_return_statement(vals, bloc);
2452 gogo->add_statement(s);
2455 // Return whether this type is stored directly in an interface's
2456 // data word.
2458 // Since finalize_methods runs before type checking, we may see a
2459 // malformed type like 'type T struct { x T }'. Use a visited map
2460 // to avoid infinite recursion.
2462 bool
2463 Type::is_direct_iface_type() const
2465 Unordered_set(const Type*) visited;
2466 return this->is_direct_iface_type_helper(&visited);
2469 bool
2470 Type::is_direct_iface_type_helper(Unordered_set(const Type*)* visited) const
2472 if (this->points_to() != NULL)
2474 // Pointers to notinheap types must be stored indirectly. See
2475 // https://golang.org/issue/42076.
2476 if (!this->points_to()->in_heap())
2477 return false;
2478 return true;
2481 if (this->channel_type() != NULL
2482 || this->function_type() != NULL
2483 || this->map_type() != NULL)
2484 return true;
2486 std::pair<Unordered_set(const Type*)::iterator, bool> ins
2487 = visited->insert(this);
2488 if (!ins.second)
2489 // malformed circular type
2490 return false;
2492 const Struct_type* st = this->struct_type();
2493 if (st != NULL)
2494 return (st->field_count() == 1
2495 && st->field(0)->type()->is_direct_iface_type_helper(visited));
2496 const Array_type* at = this->array_type();
2497 if (at != NULL && !at->is_slice_type())
2499 int64_t len;
2500 return (at->int_length(&len) && len == 1
2501 && at->element_type()->is_direct_iface_type_helper(visited));
2503 return false;
2506 // Return a composite literal for the type descriptor for a plain type
2507 // of kind RUNTIME_TYPE_KIND named NAME.
2509 Expression*
2510 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2511 Named_type* name, const Methods* methods,
2512 bool only_value_methods)
2514 Location bloc = Linemap::predeclared_location();
2516 Type* td_type = Type::make_type_descriptor_type();
2517 const Struct_field_list* fields = td_type->struct_type()->fields();
2519 Expression_list* vals = new Expression_list();
2520 vals->reserve(12);
2522 bool has_pointer;
2523 if (name != NULL)
2524 has_pointer = name->has_pointer();
2525 else
2526 has_pointer = this->has_pointer();
2527 if (!has_pointer)
2528 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2529 if (this->is_direct_iface_type())
2530 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2531 int64_t ptrsize;
2532 int64_t ptrdata;
2533 if (has_pointer && this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2534 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2536 Struct_field_list::const_iterator p = fields->begin();
2537 go_assert(p->is_field_name("size"));
2538 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2539 vals->push_back(Expression::make_type_info(this, type_info));
2541 ++p;
2542 go_assert(p->is_field_name("ptrdata"));
2543 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2544 if (has_pointer)
2545 vals->push_back(Expression::make_type_info(this, type_info));
2546 else
2547 vals->push_back(Expression::make_integer_ul(0, p->type(), bloc));
2549 ++p;
2550 go_assert(p->is_field_name("hash"));
2551 unsigned int h;
2552 if (name != NULL)
2553 h = name->hash_for_method(gogo, Type::COMPARE_TAGS);
2554 else
2555 h = this->hash_for_method(gogo, Type::COMPARE_TAGS);
2556 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2558 ++p;
2559 go_assert(p->is_field_name("tflag"));
2560 unsigned long tflag = 0;
2561 if (this->compare_is_identity(gogo))
2562 tflag |= TFLAG_REGULAR_MEMORY;
2563 vals->push_back(Expression::make_integer_ul(tflag, p->type(), bloc));
2565 ++p;
2566 go_assert(p->is_field_name("align"));
2567 type_info = Expression::TYPE_INFO_ALIGNMENT;
2568 vals->push_back(Expression::make_type_info(this, type_info));
2570 ++p;
2571 go_assert(p->is_field_name("fieldAlign"));
2572 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2573 vals->push_back(Expression::make_type_info(this, type_info));
2575 ++p;
2576 go_assert(p->is_field_name("kind"));
2577 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2578 bloc));
2580 ++p;
2581 go_assert(p->is_field_name("equal"));
2582 Function_type* equal_fntype = p->type()->function_type();
2583 Named_object* equal_fn = this->equal_function(gogo, name, equal_fntype);
2584 if (equal_fn == NULL)
2585 vals->push_back(Expression::make_cast(equal_fntype,
2586 Expression::make_nil(bloc),
2587 bloc));
2588 else
2589 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2591 ++p;
2592 go_assert(p->is_field_name("gcdata"));
2593 if (has_pointer)
2594 vals->push_back(Expression::make_gc_symbol(this));
2595 else
2596 vals->push_back(Expression::make_cast(p->type(),
2597 Expression::make_nil(bloc),
2598 bloc));
2600 ++p;
2601 go_assert(p->is_field_name("string"));
2602 Expression* s = Expression::make_string((name != NULL
2603 ? name->reflection(gogo)
2604 : this->reflection(gogo)),
2605 bloc);
2606 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2608 ++p;
2609 go_assert(p->is_field_name("uncommonType"));
2610 if (name == NULL && methods == NULL)
2611 vals->push_back(Expression::make_nil(bloc));
2612 else
2614 if (methods == NULL)
2615 methods = name->methods();
2616 vals->push_back(this->uncommon_type_constructor(gogo,
2617 p->type()->deref(),
2618 name, methods,
2619 only_value_methods));
2622 ++p;
2623 go_assert(p->is_field_name("ptrToThis"));
2624 if (name == NULL && methods == NULL)
2625 vals->push_back(Expression::make_nil(bloc));
2626 else
2628 Type* pt;
2629 if (name != NULL)
2630 pt = Type::make_pointer_type(name);
2631 else
2632 pt = Type::make_pointer_type(this);
2633 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2636 ++p;
2637 go_assert(p == fields->end());
2639 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2642 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2643 // length used by the gc toolchain, and also appears in
2644 // libgo/go/reflect/type.go.
2646 static const int64_t max_ptrmask_bytes = 2048;
2648 // Return a pointer to the Garbage Collection information for this type.
2650 Bexpression*
2651 Type::gc_symbol_pointer(Gogo* gogo)
2653 Type* t = this->unalias();
2655 if (!t->has_pointer())
2656 return gogo->backend()->nil_pointer_expression();
2658 if (t->gc_symbol_var_ == NULL)
2660 t->make_gc_symbol_var(gogo);
2661 go_assert(t->gc_symbol_var_ != NULL);
2663 Location bloc = Linemap::predeclared_location();
2664 Bexpression* var_expr =
2665 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2666 Bexpression* addr_expr =
2667 gogo->backend()->address_expression(var_expr, bloc);
2669 Type* uint8_type = Type::lookup_integer_type("uint8");
2670 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2671 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2672 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2675 // A mapping from unnamed types to GC symbol variables.
2677 Type::GC_symbol_vars Type::gc_symbol_vars;
2679 // Build the GC symbol for this type.
2681 void
2682 Type::make_gc_symbol_var(Gogo* gogo)
2684 go_assert(this->gc_symbol_var_ == NULL);
2686 Named_type* nt = this->named_type();
2688 // We can have multiple instances of unnamed types and similar to type
2689 // descriptors, we only want to the emit the GC data once, so we use a
2690 // hash table.
2691 Bvariable** phash = NULL;
2692 if (nt == NULL)
2694 Bvariable* bvnull = NULL;
2695 std::pair<GC_symbol_vars::iterator, bool> ins =
2696 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2697 if (!ins.second)
2699 // We've already built a gc symbol for this type.
2700 this->gc_symbol_var_ = ins.first->second;
2701 return;
2703 phash = &ins.first->second;
2706 int64_t ptrsize;
2707 int64_t ptrdata;
2708 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2710 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2711 if (phash != NULL)
2712 *phash = this->gc_symbol_var_;
2713 return;
2716 std::string sym_name = gogo->gc_symbol_name(this);
2718 // Build the contents of the gc symbol.
2719 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2720 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2722 // If the type descriptor for this type is defined somewhere else, so is the
2723 // GC symbol.
2724 const Package* dummy;
2725 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2727 this->gc_symbol_var_ =
2728 gogo->backend()->implicit_variable_reference(sym_name, "",
2729 sym_btype);
2730 if (phash != NULL)
2731 *phash = this->gc_symbol_var_;
2732 return;
2735 // See if this gc symbol can appear in multiple packages.
2736 bool is_common = false;
2737 if (nt != NULL)
2739 // We create the symbol for a builtin type whenever we need
2740 // it.
2741 is_common = nt->is_builtin();
2743 else
2745 // This is an unnamed type. The descriptor could be defined in
2746 // any package where it is needed, and the linker will pick one
2747 // descriptor to keep.
2748 is_common = true;
2751 // Since we are building the GC symbol in this package, we must create the
2752 // variable before converting the initializer to its backend representation
2753 // because the initializer may refer to the GC symbol for this type.
2754 unsigned int flags = Backend::variable_is_constant;
2755 if (is_common)
2756 flags |= Backend::variable_is_common;
2757 else
2758 flags |= Backend::variable_is_hidden;
2759 this->gc_symbol_var_ =
2760 gogo->backend()->implicit_variable(sym_name, "", sym_btype, flags, 0);
2761 if (phash != NULL)
2762 *phash = this->gc_symbol_var_;
2764 Translate_context context(gogo, NULL, NULL, NULL);
2765 context.set_is_const();
2766 Bexpression* sym_binit = sym_init->get_backend(&context);
2767 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2768 sym_btype, flags, sym_binit);
2771 // Return whether this type needs a GC program, and set *PTRDATA to
2772 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2773 // pointer.
2775 bool
2776 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2778 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2779 if (!voidptr->backend_type_size(gogo, ptrsize))
2780 go_unreachable();
2782 if (!this->backend_type_ptrdata(gogo, ptrdata))
2784 go_assert(saw_errors());
2785 return false;
2788 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2791 // A simple class used to build a GC ptrmask for a type.
2793 class Ptrmask
2795 public:
2796 Ptrmask(size_t count)
2797 : bits_((count + 7) / 8, 0)
2800 void
2801 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2803 std::string
2804 symname() const;
2806 Expression*
2807 constructor() const;
2809 private:
2810 void
2811 set(size_t index)
2812 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2814 // The actual bits.
2815 std::vector<unsigned char> bits_;
2818 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2819 // counts in bytes. PTRSIZE is the size of a pointer on the target
2820 // system.
2822 void
2823 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2825 if (!type->has_pointer())
2826 return;
2828 switch (type->base()->classification())
2830 default:
2831 case Type::TYPE_NIL:
2832 case Type::TYPE_CALL_MULTIPLE_RESULT:
2833 case Type::TYPE_NAMED:
2834 case Type::TYPE_FORWARD:
2835 go_unreachable();
2837 case Type::TYPE_ERROR:
2838 case Type::TYPE_VOID:
2839 case Type::TYPE_BOOLEAN:
2840 case Type::TYPE_INTEGER:
2841 case Type::TYPE_FLOAT:
2842 case Type::TYPE_COMPLEX:
2843 case Type::TYPE_SINK:
2844 break;
2846 case Type::TYPE_FUNCTION:
2847 case Type::TYPE_POINTER:
2848 case Type::TYPE_MAP:
2849 case Type::TYPE_CHANNEL:
2850 // These types are all a single pointer.
2851 go_assert((offset % ptrsize) == 0);
2852 this->set(offset / ptrsize);
2853 break;
2855 case Type::TYPE_STRING:
2856 // A string starts with a single pointer.
2857 go_assert((offset % ptrsize) == 0);
2858 this->set(offset / ptrsize);
2859 break;
2861 case Type::TYPE_INTERFACE:
2862 // An interface is two pointers.
2863 go_assert((offset % ptrsize) == 0);
2864 this->set(offset / ptrsize);
2865 this->set((offset / ptrsize) + 1);
2866 break;
2868 case Type::TYPE_STRUCT:
2870 const Struct_field_list* fields = type->struct_type()->fields();
2871 int64_t soffset = 0;
2872 for (Struct_field_list::const_iterator pf = fields->begin();
2873 pf != fields->end();
2874 ++pf)
2876 int64_t field_align;
2877 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2879 go_assert(saw_errors());
2880 return;
2882 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2884 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2886 int64_t field_size;
2887 if (!pf->type()->backend_type_size(gogo, &field_size))
2889 go_assert(saw_errors());
2890 return;
2892 soffset += field_size;
2895 break;
2897 case Type::TYPE_ARRAY:
2898 if (type->is_slice_type())
2900 // A slice starts with a single pointer.
2901 go_assert((offset % ptrsize) == 0);
2902 this->set(offset / ptrsize);
2903 break;
2905 else
2907 int64_t len;
2908 if (!type->array_type()->int_length(&len))
2910 go_assert(saw_errors());
2911 return;
2914 Type* element_type = type->array_type()->element_type();
2915 int64_t ele_size;
2916 if (!element_type->backend_type_size(gogo, &ele_size))
2918 go_assert(saw_errors());
2919 return;
2922 int64_t eoffset = 0;
2923 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2924 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2925 break;
2930 // Return a symbol name for this ptrmask. This is used to coalesce
2931 // identical ptrmasks, which are common. The symbol name must use
2932 // only characters that are valid in symbols. It's nice if it's
2933 // short. For smaller ptrmasks, we convert it to a string that uses
2934 // only 32 characters. For longer pointer masks, apply the same
2935 // process to the SHA1 digest of the bits, so as to avoid
2936 // pathologically long symbol names (see related Go issues #32083 and
2937 // #11583 for more on this). To avoid collisions between the two
2938 // encoding schemes, use a prefix ("X") for the SHA form to
2939 // disambiguate.
2941 std::string
2942 Ptrmask::symname() const
2944 const std::vector<unsigned char>* bits(&this->bits_);
2945 std::vector<unsigned char> shabits;
2946 std::string prefix;
2948 if (this->bits_.size() > 128)
2950 // Produce a SHA1 digest of the data.
2951 Go_sha1_helper* sha1_helper = go_create_sha1_helper();
2952 sha1_helper->process_bytes(&this->bits_[0], this->bits_.size());
2953 std::string digest = sha1_helper->finish();
2954 delete sha1_helper;
2956 // Redirect the bits vector to the digest, and update the prefix.
2957 prefix = "X";
2958 for (std::string::const_iterator p = digest.begin();
2959 p != digest.end();
2960 ++p)
2962 unsigned char c = *p;
2963 shabits.push_back(c);
2965 bits = &shabits;
2968 const char chars[33] = "abcdefghijklmnopqrstuvwxyzABCDEF";
2969 go_assert(chars[32] == '\0');
2970 std::string ret(prefix);
2971 unsigned int b = 0;
2972 int remaining = 0;
2973 for (std::vector<unsigned char>::const_iterator p = bits->begin();
2974 p != bits->end();
2975 ++p)
2977 b |= *p << remaining;
2978 remaining += 8;
2979 while (remaining >= 5)
2981 ret += chars[b & 0x1f];
2982 b >>= 5;
2983 remaining -= 5;
2986 while (remaining > 0)
2988 ret += chars[b & 0x1f];
2989 b >>= 5;
2990 remaining -= 5;
2992 return ret;
2995 // Return a constructor for this ptrmask. This will be used to
2996 // initialize the runtime ptrmask value.
2998 Expression*
2999 Ptrmask::constructor() const
3001 Location bloc = Linemap::predeclared_location();
3002 Type* byte_type = Type::lookup_integer_type("byte");
3003 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
3004 bloc);
3005 Array_type* at = Type::make_array_type(byte_type, len);
3006 Expression_list* vals = new Expression_list();
3007 vals->reserve(this->bits_.size());
3008 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
3009 p != this->bits_.end();
3010 ++p)
3011 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3012 return Expression::make_array_composite_literal(at, vals, bloc);
3015 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
3016 Type::GC_gcbits_vars Type::gc_gcbits_vars;
3018 // Return a ptrmask variable for a type. For a type descriptor this
3019 // is only used for variables that are small enough to not need a
3020 // gcprog, but for a global variable this is used for a variable of
3021 // any size. PTRDATA is the number of bytes of the type that contain
3022 // pointer data. PTRSIZE is the size of a pointer on the target
3023 // system.
3025 Bvariable*
3026 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3028 Ptrmask ptrmask(ptrdata / ptrsize);
3029 if (ptrdata >= ptrsize)
3030 ptrmask.set_from(gogo, this, ptrsize, 0);
3031 else
3033 // This can happen in error cases. Just build an empty gcbits.
3034 go_assert(saw_errors());
3037 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
3038 Bvariable* bvnull = NULL;
3039 std::pair<GC_gcbits_vars::iterator, bool> ins =
3040 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
3041 if (!ins.second)
3043 // We've already built a GC symbol for this set of gcbits.
3044 return ins.first->second;
3047 Expression* val = ptrmask.constructor();
3048 Translate_context context(gogo, NULL, NULL, NULL);
3049 context.set_is_const();
3050 Bexpression* bval = val->get_backend(&context);
3052 Btype *btype = val->type()->get_backend(gogo);
3053 unsigned int flags = (Backend::variable_is_constant
3054 | Backend::variable_is_common);
3055 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, "",
3056 btype, flags, 0);
3057 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, flags,
3058 bval);
3059 ins.first->second = ret;
3060 return ret;
3063 // A GCProg is used to build a program for the garbage collector.
3064 // This is used for types with a lot of pointer data, to reduce the
3065 // size of the data in the compiled program. The program is expanded
3066 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
3068 class GCProg
3070 public:
3071 GCProg()
3072 : bytes_(), index_(0), nb_(0)
3075 // The number of bits described so far.
3076 int64_t
3077 bit_index() const
3078 { return this->index_; }
3080 void
3081 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
3083 void
3084 end();
3086 Expression*
3087 constructor() const;
3089 private:
3090 void
3091 ptr(int64_t);
3093 bool
3094 should_repeat(int64_t, int64_t);
3096 void
3097 repeat(int64_t, int64_t);
3099 void
3100 zero_until(int64_t);
3102 void
3103 lit(unsigned char);
3105 void
3106 varint(int64_t);
3108 void
3109 flushlit();
3111 // Add a byte to the program.
3112 void
3113 byte(unsigned char x)
3114 { this->bytes_.push_back(x); }
3116 // The maximum number of bytes of literal bits.
3117 static const int max_literal = 127;
3119 // The program.
3120 std::vector<unsigned char> bytes_;
3121 // The index of the last bit described.
3122 int64_t index_;
3123 // The current set of literal bits.
3124 unsigned char b_[max_literal];
3125 // The current number of literal bits.
3126 int nb_;
3129 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
3130 // counts in bytes. PTRSIZE is the size of a pointer on the target
3131 // system.
3133 void
3134 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
3136 switch (type->base()->classification())
3138 default:
3139 case Type::TYPE_NIL:
3140 case Type::TYPE_CALL_MULTIPLE_RESULT:
3141 case Type::TYPE_NAMED:
3142 case Type::TYPE_FORWARD:
3143 go_unreachable();
3145 case Type::TYPE_ERROR:
3146 case Type::TYPE_VOID:
3147 case Type::TYPE_BOOLEAN:
3148 case Type::TYPE_INTEGER:
3149 case Type::TYPE_FLOAT:
3150 case Type::TYPE_COMPLEX:
3151 case Type::TYPE_SINK:
3152 break;
3154 case Type::TYPE_FUNCTION:
3155 case Type::TYPE_POINTER:
3156 case Type::TYPE_MAP:
3157 case Type::TYPE_CHANNEL:
3158 // These types are all a single pointer.
3159 go_assert((offset % ptrsize) == 0);
3160 this->ptr(offset / ptrsize);
3161 break;
3163 case Type::TYPE_STRING:
3164 // A string starts with a single pointer.
3165 go_assert((offset % ptrsize) == 0);
3166 this->ptr(offset / ptrsize);
3167 break;
3169 case Type::TYPE_INTERFACE:
3170 // An interface is two pointers.
3171 go_assert((offset % ptrsize) == 0);
3172 this->ptr(offset / ptrsize);
3173 this->ptr((offset / ptrsize) + 1);
3174 break;
3176 case Type::TYPE_STRUCT:
3178 if (!type->has_pointer())
3179 return;
3181 const Struct_field_list* fields = type->struct_type()->fields();
3182 int64_t soffset = 0;
3183 for (Struct_field_list::const_iterator pf = fields->begin();
3184 pf != fields->end();
3185 ++pf)
3187 int64_t field_align;
3188 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3190 go_assert(saw_errors());
3191 return;
3193 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
3195 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
3197 int64_t field_size;
3198 if (!pf->type()->backend_type_size(gogo, &field_size))
3200 go_assert(saw_errors());
3201 return;
3203 soffset += field_size;
3206 break;
3208 case Type::TYPE_ARRAY:
3209 if (type->is_slice_type())
3211 // A slice starts with a single pointer.
3212 go_assert((offset % ptrsize) == 0);
3213 this->ptr(offset / ptrsize);
3214 break;
3216 else
3218 if (!type->has_pointer())
3219 return;
3221 int64_t len;
3222 if (!type->array_type()->int_length(&len))
3224 go_assert(saw_errors());
3225 return;
3228 Type* element_type = type->array_type()->element_type();
3230 // Flatten array of array to a big array by multiplying counts.
3231 while (element_type->array_type() != NULL
3232 && !element_type->is_slice_type())
3234 int64_t ele_len;
3235 if (!element_type->array_type()->int_length(&ele_len))
3237 go_assert(saw_errors());
3238 return;
3241 len *= ele_len;
3242 element_type = element_type->array_type()->element_type();
3245 int64_t ele_size;
3246 if (!element_type->backend_type_size(gogo, &ele_size))
3248 go_assert(saw_errors());
3249 return;
3252 go_assert(len > 0 && ele_size > 0);
3254 if (!this->should_repeat(ele_size / ptrsize, len))
3256 // Cheaper to just emit the bits.
3257 int64_t eoffset = 0;
3258 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3259 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3261 else
3263 go_assert((offset % ptrsize) == 0);
3264 go_assert((ele_size % ptrsize) == 0);
3265 this->set_from(gogo, element_type, ptrsize, offset);
3266 this->zero_until((offset + ele_size) / ptrsize);
3267 this->repeat(ele_size / ptrsize, len - 1);
3270 break;
3275 // Emit a 1 into the bit stream of a GC program at the given bit index.
3277 void
3278 GCProg::ptr(int64_t index)
3280 go_assert(index >= this->index_);
3281 this->zero_until(index);
3282 this->lit(1);
3285 // Return whether it is worthwhile to use a repeat to describe c
3286 // elements of n bits each, compared to just emitting c copies of the
3287 // n-bit description.
3289 bool
3290 GCProg::should_repeat(int64_t n, int64_t c)
3292 // Repeat if there is more than 1 item and if the total data doesn't
3293 // fit into four bytes.
3294 return c > 1 && c * n > 4 * 8;
3297 // Emit an instruction to repeat the description of the last n words c
3298 // times (including the initial description, so c + 1 times in total).
3300 void
3301 GCProg::repeat(int64_t n, int64_t c)
3303 if (n == 0 || c == 0)
3304 return;
3305 this->flushlit();
3306 if (n < 128)
3307 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3308 else
3310 this->byte(0x80);
3311 this->varint(n);
3313 this->varint(c);
3314 this->index_ += n * c;
3317 // Add zeros to the bit stream up to the given index.
3319 void
3320 GCProg::zero_until(int64_t index)
3322 go_assert(index >= this->index_);
3323 int64_t skip = index - this->index_;
3324 if (skip == 0)
3325 return;
3326 if (skip < 4 * 8)
3328 for (int64_t i = 0; i < skip; ++i)
3329 this->lit(0);
3330 return;
3332 this->lit(0);
3333 this->flushlit();
3334 this->repeat(1, skip - 1);
3337 // Add a single literal bit to the program.
3339 void
3340 GCProg::lit(unsigned char x)
3342 if (this->nb_ == GCProg::max_literal)
3343 this->flushlit();
3344 this->b_[this->nb_] = x;
3345 ++this->nb_;
3346 ++this->index_;
3349 // Emit the varint encoding of x.
3351 void
3352 GCProg::varint(int64_t x)
3354 go_assert(x >= 0);
3355 while (x >= 0x80)
3357 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3358 x >>= 7;
3360 this->byte(static_cast<unsigned char>(x & 0x7f));
3363 // Flush any pending literal bits.
3365 void
3366 GCProg::flushlit()
3368 if (this->nb_ == 0)
3369 return;
3370 this->byte(static_cast<unsigned char>(this->nb_));
3371 unsigned char bits = 0;
3372 for (int i = 0; i < this->nb_; ++i)
3374 bits |= this->b_[i] << (i % 8);
3375 if ((i + 1) % 8 == 0)
3377 this->byte(bits);
3378 bits = 0;
3381 if (this->nb_ % 8 != 0)
3382 this->byte(bits);
3383 this->nb_ = 0;
3386 // Mark the end of a GC program.
3388 void
3389 GCProg::end()
3391 this->flushlit();
3392 this->byte(0);
3395 // Return an Expression for the bytes in a GC program.
3397 Expression*
3398 GCProg::constructor() const
3400 Location bloc = Linemap::predeclared_location();
3402 // The first four bytes are the length of the program in target byte
3403 // order. Build a struct whose first type is uint32 to make this
3404 // work.
3406 Type* uint32_type = Type::lookup_integer_type("uint32");
3408 Type* byte_type = Type::lookup_integer_type("byte");
3409 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3410 bloc);
3411 Array_type* at = Type::make_array_type(byte_type, len);
3413 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3414 "bytes", at);
3416 Expression_list* vals = new Expression_list();
3417 vals->reserve(this->bytes_.size());
3418 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3419 p != this->bytes_.end();
3420 ++p)
3421 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3422 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3424 vals = new Expression_list();
3425 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3426 bloc));
3427 vals->push_back(bytes);
3429 return Expression::make_struct_composite_literal(st, vals, bloc);
3432 // Return a composite literal for the garbage collection program for
3433 // this type. This is only used for types that are too large to use a
3434 // ptrmask.
3436 Expression*
3437 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3439 Location bloc = Linemap::predeclared_location();
3441 GCProg prog;
3442 prog.set_from(gogo, this, ptrsize, 0);
3443 int64_t offset = prog.bit_index() * ptrsize;
3444 prog.end();
3446 int64_t type_size;
3447 if (!this->backend_type_size(gogo, &type_size))
3449 go_assert(saw_errors());
3450 return Expression::make_error(bloc);
3453 go_assert(offset >= ptrdata && offset <= type_size);
3455 return prog.constructor();
3458 // Return a composite literal for the uncommon type information for
3459 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3460 // struct. If name is not NULL, it is the name of the type. If
3461 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3462 // is true if only value methods should be included. At least one of
3463 // NAME and METHODS must not be NULL.
3465 Expression*
3466 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3467 Named_type* name, const Methods* methods,
3468 bool only_value_methods) const
3470 Location bloc = Linemap::predeclared_location();
3472 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3474 Expression_list* vals = new Expression_list();
3475 vals->reserve(3);
3477 Struct_field_list::const_iterator p = fields->begin();
3478 go_assert(p->is_field_name("name"));
3480 ++p;
3481 go_assert(p->is_field_name("pkgPath"));
3483 if (name == NULL)
3485 vals->push_back(Expression::make_nil(bloc));
3486 vals->push_back(Expression::make_nil(bloc));
3488 else
3490 Named_object* no = name->named_object();
3491 std::string n = Gogo::unpack_hidden_name(no->name());
3492 Expression* s = Expression::make_string(n, bloc);
3493 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3495 if (name->is_builtin())
3496 vals->push_back(Expression::make_nil(bloc));
3497 else
3499 const Package* package = no->package();
3500 const std::string& pkgpath(package == NULL
3501 ? gogo->pkgpath()
3502 : package->pkgpath());
3503 s = Expression::make_string(pkgpath, bloc);
3504 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3508 ++p;
3509 go_assert(p->is_field_name("methods"));
3510 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3511 only_value_methods));
3513 ++p;
3514 go_assert(p == fields->end());
3516 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3517 vals, bloc);
3518 return Expression::make_unary(OPERATOR_AND, r, bloc);
3521 // Sort methods by name.
3523 class Sort_methods
3525 public:
3526 bool
3527 operator()(const std::pair<std::string, const Method*>& m1,
3528 const std::pair<std::string, const Method*>& m2) const
3530 return (Gogo::unpack_hidden_name(m1.first)
3531 < Gogo::unpack_hidden_name(m2.first));
3535 // Return a composite literal for the type method table for this type.
3536 // METHODS_TYPE is the type of the table, and is a slice type.
3537 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3538 // then only value methods are used.
3540 Expression*
3541 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3542 const Methods* methods,
3543 bool only_value_methods) const
3545 Location bloc = Linemap::predeclared_location();
3547 std::vector<std::pair<std::string, const Method*> > smethods;
3548 if (methods != NULL)
3550 smethods.reserve(methods->count());
3551 for (Methods::const_iterator p = methods->begin();
3552 p != methods->end();
3553 ++p)
3555 if (p->second->is_ambiguous())
3556 continue;
3557 if (only_value_methods && !p->second->is_value_method())
3558 continue;
3560 // This is where we implement the magic //go:nointerface
3561 // comment. If we saw that comment, we don't add this
3562 // method to the type descriptor.
3563 if (p->second->nointerface())
3564 continue;
3566 smethods.push_back(std::make_pair(p->first, p->second));
3570 if (smethods.empty())
3571 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3573 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3575 Type* method_type = methods_type->array_type()->element_type();
3577 Expression_list* vals = new Expression_list();
3578 vals->reserve(smethods.size());
3579 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3580 = smethods.begin();
3581 p != smethods.end();
3582 ++p)
3583 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3584 p->second, only_value_methods));
3586 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3589 // Return a composite literal for a single method. METHOD_TYPE is the
3590 // type of the entry. METHOD_NAME is the name of the method and M is
3591 // the method information.
3593 Expression*
3594 Type::method_constructor(Gogo*, Type* method_type,
3595 const std::string& method_name,
3596 const Method* m,
3597 bool only_value_methods) const
3599 Location bloc = Linemap::predeclared_location();
3601 const Struct_field_list* fields = method_type->struct_type()->fields();
3603 Expression_list* vals = new Expression_list();
3604 vals->reserve(5);
3606 Struct_field_list::const_iterator p = fields->begin();
3607 go_assert(p->is_field_name("name"));
3608 const std::string n = Gogo::unpack_hidden_name(method_name);
3609 Expression* s = Expression::make_string(n, bloc);
3610 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3612 ++p;
3613 go_assert(p->is_field_name("pkgPath"));
3614 if (!Gogo::is_hidden_name(method_name))
3615 vals->push_back(Expression::make_nil(bloc));
3616 else
3618 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3619 bloc);
3620 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3623 // The direct_iface_stub dereferences the value stored in the
3624 // interface when calling the method.
3626 // We need this for a value method if this type is a pointer to a
3627 // direct-iface type. For example, if we have "type C chan int" and M
3628 // is a value method on C, then since a channel is a direct-iface type
3629 // M expects a value of type C. We are generating the method table
3630 // for *C, so the value stored in the interface is *C. We have to
3631 // call the direct-iface stub to dereference *C to get C to pass to M.
3633 // We also need this for a pointer method if the pointer itself is not
3634 // a direct-iface type, as arises for notinheap types. In this case
3635 // we have "type NIH ..." where NIH is go:notinheap. Since NIH is
3636 // notinheap, *NIH is a pointer type that is not a direct-iface type,
3637 // so the value stored in the interface is actually **NIH. The method
3638 // expects *NIH, so we have to call the direct-iface stub to
3639 // dereference **NIH to get *NIH to pass to M. (This case doesn't
3640 // arise for value methods because pointer types can't have methods,
3641 // so there is no such thing as a value method for type *NIH.)
3643 bool use_direct_iface_stub = false;
3644 if (m->is_value_method()
3645 && this->points_to() != NULL
3646 && this->points_to()->is_direct_iface_type())
3647 use_direct_iface_stub = true;
3648 if (!m->is_value_method()
3649 && this->points_to() != NULL
3650 && !this->is_direct_iface_type())
3651 use_direct_iface_stub = true;
3653 Named_object* no = (use_direct_iface_stub
3654 ? m->iface_stub_object()
3655 : (m->needs_stub_method()
3656 ? m->stub_object()
3657 : m->named_object()));
3659 Function_type* mtype;
3660 if (no->is_function())
3661 mtype = no->func_value()->type();
3662 else
3663 mtype = no->func_declaration_value()->type();
3664 go_assert(mtype->is_method());
3665 Type* nonmethod_type = mtype->copy_without_receiver();
3667 ++p;
3668 go_assert(p->is_field_name("mtyp"));
3669 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3671 ++p;
3672 go_assert(p->is_field_name("typ"));
3673 bool want_pointer_receiver = (!only_value_methods && m->is_value_method()
3674 && !use_direct_iface_stub);
3675 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3676 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3678 ++p;
3679 go_assert(p->is_field_name("tfn"));
3680 vals->push_back(Expression::make_func_code_reference(no, bloc));
3682 ++p;
3683 go_assert(p == fields->end());
3685 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3688 // Return a composite literal for the type descriptor of a plain type.
3689 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3690 // NULL, it is the name to use as well as the list of methods.
3692 Expression*
3693 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3694 Named_type* name)
3696 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3697 name, NULL, true);
3700 // Return the type reflection string for this type.
3702 std::string
3703 Type::reflection(Gogo* gogo) const
3705 std::string ret;
3707 // The do_reflection virtual function should set RET to the
3708 // reflection string.
3709 this->do_reflection(gogo, &ret);
3711 return ret;
3714 // Return whether the backend size of the type is known.
3716 bool
3717 Type::is_backend_type_size_known(Gogo* gogo)
3719 switch (this->classification_)
3721 case TYPE_ERROR:
3722 case TYPE_VOID:
3723 case TYPE_BOOLEAN:
3724 case TYPE_INTEGER:
3725 case TYPE_FLOAT:
3726 case TYPE_COMPLEX:
3727 case TYPE_STRING:
3728 case TYPE_FUNCTION:
3729 case TYPE_POINTER:
3730 case TYPE_NIL:
3731 case TYPE_MAP:
3732 case TYPE_CHANNEL:
3733 case TYPE_INTERFACE:
3734 return true;
3736 case TYPE_STRUCT:
3738 const Struct_field_list* fields = this->struct_type()->fields();
3739 for (Struct_field_list::const_iterator pf = fields->begin();
3740 pf != fields->end();
3741 ++pf)
3742 if (!pf->type()->is_backend_type_size_known(gogo))
3743 return false;
3744 return true;
3747 case TYPE_ARRAY:
3749 const Array_type* at = this->array_type();
3750 if (at->length() == NULL)
3751 return true;
3752 else
3754 Numeric_constant nc;
3755 if (!at->length()->numeric_constant_value(&nc))
3756 return false;
3757 mpz_t ival;
3758 if (!nc.to_int(&ival))
3759 return false;
3760 mpz_clear(ival);
3761 return at->element_type()->is_backend_type_size_known(gogo);
3765 case TYPE_NAMED:
3766 this->named_type()->convert(gogo);
3767 return this->named_type()->is_named_backend_type_size_known();
3769 case TYPE_FORWARD:
3771 Forward_declaration_type* fdt = this->forward_declaration_type();
3772 return fdt->real_type()->is_backend_type_size_known(gogo);
3775 case TYPE_SINK:
3776 case TYPE_CALL_MULTIPLE_RESULT:
3777 go_unreachable();
3779 default:
3780 go_unreachable();
3784 // If the size of the type can be determined, set *PSIZE to the size
3785 // in bytes and return true. Otherwise, return false. This queries
3786 // the backend.
3788 bool
3789 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3791 if (!this->is_backend_type_size_known(gogo))
3792 return false;
3793 if (this->is_error_type())
3794 return false;
3795 Btype* bt = this->get_backend_placeholder(gogo);
3796 *psize = gogo->backend()->type_size(bt);
3797 if (*psize == -1)
3799 if (this->named_type() != NULL)
3800 go_error_at(this->named_type()->location(),
3801 "type %s larger than address space",
3802 Gogo::message_name(this->named_type()->name()).c_str());
3803 else
3804 go_error_at(Linemap::unknown_location(),
3805 "type %s larger than address space",
3806 this->reflection(gogo).c_str());
3808 // Make this an error type to avoid knock-on errors.
3809 this->classification_ = TYPE_ERROR;
3810 return false;
3812 return true;
3815 // If the alignment of the type can be determined, set *PALIGN to
3816 // the alignment in bytes and return true. Otherwise, return false.
3818 bool
3819 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3821 if (!this->is_backend_type_size_known(gogo))
3822 return false;
3823 Btype* bt = this->get_backend_placeholder(gogo);
3824 *palign = gogo->backend()->type_alignment(bt);
3825 return true;
3828 // Like backend_type_align, but return the alignment when used as a
3829 // field.
3831 bool
3832 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3834 if (!this->is_backend_type_size_known(gogo))
3835 return false;
3836 Btype* bt = this->get_backend_placeholder(gogo);
3837 *palign = gogo->backend()->type_field_alignment(bt);
3838 return true;
3841 // Get the ptrdata value for a type. This is the size of the prefix
3842 // of the type that contains all pointers. Store the ptrdata in
3843 // *PPTRDATA and return whether we found it.
3845 bool
3846 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3848 *pptrdata = 0;
3850 if (!this->has_pointer())
3851 return true;
3853 if (!this->is_backend_type_size_known(gogo))
3854 return false;
3856 switch (this->classification_)
3858 case TYPE_ERROR:
3859 return true;
3861 case TYPE_FUNCTION:
3862 case TYPE_POINTER:
3863 case TYPE_MAP:
3864 case TYPE_CHANNEL:
3865 // These types are nothing but a pointer.
3866 return this->backend_type_size(gogo, pptrdata);
3868 case TYPE_INTERFACE:
3869 // An interface is a struct of two pointers.
3870 return this->backend_type_size(gogo, pptrdata);
3872 case TYPE_STRING:
3874 // A string is a struct whose first field is a pointer, and
3875 // whose second field is not.
3876 Type* uint8_type = Type::lookup_integer_type("uint8");
3877 Type* ptr = Type::make_pointer_type(uint8_type);
3878 return ptr->backend_type_size(gogo, pptrdata);
3881 case TYPE_NAMED:
3882 case TYPE_FORWARD:
3883 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3885 case TYPE_STRUCT:
3887 const Struct_field_list* fields = this->struct_type()->fields();
3888 int64_t offset = 0;
3889 const Struct_field *ptr = NULL;
3890 int64_t ptr_offset = 0;
3891 for (Struct_field_list::const_iterator pf = fields->begin();
3892 pf != fields->end();
3893 ++pf)
3895 int64_t field_align;
3896 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3897 return false;
3898 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3900 if (pf->type()->has_pointer())
3902 ptr = &*pf;
3903 ptr_offset = offset;
3906 int64_t field_size;
3907 if (!pf->type()->backend_type_size(gogo, &field_size))
3908 return false;
3909 offset += field_size;
3912 if (ptr != NULL)
3914 int64_t ptr_ptrdata;
3915 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3916 return false;
3917 *pptrdata = ptr_offset + ptr_ptrdata;
3919 return true;
3922 case TYPE_ARRAY:
3923 if (this->is_slice_type())
3925 // A slice is a struct whose first field is a pointer, and
3926 // whose remaining fields are not.
3927 Type* element_type = this->array_type()->element_type();
3928 Type* ptr = Type::make_pointer_type(element_type);
3929 return ptr->backend_type_size(gogo, pptrdata);
3931 else
3933 Numeric_constant nc;
3934 if (!this->array_type()->length()->numeric_constant_value(&nc))
3935 return false;
3936 int64_t len;
3937 if (!nc.to_memory_size(&len))
3938 return false;
3940 Type* element_type = this->array_type()->element_type();
3941 int64_t ele_size;
3942 int64_t ele_ptrdata;
3943 if (!element_type->backend_type_size(gogo, &ele_size)
3944 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3945 return false;
3946 go_assert(ele_size > 0 && ele_ptrdata > 0);
3948 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3949 return true;
3952 default:
3953 case TYPE_VOID:
3954 case TYPE_BOOLEAN:
3955 case TYPE_INTEGER:
3956 case TYPE_FLOAT:
3957 case TYPE_COMPLEX:
3958 case TYPE_SINK:
3959 case TYPE_NIL:
3960 case TYPE_CALL_MULTIPLE_RESULT:
3961 go_unreachable();
3965 // Get the ptrdata value to store in a type descriptor. This is
3966 // normally the same as backend_type_ptrdata, but for a type that is
3967 // large enough to use a gcprog we may need to store a different value
3968 // if it ends with an array. If the gcprog uses a repeat descriptor
3969 // for the array, and if the array element ends with non-pointer data,
3970 // then the gcprog will produce a value that describes the complete
3971 // array where the backend ptrdata will omit the non-pointer elements
3972 // of the final array element. This is a subtle difference but the
3973 // run time code checks it to verify that it has expanded a gcprog as
3974 // expected.
3976 bool
3977 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3979 int64_t backend_ptrdata;
3980 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3981 return false;
3983 int64_t ptrsize;
3984 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3986 *pptrdata = backend_ptrdata;
3987 return true;
3990 GCProg prog;
3991 prog.set_from(gogo, this, ptrsize, 0);
3992 int64_t offset = prog.bit_index() * ptrsize;
3994 go_assert(offset >= backend_ptrdata);
3995 *pptrdata = offset;
3996 return true;
3999 // Default function to export a type.
4001 void
4002 Type::do_export(Export*) const
4004 go_unreachable();
4007 // Import a type.
4009 Type*
4010 Type::import_type(Import* imp)
4012 if (imp->match_c_string("("))
4013 return Function_type::do_import(imp);
4014 else if (imp->match_c_string("*"))
4015 return Pointer_type::do_import(imp);
4016 else if (imp->match_c_string("struct "))
4017 return Struct_type::do_import(imp);
4018 else if (imp->match_c_string("["))
4019 return Array_type::do_import(imp);
4020 else if (imp->match_c_string("map "))
4021 return Map_type::do_import(imp);
4022 else if (imp->match_c_string("chan "))
4023 return Channel_type::do_import(imp);
4024 else if (imp->match_c_string("interface"))
4025 return Interface_type::do_import(imp);
4026 else
4028 go_error_at(imp->location(), "import error: expected type");
4029 return Type::make_error_type();
4033 // Class Error_type.
4035 // Return the backend representation of an Error type.
4037 Btype*
4038 Error_type::do_get_backend(Gogo* gogo)
4040 return gogo->backend()->error_type();
4043 // Return an expression for the type descriptor for an error type.
4046 Expression*
4047 Error_type::do_type_descriptor(Gogo*, Named_type*)
4049 return Expression::make_error(Linemap::predeclared_location());
4052 // We should not be asked for the reflection string for an error type.
4054 void
4055 Error_type::do_reflection(Gogo*, std::string*) const
4057 go_assert(saw_errors());
4060 Type*
4061 Type::make_error_type()
4063 static Error_type singleton_error_type;
4064 return &singleton_error_type;
4067 // Class Void_type.
4069 // Get the backend representation of a void type.
4071 Btype*
4072 Void_type::do_get_backend(Gogo* gogo)
4074 return gogo->backend()->void_type();
4077 Type*
4078 Type::make_void_type()
4080 static Void_type singleton_void_type;
4081 return &singleton_void_type;
4084 // Class Boolean_type.
4086 // Return the backend representation of the boolean type.
4088 Btype*
4089 Boolean_type::do_get_backend(Gogo* gogo)
4091 return gogo->backend()->bool_type();
4094 // Make the type descriptor.
4096 Expression*
4097 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4099 if (name != NULL)
4100 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
4101 else
4103 Named_object* no = gogo->lookup_global("bool");
4104 go_assert(no != NULL);
4105 return Type::type_descriptor(gogo, no->type_value());
4109 Type*
4110 Type::make_boolean_type()
4112 static Boolean_type boolean_type;
4113 return &boolean_type;
4116 // The named type "bool".
4118 static Named_type* named_bool_type;
4120 // Get the named type "bool".
4122 Named_type*
4123 Type::lookup_bool_type()
4125 return named_bool_type;
4128 // Make the named type "bool".
4130 Named_type*
4131 Type::make_named_bool_type()
4133 Type* bool_type = Type::make_boolean_type();
4134 Named_object* named_object =
4135 Named_object::make_type("bool", NULL, bool_type,
4136 Linemap::predeclared_location());
4137 Named_type* named_type = named_object->type_value();
4138 named_bool_type = named_type;
4139 return named_type;
4142 // Class Integer_type.
4144 Integer_type::Named_integer_types Integer_type::named_integer_types;
4146 // Create a new integer type. Non-abstract integer types always have
4147 // names.
4149 Named_type*
4150 Integer_type::create_integer_type(const char* name, bool is_unsigned,
4151 int bits, int runtime_type_kind)
4153 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
4154 runtime_type_kind);
4155 std::string sname(name);
4156 Named_object* named_object =
4157 Named_object::make_type(sname, NULL, integer_type,
4158 Linemap::predeclared_location());
4159 Named_type* named_type = named_object->type_value();
4160 std::pair<Named_integer_types::iterator, bool> ins =
4161 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
4162 go_assert(ins.second);
4163 return named_type;
4166 // Look up an existing integer type.
4168 Named_type*
4169 Integer_type::lookup_integer_type(const char* name)
4171 Named_integer_types::const_iterator p =
4172 Integer_type::named_integer_types.find(name);
4173 go_assert(p != Integer_type::named_integer_types.end());
4174 return p->second;
4177 // Create a new abstract integer type.
4179 Integer_type*
4180 Integer_type::create_abstract_integer_type()
4182 static Integer_type* abstract_type;
4183 if (abstract_type == NULL)
4185 Type* int_type = Type::lookup_integer_type("int");
4186 abstract_type = new Integer_type(true, false,
4187 int_type->integer_type()->bits(),
4188 RUNTIME_TYPE_KIND_INT);
4190 return abstract_type;
4193 // Create a new abstract character type.
4195 Integer_type*
4196 Integer_type::create_abstract_character_type()
4198 static Integer_type* abstract_type;
4199 if (abstract_type == NULL)
4201 abstract_type = new Integer_type(true, false, 32,
4202 RUNTIME_TYPE_KIND_INT32);
4203 abstract_type->set_is_rune();
4205 return abstract_type;
4208 // Create an alias to an integer type. This is used for byte and rune.
4210 Named_type*
4211 Integer_type::create_integer_type_alias(const char* name,
4212 Named_type* real_type)
4214 std::string sname(name);
4215 Named_object* no = Named_object::make_type(sname, NULL, real_type,
4216 Linemap::predeclared_location());
4217 Named_type* nt = no->type_value();
4218 nt->set_is_alias();
4219 std::pair<Named_integer_types::iterator, bool> ins =
4220 Integer_type::named_integer_types.insert(std::make_pair(sname, nt));
4221 go_assert(ins.second);
4222 return nt;
4225 // Integer type compatibility.
4227 bool
4228 Integer_type::is_identical(const Integer_type* t) const
4230 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
4231 return false;
4232 return this->is_abstract_ == t->is_abstract_;
4235 // Hash code.
4237 unsigned int
4238 Integer_type::do_hash_for_method(Gogo*, int) const
4240 return ((this->bits_ << 4)
4241 + ((this->is_unsigned_ ? 1 : 0) << 8)
4242 + ((this->is_abstract_ ? 1 : 0) << 9));
4245 // Convert an Integer_type to the backend representation.
4247 Btype*
4248 Integer_type::do_get_backend(Gogo* gogo)
4250 if (this->is_abstract_)
4252 go_assert(saw_errors());
4253 return gogo->backend()->error_type();
4255 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4258 // The type descriptor for an integer type. Integer types are always
4259 // named.
4261 Expression*
4262 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4264 go_assert(name != NULL || saw_errors());
4265 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4268 // We should not be asked for the reflection string of a basic type.
4270 void
4271 Integer_type::do_reflection(Gogo*, std::string*) const
4273 go_assert(saw_errors());
4276 // Make an integer type.
4278 Named_type*
4279 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4280 int runtime_type_kind)
4282 return Integer_type::create_integer_type(name, is_unsigned, bits,
4283 runtime_type_kind);
4286 // Make an abstract integer type.
4288 Integer_type*
4289 Type::make_abstract_integer_type()
4291 return Integer_type::create_abstract_integer_type();
4294 // Make an abstract character type.
4296 Integer_type*
4297 Type::make_abstract_character_type()
4299 return Integer_type::create_abstract_character_type();
4302 // Make an integer type alias.
4304 Named_type*
4305 Type::make_integer_type_alias(const char* name, Named_type* real_type)
4307 return Integer_type::create_integer_type_alias(name, real_type);
4310 // Look up an integer type.
4312 Named_type*
4313 Type::lookup_integer_type(const char* name)
4315 return Integer_type::lookup_integer_type(name);
4318 // Class Float_type.
4320 Float_type::Named_float_types Float_type::named_float_types;
4322 // Create a new float type. Non-abstract float types always have
4323 // names.
4325 Named_type*
4326 Float_type::create_float_type(const char* name, int bits,
4327 int runtime_type_kind)
4329 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4330 std::string sname(name);
4331 Named_object* named_object =
4332 Named_object::make_type(sname, NULL, float_type,
4333 Linemap::predeclared_location());
4334 Named_type* named_type = named_object->type_value();
4335 std::pair<Named_float_types::iterator, bool> ins =
4336 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4337 go_assert(ins.second);
4338 return named_type;
4341 // Look up an existing float type.
4343 Named_type*
4344 Float_type::lookup_float_type(const char* name)
4346 Named_float_types::const_iterator p =
4347 Float_type::named_float_types.find(name);
4348 go_assert(p != Float_type::named_float_types.end());
4349 return p->second;
4352 // Create a new abstract float type.
4354 Float_type*
4355 Float_type::create_abstract_float_type()
4357 static Float_type* abstract_type;
4358 if (abstract_type == NULL)
4359 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4360 return abstract_type;
4363 // Whether this type is identical with T.
4365 bool
4366 Float_type::is_identical(const Float_type* t) const
4368 if (this->bits_ != t->bits_)
4369 return false;
4370 return this->is_abstract_ == t->is_abstract_;
4373 // Hash code.
4375 unsigned int
4376 Float_type::do_hash_for_method(Gogo*, int) const
4378 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4381 // Convert to the backend representation.
4383 Btype*
4384 Float_type::do_get_backend(Gogo* gogo)
4386 return gogo->backend()->float_type(this->bits_);
4389 // The type descriptor for a float type. Float types are always named.
4391 Expression*
4392 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4394 go_assert(name != NULL || saw_errors());
4395 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4398 // We should not be asked for the reflection string of a basic type.
4400 void
4401 Float_type::do_reflection(Gogo*, std::string*) const
4403 go_assert(saw_errors());
4406 // Make a floating point type.
4408 Named_type*
4409 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4411 return Float_type::create_float_type(name, bits, runtime_type_kind);
4414 // Make an abstract float type.
4416 Float_type*
4417 Type::make_abstract_float_type()
4419 return Float_type::create_abstract_float_type();
4422 // Look up a float type.
4424 Named_type*
4425 Type::lookup_float_type(const char* name)
4427 return Float_type::lookup_float_type(name);
4430 // Class Complex_type.
4432 Complex_type::Named_complex_types Complex_type::named_complex_types;
4434 // Create a new complex type. Non-abstract complex types always have
4435 // names.
4437 Named_type*
4438 Complex_type::create_complex_type(const char* name, int bits,
4439 int runtime_type_kind)
4441 Complex_type* complex_type = new Complex_type(false, bits,
4442 runtime_type_kind);
4443 std::string sname(name);
4444 Named_object* named_object =
4445 Named_object::make_type(sname, NULL, complex_type,
4446 Linemap::predeclared_location());
4447 Named_type* named_type = named_object->type_value();
4448 std::pair<Named_complex_types::iterator, bool> ins =
4449 Complex_type::named_complex_types.insert(std::make_pair(sname,
4450 named_type));
4451 go_assert(ins.second);
4452 return named_type;
4455 // Look up an existing complex type.
4457 Named_type*
4458 Complex_type::lookup_complex_type(const char* name)
4460 Named_complex_types::const_iterator p =
4461 Complex_type::named_complex_types.find(name);
4462 go_assert(p != Complex_type::named_complex_types.end());
4463 return p->second;
4466 // Create a new abstract complex type.
4468 Complex_type*
4469 Complex_type::create_abstract_complex_type()
4471 static Complex_type* abstract_type;
4472 if (abstract_type == NULL)
4473 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4474 return abstract_type;
4477 // Whether this type is identical with T.
4479 bool
4480 Complex_type::is_identical(const Complex_type *t) const
4482 if (this->bits_ != t->bits_)
4483 return false;
4484 return this->is_abstract_ == t->is_abstract_;
4487 // Hash code.
4489 unsigned int
4490 Complex_type::do_hash_for_method(Gogo*, int) const
4492 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4495 // Convert to the backend representation.
4497 Btype*
4498 Complex_type::do_get_backend(Gogo* gogo)
4500 return gogo->backend()->complex_type(this->bits_);
4503 // The type descriptor for a complex type. Complex types are always
4504 // named.
4506 Expression*
4507 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4509 go_assert(name != NULL || saw_errors());
4510 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4513 // We should not be asked for the reflection string of a basic type.
4515 void
4516 Complex_type::do_reflection(Gogo*, std::string*) const
4518 go_assert(saw_errors());
4521 // Make a complex type.
4523 Named_type*
4524 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4526 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4529 // Make an abstract complex type.
4531 Complex_type*
4532 Type::make_abstract_complex_type()
4534 return Complex_type::create_abstract_complex_type();
4537 // Look up a complex type.
4539 Named_type*
4540 Type::lookup_complex_type(const char* name)
4542 return Complex_type::lookup_complex_type(name);
4545 // Class String_type.
4547 // Convert String_type to the backend representation. A string is a
4548 // struct with two fields: a pointer to the characters and a length.
4550 Btype*
4551 String_type::do_get_backend(Gogo* gogo)
4553 static Btype* backend_string_type;
4554 if (backend_string_type == NULL)
4556 std::vector<Backend::Btyped_identifier> fields(2);
4558 Type* b = Type::lookup_integer_type("byte");
4559 Type* pb = Type::make_pointer_type(b);
4561 // We aren't going to get back to this field to finish the
4562 // backend representation, so force it to be finished now.
4563 if (!gogo->named_types_are_converted())
4565 Btype* bt = pb->get_backend_placeholder(gogo);
4566 pb->finish_backend(gogo, bt);
4569 fields[0].name = "__data";
4570 fields[0].btype = pb->get_backend(gogo);
4571 fields[0].location = Linemap::predeclared_location();
4573 Type* int_type = Type::lookup_integer_type("int");
4574 fields[1].name = "__length";
4575 fields[1].btype = int_type->get_backend(gogo);
4576 fields[1].location = fields[0].location;
4578 backend_string_type = gogo->backend()->struct_type(fields);
4580 return backend_string_type;
4583 // The type descriptor for the string type.
4585 Expression*
4586 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4588 if (name != NULL)
4589 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4590 else
4592 Named_object* no = gogo->lookup_global("string");
4593 go_assert(no != NULL);
4594 return Type::type_descriptor(gogo, no->type_value());
4598 // We should not be asked for the reflection string of a basic type.
4600 void
4601 String_type::do_reflection(Gogo*, std::string* ret) const
4603 ret->append("string");
4606 // Make a string type.
4608 Type*
4609 Type::make_string_type()
4611 static String_type string_type;
4612 return &string_type;
4615 // The named type "string".
4617 static Named_type* named_string_type;
4619 // Get the named type "string".
4621 Named_type*
4622 Type::lookup_string_type()
4624 return named_string_type;
4627 // Make the named type string.
4629 Named_type*
4630 Type::make_named_string_type()
4632 Type* string_type = Type::make_string_type();
4633 Named_object* named_object =
4634 Named_object::make_type("string", NULL, string_type,
4635 Linemap::predeclared_location());
4636 Named_type* named_type = named_object->type_value();
4637 named_string_type = named_type;
4638 return named_type;
4641 // The sink type. This is the type of the blank identifier _. Any
4642 // type may be assigned to it.
4644 class Sink_type : public Type
4646 public:
4647 Sink_type()
4648 : Type(TYPE_SINK)
4651 protected:
4652 bool
4653 do_compare_is_identity(Gogo*)
4654 { return false; }
4656 Btype*
4657 do_get_backend(Gogo* gogo)
4659 go_assert(saw_errors());
4660 return gogo->backend()->error_type();
4663 Expression*
4664 do_type_descriptor(Gogo*, Named_type*)
4665 { go_unreachable(); }
4667 void
4668 do_reflection(Gogo*, std::string*) const
4669 { go_unreachable(); }
4671 void
4672 do_mangled_name(Gogo*, std::string*, bool*) const
4673 { go_unreachable(); }
4676 // Make the sink type.
4678 Type*
4679 Type::make_sink_type()
4681 static Sink_type sink_type;
4682 return &sink_type;
4685 // Class Function_type.
4687 // Traversal.
4690 Function_type::do_traverse(Traverse* traverse)
4692 if (this->receiver_ != NULL
4693 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4694 return TRAVERSE_EXIT;
4695 if (this->parameters_ != NULL
4696 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4697 return TRAVERSE_EXIT;
4698 if (this->results_ != NULL
4699 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4700 return TRAVERSE_EXIT;
4701 return TRAVERSE_CONTINUE;
4704 // Returns whether T is a valid redeclaration of this type. If this
4705 // returns false, and REASON is not NULL, *REASON may be set to a
4706 // brief explanation of why it returned false.
4708 bool
4709 Function_type::is_valid_redeclaration(const Function_type* t,
4710 std::string* reason) const
4712 if (!this->is_identical(t, false, COMPARE_TAGS, reason))
4713 return false;
4715 // A redeclaration of a function is required to use the same names
4716 // for the receiver and parameters.
4717 if (this->receiver() != NULL
4718 && this->receiver()->name() != t->receiver()->name())
4720 if (reason != NULL)
4721 *reason = "receiver name changed";
4722 return false;
4725 const Typed_identifier_list* parms1 = this->parameters();
4726 const Typed_identifier_list* parms2 = t->parameters();
4727 if (parms1 != NULL)
4729 Typed_identifier_list::const_iterator p1 = parms1->begin();
4730 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4731 p2 != parms2->end();
4732 ++p2, ++p1)
4734 if (p1->name() != p2->name())
4736 if (reason != NULL)
4737 *reason = "parameter name changed";
4738 return false;
4741 // This is called at parse time, so we may have unknown
4742 // types.
4743 Type* t1 = p1->type()->forwarded();
4744 Type* t2 = p2->type()->forwarded();
4745 if (t1 != t2
4746 && t1->forward_declaration_type() != NULL
4747 && (t2->forward_declaration_type() == NULL
4748 || (t1->forward_declaration_type()->named_object()
4749 != t2->forward_declaration_type()->named_object())))
4750 return false;
4754 const Typed_identifier_list* results1 = this->results();
4755 const Typed_identifier_list* results2 = t->results();
4756 if (results1 != NULL)
4758 Typed_identifier_list::const_iterator res1 = results1->begin();
4759 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4760 res2 != results2->end();
4761 ++res2, ++res1)
4763 if (res1->name() != res2->name())
4765 if (reason != NULL)
4766 *reason = "result name changed";
4767 return false;
4770 // This is called at parse time, so we may have unknown
4771 // types.
4772 Type* t1 = res1->type()->forwarded();
4773 Type* t2 = res2->type()->forwarded();
4774 if (t1 != t2
4775 && t1->forward_declaration_type() != NULL
4776 && (t2->forward_declaration_type() == NULL
4777 || (t1->forward_declaration_type()->named_object()
4778 != t2->forward_declaration_type()->named_object())))
4779 return false;
4783 return true;
4786 // Check whether T is the same as this type.
4788 bool
4789 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4790 int flags, std::string* reason) const
4792 if (this->is_backend_function_type() != t->is_backend_function_type())
4793 return false;
4795 if (!ignore_receiver)
4797 const Typed_identifier* r1 = this->receiver();
4798 const Typed_identifier* r2 = t->receiver();
4799 if ((r1 != NULL) != (r2 != NULL))
4801 if (reason != NULL)
4802 *reason = _("different receiver types");
4803 return false;
4805 if (r1 != NULL)
4807 if (!Type::are_identical(r1->type(), r2->type(), flags, reason))
4809 if (reason != NULL && !reason->empty())
4810 *reason = "receiver: " + *reason;
4811 return false;
4816 const Typed_identifier_list* parms1 = this->parameters();
4817 if (parms1 != NULL && parms1->empty())
4818 parms1 = NULL;
4819 const Typed_identifier_list* parms2 = t->parameters();
4820 if (parms2 != NULL && parms2->empty())
4821 parms2 = NULL;
4822 if ((parms1 != NULL) != (parms2 != NULL))
4824 if (reason != NULL)
4825 *reason = _("different number of parameters");
4826 return false;
4828 if (parms1 != NULL)
4830 Typed_identifier_list::const_iterator p1 = parms1->begin();
4831 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4832 p2 != parms2->end();
4833 ++p2, ++p1)
4835 if (p1 == parms1->end())
4837 if (reason != NULL)
4838 *reason = _("different number of parameters");
4839 return false;
4842 if (!Type::are_identical(p1->type(), p2->type(), flags, NULL))
4844 if (reason != NULL)
4845 *reason = _("different parameter types");
4846 return false;
4849 if (p1 != parms1->end())
4851 if (reason != NULL)
4852 *reason = _("different number of parameters");
4853 return false;
4857 if (this->is_varargs() != t->is_varargs())
4859 if (reason != NULL)
4860 *reason = _("different varargs");
4861 return false;
4864 const Typed_identifier_list* results1 = this->results();
4865 if (results1 != NULL && results1->empty())
4866 results1 = NULL;
4867 const Typed_identifier_list* results2 = t->results();
4868 if (results2 != NULL && results2->empty())
4869 results2 = NULL;
4870 if ((results1 != NULL) != (results2 != NULL))
4872 if (reason != NULL)
4873 *reason = _("different number of results");
4874 return false;
4876 if (results1 != NULL)
4878 Typed_identifier_list::const_iterator res1 = results1->begin();
4879 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4880 res2 != results2->end();
4881 ++res2, ++res1)
4883 if (res1 == results1->end())
4885 if (reason != NULL)
4886 *reason = _("different number of results");
4887 return false;
4890 if (!Type::are_identical(res1->type(), res2->type(), flags, NULL))
4892 if (reason != NULL)
4893 *reason = _("different result types");
4894 return false;
4897 if (res1 != results1->end())
4899 if (reason != NULL)
4900 *reason = _("different number of results");
4901 return false;
4905 return true;
4908 // Hash code.
4910 unsigned int
4911 Function_type::do_hash_for_method(Gogo* gogo, int flags) const
4913 unsigned int ret = 0;
4914 // We ignore the receiver type for hash codes, because we need to
4915 // get the same hash code for a method in an interface and a method
4916 // declared for a type. The former will not have a receiver.
4917 if (this->parameters_ != NULL)
4919 int shift = 1;
4920 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4921 p != this->parameters_->end();
4922 ++p, ++shift)
4923 ret += p->type()->hash_for_method(gogo, flags) << shift;
4925 if (this->results_ != NULL)
4927 int shift = 2;
4928 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4929 p != this->results_->end();
4930 ++p, ++shift)
4931 ret += p->type()->hash_for_method(gogo, flags) << shift;
4933 if (this->is_varargs_)
4934 ret += 1;
4935 ret <<= 4;
4936 return ret;
4939 // Hash result parameters.
4941 unsigned int
4942 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4944 unsigned int hash = 0;
4945 for (Typed_identifier_list::const_iterator p = t->begin();
4946 p != t->end();
4947 ++p)
4949 hash <<= 2;
4950 hash = Gogo::hash_string(p->name(), hash);
4951 hash += p->type()->hash_for_method(NULL, Type::COMPARE_TAGS);
4953 return hash;
4956 // Compare result parameters so that can map identical result
4957 // parameters to a single struct type.
4959 bool
4960 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4961 const Typed_identifier_list* b) const
4963 if (a->size() != b->size())
4964 return false;
4965 Typed_identifier_list::const_iterator pa = a->begin();
4966 for (Typed_identifier_list::const_iterator pb = b->begin();
4967 pb != b->end();
4968 ++pa, ++pb)
4970 if (pa->name() != pb->name()
4971 || !Type::are_identical(pa->type(), pb->type(), Type::COMPARE_TAGS,
4972 NULL))
4973 return false;
4975 return true;
4978 // Hash from results to a backend struct type.
4980 Function_type::Results_structs Function_type::results_structs;
4982 // Get the backend representation for a function type.
4984 Btype*
4985 Function_type::get_backend_fntype(Gogo* gogo)
4987 if (this->fnbtype_ == NULL)
4989 Backend::Btyped_identifier breceiver;
4990 if (this->receiver_ != NULL)
4992 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4994 // We always pass the address of the receiver parameter, in
4995 // order to make interface calls work with unknown types,
4996 // except for direct interface types where the interface call
4997 // actually passes the underlying pointer of the value.
4998 Type* rtype = this->receiver_->type();
4999 if (rtype->points_to() == NULL)
5001 if (rtype->is_direct_iface_type())
5002 rtype = Type::make_pointer_type(Type::make_void_type());
5003 else
5004 rtype = Type::make_pointer_type(rtype);
5006 breceiver.btype = rtype->get_backend(gogo);
5007 breceiver.location = this->receiver_->location();
5010 std::vector<Backend::Btyped_identifier> bparameters;
5011 if (this->parameters_ != NULL)
5013 bparameters.resize(this->parameters_->size());
5014 size_t i = 0;
5015 for (Typed_identifier_list::const_iterator p =
5016 this->parameters_->begin(); p != this->parameters_->end();
5017 ++p, ++i)
5019 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
5020 bparameters[i].btype = p->type()->get_backend(gogo);
5021 bparameters[i].location = p->location();
5023 go_assert(i == bparameters.size());
5026 std::vector<Backend::Btyped_identifier> bresults;
5027 Btype* bresult_struct = NULL;
5028 if (this->results_ != NULL)
5030 bresults.resize(this->results_->size());
5031 size_t i = 0;
5032 for (Typed_identifier_list::const_iterator p =
5033 this->results_->begin();
5034 p != this->results_->end();
5035 ++p, ++i)
5037 bresults[i].name = Gogo::unpack_hidden_name(p->name());
5038 bresults[i].btype = p->type()->get_backend(gogo);
5039 bresults[i].location = p->location();
5041 go_assert(i == bresults.size());
5043 if (this->results_->size() > 1)
5045 // Use the same results struct for all functions that
5046 // return the same set of results. This is useful to
5047 // unify calls to interface methods with other calls.
5048 std::pair<Typed_identifier_list*, Btype*> val;
5049 val.first = this->results_;
5050 val.second = NULL;
5051 std::pair<Results_structs::iterator, bool> ins =
5052 Function_type::results_structs.insert(val);
5053 if (ins.second)
5055 // Build a new struct type.
5056 Struct_field_list* sfl = new Struct_field_list;
5057 for (Typed_identifier_list::const_iterator p =
5058 this->results_->begin();
5059 p != this->results_->end();
5060 ++p)
5062 Typed_identifier tid = *p;
5063 if (tid.name().empty())
5064 tid = Typed_identifier("UNNAMED", tid.type(),
5065 tid.location());
5066 sfl->push_back(Struct_field(tid));
5068 Struct_type* st = Type::make_struct_type(sfl,
5069 this->location());
5070 st->set_is_struct_incomparable();
5071 st->set_is_results_struct();
5072 ins.first->second = st->get_backend(gogo);
5074 bresult_struct = ins.first->second;
5078 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
5079 bresults, bresult_struct,
5080 this->location());
5084 return this->fnbtype_;
5087 // Get the backend representation for a Go function type.
5089 Btype*
5090 Function_type::do_get_backend(Gogo* gogo)
5092 // When we do anything with a function value other than call it, it
5093 // is represented as a pointer to a struct whose first field is the
5094 // actual function. So that is what we return as the type of a Go
5095 // function.
5097 Location loc = this->location();
5098 Btype* struct_type =
5099 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
5100 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
5102 std::vector<Backend::Btyped_identifier> fields(1);
5103 fields[0].name = "code";
5104 fields[0].btype = this->get_backend_fntype(gogo);
5105 fields[0].location = loc;
5106 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
5107 return gogo->backend()->error_type();
5108 return ptr_struct_type;
5111 // The type of a function type descriptor.
5113 Type*
5114 Function_type::make_function_type_descriptor_type()
5116 static Type* ret;
5117 if (ret == NULL)
5119 Type* tdt = Type::make_type_descriptor_type();
5120 Type* ptdt = Type::make_type_descriptor_ptr_type();
5122 Type* bool_type = Type::lookup_bool_type();
5124 Type* slice_type = Type::make_array_type(ptdt, NULL);
5126 Struct_type* s = Type::make_builtin_struct_type(4,
5127 "", tdt,
5128 "dotdotdot", bool_type,
5129 "in", slice_type,
5130 "out", slice_type);
5132 ret = Type::make_builtin_named_type("FuncType", s);
5135 return ret;
5138 // The type descriptor for a function type.
5140 Expression*
5141 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5143 Location bloc = Linemap::predeclared_location();
5145 Type* ftdt = Function_type::make_function_type_descriptor_type();
5147 const Struct_field_list* fields = ftdt->struct_type()->fields();
5149 Expression_list* vals = new Expression_list();
5150 vals->reserve(4);
5152 Struct_field_list::const_iterator p = fields->begin();
5153 go_assert(p->is_field_name("_type"));
5154 vals->push_back(this->type_descriptor_constructor(gogo,
5155 RUNTIME_TYPE_KIND_FUNC,
5156 name, NULL, true));
5158 ++p;
5159 go_assert(p->is_field_name("dotdotdot"));
5160 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
5162 ++p;
5163 go_assert(p->is_field_name("in"));
5164 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
5165 this->parameters()));
5167 ++p;
5168 go_assert(p->is_field_name("out"));
5169 vals->push_back(this->type_descriptor_params(p->type(), NULL,
5170 this->results()));
5172 ++p;
5173 go_assert(p == fields->end());
5175 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
5178 // Return a composite literal for the parameters or results of a type
5179 // descriptor.
5181 Expression*
5182 Function_type::type_descriptor_params(Type* params_type,
5183 const Typed_identifier* receiver,
5184 const Typed_identifier_list* params)
5186 Location bloc = Linemap::predeclared_location();
5188 if (receiver == NULL && params == NULL)
5189 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
5191 Expression_list* vals = new Expression_list();
5192 vals->reserve((params == NULL ? 0 : params->size())
5193 + (receiver != NULL ? 1 : 0));
5195 if (receiver != NULL)
5196 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
5198 if (params != NULL)
5200 for (Typed_identifier_list::const_iterator p = params->begin();
5201 p != params->end();
5202 ++p)
5203 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
5206 return Expression::make_slice_composite_literal(params_type, vals, bloc);
5209 // The reflection string.
5211 void
5212 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
5214 // FIXME: Turn this off until we straighten out the type of the
5215 // struct field used in a go statement which calls a method.
5216 // go_assert(this->receiver_ == NULL);
5218 ret->append("func");
5220 if (this->receiver_ != NULL)
5222 ret->push_back('(');
5223 this->append_reflection(this->receiver_->type(), gogo, ret);
5224 ret->push_back(')');
5227 ret->push_back('(');
5228 const Typed_identifier_list* params = this->parameters();
5229 if (params != NULL)
5231 bool is_varargs = this->is_varargs_;
5232 for (Typed_identifier_list::const_iterator p = params->begin();
5233 p != params->end();
5234 ++p)
5236 if (p != params->begin())
5237 ret->append(", ");
5238 if (!is_varargs || p + 1 != params->end())
5239 this->append_reflection(p->type(), gogo, ret);
5240 else
5242 ret->append("...");
5243 this->append_reflection(p->type()->array_type()->element_type(),
5244 gogo, ret);
5248 ret->push_back(')');
5250 const Typed_identifier_list* results = this->results();
5251 if (results != NULL && !results->empty())
5253 if (results->size() == 1)
5254 ret->push_back(' ');
5255 else
5256 ret->append(" (");
5257 for (Typed_identifier_list::const_iterator p = results->begin();
5258 p != results->end();
5259 ++p)
5261 if (p != results->begin())
5262 ret->append(", ");
5263 this->append_reflection(p->type(), gogo, ret);
5265 if (results->size() > 1)
5266 ret->push_back(')');
5270 // Export a function type.
5272 void
5273 Function_type::do_export(Export* exp) const
5275 // We don't write out the receiver. The only function types which
5276 // should have a receiver are the ones associated with explicitly
5277 // defined methods. For those the receiver type is written out by
5278 // Function::export_func.
5280 exp->write_c_string("(");
5281 bool first = true;
5282 if (this->parameters_ != NULL)
5284 bool is_varargs = this->is_varargs_;
5285 for (Typed_identifier_list::const_iterator p =
5286 this->parameters_->begin();
5287 p != this->parameters_->end();
5288 ++p)
5290 if (first)
5291 first = false;
5292 else
5293 exp->write_c_string(", ");
5294 // The hash for a function type ignores parameter names, so
5295 // we don't want to write them out here. If we did write
5296 // them out, we could get spurious changes in export data
5297 // when recompiling a package.
5298 exp->write_name("");
5299 exp->write_c_string(" ");
5300 if (!is_varargs || p + 1 != this->parameters_->end())
5301 exp->write_type(p->type());
5302 else
5304 exp->write_c_string("...");
5305 exp->write_type(p->type()->array_type()->element_type());
5309 exp->write_c_string(")");
5311 const Typed_identifier_list* results = this->results_;
5312 if (results != NULL)
5314 exp->write_c_string(" ");
5315 if (results->size() == 1)
5316 exp->write_type(results->begin()->type());
5317 else
5319 first = true;
5320 exp->write_c_string("(");
5321 for (Typed_identifier_list::const_iterator p = results->begin();
5322 p != results->end();
5323 ++p)
5325 if (first)
5326 first = false;
5327 else
5328 exp->write_c_string(", ");
5329 exp->write_name("");
5330 exp->write_c_string(" ");
5331 exp->write_type(p->type());
5333 exp->write_c_string(")");
5338 // Import a function type.
5340 Function_type*
5341 Function_type::do_import(Import* imp)
5343 imp->require_c_string("(");
5344 Typed_identifier_list* parameters;
5345 bool is_varargs = false;
5346 if (imp->peek_char() == ')')
5347 parameters = NULL;
5348 else
5350 parameters = new Typed_identifier_list();
5351 while (true)
5353 std::string name = imp->read_name();
5354 imp->require_c_string(" ");
5356 if (imp->match_c_string("..."))
5358 imp->advance(3);
5359 is_varargs = true;
5362 Type* ptype = imp->read_type();
5363 if (is_varargs)
5364 ptype = Type::make_array_type(ptype, NULL);
5365 parameters->push_back(Typed_identifier(name, ptype,
5366 imp->location()));
5367 if (imp->peek_char() != ',')
5368 break;
5369 go_assert(!is_varargs);
5370 imp->require_c_string(", ");
5373 imp->require_c_string(")");
5375 Typed_identifier_list* results;
5376 if (imp->peek_char() != ' ')
5377 results = NULL;
5378 else
5380 imp->advance(1);
5381 results = new Typed_identifier_list;
5382 if (imp->peek_char() != '(')
5384 Type* rtype = imp->read_type();
5385 results->push_back(Typed_identifier("", rtype, imp->location()));
5387 else
5389 imp->advance(1);
5390 while (true)
5392 std::string name = imp->read_name();
5393 imp->require_c_string(" ");
5394 Type* rtype = imp->read_type();
5395 results->push_back(Typed_identifier(name, rtype,
5396 imp->location()));
5397 if (imp->peek_char() != ',')
5398 break;
5399 imp->require_c_string(", ");
5401 imp->require_c_string(")");
5405 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5406 imp->location());
5407 if (is_varargs)
5408 ret->set_is_varargs();
5409 return ret;
5412 // Make a copy of a function type without a receiver.
5414 Function_type*
5415 Function_type::copy_without_receiver() const
5417 go_assert(this->is_method());
5418 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5419 this->results_,
5420 this->location_);
5421 if (this->is_varargs())
5422 ret->set_is_varargs();
5423 if (this->is_builtin())
5424 ret->set_is_builtin();
5425 return ret;
5428 // Make a copy of a function type with a receiver.
5430 Function_type*
5431 Function_type::copy_with_receiver(Type* receiver_type) const
5433 go_assert(!this->is_method());
5434 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5435 this->location_);
5436 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5437 this->results_,
5438 this->location_);
5439 if (this->is_varargs_)
5440 ret->set_is_varargs();
5441 return ret;
5444 // Make a copy of a function type with the receiver as the first
5445 // parameter.
5447 Function_type*
5448 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5450 go_assert(this->is_method());
5451 Typed_identifier_list* new_params = new Typed_identifier_list();
5452 Type* rtype = this->receiver_->type();
5453 if (want_pointer_receiver)
5454 rtype = Type::make_pointer_type(rtype);
5455 Typed_identifier receiver(this->receiver_->name(), rtype,
5456 this->receiver_->location());
5457 new_params->push_back(receiver);
5458 const Typed_identifier_list* orig_params = this->parameters_;
5459 if (orig_params != NULL && !orig_params->empty())
5461 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5462 p != orig_params->end();
5463 ++p)
5464 new_params->push_back(*p);
5466 Function_type* ret = Type::make_function_type(NULL, new_params,
5467 this->results_,
5468 this->location_);
5469 if (this->is_varargs_)
5470 ret->set_is_varargs();
5471 return ret;
5474 // Make a copy of a function type ignoring any receiver and adding a
5475 // closure parameter.
5477 Function_type*
5478 Function_type::copy_with_names() const
5480 Typed_identifier_list* new_params = new Typed_identifier_list();
5481 const Typed_identifier_list* orig_params = this->parameters_;
5482 if (orig_params != NULL && !orig_params->empty())
5484 static int count;
5485 char buf[50];
5486 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5487 p != orig_params->end();
5488 ++p)
5490 snprintf(buf, sizeof buf, "pt.%u", count);
5491 ++count;
5492 new_params->push_back(Typed_identifier(buf, p->type(),
5493 p->location()));
5497 const Typed_identifier_list* orig_results = this->results_;
5498 Typed_identifier_list* new_results;
5499 if (orig_results == NULL || orig_results->empty())
5500 new_results = NULL;
5501 else
5503 new_results = new Typed_identifier_list();
5504 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5505 p != orig_results->end();
5506 ++p)
5507 new_results->push_back(Typed_identifier("", p->type(),
5508 p->location()));
5511 return Type::make_function_type(NULL, new_params, new_results,
5512 this->location());
5515 // Make a function type.
5517 Function_type*
5518 Type::make_function_type(Typed_identifier* receiver,
5519 Typed_identifier_list* parameters,
5520 Typed_identifier_list* results,
5521 Location location)
5523 return new Function_type(receiver, parameters, results, location);
5526 // Make a backend function type.
5528 Backend_function_type*
5529 Type::make_backend_function_type(Typed_identifier* receiver,
5530 Typed_identifier_list* parameters,
5531 Typed_identifier_list* results,
5532 Location location)
5534 return new Backend_function_type(receiver, parameters, results, location);
5537 // Class Pointer_type.
5539 // Traversal.
5542 Pointer_type::do_traverse(Traverse* traverse)
5544 return Type::traverse(this->to_type_, traverse);
5547 // Hash code.
5549 unsigned int
5550 Pointer_type::do_hash_for_method(Gogo* gogo, int flags) const
5552 return this->to_type_->hash_for_method(gogo, flags) << 4;
5555 // Get the backend representation for a pointer type.
5557 Btype*
5558 Pointer_type::do_get_backend(Gogo* gogo)
5560 Btype* to_btype = this->to_type_->get_backend(gogo);
5561 return gogo->backend()->pointer_type(to_btype);
5564 // The type of a pointer type descriptor.
5566 Type*
5567 Pointer_type::make_pointer_type_descriptor_type()
5569 static Type* ret;
5570 if (ret == NULL)
5572 Type* tdt = Type::make_type_descriptor_type();
5573 Type* ptdt = Type::make_type_descriptor_ptr_type();
5575 Struct_type* s = Type::make_builtin_struct_type(2,
5576 "", tdt,
5577 "elem", ptdt);
5579 ret = Type::make_builtin_named_type("PtrType", s);
5582 return ret;
5585 // The type descriptor for a pointer type.
5587 Expression*
5588 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5590 if (this->is_unsafe_pointer_type())
5592 go_assert(name != NULL);
5593 return this->plain_type_descriptor(gogo,
5594 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5595 name);
5597 else
5599 Location bloc = Linemap::predeclared_location();
5601 const Methods* methods;
5602 Type* deref = this->points_to();
5603 if (deref->named_type() != NULL)
5604 methods = deref->named_type()->methods();
5605 else if (deref->struct_type() != NULL)
5606 methods = deref->struct_type()->methods();
5607 else
5608 methods = NULL;
5610 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5612 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5614 Expression_list* vals = new Expression_list();
5615 vals->reserve(2);
5617 Struct_field_list::const_iterator p = fields->begin();
5618 go_assert(p->is_field_name("_type"));
5619 vals->push_back(this->type_descriptor_constructor(gogo,
5620 RUNTIME_TYPE_KIND_PTR,
5621 name, methods, false));
5623 ++p;
5624 go_assert(p->is_field_name("elem"));
5625 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5627 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5631 // Reflection string.
5633 void
5634 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5636 ret->push_back('*');
5637 this->append_reflection(this->to_type_, gogo, ret);
5640 // Export.
5642 void
5643 Pointer_type::do_export(Export* exp) const
5645 exp->write_c_string("*");
5646 if (this->is_unsafe_pointer_type())
5647 exp->write_c_string("any");
5648 else
5649 exp->write_type(this->to_type_);
5652 // Import.
5654 Pointer_type*
5655 Pointer_type::do_import(Import* imp)
5657 imp->require_c_string("*");
5658 if (imp->match_c_string("any"))
5660 imp->advance(3);
5661 return Type::make_pointer_type(Type::make_void_type());
5663 Type* to = imp->read_type();
5664 return Type::make_pointer_type(to);
5667 // Cache of pointer types. Key is "to" type, value is pointer type
5668 // that points to key.
5670 Type::Pointer_type_table Type::pointer_types;
5672 // A list of placeholder pointer types; items on this list will be either be
5673 // Pointer_type or Function_type. We keep this so we can ensure they are
5674 // finalized.
5676 std::vector<Type*> Type::placeholder_pointers;
5678 // Make a pointer type.
5680 Pointer_type*
5681 Type::make_pointer_type(Type* to_type)
5683 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5684 if (p != pointer_types.end())
5685 return p->second;
5686 Pointer_type* ret = new Pointer_type(to_type);
5687 pointer_types[to_type] = ret;
5688 return ret;
5691 // This helper is invoked immediately after named types have been
5692 // converted, to clean up any unresolved pointer types remaining in
5693 // the pointer type cache.
5695 // The motivation for this routine: occasionally the compiler creates
5696 // some specific pointer type as part of a lowering operation (ex:
5697 // pointer-to-void), then Type::backend_type_size() is invoked on the
5698 // type (which creates a Btype placeholder for it), that placeholder
5699 // passed somewhere along the line to the back end, but since there is
5700 // no reference to the type in user code, there is never a call to
5701 // Type::finish_backend for the type (hence the Btype remains as an
5702 // unresolved placeholder). Calling this routine will clean up such
5703 // instances.
5705 void
5706 Type::finish_pointer_types(Gogo* gogo)
5708 // We don't use begin() and end() because it is possible to add new
5709 // placeholder pointer types as we finalized existing ones.
5710 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5712 Type* typ = Type::placeholder_pointers[i];
5713 Type_btypes::iterator tbti = Type::type_btypes.find(typ);
5714 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5716 typ->finish_backend(gogo, tbti->second.btype);
5717 tbti->second.is_placeholder = false;
5722 // Class Nil_type.
5724 // Get the backend representation of a nil type. FIXME: Is this ever
5725 // actually called?
5727 Btype*
5728 Nil_type::do_get_backend(Gogo* gogo)
5730 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5733 // Make the nil type.
5735 Type*
5736 Type::make_nil_type()
5738 static Nil_type singleton_nil_type;
5739 return &singleton_nil_type;
5742 // The type of a function call which returns multiple values. This is
5743 // really a struct, but we don't want to confuse a function call which
5744 // returns a struct with a function call which returns multiple
5745 // values.
5747 class Call_multiple_result_type : public Type
5749 public:
5750 Call_multiple_result_type()
5751 : Type(TYPE_CALL_MULTIPLE_RESULT)
5754 protected:
5755 bool
5756 do_has_pointer() const
5757 { return false; }
5759 bool
5760 do_compare_is_identity(Gogo*)
5761 { return false; }
5763 Btype*
5764 do_get_backend(Gogo* gogo)
5766 go_assert(saw_errors());
5767 return gogo->backend()->error_type();
5770 Expression*
5771 do_type_descriptor(Gogo*, Named_type*)
5773 go_assert(saw_errors());
5774 return Expression::make_error(Linemap::unknown_location());
5777 void
5778 do_reflection(Gogo*, std::string*) const
5779 { go_assert(saw_errors()); }
5781 void
5782 do_mangled_name(Gogo*, std::string*, bool*) const
5783 { go_assert(saw_errors()); }
5786 // Make a call result type.
5788 Type*
5789 Type::make_call_multiple_result_type()
5791 return new Call_multiple_result_type;
5794 // Class Struct_field.
5796 // Get the name of a field.
5798 const std::string&
5799 Struct_field::field_name() const
5801 const std::string& name(this->typed_identifier_.name());
5802 if (!name.empty())
5803 return name;
5804 else
5806 // This is called during parsing, before anything is lowered, so
5807 // we have to be pretty careful to avoid dereferencing an
5808 // unknown type name.
5809 Type* t = this->typed_identifier_.type();
5810 Type* dt = t;
5811 if (t->classification() == Type::TYPE_POINTER)
5813 // Very ugly.
5814 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5815 dt = ptype->points_to();
5817 if (dt->forward_declaration_type() != NULL)
5818 return dt->forward_declaration_type()->name();
5819 else if (dt->named_type() != NULL)
5821 // Note that this can be an alias name.
5822 return dt->named_type()->name();
5824 else if (t->is_error_type() || dt->is_error_type())
5826 static const std::string error_string = "*error*";
5827 return error_string;
5829 else
5831 // Avoid crashing in the erroneous case where T is named but
5832 // DT is not.
5833 go_assert(t != dt);
5834 if (t->forward_declaration_type() != NULL)
5835 return t->forward_declaration_type()->name();
5836 else if (t->named_type() != NULL)
5837 return t->named_type()->name();
5838 else
5839 go_unreachable();
5844 // Return whether this field is named NAME.
5846 bool
5847 Struct_field::is_field_name(const std::string& name) const
5849 const std::string& me(this->typed_identifier_.name());
5850 if (!me.empty())
5851 return me == name;
5852 else
5854 Type* t = this->typed_identifier_.type();
5855 if (t->points_to() != NULL)
5856 t = t->points_to();
5857 Named_type* nt = t->named_type();
5858 if (nt != NULL && nt->name() == name)
5859 return true;
5861 // This is a horrible hack caused by the fact that we don't pack
5862 // the names of builtin types. FIXME.
5863 if (!this->is_imported_
5864 && nt != NULL
5865 && nt->is_builtin()
5866 && nt->name() == Gogo::unpack_hidden_name(name))
5867 return true;
5869 return false;
5873 // Return whether this field is an unexported field named NAME.
5875 bool
5876 Struct_field::is_unexported_field_name(Gogo* gogo,
5877 const std::string& name) const
5879 const std::string& field_name(this->field_name());
5880 if (Gogo::is_hidden_name(field_name)
5881 && name == Gogo::unpack_hidden_name(field_name)
5882 && gogo->pack_hidden_name(name, false) != field_name)
5883 return true;
5885 // Check for the name of a builtin type. This is like the test in
5886 // is_field_name, only there we return false if this->is_imported_,
5887 // and here we return true.
5888 if (this->is_imported_ && this->is_anonymous())
5890 Type* t = this->typed_identifier_.type();
5891 if (t->points_to() != NULL)
5892 t = t->points_to();
5893 Named_type* nt = t->named_type();
5894 if (nt != NULL
5895 && nt->is_builtin()
5896 && nt->name() == Gogo::unpack_hidden_name(name))
5897 return true;
5900 return false;
5903 // Return whether this field is an embedded built-in type.
5905 bool
5906 Struct_field::is_embedded_builtin(Gogo* gogo) const
5908 const std::string& name(this->field_name());
5909 // We know that a field is an embedded type if it is anonymous.
5910 // We can decide if it is a built-in type by checking to see if it is
5911 // registered globally under the field's name.
5912 // This allows us to distinguish between embedded built-in types and
5913 // embedded types that are aliases to built-in types.
5914 return (this->is_anonymous()
5915 && !Gogo::is_hidden_name(name)
5916 && gogo->lookup_global(name.c_str()) != NULL);
5919 // Class Struct_type.
5921 // A hash table used to find identical unnamed structs so that they
5922 // share method tables.
5924 Struct_type::Identical_structs Struct_type::identical_structs;
5926 // A hash table used to merge method sets for identical unnamed
5927 // structs.
5929 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5931 // Traversal.
5934 Struct_type::do_traverse(Traverse* traverse)
5936 Struct_field_list* fields = this->fields_;
5937 if (fields != NULL)
5939 for (Struct_field_list::iterator p = fields->begin();
5940 p != fields->end();
5941 ++p)
5943 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5944 return TRAVERSE_EXIT;
5947 return TRAVERSE_CONTINUE;
5950 // Verify that the struct type is complete and valid.
5952 bool
5953 Struct_type::do_verify()
5955 Struct_field_list* fields = this->fields_;
5956 if (fields == NULL)
5957 return true;
5958 for (Struct_field_list::iterator p = fields->begin();
5959 p != fields->end();
5960 ++p)
5962 Type* t = p->type();
5963 if (p->is_anonymous())
5965 if ((t->named_type() != NULL && t->points_to() != NULL)
5966 || (t->named_type() == NULL && t->points_to() != NULL
5967 && t->points_to()->points_to() != NULL))
5969 go_error_at(p->location(), "embedded type may not be a pointer");
5970 p->set_type(Type::make_error_type());
5971 this->set_is_error();
5973 else if (t->points_to() != NULL
5974 && t->points_to()->interface_type() != NULL)
5976 go_error_at(p->location(),
5977 "embedded type may not be pointer to interface");
5978 p->set_type(Type::make_error_type());
5979 this->set_is_error();
5983 return true;
5986 // Whether this contains a pointer.
5988 bool
5989 Struct_type::do_has_pointer() const
5991 const Struct_field_list* fields = this->fields();
5992 if (fields == NULL)
5993 return false;
5994 for (Struct_field_list::const_iterator p = fields->begin();
5995 p != fields->end();
5996 ++p)
5998 if (p->type()->has_pointer())
5999 return true;
6001 return false;
6004 // Whether this type is identical to T.
6006 bool
6007 Struct_type::is_identical(const Struct_type* t, int flags) const
6009 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
6010 return false;
6011 const Struct_field_list* fields1 = this->fields();
6012 const Struct_field_list* fields2 = t->fields();
6013 if (fields1 == NULL || fields2 == NULL)
6014 return fields1 == fields2;
6015 Struct_field_list::const_iterator pf2 = fields2->begin();
6016 for (Struct_field_list::const_iterator pf1 = fields1->begin();
6017 pf1 != fields1->end();
6018 ++pf1, ++pf2)
6020 if (pf2 == fields2->end())
6021 return false;
6022 if (pf1->field_name() != pf2->field_name())
6023 return false;
6024 if (pf1->is_anonymous() != pf2->is_anonymous()
6025 || !Type::are_identical(pf1->type(), pf2->type(), flags, NULL))
6026 return false;
6027 if ((flags & Type::COMPARE_TAGS) != 0)
6029 if (!pf1->has_tag())
6031 if (pf2->has_tag())
6032 return false;
6034 else
6036 if (!pf2->has_tag())
6037 return false;
6038 if (pf1->tag() != pf2->tag())
6039 return false;
6043 if (pf2 != fields2->end())
6044 return false;
6045 return true;
6048 // Whether comparisons of this struct type are simple identity
6049 // comparisons.
6051 bool
6052 Struct_type::do_compare_is_identity(Gogo* gogo)
6054 const Struct_field_list* fields = this->fields_;
6055 if (fields == NULL)
6056 return true;
6057 int64_t offset = 0;
6058 for (Struct_field_list::const_iterator pf = fields->begin();
6059 pf != fields->end();
6060 ++pf)
6062 if (Gogo::is_sink_name(pf->field_name()))
6063 return false;
6065 if (!pf->type()->compare_is_identity(gogo))
6066 return false;
6068 int64_t field_align;
6069 if (!pf->type()->backend_type_align(gogo, &field_align))
6070 return false;
6071 if ((offset & (field_align - 1)) != 0)
6073 // This struct has padding. We don't guarantee that that
6074 // padding is zero-initialized for a stack variable, so we
6075 // can't use memcmp to compare struct values.
6076 return false;
6079 int64_t field_size;
6080 if (!pf->type()->backend_type_size(gogo, &field_size))
6081 return false;
6082 offset += field_size;
6085 int64_t struct_size;
6086 if (!this->backend_type_size(gogo, &struct_size))
6087 return false;
6088 if (offset != struct_size)
6090 // Trailing padding may not be zero when on the stack.
6091 return false;
6094 return true;
6097 // Return whether this struct type is reflexive--whether a value of
6098 // this type is always equal to itself.
6100 bool
6101 Struct_type::do_is_reflexive()
6103 const Struct_field_list* fields = this->fields_;
6104 if (fields == NULL)
6105 return true;
6106 for (Struct_field_list::const_iterator pf = fields->begin();
6107 pf != fields->end();
6108 ++pf)
6110 if (!pf->type()->is_reflexive())
6111 return false;
6113 return true;
6116 // Return whether this struct type needs a key update when used as a
6117 // map key.
6119 bool
6120 Struct_type::do_needs_key_update()
6122 const Struct_field_list* fields = this->fields_;
6123 if (fields == NULL)
6124 return false;
6125 for (Struct_field_list::const_iterator pf = fields->begin();
6126 pf != fields->end();
6127 ++pf)
6129 if (pf->type()->needs_key_update())
6130 return true;
6132 return false;
6135 // Return whether computing the hash value of an instance of this
6136 // struct type might panic.
6138 bool
6139 Struct_type::do_hash_might_panic()
6141 const Struct_field_list* fields = this->fields_;
6142 if (fields == NULL)
6143 return false;
6144 for (Struct_field_list::const_iterator pf = fields->begin();
6145 pf != fields->end();
6146 ++pf)
6148 if (pf->type()->hash_might_panic())
6149 return true;
6151 return false;
6154 // Return whether this struct type is permitted to be in the heap.
6156 bool
6157 Struct_type::do_in_heap() const
6159 const Struct_field_list* fields = this->fields_;
6160 if (fields == NULL)
6161 return true;
6162 for (Struct_field_list::const_iterator pf = fields->begin();
6163 pf != fields->end();
6164 ++pf)
6166 if (!pf->type()->in_heap())
6167 return false;
6169 return true;
6172 // Build identity and hash functions for this struct.
6174 // Hash code.
6176 unsigned int
6177 Struct_type::do_hash_for_method(Gogo* gogo, int flags) const
6179 unsigned int ret = 0;
6180 if (this->fields() != NULL)
6182 for (Struct_field_list::const_iterator pf = this->fields()->begin();
6183 pf != this->fields()->end();
6184 ++pf)
6185 ret = (ret << 1) + pf->type()->hash_for_method(gogo, flags);
6187 ret <<= 2;
6188 if (this->is_struct_incomparable_)
6189 ret <<= 1;
6190 return ret;
6193 // Find the local field NAME.
6195 const Struct_field*
6196 Struct_type::find_local_field(const std::string& name,
6197 unsigned int *pindex) const
6199 const Struct_field_list* fields = this->fields_;
6200 if (fields == NULL)
6201 return NULL;
6202 unsigned int i = 0;
6203 for (Struct_field_list::const_iterator pf = fields->begin();
6204 pf != fields->end();
6205 ++pf, ++i)
6207 if (pf->is_field_name(name))
6209 if (pindex != NULL)
6210 *pindex = i;
6211 return &*pf;
6214 return NULL;
6217 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
6219 Field_reference_expression*
6220 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
6221 Location location) const
6223 unsigned int depth;
6224 return this->field_reference_depth(struct_expr, name, location, NULL,
6225 &depth);
6228 // Return an expression for a field, along with the depth at which it
6229 // was found.
6231 Field_reference_expression*
6232 Struct_type::field_reference_depth(Expression* struct_expr,
6233 const std::string& name,
6234 Location location,
6235 Saw_named_type* saw,
6236 unsigned int* depth) const
6238 const Struct_field_list* fields = this->fields_;
6239 if (fields == NULL)
6240 return NULL;
6242 // Look for a field with this name.
6243 unsigned int i = 0;
6244 for (Struct_field_list::const_iterator pf = fields->begin();
6245 pf != fields->end();
6246 ++pf, ++i)
6248 if (pf->is_field_name(name))
6250 *depth = 0;
6251 return Expression::make_field_reference(struct_expr, i, location);
6255 // Look for an anonymous field which contains a field with this
6256 // name.
6257 unsigned int found_depth = 0;
6258 Field_reference_expression* ret = NULL;
6259 i = 0;
6260 for (Struct_field_list::const_iterator pf = fields->begin();
6261 pf != fields->end();
6262 ++pf, ++i)
6264 if (!pf->is_anonymous())
6265 continue;
6267 Struct_type* st = pf->type()->deref()->struct_type();
6268 if (st == NULL)
6269 continue;
6271 Saw_named_type* hold_saw = saw;
6272 Saw_named_type saw_here;
6273 Named_type* nt = pf->type()->named_type();
6274 if (nt == NULL)
6275 nt = pf->type()->deref()->named_type();
6276 if (nt != NULL)
6278 Saw_named_type* q;
6279 for (q = saw; q != NULL; q = q->next)
6281 if (q->nt == nt)
6283 // If this is an error, it will be reported
6284 // elsewhere.
6285 break;
6288 if (q != NULL)
6289 continue;
6290 saw_here.next = saw;
6291 saw_here.nt = nt;
6292 saw = &saw_here;
6295 // Look for a reference using a NULL struct expression. If we
6296 // find one, fill in the struct expression with a reference to
6297 // this field.
6298 unsigned int subdepth;
6299 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6300 location,
6301 saw,
6302 &subdepth);
6304 saw = hold_saw;
6306 if (sub == NULL)
6307 continue;
6309 if (ret == NULL || subdepth < found_depth)
6311 if (ret != NULL)
6312 delete ret;
6313 ret = sub;
6314 found_depth = subdepth;
6315 Expression* here = Expression::make_field_reference(struct_expr, i,
6316 location);
6317 if (pf->type()->points_to() != NULL)
6318 here = Expression::make_dereference(here,
6319 Expression::NIL_CHECK_DEFAULT,
6320 location);
6321 while (sub->expr() != NULL)
6323 sub = sub->expr()->deref()->field_reference_expression();
6324 go_assert(sub != NULL);
6326 sub->set_struct_expression(here);
6327 sub->set_implicit(true);
6329 else if (subdepth > found_depth)
6330 delete sub;
6331 else
6333 // We do not handle ambiguity here--it should be handled by
6334 // Type::bind_field_or_method.
6335 delete sub;
6336 found_depth = 0;
6337 ret = NULL;
6341 if (ret != NULL)
6342 *depth = found_depth + 1;
6344 return ret;
6347 // Return the total number of fields, including embedded fields.
6349 unsigned int
6350 Struct_type::total_field_count() const
6352 if (this->fields_ == NULL)
6353 return 0;
6354 unsigned int ret = 0;
6355 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6356 pf != this->fields_->end();
6357 ++pf)
6359 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6360 ++ret;
6361 else
6362 ret += pf->type()->struct_type()->total_field_count();
6364 return ret;
6367 // Return whether NAME is an unexported field, for better error reporting.
6369 bool
6370 Struct_type::is_unexported_local_field(Gogo* gogo,
6371 const std::string& name) const
6373 const Struct_field_list* fields = this->fields_;
6374 if (fields != NULL)
6376 for (Struct_field_list::const_iterator pf = fields->begin();
6377 pf != fields->end();
6378 ++pf)
6379 if (pf->is_unexported_field_name(gogo, name))
6380 return true;
6382 return false;
6385 // Finalize the methods of an unnamed struct.
6387 void
6388 Struct_type::finalize_methods(Gogo* gogo)
6390 if (this->all_methods_ != NULL)
6391 return;
6393 // It is possible to have multiple identical structs that have
6394 // methods. We want them to share method tables. Otherwise we will
6395 // emit identical methods more than once, which is bad since they
6396 // will even have the same names.
6397 std::pair<Identical_structs::iterator, bool> ins =
6398 Struct_type::identical_structs.insert(std::make_pair(this, this));
6399 if (!ins.second)
6401 // An identical struct was already entered into the hash table.
6402 // Note that finalize_methods is, fortunately, not recursive.
6403 this->all_methods_ = ins.first->second->all_methods_;
6404 return;
6407 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6410 // Return the method NAME, or NULL if there isn't one or if it is
6411 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6412 // ambiguous.
6414 Method*
6415 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6417 return Type::method_function(this->all_methods_, name, is_ambiguous);
6420 // Return a pointer to the interface method table for this type for
6421 // the interface INTERFACE. IS_POINTER is true if this is for a
6422 // pointer to THIS.
6424 Expression*
6425 Struct_type::interface_method_table(Interface_type* interface,
6426 bool is_pointer)
6428 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6429 val(this, nullptr);
6430 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6431 Struct_type::struct_method_tables.insert(val);
6433 Struct_method_table_pair* smtp;
6434 if (!ins.second)
6435 smtp = ins.first->second;
6436 else
6438 smtp = new Struct_method_table_pair();
6439 smtp->first = NULL;
6440 smtp->second = NULL;
6441 ins.first->second = smtp;
6444 return Type::interface_method_table(this, interface, is_pointer,
6445 &smtp->first, &smtp->second);
6448 // Convert struct fields to the backend representation. This is not
6449 // declared in types.h so that types.h doesn't have to #include
6450 // backend.h.
6452 static void
6453 get_backend_struct_fields(Gogo* gogo, Struct_type* type, bool use_placeholder,
6454 std::vector<Backend::Btyped_identifier>* bfields)
6456 const Struct_field_list* fields = type->fields();
6457 bfields->resize(fields->size());
6458 size_t i = 0;
6459 int64_t lastsize = 0;
6460 bool saw_nonzero = false;
6461 for (Struct_field_list::const_iterator p = fields->begin();
6462 p != fields->end();
6463 ++p, ++i)
6465 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6466 (*bfields)[i].btype = (use_placeholder
6467 ? p->type()->get_backend_placeholder(gogo)
6468 : p->type()->get_backend(gogo));
6469 (*bfields)[i].location = p->location();
6470 int64_t size = gogo->backend()->type_size((*bfields)[i].btype);
6471 if (size != 0)
6472 saw_nonzero = true;
6474 if (size > 0 || !Gogo::is_sink_name(p->field_name()))
6475 lastsize = size;
6476 else
6478 // There is an unreferenceable field of zero size. This
6479 // doesn't affect whether we may need zero padding, so leave
6480 // lastsize unchanged.
6483 go_assert(i == fields->size());
6484 if (saw_nonzero && lastsize == 0 && !type->is_results_struct())
6486 // For nonzero-sized structs which end in a zero-sized thing, we add
6487 // an extra byte of padding to the type. This padding ensures that
6488 // taking the address of the zero-sized thing can't manufacture a
6489 // pointer to the next object in the heap. See issue 9401.
6490 size_t n = fields->size();
6491 bfields->resize(n + 1);
6492 (*bfields)[n].name = "_";
6493 (*bfields)[n].btype = Type::lookup_integer_type("uint8")->get_backend(gogo);
6494 (*bfields)[n].location = (*bfields)[n-1].location;
6495 type->set_has_padding();
6499 // Get the backend representation for a struct type.
6501 Btype*
6502 Struct_type::do_get_backend(Gogo* gogo)
6504 std::vector<Backend::Btyped_identifier> bfields;
6505 get_backend_struct_fields(gogo, this, false, &bfields);
6506 return gogo->backend()->struct_type(bfields);
6509 // Finish the backend representation of the fields of a struct.
6511 void
6512 Struct_type::finish_backend_fields(Gogo* gogo)
6514 const Struct_field_list* fields = this->fields_;
6515 if (fields != NULL)
6517 for (Struct_field_list::const_iterator p = fields->begin();
6518 p != fields->end();
6519 ++p)
6520 p->type()->get_backend(gogo);
6524 // The type of a struct type descriptor.
6526 Type*
6527 Struct_type::make_struct_type_descriptor_type()
6529 static Type* ret;
6530 if (ret == NULL)
6532 Type* tdt = Type::make_type_descriptor_type();
6533 Type* ptdt = Type::make_type_descriptor_ptr_type();
6535 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6536 Type* string_type = Type::lookup_string_type();
6537 Type* pointer_string_type = Type::make_pointer_type(string_type);
6539 Struct_type* sf =
6540 Type::make_builtin_struct_type(5,
6541 "name", pointer_string_type,
6542 "pkgPath", pointer_string_type,
6543 "typ", ptdt,
6544 "tag", pointer_string_type,
6545 "offsetAnon", uintptr_type);
6546 Type* nsf = Type::make_builtin_named_type("structField", sf);
6548 Type* slice_type = Type::make_array_type(nsf, NULL);
6550 Struct_type* s = Type::make_builtin_struct_type(2,
6551 "", tdt,
6552 "fields", slice_type);
6554 ret = Type::make_builtin_named_type("StructType", s);
6557 return ret;
6560 // Build a type descriptor for a struct type.
6562 Expression*
6563 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6565 Location bloc = Linemap::predeclared_location();
6567 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6569 const Struct_field_list* fields = stdt->struct_type()->fields();
6571 Expression_list* vals = new Expression_list();
6572 vals->reserve(2);
6574 const Methods* methods = this->methods();
6575 // A named struct should not have methods--the methods should attach
6576 // to the named type.
6577 go_assert(methods == NULL || name == NULL);
6579 Struct_field_list::const_iterator ps = fields->begin();
6580 go_assert(ps->is_field_name("_type"));
6581 vals->push_back(this->type_descriptor_constructor(gogo,
6582 RUNTIME_TYPE_KIND_STRUCT,
6583 name, methods, true));
6585 ++ps;
6586 go_assert(ps->is_field_name("fields"));
6588 Expression_list* elements = new Expression_list();
6589 elements->reserve(this->fields_->size());
6590 Type* element_type = ps->type()->array_type()->element_type();
6591 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6592 pf != this->fields_->end();
6593 ++pf)
6595 const Struct_field_list* f = element_type->struct_type()->fields();
6597 Expression_list* fvals = new Expression_list();
6598 fvals->reserve(5);
6600 Struct_field_list::const_iterator q = f->begin();
6601 go_assert(q->is_field_name("name"));
6602 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6603 Expression* s = Expression::make_string(n, bloc);
6604 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6606 ++q;
6607 go_assert(q->is_field_name("pkgPath"));
6608 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6609 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6610 fvals->push_back(Expression::make_nil(bloc));
6611 else
6613 if (is_embedded_builtin)
6614 n = gogo->package_name();
6615 else
6616 n = Gogo::hidden_name_pkgpath(pf->field_name());
6617 s = Expression::make_string(n, bloc);
6618 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6621 ++q;
6622 go_assert(q->is_field_name("typ"));
6623 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6625 ++q;
6626 go_assert(q->is_field_name("tag"));
6627 if (!pf->has_tag())
6628 fvals->push_back(Expression::make_nil(bloc));
6629 else
6631 s = Expression::make_string(pf->tag(), bloc);
6632 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6635 ++q;
6636 go_assert(q->is_field_name("offsetAnon"));
6637 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6638 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6639 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6640 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6641 int av = pf->is_anonymous() ? 1 : 0;
6642 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6643 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6644 fvals->push_back(o);
6646 Expression* v = Expression::make_struct_composite_literal(element_type,
6647 fvals, bloc);
6648 elements->push_back(v);
6651 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6652 elements, bloc));
6654 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6657 // Write the hash function for a struct which can not use the identity
6658 // function.
6660 void
6661 Struct_type::write_hash_function(Gogo* gogo, Function_type* hash_fntype)
6663 Location bloc = Linemap::predeclared_location();
6665 // The pointer to the struct that we are going to hash. This is an
6666 // argument to the hash function we are implementing here.
6667 Named_object* key_arg = gogo->lookup("key", NULL);
6668 go_assert(key_arg != NULL);
6669 Type* key_arg_type = key_arg->var_value()->type();
6671 // The seed argument to the hash function.
6672 Named_object* seed_arg = gogo->lookup("seed", NULL);
6673 go_assert(seed_arg != NULL);
6675 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6677 // Make a temporary to hold the return value, initialized to the seed.
6678 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6679 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6680 bloc);
6681 gogo->add_statement(retval);
6683 // Make a temporary to hold the key as a uintptr.
6684 ref = Expression::make_var_reference(key_arg, bloc);
6685 ref = Expression::make_cast(uintptr_type, ref, bloc);
6686 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6687 bloc);
6688 gogo->add_statement(key);
6690 // Loop over the struct fields.
6691 const Struct_field_list* fields = this->fields_;
6692 for (Struct_field_list::const_iterator pf = fields->begin();
6693 pf != fields->end();
6694 ++pf)
6696 if (Gogo::is_sink_name(pf->field_name()))
6697 continue;
6699 // Get a pointer to the value of this field.
6700 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6701 ref = Expression::make_temporary_reference(key, bloc);
6702 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6703 bloc);
6704 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6706 // Get the hash function to use for the type of this field.
6707 Named_object* hash_fn =
6708 pf->type()->unalias()->hash_function(gogo, hash_fntype);
6710 // Call the hash function for the field, passing retval as the seed.
6711 ref = Expression::make_temporary_reference(retval, bloc);
6712 Expression_list* args = new Expression_list();
6713 args->push_back(subkey);
6714 args->push_back(ref);
6715 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6716 Expression* call = Expression::make_call(func, args, false, bloc);
6718 // Set retval to the result.
6719 Temporary_reference_expression* tref =
6720 Expression::make_temporary_reference(retval, bloc);
6721 tref->set_is_lvalue();
6722 Statement* s = Statement::make_assignment(tref, call, bloc);
6723 gogo->add_statement(s);
6726 // Return retval to the caller of the hash function.
6727 Expression_list* vals = new Expression_list();
6728 ref = Expression::make_temporary_reference(retval, bloc);
6729 vals->push_back(ref);
6730 Statement* s = Statement::make_return_statement(vals, bloc);
6731 gogo->add_statement(s);
6734 // Write the equality function for a struct which can not use the
6735 // identity function.
6737 void
6738 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6740 Location bloc = Linemap::predeclared_location();
6742 // The pointers to the structs we are going to compare.
6743 Named_object* key1_arg = gogo->lookup("key1", NULL);
6744 Named_object* key2_arg = gogo->lookup("key2", NULL);
6745 go_assert(key1_arg != NULL && key2_arg != NULL);
6747 // Build temporaries with the right types.
6748 Type* pt = Type::make_pointer_type(name != NULL
6749 ? static_cast<Type*>(name)
6750 : static_cast<Type*>(this));
6752 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6753 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6754 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6755 gogo->add_statement(p1);
6757 ref = Expression::make_var_reference(key2_arg, bloc);
6758 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6759 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6760 gogo->add_statement(p2);
6762 const Struct_field_list* fields = this->fields_;
6763 unsigned int field_index = 0;
6764 for (Struct_field_list::const_iterator pf = fields->begin();
6765 pf != fields->end();
6766 ++pf, ++field_index)
6768 if (Gogo::is_sink_name(pf->field_name()))
6769 continue;
6771 // Compare one field in both P1 and P2.
6772 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6773 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6774 bloc);
6775 f1 = Expression::make_field_reference(f1, field_index, bloc);
6777 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6778 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6779 bloc);
6780 f2 = Expression::make_field_reference(f2, field_index, bloc);
6782 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6784 // If the values are not equal, return false.
6785 gogo->start_block(bloc);
6786 Expression_list* vals = new Expression_list();
6787 vals->push_back(Expression::make_boolean(false, bloc));
6788 Statement* s = Statement::make_return_statement(vals, bloc);
6789 gogo->add_statement(s);
6790 Block* then_block = gogo->finish_block(bloc);
6792 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6793 gogo->add_statement(s);
6796 // All the fields are equal, so return true.
6797 Expression_list* vals = new Expression_list();
6798 vals->push_back(Expression::make_boolean(true, bloc));
6799 Statement* s = Statement::make_return_statement(vals, bloc);
6800 gogo->add_statement(s);
6803 // Reflection string.
6805 void
6806 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6808 ret->append("struct {");
6810 for (Struct_field_list::const_iterator p = this->fields_->begin();
6811 p != this->fields_->end();
6812 ++p)
6814 if (p != this->fields_->begin())
6815 ret->push_back(';');
6816 ret->push_back(' ');
6817 if (!p->is_anonymous())
6819 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6820 ret->push_back(' ');
6822 if (p->is_anonymous()
6823 && p->type()->named_type() != NULL
6824 && p->type()->named_type()->is_alias())
6825 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6826 else
6827 this->append_reflection(p->type(), gogo, ret);
6829 if (p->has_tag())
6831 const std::string& tag(p->tag());
6832 ret->append(" \"");
6833 for (std::string::const_iterator pt = tag.begin();
6834 pt != tag.end();
6835 ++pt)
6837 if (*pt == '\0')
6838 ret->append("\\x00");
6839 else if (*pt == '\n')
6840 ret->append("\\n");
6841 else if (*pt == '\t')
6842 ret->append("\\t");
6843 else if (*pt == '"')
6844 ret->append("\\\"");
6845 else if (*pt == '\\')
6846 ret->append("\\\\");
6847 else
6848 ret->push_back(*pt);
6850 ret->push_back('"');
6854 if (!this->fields_->empty())
6855 ret->push_back(' ');
6857 ret->push_back('}');
6860 // If the offset of field INDEX in the backend implementation can be
6861 // determined, set *POFFSET to the offset in bytes and return true.
6862 // Otherwise, return false.
6864 bool
6865 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6866 int64_t* poffset)
6868 if (!this->is_backend_type_size_known(gogo))
6869 return false;
6870 Btype* bt = this->get_backend_placeholder(gogo);
6871 *poffset = gogo->backend()->type_field_offset(bt, index);
6872 return true;
6875 // Export.
6877 void
6878 Struct_type::do_export(Export* exp) const
6880 exp->write_c_string("struct { ");
6881 const Struct_field_list* fields = this->fields_;
6882 go_assert(fields != NULL);
6883 for (Struct_field_list::const_iterator p = fields->begin();
6884 p != fields->end();
6885 ++p)
6887 if (p->is_anonymous())
6888 exp->write_string("? ");
6889 else
6891 exp->write_string(p->field_name());
6892 exp->write_c_string(" ");
6894 exp->write_type(p->type());
6896 if (p->has_tag())
6898 exp->write_c_string(" ");
6899 Expression* expr =
6900 Expression::make_string(p->tag(), Linemap::predeclared_location());
6902 Export_function_body efb(exp, 0);
6903 expr->export_expression(&efb);
6904 exp->write_string(efb.body());
6906 delete expr;
6909 exp->write_c_string("; ");
6911 exp->write_c_string("}");
6914 // Import.
6916 Struct_type*
6917 Struct_type::do_import(Import* imp)
6919 imp->require_c_string("struct { ");
6920 Struct_field_list* fields = new Struct_field_list;
6921 if (imp->peek_char() != '}')
6923 while (true)
6925 std::string name;
6926 if (imp->match_c_string("? "))
6927 imp->advance(2);
6928 else
6930 name = imp->read_identifier();
6931 imp->require_c_string(" ");
6933 Type* ftype = imp->read_type();
6935 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6936 sf.set_is_imported();
6938 if (imp->peek_char() == ' ')
6940 imp->advance(1);
6941 Expression* expr = Expression::import_expression(imp,
6942 imp->location());
6943 String_expression* sexpr = expr->string_expression();
6944 go_assert(sexpr != NULL);
6945 sf.set_tag(sexpr->val());
6946 delete sexpr;
6949 imp->require_c_string("; ");
6950 fields->push_back(sf);
6951 if (imp->peek_char() == '}')
6952 break;
6955 imp->require_c_string("}");
6957 return Type::make_struct_type(fields, imp->location());
6960 // Whether we can write this struct type to a C header file.
6961 // We can't if any of the fields are structs defined in a different package.
6963 bool
6964 Struct_type::can_write_to_c_header(
6965 std::vector<const Named_object*>* needs,
6966 std::vector<const Named_object*>* declare) const
6968 const Struct_field_list* fields = this->fields_;
6969 if (fields == NULL || fields->empty())
6970 return false;
6971 int sinks = 0;
6972 for (Struct_field_list::const_iterator p = fields->begin();
6973 p != fields->end();
6974 ++p)
6976 if (!this->can_write_type_to_c_header(p->type(), needs, declare))
6977 return false;
6978 if (Gogo::message_name(p->field_name()) == "_")
6979 sinks++;
6981 if (sinks > 1)
6982 return false;
6983 return true;
6986 // Whether we can write the type T to a C header file.
6988 bool
6989 Struct_type::can_write_type_to_c_header(
6990 const Type* t,
6991 std::vector<const Named_object*>* needs,
6992 std::vector<const Named_object*>* declare) const
6994 t = t->forwarded();
6995 switch (t->classification())
6997 case TYPE_ERROR:
6998 case TYPE_FORWARD:
6999 return false;
7001 case TYPE_VOID:
7002 case TYPE_BOOLEAN:
7003 case TYPE_INTEGER:
7004 case TYPE_FLOAT:
7005 case TYPE_COMPLEX:
7006 case TYPE_STRING:
7007 case TYPE_FUNCTION:
7008 case TYPE_MAP:
7009 case TYPE_CHANNEL:
7010 case TYPE_INTERFACE:
7011 return true;
7013 case TYPE_POINTER:
7014 // Don't try to handle a pointer to an array.
7015 if (t->points_to()->array_type() != NULL
7016 && !t->points_to()->is_slice_type())
7017 return false;
7019 if (t->points_to()->named_type() != NULL
7020 && t->points_to()->struct_type() != NULL)
7021 declare->push_back(t->points_to()->named_type()->named_object());
7022 return true;
7024 case TYPE_STRUCT:
7025 return t->struct_type()->can_write_to_c_header(needs, declare);
7027 case TYPE_ARRAY:
7028 if (t->is_slice_type())
7029 return true;
7030 return this->can_write_type_to_c_header(t->array_type()->element_type(),
7031 needs, declare);
7033 case TYPE_NAMED:
7035 const Named_object* no = t->named_type()->named_object();
7036 if (no->package() != NULL)
7038 if (t->is_unsafe_pointer_type())
7039 return true;
7040 return false;
7042 if (t->struct_type() != NULL)
7044 // We will accept empty struct fields, but not print them.
7045 if (t->struct_type()->total_field_count() == 0)
7046 return true;
7047 needs->push_back(no);
7048 return t->struct_type()->can_write_to_c_header(needs, declare);
7050 return this->can_write_type_to_c_header(t->base(), needs, declare);
7053 case TYPE_CALL_MULTIPLE_RESULT:
7054 case TYPE_NIL:
7055 case TYPE_SINK:
7056 default:
7057 go_unreachable();
7061 // Write this struct to a C header file.
7063 void
7064 Struct_type::write_to_c_header(std::ostream& os) const
7066 const Struct_field_list* fields = this->fields_;
7067 for (Struct_field_list::const_iterator p = fields->begin();
7068 p != fields->end();
7069 ++p)
7071 // Skip fields that are empty struct types. The C code can't
7072 // refer to them anyhow.
7073 if (p->type()->struct_type() != NULL
7074 && p->type()->struct_type()->total_field_count() == 0)
7075 continue;
7077 os << '\t';
7078 this->write_field_to_c_header(os, p->field_name(), p->type());
7079 os << ';' << std::endl;
7083 // Write the type of a struct field to a C header file.
7085 void
7086 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
7087 const Type *t) const
7089 bool print_name = true;
7090 t = t->forwarded();
7091 switch (t->classification())
7093 case TYPE_VOID:
7094 os << "void";
7095 break;
7097 case TYPE_BOOLEAN:
7098 os << "_Bool";
7099 break;
7101 case TYPE_INTEGER:
7103 const Integer_type* it = t->integer_type();
7104 if (it->is_unsigned())
7105 os << 'u';
7106 os << "int" << it->bits() << "_t";
7108 break;
7110 case TYPE_FLOAT:
7111 switch (t->float_type()->bits())
7113 case 32:
7114 os << "float";
7115 break;
7116 case 64:
7117 os << "double";
7118 break;
7119 default:
7120 go_unreachable();
7122 break;
7124 case TYPE_COMPLEX:
7125 switch (t->complex_type()->bits())
7127 case 64:
7128 os << "float _Complex";
7129 break;
7130 case 128:
7131 os << "double _Complex";
7132 break;
7133 default:
7134 go_unreachable();
7136 break;
7138 case TYPE_STRING:
7139 os << "String";
7140 break;
7142 case TYPE_FUNCTION:
7143 os << "FuncVal*";
7144 break;
7146 case TYPE_POINTER:
7148 std::vector<const Named_object*> needs;
7149 std::vector<const Named_object*> declare;
7150 if (!this->can_write_type_to_c_header(t->points_to(), &needs,
7151 &declare))
7152 os << "void*";
7153 else
7155 this->write_field_to_c_header(os, "", t->points_to());
7156 os << '*';
7159 break;
7161 case TYPE_MAP:
7162 os << "Map*";
7163 break;
7165 case TYPE_CHANNEL:
7166 os << "Chan*";
7167 break;
7169 case TYPE_INTERFACE:
7170 if (t->interface_type()->is_empty())
7171 os << "Eface";
7172 else
7173 os << "Iface";
7174 break;
7176 case TYPE_STRUCT:
7177 os << "struct {" << std::endl;
7178 t->struct_type()->write_to_c_header(os);
7179 os << "\t}";
7180 break;
7182 case TYPE_ARRAY:
7183 if (t->is_slice_type())
7184 os << "Slice";
7185 else
7187 const Type *ele = t;
7188 std::vector<const Type*> array_types;
7189 while (ele->array_type() != NULL && !ele->is_slice_type())
7191 array_types.push_back(ele);
7192 ele = ele->array_type()->element_type();
7194 this->write_field_to_c_header(os, "", ele);
7195 os << ' ' << Gogo::message_name(name);
7196 print_name = false;
7197 while (!array_types.empty())
7199 ele = array_types.back();
7200 array_types.pop_back();
7201 os << '[';
7202 Numeric_constant nc;
7203 if (!ele->array_type()->length()->numeric_constant_value(&nc))
7204 go_unreachable();
7205 mpz_t val;
7206 if (!nc.to_int(&val))
7207 go_unreachable();
7208 char* s = mpz_get_str(NULL, 10, val);
7209 os << s;
7210 free(s);
7211 mpz_clear(val);
7212 os << ']';
7215 break;
7217 case TYPE_NAMED:
7219 const Named_object* no = t->named_type()->named_object();
7220 if (t->struct_type() != NULL)
7221 os << "struct " << no->message_name();
7222 else if (t->is_unsafe_pointer_type())
7223 os << "void*";
7224 else if (t == Type::lookup_integer_type("uintptr"))
7225 os << "uintptr_t";
7226 else
7228 this->write_field_to_c_header(os, name, t->base());
7229 print_name = false;
7232 break;
7234 case TYPE_ERROR:
7235 case TYPE_FORWARD:
7236 case TYPE_CALL_MULTIPLE_RESULT:
7237 case TYPE_NIL:
7238 case TYPE_SINK:
7239 default:
7240 go_unreachable();
7243 if (print_name && !name.empty())
7244 os << ' ' << Gogo::message_name(name);
7247 // Make a struct type.
7249 Struct_type*
7250 Type::make_struct_type(Struct_field_list* fields,
7251 Location location)
7253 return new Struct_type(fields, location);
7256 // Class Array_type.
7258 // Store the length of an array as an int64_t into *PLEN. Return
7259 // false if the length can not be determined. This will assert if
7260 // called for a slice.
7262 bool
7263 Array_type::int_length(int64_t* plen) const
7265 go_assert(this->length_ != NULL);
7266 Numeric_constant nc;
7267 if (!this->length_->numeric_constant_value(&nc))
7268 return false;
7269 return nc.to_memory_size(plen);
7272 // Whether two array types are identical.
7274 bool
7275 Array_type::is_identical(const Array_type* t, int flags) const
7277 if (!Type::are_identical(this->element_type(), t->element_type(),
7278 flags, NULL))
7279 return false;
7281 if (this->is_array_incomparable_ != t->is_array_incomparable_)
7282 return false;
7284 Expression* l1 = this->length();
7285 Expression* l2 = t->length();
7287 // Slices of the same element type are identical.
7288 if (l1 == NULL && l2 == NULL)
7289 return true;
7291 // Arrays of the same element type are identical if they have the
7292 // same length.
7293 if (l1 != NULL && l2 != NULL)
7295 if (l1 == l2)
7296 return true;
7298 // Try to determine the lengths. If we can't, assume the arrays
7299 // are not identical.
7300 bool ret = false;
7301 Numeric_constant nc1, nc2;
7302 if (l1->numeric_constant_value(&nc1)
7303 && l2->numeric_constant_value(&nc2))
7305 mpz_t v1;
7306 if (nc1.to_int(&v1))
7308 mpz_t v2;
7309 if (nc2.to_int(&v2))
7311 ret = mpz_cmp(v1, v2) == 0;
7312 mpz_clear(v2);
7314 mpz_clear(v1);
7317 return ret;
7320 // Otherwise the arrays are not identical.
7321 return false;
7324 // Traversal.
7327 Array_type::do_traverse(Traverse* traverse)
7329 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7330 return TRAVERSE_EXIT;
7331 if (this->length_ != NULL
7332 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7333 return TRAVERSE_EXIT;
7334 return TRAVERSE_CONTINUE;
7337 // Check that the length is valid.
7339 bool
7340 Array_type::verify_length()
7342 if (this->length_ == NULL)
7343 return true;
7345 Type_context context(Type::lookup_integer_type("int"), false);
7346 this->length_->determine_type(&context);
7348 if (this->length_->is_error_expression()
7349 || this->length_->type()->is_error())
7351 go_assert(saw_errors());
7352 return false;
7355 if (!this->length_->is_constant())
7357 go_error_at(this->length_->location(), "array bound is not constant");
7358 return false;
7361 // For array types, the length expression can be an untyped constant
7362 // representable as an int, but we don't allow explicitly non-integer
7363 // values such as "float64(10)". See issues #13485 and #13486.
7364 if (this->length_->type()->integer_type() == NULL
7365 && !this->length_->type()->is_error_type())
7367 go_error_at(this->length_->location(), "invalid array bound");
7368 return false;
7371 Numeric_constant nc;
7372 if (!this->length_->numeric_constant_value(&nc))
7374 if (this->length_->type()->integer_type() != NULL
7375 || this->length_->type()->float_type() != NULL)
7376 go_error_at(this->length_->location(), "array bound is not constant");
7377 else
7378 go_error_at(this->length_->location(), "array bound is not numeric");
7379 return false;
7382 Type* int_type = Type::lookup_integer_type("int");
7383 unsigned int tbits = int_type->integer_type()->bits();
7384 unsigned long val;
7385 switch (nc.to_unsigned_long(&val))
7387 case Numeric_constant::NC_UL_VALID:
7388 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7390 go_error_at(this->length_->location(), "array bound overflows");
7391 return false;
7393 break;
7394 case Numeric_constant::NC_UL_NOTINT:
7395 go_error_at(this->length_->location(), "array bound truncated to integer");
7396 return false;
7397 case Numeric_constant::NC_UL_NEGATIVE:
7398 go_error_at(this->length_->location(), "negative array bound");
7399 return false;
7400 case Numeric_constant::NC_UL_BIG:
7402 mpz_t mval;
7403 if (!nc.to_int(&mval))
7404 go_unreachable();
7405 unsigned int bits = mpz_sizeinbase(mval, 2);
7406 mpz_clear(mval);
7407 if (bits >= tbits)
7409 go_error_at(this->length_->location(), "array bound overflows");
7410 return false;
7413 break;
7414 default:
7415 go_unreachable();
7418 return true;
7421 // Verify the type.
7423 bool
7424 Array_type::do_verify()
7426 if (this->element_type()->is_error_type())
7428 this->set_is_error();
7429 return false;
7431 if (!this->verify_length())
7433 this->length_ = Expression::make_error(this->length_->location());
7434 this->set_is_error();
7436 return true;
7439 // Whether the type contains pointers. This is always true for a
7440 // slice. For an array it is true if the element type has pointers
7441 // and the length is greater than zero.
7443 bool
7444 Array_type::do_has_pointer() const
7446 if (this->length_ == NULL)
7447 return true;
7448 if (!this->element_type_->has_pointer())
7449 return false;
7451 Numeric_constant nc;
7452 if (!this->length_->numeric_constant_value(&nc))
7454 // Error reported elsewhere.
7455 return false;
7458 unsigned long val;
7459 switch (nc.to_unsigned_long(&val))
7461 case Numeric_constant::NC_UL_VALID:
7462 return val > 0;
7463 case Numeric_constant::NC_UL_BIG:
7464 return true;
7465 default:
7466 // Error reported elsewhere.
7467 return false;
7471 // Whether we can use memcmp to compare this array.
7473 bool
7474 Array_type::do_compare_is_identity(Gogo* gogo)
7476 if (this->length_ == NULL)
7477 return false;
7479 // Check for [...], which indicates that this is not a real type.
7480 if (this->length_->is_nil_expression())
7481 return false;
7483 if (!this->element_type_->compare_is_identity(gogo))
7484 return false;
7486 // If there is any padding, then we can't use memcmp.
7487 int64_t size;
7488 int64_t align;
7489 if (!this->element_type_->backend_type_size(gogo, &size)
7490 || !this->element_type_->backend_type_align(gogo, &align))
7491 return false;
7492 if ((size & (align - 1)) != 0)
7493 return false;
7495 return true;
7498 // Array type hash code.
7500 unsigned int
7501 Array_type::do_hash_for_method(Gogo* gogo, int flags) const
7503 unsigned int ret;
7505 // There is no very convenient way to get a hash code for the
7506 // length.
7507 ret = this->element_type_->hash_for_method(gogo, flags) + 1;
7508 if (this->is_array_incomparable_)
7509 ret <<= 1;
7510 return ret;
7513 // Write the hash function for an array which can not use the identify
7514 // function.
7516 void
7517 Array_type::write_hash_function(Gogo* gogo, Function_type* hash_fntype)
7519 Location bloc = Linemap::predeclared_location();
7521 // The pointer to the array that we are going to hash. This is an
7522 // argument to the hash function we are implementing here.
7523 Named_object* key_arg = gogo->lookup("key", NULL);
7524 go_assert(key_arg != NULL);
7525 Type* key_arg_type = key_arg->var_value()->type();
7527 // The seed argument to the hash function.
7528 Named_object* seed_arg = gogo->lookup("seed", NULL);
7529 go_assert(seed_arg != NULL);
7531 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7533 // Make a temporary to hold the return value, initialized to the seed.
7534 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7535 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7536 bloc);
7537 gogo->add_statement(retval);
7539 // Make a temporary to hold the key as a uintptr.
7540 ref = Expression::make_var_reference(key_arg, bloc);
7541 ref = Expression::make_cast(uintptr_type, ref, bloc);
7542 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7543 bloc);
7544 gogo->add_statement(key);
7546 // Loop over the array elements.
7547 // for i = range a
7548 Type* int_type = Type::lookup_integer_type("int");
7549 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7550 gogo->add_statement(index);
7552 Expression* iref = Expression::make_temporary_reference(index, bloc);
7553 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7554 Type* pt = Type::make_pointer_type(static_cast<Type*>(this));
7555 aref = Expression::make_cast(pt, aref, bloc);
7556 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7557 NULL,
7558 aref,
7559 bloc);
7561 gogo->start_block(bloc);
7563 // Get the hash function for the element type.
7564 Named_object* hash_fn =
7565 this->element_type_->unalias()->hash_function(gogo, hash_fntype);
7567 // Get a pointer to this element in the loop.
7568 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7569 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7571 // Get the size of each element.
7572 Expression* ele_size = Expression::make_type_info(this->element_type_,
7573 Expression::TYPE_INFO_SIZE);
7575 // Get the hash of this element, passing retval as the seed.
7576 ref = Expression::make_temporary_reference(retval, bloc);
7577 Expression_list* args = new Expression_list();
7578 args->push_back(subkey);
7579 args->push_back(ref);
7580 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7581 Expression* call = Expression::make_call(func, args, false, bloc);
7583 // Set retval to the result.
7584 Temporary_reference_expression* tref =
7585 Expression::make_temporary_reference(retval, bloc);
7586 tref->set_is_lvalue();
7587 Statement* s = Statement::make_assignment(tref, call, bloc);
7588 gogo->add_statement(s);
7590 // Increase the element pointer.
7591 tref = Expression::make_temporary_reference(key, bloc);
7592 tref->set_is_lvalue();
7593 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7594 bloc);
7595 Block* statements = gogo->finish_block(bloc);
7597 for_range->add_statements(statements);
7598 gogo->add_statement(for_range);
7600 // Return retval to the caller of the hash function.
7601 Expression_list* vals = new Expression_list();
7602 ref = Expression::make_temporary_reference(retval, bloc);
7603 vals->push_back(ref);
7604 s = Statement::make_return_statement(vals, bloc);
7605 gogo->add_statement(s);
7608 // Write the equality function for an array which can not use the
7609 // identity function.
7611 void
7612 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7614 Location bloc = Linemap::predeclared_location();
7616 // The pointers to the arrays we are going to compare.
7617 Named_object* key1_arg = gogo->lookup("key1", NULL);
7618 Named_object* key2_arg = gogo->lookup("key2", NULL);
7619 go_assert(key1_arg != NULL && key2_arg != NULL);
7621 // Build temporaries for the keys with the right types.
7622 Type* pt = Type::make_pointer_type(name != NULL
7623 ? static_cast<Type*>(name)
7624 : static_cast<Type*>(this));
7626 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7627 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7628 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7629 gogo->add_statement(p1);
7631 ref = Expression::make_var_reference(key2_arg, bloc);
7632 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7633 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7634 gogo->add_statement(p2);
7636 // Loop over the array elements.
7637 // for i = range a
7638 Type* int_type = Type::lookup_integer_type("int");
7639 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7640 gogo->add_statement(index);
7642 Expression* iref = Expression::make_temporary_reference(index, bloc);
7643 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7644 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7645 NULL,
7646 aref,
7647 bloc);
7649 gogo->start_block(bloc);
7651 // Compare element in P1 and P2.
7652 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7653 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7654 ref = Expression::make_temporary_reference(index, bloc);
7655 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7657 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7658 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7659 ref = Expression::make_temporary_reference(index, bloc);
7660 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7662 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7664 // If the elements are not equal, return false.
7665 gogo->start_block(bloc);
7666 Expression_list* vals = new Expression_list();
7667 vals->push_back(Expression::make_boolean(false, bloc));
7668 Statement* s = Statement::make_return_statement(vals, bloc);
7669 gogo->add_statement(s);
7670 Block* then_block = gogo->finish_block(bloc);
7672 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7673 gogo->add_statement(s);
7675 Block* statements = gogo->finish_block(bloc);
7677 for_range->add_statements(statements);
7678 gogo->add_statement(for_range);
7680 // All the elements are equal, so return true.
7681 vals = new Expression_list();
7682 vals->push_back(Expression::make_boolean(true, bloc));
7683 s = Statement::make_return_statement(vals, bloc);
7684 gogo->add_statement(s);
7687 // Get the backend representation of the fields of a slice. This is
7688 // not declared in types.h so that types.h doesn't have to #include
7689 // backend.h.
7691 // We use int for the count and capacity fields. This matches 6g.
7692 // The language more or less assumes that we can't allocate space of a
7693 // size which does not fit in int.
7695 static void
7696 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7697 std::vector<Backend::Btyped_identifier>* bfields)
7699 bfields->resize(3);
7701 Type* pet = Type::make_pointer_type(type->element_type());
7702 Btype* pbet = (use_placeholder
7703 ? pet->get_backend_placeholder(gogo)
7704 : pet->get_backend(gogo));
7705 Location ploc = Linemap::predeclared_location();
7707 Backend::Btyped_identifier* p = &(*bfields)[0];
7708 p->name = "__values";
7709 p->btype = pbet;
7710 p->location = ploc;
7712 Type* int_type = Type::lookup_integer_type("int");
7714 p = &(*bfields)[1];
7715 p->name = "__count";
7716 p->btype = int_type->get_backend(gogo);
7717 p->location = ploc;
7719 p = &(*bfields)[2];
7720 p->name = "__capacity";
7721 p->btype = int_type->get_backend(gogo);
7722 p->location = ploc;
7725 // Get the backend representation for the type of this array. A fixed array is
7726 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7727 // just like an array in C. An open array is a struct with three
7728 // fields: a data pointer, the length, and the capacity.
7730 Btype*
7731 Array_type::do_get_backend(Gogo* gogo)
7733 if (this->length_ == NULL)
7735 std::vector<Backend::Btyped_identifier> bfields;
7736 get_backend_slice_fields(gogo, this, false, &bfields);
7737 return gogo->backend()->struct_type(bfields);
7739 else
7741 Btype* element = this->get_backend_element(gogo, false);
7742 Bexpression* len = this->get_backend_length(gogo);
7743 return gogo->backend()->array_type(element, len);
7747 // Return the backend representation of the element type.
7749 Btype*
7750 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7752 if (use_placeholder)
7753 return this->element_type_->get_backend_placeholder(gogo);
7754 else
7755 return this->element_type_->get_backend(gogo);
7758 // Return the backend representation of the length. The length may be
7759 // computed using a function call, so we must only evaluate it once.
7761 Bexpression*
7762 Array_type::get_backend_length(Gogo* gogo)
7764 go_assert(this->length_ != NULL);
7765 if (this->blength_ == NULL)
7767 if (this->length_->is_error_expression())
7769 this->blength_ = gogo->backend()->error_expression();
7770 return this->blength_;
7772 Numeric_constant nc;
7773 mpz_t val;
7774 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7776 if (mpz_sgn(val) < 0)
7778 this->blength_ = gogo->backend()->error_expression();
7779 return this->blength_;
7781 Type* t = nc.type();
7782 if (t == NULL)
7783 t = Type::lookup_integer_type("int");
7784 else if (t->is_abstract())
7785 t = t->make_non_abstract_type();
7786 Btype* btype = t->get_backend(gogo);
7787 this->blength_ =
7788 gogo->backend()->integer_constant_expression(btype, val);
7789 mpz_clear(val);
7791 else
7793 // Make up a translation context for the array length
7794 // expression. FIXME: This won't work in general.
7795 Translate_context context(gogo, NULL, NULL, NULL);
7796 this->blength_ = this->length_->get_backend(&context);
7798 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7799 this->blength_ =
7800 gogo->backend()->convert_expression(ibtype, this->blength_,
7801 this->length_->location());
7804 return this->blength_;
7807 // Finish backend representation of the array.
7809 void
7810 Array_type::finish_backend_element(Gogo* gogo)
7812 Type* et = this->array_type()->element_type();
7813 et->get_backend(gogo);
7814 if (this->is_slice_type())
7816 // This relies on the fact that we always use the same
7817 // structure for a pointer to any given type.
7818 Type* pet = Type::make_pointer_type(et);
7819 pet->get_backend(gogo);
7823 // Return an expression for a pointer to the values in ARRAY.
7825 Expression*
7826 Array_type::get_value_pointer(Gogo*, Expression* array) const
7828 if (this->length() != NULL)
7830 // Fixed array.
7831 go_assert(array->type()->array_type() != NULL);
7832 Type* etype = array->type()->array_type()->element_type();
7833 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7834 return Expression::make_cast(Type::make_pointer_type(etype), array,
7835 array->location());
7838 // Slice.
7839 return Expression::make_slice_info(array,
7840 Expression::SLICE_INFO_VALUE_POINTER,
7841 array->location());
7844 // Return an expression for the length of the array ARRAY which has this
7845 // type.
7847 Expression*
7848 Array_type::get_length(Gogo*, Expression* array) const
7850 if (this->length_ != NULL)
7851 return this->length_;
7853 // This is a slice. We need to read the length field.
7854 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7855 array->location());
7858 // Return an expression for the capacity of the array ARRAY which has this
7859 // type.
7861 Expression*
7862 Array_type::get_capacity(Gogo*, Expression* array) const
7864 if (this->length_ != NULL)
7865 return this->length_;
7867 // This is a slice. We need to read the capacity field.
7868 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7869 array->location());
7872 // Export.
7874 void
7875 Array_type::do_export(Export* exp) const
7877 exp->write_c_string("[");
7878 if (this->length_ != NULL)
7880 Numeric_constant nc;
7881 mpz_t val;
7882 if (!this->length_->numeric_constant_value(&nc) || !nc.to_int(&val))
7884 go_assert(saw_errors());
7885 return;
7887 char* s = mpz_get_str(NULL, 10, val);
7888 exp->write_string(s);
7889 free(s);
7890 exp->write_string(" ");
7891 mpz_clear(val);
7893 exp->write_c_string("] ");
7894 exp->write_type(this->element_type_);
7897 // Import.
7899 Array_type*
7900 Array_type::do_import(Import* imp)
7902 imp->require_c_string("[");
7903 Expression* length;
7904 if (imp->peek_char() == ']')
7905 length = NULL;
7906 else
7907 length = Expression::import_expression(imp, imp->location());
7908 imp->require_c_string("] ");
7909 Type* element_type = imp->read_type();
7910 return Type::make_array_type(element_type, length);
7913 // The type of an array type descriptor.
7915 Type*
7916 Array_type::make_array_type_descriptor_type()
7918 static Type* ret;
7919 if (ret == NULL)
7921 Type* tdt = Type::make_type_descriptor_type();
7922 Type* ptdt = Type::make_type_descriptor_ptr_type();
7924 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7926 Struct_type* sf =
7927 Type::make_builtin_struct_type(4,
7928 "", tdt,
7929 "elem", ptdt,
7930 "slice", ptdt,
7931 "len", uintptr_type);
7933 ret = Type::make_builtin_named_type("ArrayType", sf);
7936 return ret;
7939 // The type of an slice type descriptor.
7941 Type*
7942 Array_type::make_slice_type_descriptor_type()
7944 static Type* ret;
7945 if (ret == NULL)
7947 Type* tdt = Type::make_type_descriptor_type();
7948 Type* ptdt = Type::make_type_descriptor_ptr_type();
7950 Struct_type* sf =
7951 Type::make_builtin_struct_type(2,
7952 "", tdt,
7953 "elem", ptdt);
7955 ret = Type::make_builtin_named_type("SliceType", sf);
7958 return ret;
7961 // Build a type descriptor for an array/slice type.
7963 Expression*
7964 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7966 if (this->length_ != NULL)
7967 return this->array_type_descriptor(gogo, name);
7968 else
7969 return this->slice_type_descriptor(gogo, name);
7972 // Build a type descriptor for an array type.
7974 Expression*
7975 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7977 Location bloc = Linemap::predeclared_location();
7979 Type* atdt = Array_type::make_array_type_descriptor_type();
7981 const Struct_field_list* fields = atdt->struct_type()->fields();
7983 Expression_list* vals = new Expression_list();
7984 vals->reserve(3);
7986 Struct_field_list::const_iterator p = fields->begin();
7987 go_assert(p->is_field_name("_type"));
7988 vals->push_back(this->type_descriptor_constructor(gogo,
7989 RUNTIME_TYPE_KIND_ARRAY,
7990 name, NULL, true));
7992 ++p;
7993 go_assert(p->is_field_name("elem"));
7994 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7996 ++p;
7997 go_assert(p->is_field_name("slice"));
7998 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7999 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
8001 ++p;
8002 go_assert(p->is_field_name("len"));
8003 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
8005 ++p;
8006 go_assert(p == fields->end());
8008 return Expression::make_struct_composite_literal(atdt, vals, bloc);
8011 // Build a type descriptor for a slice type.
8013 Expression*
8014 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
8016 Location bloc = Linemap::predeclared_location();
8018 Type* stdt = Array_type::make_slice_type_descriptor_type();
8020 const Struct_field_list* fields = stdt->struct_type()->fields();
8022 Expression_list* vals = new Expression_list();
8023 vals->reserve(2);
8025 Struct_field_list::const_iterator p = fields->begin();
8026 go_assert(p->is_field_name("_type"));
8027 vals->push_back(this->type_descriptor_constructor(gogo,
8028 RUNTIME_TYPE_KIND_SLICE,
8029 name, NULL, true));
8031 ++p;
8032 go_assert(p->is_field_name("elem"));
8033 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8035 ++p;
8036 go_assert(p == fields->end());
8038 return Expression::make_struct_composite_literal(stdt, vals, bloc);
8041 // Reflection string.
8043 void
8044 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
8046 ret->push_back('[');
8047 if (this->length_ != NULL)
8049 Numeric_constant nc;
8050 if (!this->length_->numeric_constant_value(&nc))
8052 go_assert(saw_errors());
8053 return;
8055 mpz_t val;
8056 if (!nc.to_int(&val))
8058 go_assert(saw_errors());
8059 return;
8061 char* s = mpz_get_str(NULL, 10, val);
8062 ret->append(s);
8063 free(s);
8064 mpz_clear(val);
8066 ret->push_back(']');
8068 this->append_reflection(this->element_type_, gogo, ret);
8071 // Make an array type.
8073 Array_type*
8074 Type::make_array_type(Type* element_type, Expression* length)
8076 return new Array_type(element_type, length);
8079 // Class Map_type.
8081 Named_object* Map_type::zero_value;
8082 int64_t Map_type::zero_value_size;
8083 int64_t Map_type::zero_value_align;
8085 // If this map requires the "fat" functions, return the pointer to
8086 // pass as the zero value to those functions. Otherwise, in the
8087 // normal case, return NULL. The map requires the "fat" functions if
8088 // the value size is larger than max_zero_size bytes. max_zero_size
8089 // must match maxZero in libgo/go/runtime/map.go.
8091 Expression*
8092 Map_type::fat_zero_value(Gogo* gogo)
8094 int64_t valsize;
8095 if (!this->val_type_->backend_type_size(gogo, &valsize))
8097 go_assert(saw_errors());
8098 return NULL;
8100 if (valsize <= Map_type::max_zero_size)
8101 return NULL;
8103 if (Map_type::zero_value_size < valsize)
8104 Map_type::zero_value_size = valsize;
8106 int64_t valalign;
8107 if (!this->val_type_->backend_type_align(gogo, &valalign))
8109 go_assert(saw_errors());
8110 return NULL;
8113 if (Map_type::zero_value_align < valalign)
8114 Map_type::zero_value_align = valalign;
8116 Location bloc = Linemap::predeclared_location();
8118 if (Map_type::zero_value == NULL)
8120 // The final type will be set in backend_zero_value.
8121 Type* uint8_type = Type::lookup_integer_type("uint8");
8122 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
8123 Array_type* array_type = Type::make_array_type(uint8_type, size);
8124 array_type->set_is_array_incomparable();
8125 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
8126 std::string name = gogo->map_zero_value_name();
8127 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
8130 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
8131 z = Expression::make_unary(OPERATOR_AND, z, bloc);
8132 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8133 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
8134 return z;
8137 // Map algorithm to use for this map type.
8139 Map_type::Map_alg
8140 Map_type::algorithm(Gogo* gogo)
8142 int64_t size;
8143 bool ok = this->val_type_->backend_type_size(gogo, &size);
8144 if (!ok || size > Map_type::max_val_size)
8145 return MAP_ALG_SLOW;
8147 Type* key_type = this->key_type_;
8148 if (key_type->is_string_type())
8149 return MAP_ALG_FASTSTR;
8150 if (!key_type->compare_is_identity(gogo))
8151 return MAP_ALG_SLOW;
8153 ok = key_type->backend_type_size(gogo, &size);
8154 if (!ok)
8155 return MAP_ALG_SLOW;
8156 if (size == 4)
8157 return (key_type->has_pointer()
8158 ? MAP_ALG_FAST32PTR
8159 : MAP_ALG_FAST32);
8160 if (size == 8)
8162 if (!key_type->has_pointer())
8163 return MAP_ALG_FAST64;
8164 Type* ptr_type = Type::make_pointer_type(Type::make_void_type());
8165 ok = ptr_type->backend_type_size(gogo, &size);
8166 if (ok && size == 8)
8167 return MAP_ALG_FAST64PTR;
8168 // Key contains pointer but is not a single pointer.
8169 // Use slow version.
8171 return MAP_ALG_SLOW;
8174 // Return whether VAR is the map zero value.
8176 bool
8177 Map_type::is_zero_value(Variable* var)
8179 return (Map_type::zero_value != NULL
8180 && Map_type::zero_value->var_value() == var);
8183 // Return the backend representation for the zero value.
8185 Bvariable*
8186 Map_type::backend_zero_value(Gogo* gogo)
8188 Location bloc = Linemap::predeclared_location();
8190 go_assert(Map_type::zero_value != NULL);
8192 Type* uint8_type = Type::lookup_integer_type("uint8");
8193 Btype* buint8_type = uint8_type->get_backend(gogo);
8195 Type* int_type = Type::lookup_integer_type("int");
8197 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
8198 int_type, bloc);
8199 Translate_context context(gogo, NULL, NULL, NULL);
8200 Bexpression* blength = e->get_backend(&context);
8202 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
8204 std::string zname = Map_type::zero_value->name();
8205 unsigned int flags = Backend::variable_is_common;
8206 Bvariable* zvar =
8207 gogo->backend()->implicit_variable(zname, "", barray_type, flags,
8208 Map_type::zero_value_align);
8209 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
8210 flags, NULL);
8211 return zvar;
8214 // Traversal.
8217 Map_type::do_traverse(Traverse* traverse)
8219 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
8220 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
8221 return TRAVERSE_EXIT;
8222 return TRAVERSE_CONTINUE;
8225 // Check that the map type is OK.
8227 bool
8228 Map_type::do_verify()
8230 // The runtime support uses "map[void]void".
8231 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
8233 go_error_at(this->location_, "invalid map key type");
8234 this->set_is_error();
8236 if (!this->key_type_->in_heap())
8238 go_error_at(this->location_, "go:notinheap map key not allowed");
8239 this->set_is_error();
8241 if (!this->val_type_->in_heap())
8243 go_error_at(this->location_, "go:notinheap map value not allowed");
8244 this->set_is_error();
8246 return true;
8249 // Whether two map types are identical.
8251 bool
8252 Map_type::is_identical(const Map_type* t, int flags) const
8254 return (Type::are_identical(this->key_type(), t->key_type(), flags, NULL)
8255 && Type::are_identical(this->val_type(), t->val_type(), flags,
8256 NULL));
8259 // Hash code.
8261 unsigned int
8262 Map_type::do_hash_for_method(Gogo* gogo, int flags) const
8264 return (this->key_type_->hash_for_method(gogo, flags)
8265 + this->val_type_->hash_for_method(gogo, flags)
8266 + 2);
8269 // Get the backend representation for a map type. A map type is
8270 // represented as a pointer to a struct. The struct is hmap in
8271 // runtime/map.go.
8273 Btype*
8274 Map_type::do_get_backend(Gogo* gogo)
8276 static Btype* backend_map_type;
8277 if (backend_map_type == NULL)
8279 std::vector<Backend::Btyped_identifier> bfields(9);
8281 Location bloc = Linemap::predeclared_location();
8283 Type* int_type = Type::lookup_integer_type("int");
8284 bfields[0].name = "count";
8285 bfields[0].btype = int_type->get_backend(gogo);
8286 bfields[0].location = bloc;
8288 Type* uint8_type = Type::lookup_integer_type("uint8");
8289 bfields[1].name = "flags";
8290 bfields[1].btype = uint8_type->get_backend(gogo);
8291 bfields[1].location = bloc;
8293 bfields[2].name = "B";
8294 bfields[2].btype = bfields[1].btype;
8295 bfields[2].location = bloc;
8297 Type* uint16_type = Type::lookup_integer_type("uint16");
8298 bfields[3].name = "noverflow";
8299 bfields[3].btype = uint16_type->get_backend(gogo);
8300 bfields[3].location = bloc;
8302 Type* uint32_type = Type::lookup_integer_type("uint32");
8303 bfields[4].name = "hash0";
8304 bfields[4].btype = uint32_type->get_backend(gogo);
8305 bfields[4].location = bloc;
8307 Btype* bvt = gogo->backend()->void_type();
8308 Btype* bpvt = gogo->backend()->pointer_type(bvt);
8309 bfields[5].name = "buckets";
8310 bfields[5].btype = bpvt;
8311 bfields[5].location = bloc;
8313 bfields[6].name = "oldbuckets";
8314 bfields[6].btype = bpvt;
8315 bfields[6].location = bloc;
8317 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8318 bfields[7].name = "nevacuate";
8319 bfields[7].btype = uintptr_type->get_backend(gogo);
8320 bfields[7].location = bloc;
8322 bfields[8].name = "extra";
8323 bfields[8].btype = bpvt;
8324 bfields[8].location = bloc;
8326 Btype *bt = gogo->backend()->struct_type(bfields);
8327 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
8328 backend_map_type = gogo->backend()->pointer_type(bt);
8330 return backend_map_type;
8333 // The type of a map type descriptor.
8335 Type*
8336 Map_type::make_map_type_descriptor_type()
8338 static Type* ret;
8339 if (ret == NULL)
8341 Type* tdt = Type::make_type_descriptor_type();
8342 Type* ptdt = Type::make_type_descriptor_ptr_type();
8343 Type* uint8_type = Type::lookup_integer_type("uint8");
8344 Type* uint16_type = Type::lookup_integer_type("uint16");
8345 Type* uint32_type = Type::lookup_integer_type("uint32");
8346 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8347 Type* void_type = Type::make_void_type();
8348 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
8350 Location bloc = Linemap::predeclared_location();
8351 Typed_identifier_list *params = new Typed_identifier_list();
8352 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
8353 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
8355 Typed_identifier_list* results = new Typed_identifier_list();
8356 results->push_back(Typed_identifier("", uintptr_type, bloc));
8358 Type* hasher_fntype = Type::make_function_type(NULL, params, results,
8359 bloc);
8361 Struct_type* sf =
8362 Type::make_builtin_struct_type(9,
8363 "", tdt,
8364 "key", ptdt,
8365 "elem", ptdt,
8366 "bucket", ptdt,
8367 "hasher", hasher_fntype,
8368 "keysize", uint8_type,
8369 "valuesize", uint8_type,
8370 "bucketsize", uint16_type,
8371 "flags", uint32_type);
8373 ret = Type::make_builtin_named_type("MapType", sf);
8376 return ret;
8379 // Build a type descriptor for a map type.
8381 Expression*
8382 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8384 Location bloc = Linemap::predeclared_location();
8386 Type* mtdt = Map_type::make_map_type_descriptor_type();
8387 Type* uint8_type = Type::lookup_integer_type("uint8");
8388 Type* uint16_type = Type::lookup_integer_type("uint16");
8389 Type* uint32_type = Type::lookup_integer_type("uint32");
8391 int64_t keysize;
8392 if (!this->key_type_->backend_type_size(gogo, &keysize))
8394 go_error_at(this->location_, "error determining map key type size");
8395 return Expression::make_error(this->location_);
8398 int64_t valsize;
8399 if (!this->val_type_->backend_type_size(gogo, &valsize))
8401 go_error_at(this->location_, "error determining map value type size");
8402 return Expression::make_error(this->location_);
8405 int64_t ptrsize;
8406 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8408 go_assert(saw_errors());
8409 return Expression::make_error(this->location_);
8412 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8413 if (bucket_type == NULL)
8415 go_assert(saw_errors());
8416 return Expression::make_error(this->location_);
8419 int64_t bucketsize;
8420 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8422 go_assert(saw_errors());
8423 return Expression::make_error(this->location_);
8426 const Struct_field_list* fields = mtdt->struct_type()->fields();
8428 Expression_list* vals = new Expression_list();
8429 vals->reserve(12);
8431 Struct_field_list::const_iterator p = fields->begin();
8432 go_assert(p->is_field_name("_type"));
8433 vals->push_back(this->type_descriptor_constructor(gogo,
8434 RUNTIME_TYPE_KIND_MAP,
8435 name, NULL, true));
8437 ++p;
8438 go_assert(p->is_field_name("key"));
8439 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8441 ++p;
8442 go_assert(p->is_field_name("elem"));
8443 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8445 ++p;
8446 go_assert(p->is_field_name("bucket"));
8447 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8449 ++p;
8450 go_assert(p->is_field_name("hasher"));
8451 Function_type* hasher_fntype = p->type()->function_type();
8452 Named_object* hasher_fn =
8453 this->key_type_->unalias()->hash_function(gogo, hasher_fntype);
8454 if (hasher_fn == NULL)
8455 vals->push_back(Expression::make_cast(hasher_fntype,
8456 Expression::make_nil(bloc),
8457 bloc));
8458 else
8459 vals->push_back(Expression::make_func_reference(hasher_fn, NULL, bloc));
8461 ++p;
8462 go_assert(p->is_field_name("keysize"));
8463 if (keysize > Map_type::max_key_size)
8464 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8465 else
8466 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8468 ++p;
8469 go_assert(p->is_field_name("valuesize"));
8470 if (valsize > Map_type::max_val_size)
8471 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8472 else
8473 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8475 ++p;
8476 go_assert(p->is_field_name("bucketsize"));
8477 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8478 bloc));
8480 ++p;
8481 go_assert(p->is_field_name("flags"));
8482 // As with the other fields, the flag bits must match the reflect
8483 // and runtime packages.
8484 unsigned long flags = 0;
8485 if (keysize > Map_type::max_key_size)
8486 flags |= 1;
8487 if (valsize > Map_type::max_val_size)
8488 flags |= 2;
8489 if (this->key_type_->is_reflexive())
8490 flags |= 4;
8491 if (this->key_type_->needs_key_update())
8492 flags |= 8;
8493 if (this->key_type_->hash_might_panic())
8494 flags |= 16;
8495 vals->push_back(Expression::make_integer_ul(flags, uint32_type, bloc));
8497 ++p;
8498 go_assert(p == fields->end());
8500 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8503 // Return the bucket type to use for a map type. This must correspond
8504 // to libgo/go/runtime/map.go.
8506 Type*
8507 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8509 if (this->bucket_type_ != NULL)
8510 return this->bucket_type_;
8512 Type* key_type = this->key_type_;
8513 if (keysize > Map_type::max_key_size)
8514 key_type = Type::make_pointer_type(key_type);
8516 Type* val_type = this->val_type_;
8517 if (valsize > Map_type::max_val_size)
8518 val_type = Type::make_pointer_type(val_type);
8520 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8521 NULL, this->location_);
8523 Type* uint8_type = Type::lookup_integer_type("uint8");
8524 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8525 topbits_type->set_is_array_incomparable();
8526 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8527 keys_type->set_is_array_incomparable();
8528 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8529 values_type->set_is_array_incomparable();
8531 // If keys and values have no pointers, the map implementation can
8532 // keep a list of overflow pointers on the side so that buckets can
8533 // be marked as having no pointers. Arrange for the bucket to have
8534 // no pointers by changing the type of the overflow field to uintptr
8535 // in this case. See comment on the hmap.overflow field in
8536 // libgo/go/runtime/map.go.
8537 Type* overflow_type;
8538 if (!key_type->has_pointer() && !val_type->has_pointer())
8539 overflow_type = Type::lookup_integer_type("uintptr");
8540 else
8542 // This should really be a pointer to the bucket type itself,
8543 // but that would require us to construct a Named_type for it to
8544 // give it a way to refer to itself. Since nothing really cares
8545 // (except perhaps for someone using a debugger) just use an
8546 // unsafe pointer.
8547 overflow_type = Type::make_pointer_type(Type::make_void_type());
8550 // Make sure the overflow pointer is the last memory in the struct,
8551 // because the runtime assumes it can use size-ptrSize as the offset
8552 // of the overflow pointer. We double-check that property below
8553 // once the offsets and size are computed.
8555 int64_t topbits_field_size, topbits_field_align;
8556 int64_t keys_field_size, keys_field_align;
8557 int64_t values_field_size, values_field_align;
8558 int64_t overflow_field_size, overflow_field_align;
8559 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8560 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8561 || !keys_type->backend_type_size(gogo, &keys_field_size)
8562 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8563 || !values_type->backend_type_size(gogo, &values_field_size)
8564 || !values_type->backend_type_field_align(gogo, &values_field_align)
8565 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8566 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8568 go_assert(saw_errors());
8569 return NULL;
8572 Struct_type* ret;
8573 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8574 values_field_align);
8575 if (max_align <= overflow_field_align)
8576 ret = make_builtin_struct_type(4,
8577 "topbits", topbits_type,
8578 "keys", keys_type,
8579 "values", values_type,
8580 "overflow", overflow_type);
8581 else
8583 size_t off = topbits_field_size;
8584 off = ((off + keys_field_align - 1)
8585 &~ static_cast<size_t>(keys_field_align - 1));
8586 off += keys_field_size;
8587 off = ((off + values_field_align - 1)
8588 &~ static_cast<size_t>(values_field_align - 1));
8589 off += values_field_size;
8591 int64_t padded_overflow_field_size =
8592 ((overflow_field_size + max_align - 1)
8593 &~ static_cast<size_t>(max_align - 1));
8595 size_t ovoff = off;
8596 ovoff = ((ovoff + max_align - 1)
8597 &~ static_cast<size_t>(max_align - 1));
8598 size_t pad = (ovoff - off
8599 + padded_overflow_field_size - overflow_field_size);
8601 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8602 this->location_);
8603 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8604 pad_type->set_is_array_incomparable();
8606 ret = make_builtin_struct_type(5,
8607 "topbits", topbits_type,
8608 "keys", keys_type,
8609 "values", values_type,
8610 "pad", pad_type,
8611 "overflow", overflow_type);
8614 // Verify that the overflow field is just before the end of the
8615 // bucket type.
8617 Btype* btype = ret->get_backend(gogo);
8618 int64_t offset = gogo->backend()->type_field_offset(btype,
8619 ret->field_count() - 1);
8620 int64_t size;
8621 if (!ret->backend_type_size(gogo, &size))
8623 go_assert(saw_errors());
8624 return NULL;
8627 int64_t ptr_size;
8628 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8630 go_assert(saw_errors());
8631 return NULL;
8634 go_assert(offset + ptr_size == size);
8636 ret->set_is_struct_incomparable();
8638 this->bucket_type_ = ret;
8639 return ret;
8642 // Return the hashmap type for a map type.
8644 Type*
8645 Map_type::hmap_type(Type* bucket_type)
8647 if (this->hmap_type_ != NULL)
8648 return this->hmap_type_;
8650 Type* int_type = Type::lookup_integer_type("int");
8651 Type* uint8_type = Type::lookup_integer_type("uint8");
8652 Type* uint16_type = Type::lookup_integer_type("uint16");
8653 Type* uint32_type = Type::lookup_integer_type("uint32");
8654 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8655 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8657 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8659 Struct_type* ret = make_builtin_struct_type(9,
8660 "count", int_type,
8661 "flags", uint8_type,
8662 "B", uint8_type,
8663 "noverflow", uint16_type,
8664 "hash0", uint32_type,
8665 "buckets", ptr_bucket_type,
8666 "oldbuckets", ptr_bucket_type,
8667 "nevacuate", uintptr_type,
8668 "extra", void_ptr_type);
8669 ret->set_is_struct_incomparable();
8670 this->hmap_type_ = ret;
8671 return ret;
8674 // Return the iterator type for a map type. This is the type of the
8675 // value used when doing a range over a map.
8677 Type*
8678 Map_type::hiter_type(Gogo* gogo)
8680 if (this->hiter_type_ != NULL)
8681 return this->hiter_type_;
8683 int64_t keysize, valsize;
8684 if (!this->key_type_->backend_type_size(gogo, &keysize)
8685 || !this->val_type_->backend_type_size(gogo, &valsize))
8687 go_assert(saw_errors());
8688 return NULL;
8691 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8692 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8693 Type* uint8_type = Type::lookup_integer_type("uint8");
8694 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8695 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8696 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8697 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8698 Type* hmap_type = this->hmap_type(bucket_type);
8699 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8700 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8701 Type* bool_type = Type::lookup_bool_type();
8703 Struct_type* ret = make_builtin_struct_type(15,
8704 "key", key_ptr_type,
8705 "val", val_ptr_type,
8706 "t", uint8_ptr_type,
8707 "h", hmap_ptr_type,
8708 "buckets", bucket_ptr_type,
8709 "bptr", bucket_ptr_type,
8710 "overflow", void_ptr_type,
8711 "oldoverflow", void_ptr_type,
8712 "startBucket", uintptr_type,
8713 "offset", uint8_type,
8714 "wrapped", bool_type,
8715 "B", uint8_type,
8716 "i", uint8_type,
8717 "bucket", uintptr_type,
8718 "checkBucket", uintptr_type);
8719 ret->set_is_struct_incomparable();
8720 this->hiter_type_ = ret;
8721 return ret;
8724 // Reflection string for a map.
8726 void
8727 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8729 ret->append("map[");
8730 this->append_reflection(this->key_type_, gogo, ret);
8731 ret->append("]");
8732 this->append_reflection(this->val_type_, gogo, ret);
8735 // Export a map type.
8737 void
8738 Map_type::do_export(Export* exp) const
8740 exp->write_c_string("map [");
8741 exp->write_type(this->key_type_);
8742 exp->write_c_string("] ");
8743 exp->write_type(this->val_type_);
8746 // Import a map type.
8748 Map_type*
8749 Map_type::do_import(Import* imp)
8751 imp->require_c_string("map [");
8752 Type* key_type = imp->read_type();
8753 imp->require_c_string("] ");
8754 Type* val_type = imp->read_type();
8755 return Type::make_map_type(key_type, val_type, imp->location());
8758 // Make a map type.
8760 Map_type*
8761 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8763 return new Map_type(key_type, val_type, location);
8766 // Class Channel_type.
8768 // Verify.
8770 bool
8771 Channel_type::do_verify()
8773 // We have no location for this error, but this is not something the
8774 // ordinary user will see.
8775 if (!this->element_type_->in_heap())
8777 go_error_at(Linemap::unknown_location(),
8778 "chan of go:notinheap type not allowed");
8779 this->set_is_error();
8781 return true;
8784 // Hash code.
8786 unsigned int
8787 Channel_type::do_hash_for_method(Gogo* gogo, int flags) const
8789 unsigned int ret = 0;
8790 if (this->may_send_)
8791 ret += 1;
8792 if (this->may_receive_)
8793 ret += 2;
8794 if (this->element_type_ != NULL)
8795 ret += this->element_type_->hash_for_method(gogo, flags) << 2;
8796 return ret << 3;
8799 // Whether this type is the same as T.
8801 bool
8802 Channel_type::is_identical(const Channel_type* t, int flags) const
8804 if (!Type::are_identical(this->element_type(), t->element_type(), flags,
8805 NULL))
8806 return false;
8807 return (this->may_send_ == t->may_send_
8808 && this->may_receive_ == t->may_receive_);
8811 // Return the backend representation for a channel type. A channel is a pointer
8812 // to a __go_channel struct. The __go_channel struct is defined in
8813 // libgo/runtime/channel.h.
8815 Btype*
8816 Channel_type::do_get_backend(Gogo* gogo)
8818 static Btype* backend_channel_type;
8819 if (backend_channel_type == NULL)
8821 std::vector<Backend::Btyped_identifier> bfields;
8822 Btype* bt = gogo->backend()->struct_type(bfields);
8823 bt = gogo->backend()->named_type("__go_channel", bt,
8824 Linemap::predeclared_location());
8825 backend_channel_type = gogo->backend()->pointer_type(bt);
8827 return backend_channel_type;
8830 // Build a type descriptor for a channel type.
8832 Type*
8833 Channel_type::make_chan_type_descriptor_type()
8835 static Type* ret;
8836 if (ret == NULL)
8838 Type* tdt = Type::make_type_descriptor_type();
8839 Type* ptdt = Type::make_type_descriptor_ptr_type();
8841 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8843 Struct_type* sf =
8844 Type::make_builtin_struct_type(3,
8845 "", tdt,
8846 "elem", ptdt,
8847 "dir", uintptr_type);
8849 ret = Type::make_builtin_named_type("ChanType", sf);
8852 return ret;
8855 // Build a type descriptor for a map type.
8857 Expression*
8858 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8860 Location bloc = Linemap::predeclared_location();
8862 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8864 const Struct_field_list* fields = ctdt->struct_type()->fields();
8866 Expression_list* vals = new Expression_list();
8867 vals->reserve(3);
8869 Struct_field_list::const_iterator p = fields->begin();
8870 go_assert(p->is_field_name("_type"));
8871 vals->push_back(this->type_descriptor_constructor(gogo,
8872 RUNTIME_TYPE_KIND_CHAN,
8873 name, NULL, true));
8875 ++p;
8876 go_assert(p->is_field_name("elem"));
8877 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8879 ++p;
8880 go_assert(p->is_field_name("dir"));
8881 // These bits must match the ones in libgo/runtime/go-type.h.
8882 int val = 0;
8883 if (this->may_receive_)
8884 val |= 1;
8885 if (this->may_send_)
8886 val |= 2;
8887 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8889 ++p;
8890 go_assert(p == fields->end());
8892 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8895 // Reflection string.
8897 void
8898 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8900 if (!this->may_send_)
8901 ret->append("<-");
8902 ret->append("chan");
8903 if (!this->may_receive_)
8904 ret->append("<-");
8905 ret->push_back(' ');
8907 bool need_paren = false;
8908 if (this->may_send_
8909 && this->may_receive_
8910 && this->element_type_->channel_type() != NULL
8911 && this->element_type_->unalias()->named_type() == NULL
8912 && !this->element_type_->channel_type()->may_send())
8914 ret->push_back('(');
8915 need_paren = true;
8918 this->append_reflection(this->element_type_, gogo, ret);
8920 if (need_paren)
8921 ret->push_back(')');
8924 // Export.
8926 void
8927 Channel_type::do_export(Export* exp) const
8929 exp->write_c_string("chan ");
8930 if (this->may_send_ && !this->may_receive_)
8931 exp->write_c_string("-< ");
8932 else if (this->may_receive_ && !this->may_send_)
8933 exp->write_c_string("<- ");
8934 exp->write_type(this->element_type_);
8937 // Import.
8939 Channel_type*
8940 Channel_type::do_import(Import* imp)
8942 imp->require_c_string("chan ");
8944 bool may_send;
8945 bool may_receive;
8946 if (imp->match_c_string("-< "))
8948 imp->advance(3);
8949 may_send = true;
8950 may_receive = false;
8952 else if (imp->match_c_string("<- "))
8954 imp->advance(3);
8955 may_receive = true;
8956 may_send = false;
8958 else
8960 may_send = true;
8961 may_receive = true;
8964 Type* element_type = imp->read_type();
8966 return Type::make_channel_type(may_send, may_receive, element_type);
8969 // Return the type that the runtime package uses for one case of a
8970 // select statement. An array of values of this type is allocated on
8971 // the stack. This must match scase in libgo/go/runtime/select.go.
8973 Type*
8974 Channel_type::select_case_type()
8976 static Struct_type* scase_type;
8977 if (scase_type == NULL)
8979 Type* unsafe_pointer_type =
8980 Type::make_pointer_type(Type::make_void_type());
8981 scase_type =
8982 Type::make_builtin_struct_type(2,
8983 "c", unsafe_pointer_type,
8984 "elem", unsafe_pointer_type);
8985 scase_type->set_is_struct_incomparable();
8987 return scase_type;
8990 // Make a new channel type.
8992 Channel_type*
8993 Type::make_channel_type(bool send, bool receive, Type* element_type)
8995 return new Channel_type(send, receive, element_type);
8998 // Class Interface_type.
9000 // Return the list of methods.
9002 const Typed_identifier_list*
9003 Interface_type::methods() const
9005 go_assert(this->methods_are_finalized_ || saw_errors());
9006 return this->all_methods_;
9009 // Return the number of methods.
9011 size_t
9012 Interface_type::method_count() const
9014 go_assert(this->methods_are_finalized_ || saw_errors());
9015 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
9018 // Traversal.
9021 Interface_type::do_traverse(Traverse* traverse)
9023 Typed_identifier_list* methods = (this->methods_are_finalized_
9024 ? this->all_methods_
9025 : this->parse_methods_);
9026 if (methods == NULL)
9027 return TRAVERSE_CONTINUE;
9028 return methods->traverse(traverse);
9031 // Finalize the methods. This handles interface inheritance.
9033 void
9034 Interface_type::finalize_methods()
9036 if (this->methods_are_finalized_)
9037 return;
9038 this->methods_are_finalized_ = true;
9039 if (this->parse_methods_ == NULL)
9040 return;
9042 // The exporter uses parse_methods_.
9043 this->parse_methods_->sort_by_name();
9045 this->all_methods_ = new Typed_identifier_list();
9046 this->all_methods_->reserve(this->parse_methods_->size());
9047 Typed_identifier_list inherit;
9048 for (Typed_identifier_list::const_iterator pm =
9049 this->parse_methods_->begin();
9050 pm != this->parse_methods_->end();
9051 ++pm)
9053 const Typed_identifier* p = &*pm;
9054 if (p->name().empty())
9055 inherit.push_back(*p);
9056 else if (this->find_method(p->name()) == NULL)
9057 this->all_methods_->push_back(*p);
9058 else
9060 go_error_at(p->location(), "duplicate method %qs",
9061 Gogo::message_name(p->name()).c_str());
9062 this->set_is_error();
9066 std::vector<Named_type*> seen;
9067 seen.reserve(inherit.size());
9068 bool issued_recursive_error = false;
9069 while (!inherit.empty())
9071 Type* t = inherit.back().type();
9072 Location tl = inherit.back().location();
9073 inherit.pop_back();
9075 Interface_type* it = t->interface_type();
9076 if (it == NULL)
9078 if (!t->is_error())
9080 go_error_at(tl, "interface contains embedded non-interface");
9081 this->set_is_error();
9083 continue;
9085 if (it == this)
9087 if (!issued_recursive_error)
9089 go_error_at(tl, "invalid recursive interface");
9090 this->set_is_error();
9091 issued_recursive_error = true;
9093 continue;
9096 const Typed_identifier_list* imethods = it->parse_methods_;
9097 if (imethods == NULL)
9098 continue;
9100 Named_type* nt = t->named_type();
9101 if (nt != NULL)
9103 std::vector<Named_type*>::const_iterator q;
9104 for (q = seen.begin(); q != seen.end(); ++q)
9106 if (*q == nt)
9108 go_error_at(tl, "inherited interface loop");
9109 this->set_is_error();
9110 break;
9113 if (q != seen.end())
9114 continue;
9115 seen.push_back(nt);
9118 for (Typed_identifier_list::const_iterator q = imethods->begin();
9119 q != imethods->end();
9120 ++q)
9122 if (q->name().empty())
9123 inherit.push_back(*q);
9124 else
9126 const Typed_identifier* oldm = this->find_method(q->name());
9127 if (oldm == NULL)
9128 this->all_methods_->push_back(Typed_identifier(q->name(),
9129 q->type(), tl));
9130 else if (!Type::are_identical(q->type(), oldm->type(),
9131 Type::COMPARE_TAGS, NULL))
9133 go_error_at(tl, "duplicate method %qs",
9134 Gogo::message_name(q->name()).c_str());
9135 this->set_is_error();
9140 seen.pop_back();
9143 if (!this->all_methods_->empty())
9144 this->all_methods_->sort_by_name();
9145 else
9147 delete this->all_methods_;
9148 this->all_methods_ = NULL;
9152 // Return the method NAME, or NULL.
9154 const Typed_identifier*
9155 Interface_type::find_method(const std::string& name) const
9157 go_assert(this->methods_are_finalized_);
9158 if (this->all_methods_ == NULL)
9159 return NULL;
9160 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9161 p != this->all_methods_->end();
9162 ++p)
9163 if (p->name() == name)
9164 return &*p;
9165 return NULL;
9168 // Return the method index.
9170 size_t
9171 Interface_type::method_index(const std::string& name) const
9173 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
9174 size_t ret = 0;
9175 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9176 p != this->all_methods_->end();
9177 ++p, ++ret)
9178 if (p->name() == name)
9179 return ret;
9180 go_unreachable();
9183 // Return whether NAME is an unexported method, for better error
9184 // reporting.
9186 bool
9187 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
9189 go_assert(this->methods_are_finalized_);
9190 if (this->all_methods_ == NULL)
9191 return false;
9192 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9193 p != this->all_methods_->end();
9194 ++p)
9196 const std::string& method_name(p->name());
9197 if (Gogo::is_hidden_name(method_name)
9198 && name == Gogo::unpack_hidden_name(method_name)
9199 && gogo->pack_hidden_name(name, false) != method_name)
9200 return true;
9202 return false;
9205 // Whether this type is identical with T.
9207 bool
9208 Interface_type::is_identical(const Interface_type* t, int flags) const
9210 // If methods have not been finalized, then we are asking whether
9211 // func redeclarations are the same. This is an error, so for
9212 // simplicity we say they are never the same.
9213 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
9214 return false;
9216 // Consult a flag to see whether we need to compare based on
9217 // parse methods or all methods.
9218 Typed_identifier_list* methods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9219 ? this->parse_methods_
9220 : this->all_methods_);
9221 Typed_identifier_list* tmethods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9222 ? t->parse_methods_
9223 : t->all_methods_);
9225 // We require the same methods with the same types. The methods
9226 // have already been sorted.
9227 if (methods == NULL || tmethods == NULL)
9228 return methods == tmethods;
9230 if (this->assume_identical(this, t) || t->assume_identical(t, this))
9231 return true;
9233 Assume_identical* hold_ai = this->assume_identical_;
9234 Assume_identical ai;
9235 ai.t1 = this;
9236 ai.t2 = t;
9237 ai.next = hold_ai;
9238 this->assume_identical_ = &ai;
9240 Typed_identifier_list::const_iterator p1 = methods->begin();
9241 Typed_identifier_list::const_iterator p2;
9242 for (p2 = tmethods->begin(); p2 != tmethods->end(); ++p1, ++p2)
9244 if (p1 == methods->end())
9245 break;
9246 if (p1->name() != p2->name()
9247 || !Type::are_identical(p1->type(), p2->type(), flags, NULL))
9248 break;
9251 this->assume_identical_ = hold_ai;
9253 return p1 == methods->end() && p2 == tmethods->end();
9256 // Return true if T1 and T2 are assumed to be identical during a type
9257 // comparison.
9259 bool
9260 Interface_type::assume_identical(const Interface_type* t1,
9261 const Interface_type* t2) const
9263 for (Assume_identical* p = this->assume_identical_;
9264 p != NULL;
9265 p = p->next)
9266 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
9267 return true;
9268 return false;
9271 // Whether we can assign the interface type T to this type. The types
9272 // are known to not be identical. An interface assignment is only
9273 // permitted if T is known to implement all methods in THIS.
9274 // Otherwise a type guard is required.
9276 bool
9277 Interface_type::is_compatible_for_assign(const Interface_type* t,
9278 std::string* reason) const
9280 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
9281 if (this->all_methods_ == NULL)
9282 return true;
9283 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9284 p != this->all_methods_->end();
9285 ++p)
9287 const Typed_identifier* m = t->find_method(p->name());
9288 if (m == NULL)
9290 if (reason != NULL)
9292 char buf[200];
9293 snprintf(buf, sizeof buf,
9294 _("need explicit conversion; missing method %s%s%s"),
9295 go_open_quote(), Gogo::message_name(p->name()).c_str(),
9296 go_close_quote());
9297 reason->assign(buf);
9299 return false;
9302 std::string subreason;
9303 if (!Type::are_identical(p->type(), m->type(), Type::COMPARE_TAGS,
9304 &subreason))
9306 if (reason != NULL)
9308 std::string n = Gogo::message_name(p->name());
9309 size_t len = 100 + n.length() + subreason.length();
9310 char* buf = new char[len];
9311 if (subreason.empty())
9312 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9313 go_open_quote(), n.c_str(), go_close_quote());
9314 else
9315 snprintf(buf, len,
9316 _("incompatible type for method %s%s%s (%s)"),
9317 go_open_quote(), n.c_str(), go_close_quote(),
9318 subreason.c_str());
9319 reason->assign(buf);
9320 delete[] buf;
9322 return false;
9326 return true;
9329 // Hash code.
9331 unsigned int
9332 Interface_type::do_hash_for_method(Gogo*, int flags) const
9334 go_assert(this->methods_are_finalized_);
9335 Typed_identifier_list* methods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9336 ? this->parse_methods_
9337 : this->all_methods_);
9338 unsigned int ret = 0;
9339 if (methods != NULL)
9341 for (Typed_identifier_list::const_iterator p = methods->begin();
9342 p != methods->end();
9343 ++p)
9345 ret = Gogo::hash_string(p->name(), ret);
9346 // We don't use the method type in the hash, to avoid
9347 // infinite recursion if an interface method uses a type
9348 // which is an interface which inherits from the interface
9349 // itself.
9350 // type T interface { F() interface {T}}
9351 ret <<= 1;
9354 return ret;
9357 // Return true if T implements the interface. If it does not, and
9358 // REASON is not NULL, set *REASON to a useful error message.
9360 bool
9361 Interface_type::implements_interface(const Type* t, std::string* reason) const
9363 go_assert(this->methods_are_finalized_);
9364 if (this->all_methods_ == NULL)
9365 return true;
9367 t = t->unalias();
9368 bool is_pointer = false;
9369 const Named_type* nt = t->named_type();
9370 const Struct_type* st = t->struct_type();
9371 // If we start with a named type, we don't dereference it to find
9372 // methods.
9373 if (nt == NULL)
9375 const Type* pt = t->points_to();
9376 if (pt != NULL)
9378 // If T is a pointer to a named type, then we need to look at
9379 // the type to which it points.
9380 pt = pt->unalias();
9381 is_pointer = true;
9382 nt = pt->named_type();
9383 st = pt->struct_type();
9387 // If we have a named type, get the methods from it rather than from
9388 // any struct type.
9389 if (nt != NULL)
9390 st = NULL;
9392 // Only named and struct types have methods.
9393 if (nt == NULL && st == NULL)
9395 if (reason != NULL)
9397 if (t->points_to() != NULL
9398 && t->points_to()->interface_type() != NULL)
9399 reason->assign(_("pointer to interface type has no methods"));
9400 else
9401 reason->assign(_("type has no methods"));
9403 return false;
9406 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
9408 if (reason != NULL)
9410 if (t->points_to() != NULL
9411 && t->points_to()->interface_type() != NULL)
9412 reason->assign(_("pointer to interface type has no methods"));
9413 else
9414 reason->assign(_("type has no methods"));
9416 return false;
9419 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9420 p != this->all_methods_->end();
9421 ++p)
9423 bool is_ambiguous = false;
9424 Method* m = (nt != NULL
9425 ? nt->method_function(p->name(), &is_ambiguous)
9426 : st->method_function(p->name(), &is_ambiguous));
9427 if (m == NULL)
9429 if (reason != NULL)
9431 std::string n = Gogo::message_name(p->name());
9432 size_t len = n.length() + 100;
9433 char* buf = new char[len];
9434 if (is_ambiguous)
9435 snprintf(buf, len, _("ambiguous method %s%s%s"),
9436 go_open_quote(), n.c_str(), go_close_quote());
9437 else
9438 snprintf(buf, len, _("missing method %s%s%s"),
9439 go_open_quote(), n.c_str(), go_close_quote());
9440 reason->assign(buf);
9441 delete[] buf;
9443 return false;
9446 Function_type *p_fn_type = p->type()->function_type();
9447 Function_type* m_fn_type = m->type()->function_type();
9448 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9449 std::string subreason;
9450 if (!p_fn_type->is_identical(m_fn_type, true, Type::COMPARE_TAGS,
9451 &subreason))
9453 if (reason != NULL)
9455 std::string n = Gogo::message_name(p->name());
9456 size_t len = 100 + n.length() + subreason.length();
9457 char* buf = new char[len];
9458 if (subreason.empty())
9459 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9460 go_open_quote(), n.c_str(), go_close_quote());
9461 else
9462 snprintf(buf, len,
9463 _("incompatible type for method %s%s%s (%s)"),
9464 go_open_quote(), n.c_str(), go_close_quote(),
9465 subreason.c_str());
9466 reason->assign(buf);
9467 delete[] buf;
9469 return false;
9472 if (!is_pointer && !m->is_value_method())
9474 if (reason != NULL)
9476 std::string n = Gogo::message_name(p->name());
9477 size_t len = 100 + n.length();
9478 char* buf = new char[len];
9479 snprintf(buf, len,
9480 _("method %s%s%s requires a pointer receiver"),
9481 go_open_quote(), n.c_str(), go_close_quote());
9482 reason->assign(buf);
9483 delete[] buf;
9485 return false;
9488 // If the magic //go:nointerface comment was used, the method
9489 // may not be used to implement interfaces.
9490 if (m->nointerface())
9492 if (reason != NULL)
9494 std::string n = Gogo::message_name(p->name());
9495 size_t len = 100 + n.length();
9496 char* buf = new char[len];
9497 snprintf(buf, len,
9498 _("method %s%s%s is marked go:nointerface"),
9499 go_open_quote(), n.c_str(), go_close_quote());
9500 reason->assign(buf);
9501 delete[] buf;
9503 return false;
9507 return true;
9510 // Return the backend representation of the empty interface type. We
9511 // use the same struct for all empty interfaces.
9513 Btype*
9514 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9516 static Btype* empty_interface_type;
9517 if (empty_interface_type == NULL)
9519 std::vector<Backend::Btyped_identifier> bfields(2);
9521 Location bloc = Linemap::predeclared_location();
9523 Type* pdt = Type::make_type_descriptor_ptr_type();
9524 bfields[0].name = "__type_descriptor";
9525 bfields[0].btype = pdt->get_backend(gogo);
9526 bfields[0].location = bloc;
9528 Type* vt = Type::make_pointer_type(Type::make_void_type());
9529 bfields[1].name = "__object";
9530 bfields[1].btype = vt->get_backend(gogo);
9531 bfields[1].location = bloc;
9533 empty_interface_type = gogo->backend()->struct_type(bfields);
9535 return empty_interface_type;
9538 Interface_type::Bmethods_map Interface_type::bmethods_map;
9540 // Return a pointer to the backend representation of the method table.
9542 Btype*
9543 Interface_type::get_backend_methods(Gogo* gogo)
9545 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9546 return this->bmethods_;
9548 std::pair<Interface_type*, Bmethods_map_entry> val;
9549 val.first = this;
9550 val.second.btype = NULL;
9551 val.second.is_placeholder = false;
9552 std::pair<Bmethods_map::iterator, bool> ins =
9553 Interface_type::bmethods_map.insert(val);
9554 if (!ins.second
9555 && ins.first->second.btype != NULL
9556 && !ins.first->second.is_placeholder)
9558 this->bmethods_ = ins.first->second.btype;
9559 this->bmethods_is_placeholder_ = false;
9560 return this->bmethods_;
9563 Location loc = this->location();
9565 std::vector<Backend::Btyped_identifier>
9566 mfields(this->all_methods_->size() + 1);
9568 Type* pdt = Type::make_type_descriptor_ptr_type();
9569 mfields[0].name = "__type_descriptor";
9570 mfields[0].btype = pdt->get_backend(gogo);
9571 mfields[0].location = loc;
9573 std::string last_name = "";
9574 size_t i = 1;
9575 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9576 p != this->all_methods_->end();
9577 ++p, ++i)
9579 // The type of the method in Go only includes the parameters.
9580 // The actual method also has a receiver, which is always a
9581 // pointer. We need to add that pointer type here in order to
9582 // generate the correct type for the backend.
9583 Function_type* ft = p->type()->function_type();
9584 go_assert(ft->receiver() == NULL);
9586 const Typed_identifier_list* params = ft->parameters();
9587 Typed_identifier_list* mparams = new Typed_identifier_list();
9588 if (params != NULL)
9589 mparams->reserve(params->size() + 1);
9590 Type* vt = Type::make_pointer_type(Type::make_void_type());
9591 mparams->push_back(Typed_identifier("", vt, ft->location()));
9592 if (params != NULL)
9594 for (Typed_identifier_list::const_iterator pp = params->begin();
9595 pp != params->end();
9596 ++pp)
9597 mparams->push_back(*pp);
9600 Typed_identifier_list* mresults = (ft->results() == NULL
9601 ? NULL
9602 : ft->results()->copy());
9603 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9604 ft->location());
9606 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9607 mfields[i].btype = mft->get_backend_fntype(gogo);
9608 mfields[i].location = loc;
9610 // Sanity check: the names should be sorted.
9611 go_assert(Gogo::unpack_hidden_name(p->name())
9612 > Gogo::unpack_hidden_name(last_name));
9613 last_name = p->name();
9616 Btype* st = gogo->backend()->struct_type(mfields);
9617 Btype* ret = gogo->backend()->pointer_type(st);
9619 if (ins.first->second.btype != NULL
9620 && ins.first->second.is_placeholder)
9621 gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9622 ret);
9623 this->bmethods_ = ret;
9624 ins.first->second.btype = ret;
9625 this->bmethods_is_placeholder_ = false;
9626 ins.first->second.is_placeholder = false;
9627 return ret;
9630 // Return a placeholder for the pointer to the backend methods table.
9632 Btype*
9633 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9635 if (this->bmethods_ == NULL)
9637 std::pair<Interface_type*, Bmethods_map_entry> val;
9638 val.first = this;
9639 val.second.btype = NULL;
9640 val.second.is_placeholder = false;
9641 std::pair<Bmethods_map::iterator, bool> ins =
9642 Interface_type::bmethods_map.insert(val);
9643 if (!ins.second && ins.first->second.btype != NULL)
9645 this->bmethods_ = ins.first->second.btype;
9646 this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9647 return this->bmethods_;
9650 Location loc = this->location();
9651 Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9652 this->bmethods_ = bt;
9653 ins.first->second.btype = bt;
9654 this->bmethods_is_placeholder_ = true;
9655 ins.first->second.is_placeholder = true;
9657 return this->bmethods_;
9660 // Return the fields of a non-empty interface type. This is not
9661 // declared in types.h so that types.h doesn't have to #include
9662 // backend.h.
9664 static void
9665 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9666 bool use_placeholder,
9667 std::vector<Backend::Btyped_identifier>* bfields)
9669 Location loc = type->location();
9671 bfields->resize(2);
9673 (*bfields)[0].name = "__methods";
9674 (*bfields)[0].btype = (use_placeholder
9675 ? type->get_backend_methods_placeholder(gogo)
9676 : type->get_backend_methods(gogo));
9677 (*bfields)[0].location = loc;
9679 Type* vt = Type::make_pointer_type(Type::make_void_type());
9680 (*bfields)[1].name = "__object";
9681 (*bfields)[1].btype = vt->get_backend(gogo);
9682 (*bfields)[1].location = Linemap::predeclared_location();
9685 // Return the backend representation for an interface type. An interface is a
9686 // pointer to a struct. The struct has three fields. The first field is a
9687 // pointer to the type descriptor for the dynamic type of the object.
9688 // The second field is a pointer to a table of methods for the
9689 // interface to be used with the object. The third field is the value
9690 // of the object itself.
9692 Btype*
9693 Interface_type::do_get_backend(Gogo* gogo)
9695 if (this->is_empty())
9696 return Interface_type::get_backend_empty_interface_type(gogo);
9697 else
9699 if (this->interface_btype_ != NULL)
9700 return this->interface_btype_;
9701 this->interface_btype_ =
9702 gogo->backend()->placeholder_struct_type("", this->location_);
9703 std::vector<Backend::Btyped_identifier> bfields;
9704 get_backend_interface_fields(gogo, this, false, &bfields);
9705 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9706 bfields))
9707 this->interface_btype_ = gogo->backend()->error_type();
9708 return this->interface_btype_;
9712 // Finish the backend representation of the methods.
9714 void
9715 Interface_type::finish_backend_methods(Gogo* gogo)
9717 if (!this->is_empty())
9719 const Typed_identifier_list* methods = this->methods();
9720 if (methods != NULL)
9722 for (Typed_identifier_list::const_iterator p = methods->begin();
9723 p != methods->end();
9724 ++p)
9725 p->type()->get_backend(gogo);
9728 // Getting the backend methods now will set the placeholder
9729 // pointer.
9730 this->get_backend_methods(gogo);
9734 // The type of an interface type descriptor.
9736 Type*
9737 Interface_type::make_interface_type_descriptor_type()
9739 static Type* ret;
9740 if (ret == NULL)
9742 Type* tdt = Type::make_type_descriptor_type();
9743 Type* ptdt = Type::make_type_descriptor_ptr_type();
9745 Type* string_type = Type::lookup_string_type();
9746 Type* pointer_string_type = Type::make_pointer_type(string_type);
9748 Struct_type* sm =
9749 Type::make_builtin_struct_type(3,
9750 "name", pointer_string_type,
9751 "pkgPath", pointer_string_type,
9752 "typ", ptdt);
9754 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9756 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9758 Struct_type* s = Type::make_builtin_struct_type(2,
9759 "", tdt,
9760 "methods", slice_nsm);
9762 ret = Type::make_builtin_named_type("InterfaceType", s);
9765 return ret;
9768 // Build a type descriptor for an interface type.
9770 Expression*
9771 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9773 Location bloc = Linemap::predeclared_location();
9775 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9777 const Struct_field_list* ifields = itdt->struct_type()->fields();
9779 Expression_list* ivals = new Expression_list();
9780 ivals->reserve(2);
9782 Struct_field_list::const_iterator pif = ifields->begin();
9783 go_assert(pif->is_field_name("_type"));
9784 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9785 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9786 true));
9788 ++pif;
9789 go_assert(pif->is_field_name("methods"));
9791 Expression_list* methods = new Expression_list();
9792 if (this->all_methods_ != NULL)
9794 Type* elemtype = pif->type()->array_type()->element_type();
9796 methods->reserve(this->all_methods_->size());
9797 for (Typed_identifier_list::const_iterator pm =
9798 this->all_methods_->begin();
9799 pm != this->all_methods_->end();
9800 ++pm)
9802 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9804 Expression_list* mvals = new Expression_list();
9805 mvals->reserve(3);
9807 Struct_field_list::const_iterator pmf = mfields->begin();
9808 go_assert(pmf->is_field_name("name"));
9809 std::string s = Gogo::unpack_hidden_name(pm->name());
9810 Expression* e = Expression::make_string(s, bloc);
9811 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9813 ++pmf;
9814 go_assert(pmf->is_field_name("pkgPath"));
9815 if (!Gogo::is_hidden_name(pm->name()))
9816 mvals->push_back(Expression::make_nil(bloc));
9817 else
9819 s = Gogo::hidden_name_pkgpath(pm->name());
9820 e = Expression::make_string(s, bloc);
9821 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9824 ++pmf;
9825 go_assert(pmf->is_field_name("typ"));
9826 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9828 ++pmf;
9829 go_assert(pmf == mfields->end());
9831 e = Expression::make_struct_composite_literal(elemtype, mvals,
9832 bloc);
9833 methods->push_back(e);
9837 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9838 methods, bloc));
9840 ++pif;
9841 go_assert(pif == ifields->end());
9843 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9846 // Reflection string.
9848 void
9849 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9851 ret->append("interface {");
9852 const Typed_identifier_list* methods = this->parse_methods_;
9853 if (methods != NULL)
9855 ret->push_back(' ');
9856 for (Typed_identifier_list::const_iterator p = methods->begin();
9857 p != methods->end();
9858 ++p)
9860 if (p != methods->begin())
9861 ret->append("; ");
9862 if (p->name().empty())
9863 this->append_reflection(p->type(), gogo, ret);
9864 else
9866 if (!Gogo::is_hidden_name(p->name()))
9867 ret->append(p->name());
9868 else if (gogo->pkgpath_from_option())
9869 ret->append(p->name().substr(1));
9870 else
9872 // If no -fgo-pkgpath option, backward compatibility
9873 // for how this used to work before -fgo-pkgpath was
9874 // introduced.
9875 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9876 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9877 ret->push_back('.');
9878 ret->append(Gogo::unpack_hidden_name(p->name()));
9880 std::string sub = p->type()->reflection(gogo);
9881 go_assert(sub.compare(0, 4, "func") == 0);
9882 sub = sub.substr(4);
9883 ret->append(sub);
9886 ret->push_back(' ');
9888 ret->append("}");
9891 // Export.
9893 void
9894 Interface_type::do_export(Export* exp) const
9896 exp->write_c_string("interface { ");
9898 const Typed_identifier_list* methods = this->parse_methods_;
9899 if (methods != NULL)
9901 for (Typed_identifier_list::const_iterator pm = methods->begin();
9902 pm != methods->end();
9903 ++pm)
9905 if (pm->name().empty())
9907 exp->write_c_string("? ");
9908 exp->write_type(pm->type());
9910 else
9912 exp->write_string(pm->name());
9913 exp->write_c_string(" (");
9915 const Function_type* fntype = pm->type()->function_type();
9917 bool first = true;
9918 const Typed_identifier_list* parameters = fntype->parameters();
9919 if (parameters != NULL)
9921 bool is_varargs = fntype->is_varargs();
9922 for (Typed_identifier_list::const_iterator pp =
9923 parameters->begin();
9924 pp != parameters->end();
9925 ++pp)
9927 if (first)
9928 first = false;
9929 else
9930 exp->write_c_string(", ");
9931 exp->write_name(pp->name());
9932 exp->write_c_string(" ");
9933 if (!is_varargs || pp + 1 != parameters->end())
9934 exp->write_type(pp->type());
9935 else
9937 exp->write_c_string("...");
9938 Type *pptype = pp->type();
9939 exp->write_type(pptype->array_type()->element_type());
9944 exp->write_c_string(")");
9946 const Typed_identifier_list* results = fntype->results();
9947 if (results != NULL)
9949 exp->write_c_string(" ");
9950 if (results->size() == 1 && results->begin()->name().empty())
9951 exp->write_type(results->begin()->type());
9952 else
9954 first = true;
9955 exp->write_c_string("(");
9956 for (Typed_identifier_list::const_iterator p =
9957 results->begin();
9958 p != results->end();
9959 ++p)
9961 if (first)
9962 first = false;
9963 else
9964 exp->write_c_string(", ");
9965 exp->write_name(p->name());
9966 exp->write_c_string(" ");
9967 exp->write_type(p->type());
9969 exp->write_c_string(")");
9974 exp->write_c_string("; ");
9978 exp->write_c_string("}");
9981 // Import an interface type.
9983 Interface_type*
9984 Interface_type::do_import(Import* imp)
9986 imp->require_c_string("interface { ");
9988 Typed_identifier_list* methods = new Typed_identifier_list;
9989 while (imp->peek_char() != '}')
9991 std::string name = imp->read_identifier();
9993 if (name == "?")
9995 imp->require_c_string(" ");
9996 Type* t = imp->read_type();
9997 methods->push_back(Typed_identifier("", t, imp->location()));
9998 imp->require_c_string("; ");
9999 continue;
10002 imp->require_c_string(" (");
10004 Typed_identifier_list* parameters;
10005 bool is_varargs = false;
10006 if (imp->peek_char() == ')')
10007 parameters = NULL;
10008 else
10010 parameters = new Typed_identifier_list;
10011 while (true)
10013 std::string pname = imp->read_name();
10014 imp->require_c_string(" ");
10016 if (imp->match_c_string("..."))
10018 imp->advance(3);
10019 is_varargs = true;
10022 Type* ptype = imp->read_type();
10023 if (is_varargs)
10024 ptype = Type::make_array_type(ptype, NULL);
10025 parameters->push_back(Typed_identifier(pname, ptype,
10026 imp->location()));
10027 if (imp->peek_char() != ',')
10028 break;
10029 go_assert(!is_varargs);
10030 imp->require_c_string(", ");
10033 imp->require_c_string(")");
10035 Typed_identifier_list* results;
10036 if (imp->peek_char() != ' ')
10037 results = NULL;
10038 else
10040 results = new Typed_identifier_list;
10041 imp->advance(1);
10042 if (imp->peek_char() != '(')
10044 Type* rtype = imp->read_type();
10045 results->push_back(Typed_identifier("", rtype, imp->location()));
10047 else
10049 imp->advance(1);
10050 while (true)
10052 std::string rname = imp->read_name();
10053 imp->require_c_string(" ");
10054 Type* rtype = imp->read_type();
10055 results->push_back(Typed_identifier(rname, rtype,
10056 imp->location()));
10057 if (imp->peek_char() != ',')
10058 break;
10059 imp->require_c_string(", ");
10061 imp->require_c_string(")");
10065 Function_type* fntype = Type::make_function_type(NULL, parameters,
10066 results,
10067 imp->location());
10068 if (is_varargs)
10069 fntype->set_is_varargs();
10070 methods->push_back(Typed_identifier(name, fntype, imp->location()));
10072 imp->require_c_string("; ");
10075 imp->require_c_string("}");
10077 if (methods->empty())
10079 delete methods;
10080 methods = NULL;
10083 Interface_type* ret = Type::make_interface_type(methods, imp->location());
10084 ret->package_ = imp->package();
10085 return ret;
10088 // Make an interface type.
10090 Interface_type*
10091 Type::make_interface_type(Typed_identifier_list* methods,
10092 Location location)
10094 return new Interface_type(methods, location);
10097 // Make an empty interface type.
10099 Interface_type*
10100 Type::make_empty_interface_type(Location location)
10102 Interface_type* ret = new Interface_type(NULL, location);
10103 ret->finalize_methods();
10104 return ret;
10107 // Class Method.
10109 // Bind a method to an object.
10111 Expression*
10112 Method::bind_method(Expression* expr, Location location) const
10114 if (this->stub_ == NULL)
10116 // When there is no stub object, the binding is determined by
10117 // the child class.
10118 return this->do_bind_method(expr, location);
10120 return Expression::make_bound_method(expr, this, this->stub_, location);
10123 // Return the named object associated with a method. This may only be
10124 // called after methods are finalized.
10126 Named_object*
10127 Method::named_object() const
10129 if (this->stub_ != NULL)
10130 return this->stub_;
10131 return this->do_named_object();
10134 // Class Named_method.
10136 // The type of the method.
10138 Function_type*
10139 Named_method::do_type() const
10141 if (this->named_object_->is_function())
10142 return this->named_object_->func_value()->type();
10143 else if (this->named_object_->is_function_declaration())
10144 return this->named_object_->func_declaration_value()->type();
10145 else
10146 go_unreachable();
10149 // Return the location of the method receiver.
10151 Location
10152 Named_method::do_receiver_location() const
10154 return this->do_type()->receiver()->location();
10157 // Bind a method to an object.
10159 Expression*
10160 Named_method::do_bind_method(Expression* expr, Location location) const
10162 Named_object* no = this->named_object_;
10163 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
10164 no, location);
10165 // If this is not a local method, and it does not use a stub, then
10166 // the real method expects a different type. We need to cast the
10167 // first argument.
10168 if (this->depth() > 0 && !this->needs_stub_method())
10170 Function_type* ftype = this->do_type();
10171 go_assert(ftype->is_method());
10172 Type* frtype = ftype->receiver()->type();
10173 bme->set_first_argument_type(frtype);
10175 return bme;
10178 // Return whether this method should not participate in interfaces.
10180 bool
10181 Named_method::do_nointerface() const
10183 Named_object* no = this->named_object_;
10184 if (no->is_function())
10185 return no->func_value()->nointerface();
10186 else if (no->is_function_declaration())
10187 return no->func_declaration_value()->nointerface();
10188 else
10189 go_unreachable();
10192 // Class Interface_method.
10194 // Bind a method to an object.
10196 Expression*
10197 Interface_method::do_bind_method(Expression* expr,
10198 Location location) const
10200 return Expression::make_interface_field_reference(expr, this->name_,
10201 location);
10204 // Class Methods.
10206 // Insert a new method. Return true if it was inserted, false
10207 // otherwise.
10209 bool
10210 Methods::insert(const std::string& name, Method* m)
10212 std::pair<Method_map::iterator, bool> ins =
10213 this->methods_.insert(std::make_pair(name, m));
10214 if (ins.second)
10215 return true;
10216 else
10218 Method* old_method = ins.first->second;
10219 if (m->depth() < old_method->depth())
10221 delete old_method;
10222 ins.first->second = m;
10223 return true;
10225 else
10227 if (m->depth() == old_method->depth())
10228 old_method->set_is_ambiguous();
10229 return false;
10234 // Return the number of unambiguous methods.
10236 size_t
10237 Methods::count() const
10239 size_t ret = 0;
10240 for (Method_map::const_iterator p = this->methods_.begin();
10241 p != this->methods_.end();
10242 ++p)
10243 if (!p->second->is_ambiguous())
10244 ++ret;
10245 return ret;
10248 // Class Named_type.
10250 // Return the name of the type.
10252 const std::string&
10253 Named_type::name() const
10255 return this->named_object_->name();
10258 // Return the name of the type to use in an error message.
10260 std::string
10261 Named_type::message_name() const
10263 return this->named_object_->message_name();
10266 // Return the base type for this type. We have to be careful about
10267 // circular type definitions, which are invalid but may be seen here.
10269 Type*
10270 Named_type::named_base()
10272 if (this->seen_)
10273 return this;
10274 this->seen_ = true;
10275 Type* ret = this->type_->base();
10276 this->seen_ = false;
10277 return ret;
10280 const Type*
10281 Named_type::named_base() const
10283 if (this->seen_)
10284 return this;
10285 this->seen_ = true;
10286 const Type* ret = this->type_->base();
10287 this->seen_ = false;
10288 return ret;
10291 // Return whether this is an error type. We have to be careful about
10292 // circular type definitions, which are invalid but may be seen here.
10294 bool
10295 Named_type::is_named_error_type() const
10297 if (this->seen_)
10298 return false;
10299 this->seen_ = true;
10300 bool ret = this->type_->is_error_type();
10301 this->seen_ = false;
10302 return ret;
10305 // Whether this type is comparable. We have to be careful about
10306 // circular type definitions.
10308 bool
10309 Named_type::named_type_is_comparable(std::string* reason) const
10311 if (this->seen_)
10312 return false;
10313 this->seen_ = true;
10314 bool ret = Type::are_compatible_for_comparison(true, this->type_,
10315 this->type_, reason);
10316 this->seen_ = false;
10317 return ret;
10320 // Add a method to this type.
10322 Named_object*
10323 Named_type::add_method(const std::string& name, Function* function)
10325 go_assert(!this->is_alias_);
10326 if (this->local_methods_ == NULL)
10327 this->local_methods_ = new Bindings(NULL);
10328 return this->local_methods_->add_function(name,
10329 this->named_object_->package(),
10330 function);
10333 // Add a method declaration to this type.
10335 Named_object*
10336 Named_type::add_method_declaration(const std::string& name, Package* package,
10337 Function_type* type,
10338 Location location)
10340 go_assert(!this->is_alias_);
10341 if (this->local_methods_ == NULL)
10342 this->local_methods_ = new Bindings(NULL);
10343 return this->local_methods_->add_function_declaration(name, package, type,
10344 location);
10347 // Add an existing method to this type.
10349 void
10350 Named_type::add_existing_method(Named_object* no)
10352 go_assert(!this->is_alias_);
10353 if (this->local_methods_ == NULL)
10354 this->local_methods_ = new Bindings(NULL);
10355 this->local_methods_->add_named_object(no);
10358 // Look for a local method NAME, and returns its named object, or NULL
10359 // if not there.
10361 Named_object*
10362 Named_type::find_local_method(const std::string& name) const
10364 if (this->is_error_)
10365 return NULL;
10366 if (this->is_alias_)
10368 Named_type* nt = this->type_->named_type();
10369 if (nt != NULL)
10371 if (this->seen_alias_)
10372 return NULL;
10373 this->seen_alias_ = true;
10374 Named_object* ret = nt->find_local_method(name);
10375 this->seen_alias_ = false;
10376 return ret;
10378 return NULL;
10380 if (this->local_methods_ == NULL)
10381 return NULL;
10382 return this->local_methods_->lookup(name);
10385 // Return the list of local methods.
10387 const Bindings*
10388 Named_type::local_methods() const
10390 if (this->is_error_)
10391 return NULL;
10392 if (this->is_alias_)
10394 Named_type* nt = this->type_->named_type();
10395 if (nt != NULL)
10397 if (this->seen_alias_)
10398 return NULL;
10399 this->seen_alias_ = true;
10400 const Bindings* ret = nt->local_methods();
10401 this->seen_alias_ = false;
10402 return ret;
10404 return NULL;
10406 return this->local_methods_;
10409 // Return whether NAME is an unexported field or method, for better
10410 // error reporting.
10412 bool
10413 Named_type::is_unexported_local_method(Gogo* gogo,
10414 const std::string& name) const
10416 if (this->is_error_)
10417 return false;
10418 if (this->is_alias_)
10420 Named_type* nt = this->type_->named_type();
10421 if (nt != NULL)
10423 if (this->seen_alias_)
10424 return false;
10425 this->seen_alias_ = true;
10426 bool ret = nt->is_unexported_local_method(gogo, name);
10427 this->seen_alias_ = false;
10428 return ret;
10430 return false;
10432 Bindings* methods = this->local_methods_;
10433 if (methods != NULL)
10435 for (Bindings::const_declarations_iterator p =
10436 methods->begin_declarations();
10437 p != methods->end_declarations();
10438 ++p)
10440 if (Gogo::is_hidden_name(p->first)
10441 && name == Gogo::unpack_hidden_name(p->first)
10442 && gogo->pack_hidden_name(name, false) != p->first)
10443 return true;
10446 return false;
10449 // Build the complete list of methods for this type, which means
10450 // recursively including all methods for anonymous fields. Create all
10451 // stub methods.
10453 void
10454 Named_type::finalize_methods(Gogo* gogo)
10456 if (this->is_alias_)
10457 return;
10458 if (this->all_methods_ != NULL)
10459 return;
10461 if (this->local_methods_ != NULL
10462 && (this->points_to() != NULL || this->interface_type() != NULL))
10464 const Bindings* lm = this->local_methods_;
10465 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10466 p != lm->end_declarations();
10467 ++p)
10468 go_error_at(p->second->location(),
10469 "invalid pointer or interface receiver type");
10470 delete this->local_methods_;
10471 this->local_methods_ = NULL;
10472 return;
10475 // Remove any aliases in the local method receiver types.
10476 Bindings* methods = this->local_methods_;
10477 if (methods != NULL)
10479 for (Bindings::const_declarations_iterator p =
10480 methods->begin_declarations();
10481 p != methods->end_declarations();
10482 ++p)
10484 Named_object* no = p->second;
10485 Function_type* fntype;
10486 if (no->is_function())
10487 fntype = no->func_value()->type();
10488 else if (no->is_function_declaration())
10489 fntype = no->func_declaration_value()->type();
10490 else
10492 go_assert(saw_errors());
10493 continue;
10496 Type* rtype = fntype->receiver()->type();
10497 bool is_pointer = false;
10498 Type* pt = rtype->points_to();
10499 if (pt != NULL)
10501 rtype = pt;
10502 is_pointer = true;
10504 if (rtype->named_type() != this)
10506 if (rtype->unalias() != this)
10508 go_assert(saw_errors());
10509 continue;
10512 rtype = this;
10513 if (is_pointer)
10514 rtype = Type::make_pointer_type(rtype);
10516 if (no->is_function())
10517 no->func_value()->set_receiver_type(rtype);
10518 else if (no->is_function_declaration())
10519 no->func_declaration_value()->set_receiver_type(rtype);
10520 else
10521 go_unreachable();
10526 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10529 // Return whether this type has any methods.
10531 bool
10532 Named_type::has_any_methods() const
10534 if (this->is_error_)
10535 return false;
10536 if (this->is_alias_)
10538 if (this->type_->named_type() != NULL)
10540 if (this->seen_alias_)
10541 return false;
10542 this->seen_alias_ = true;
10543 bool ret = this->type_->named_type()->has_any_methods();
10544 this->seen_alias_ = false;
10545 return ret;
10547 if (this->type_->struct_type() != NULL)
10548 return this->type_->struct_type()->has_any_methods();
10549 return false;
10551 return this->all_methods_ != NULL;
10554 // Return the methods for this type.
10556 const Methods*
10557 Named_type::methods() const
10559 if (this->is_error_)
10560 return NULL;
10561 if (this->is_alias_)
10563 if (this->type_->named_type() != NULL)
10565 if (this->seen_alias_)
10566 return NULL;
10567 this->seen_alias_ = true;
10568 const Methods* ret = this->type_->named_type()->methods();
10569 this->seen_alias_ = false;
10570 return ret;
10572 if (this->type_->struct_type() != NULL)
10573 return this->type_->struct_type()->methods();
10574 return NULL;
10576 return this->all_methods_;
10579 // Return the method NAME, or NULL if there isn't one or if it is
10580 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10581 // ambiguous.
10583 Method*
10584 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10586 if (this->is_error_)
10587 return NULL;
10588 if (this->is_alias_)
10590 if (is_ambiguous != NULL)
10591 *is_ambiguous = false;
10592 if (this->type_->named_type() != NULL)
10594 if (this->seen_alias_)
10595 return NULL;
10596 this->seen_alias_ = true;
10597 Named_type* nt = this->type_->named_type();
10598 Method* ret = nt->method_function(name, is_ambiguous);
10599 this->seen_alias_ = false;
10600 return ret;
10602 if (this->type_->struct_type() != NULL)
10603 return this->type_->struct_type()->method_function(name, is_ambiguous);
10604 return NULL;
10606 return Type::method_function(this->all_methods_, name, is_ambiguous);
10609 // Return a pointer to the interface method table for this type for
10610 // the interface INTERFACE. IS_POINTER is true if this is for a
10611 // pointer to THIS.
10613 Expression*
10614 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10616 if (this->is_error_)
10617 return Expression::make_error(this->location_);
10618 if (this->is_alias_)
10620 Type* t = this->type_;
10621 if (!is_pointer && t->points_to() != NULL)
10623 t = t->points_to();
10624 is_pointer = true;
10626 if (t->named_type() != NULL)
10628 if (this->seen_alias_)
10629 return Expression::make_error(this->location_);
10630 this->seen_alias_ = true;
10631 Named_type* nt = t->named_type();
10632 Expression* ret = nt->interface_method_table(interface, is_pointer);
10633 this->seen_alias_ = false;
10634 return ret;
10636 if (t->struct_type() != NULL)
10637 return t->struct_type()->interface_method_table(interface, is_pointer);
10638 go_unreachable();
10640 return Type::interface_method_table(this, interface, is_pointer,
10641 &this->interface_method_tables_,
10642 &this->pointer_interface_method_tables_);
10645 // Look for a use of a complete type within another type. This is
10646 // used to check that we don't try to use a type within itself.
10648 class Find_type_use : public Traverse
10650 public:
10651 Find_type_use(Named_type* find_type)
10652 : Traverse(traverse_types),
10653 find_type_(find_type), found_(false)
10656 // Whether we found the type.
10657 bool
10658 found() const
10659 { return this->found_; }
10661 protected:
10663 type(Type*);
10665 private:
10666 // The type we are looking for.
10667 Named_type* find_type_;
10668 // Whether we found the type.
10669 bool found_;
10672 // Check for FIND_TYPE in TYPE.
10675 Find_type_use::type(Type* type)
10677 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10679 this->found_ = true;
10680 return TRAVERSE_EXIT;
10683 // It's OK if we see a reference to the type in any type which is
10684 // essentially a pointer: a pointer, a slice, a function, a map, or
10685 // a channel.
10686 if (type->points_to() != NULL
10687 || type->is_slice_type()
10688 || type->function_type() != NULL
10689 || type->map_type() != NULL
10690 || type->channel_type() != NULL)
10691 return TRAVERSE_SKIP_COMPONENTS;
10693 // For an interface, a reference to the type in a method type should
10694 // be ignored, but we have to consider direct inheritance. When
10695 // this is called, there may be cases of direct inheritance
10696 // represented as a method with no name.
10697 if (type->interface_type() != NULL)
10699 const Typed_identifier_list* methods = type->interface_type()->methods();
10700 if (methods != NULL)
10702 for (Typed_identifier_list::const_iterator p = methods->begin();
10703 p != methods->end();
10704 ++p)
10706 if (p->name().empty())
10708 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10709 return TRAVERSE_EXIT;
10713 return TRAVERSE_SKIP_COMPONENTS;
10716 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10717 // to convert TYPE to the backend representation before we convert
10718 // FIND_TYPE_.
10719 if (type->named_type() != NULL)
10721 switch (type->base()->classification())
10723 case Type::TYPE_ERROR:
10724 case Type::TYPE_BOOLEAN:
10725 case Type::TYPE_INTEGER:
10726 case Type::TYPE_FLOAT:
10727 case Type::TYPE_COMPLEX:
10728 case Type::TYPE_STRING:
10729 case Type::TYPE_NIL:
10730 break;
10732 case Type::TYPE_ARRAY:
10733 case Type::TYPE_STRUCT:
10734 this->find_type_->add_dependency(type->named_type());
10735 break;
10737 case Type::TYPE_NAMED:
10738 if (type->named_type() == type->base()->named_type())
10740 this->found_ = true;
10741 return TRAVERSE_EXIT;
10743 else
10744 go_assert(saw_errors());
10745 break;
10747 case Type::TYPE_FORWARD:
10748 go_assert(saw_errors());
10749 break;
10751 case Type::TYPE_VOID:
10752 case Type::TYPE_SINK:
10753 case Type::TYPE_FUNCTION:
10754 case Type::TYPE_POINTER:
10755 case Type::TYPE_CALL_MULTIPLE_RESULT:
10756 case Type::TYPE_MAP:
10757 case Type::TYPE_CHANNEL:
10758 case Type::TYPE_INTERFACE:
10759 default:
10760 go_unreachable();
10764 return TRAVERSE_CONTINUE;
10767 // Look for a circular reference of an alias.
10769 class Find_alias : public Traverse
10771 public:
10772 Find_alias(Named_type* find_type)
10773 : Traverse(traverse_types),
10774 find_type_(find_type), found_(false)
10777 // Whether we found the type.
10778 bool
10779 found() const
10780 { return this->found_; }
10782 protected:
10784 type(Type*);
10786 private:
10787 // The type we are looking for.
10788 Named_type* find_type_;
10789 // Whether we found the type.
10790 bool found_;
10794 Find_alias::type(Type* type)
10796 Named_type* nt = type->named_type();
10797 if (nt != NULL)
10799 if (nt == this->find_type_)
10801 this->found_ = true;
10802 return TRAVERSE_EXIT;
10805 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10806 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10807 // an alias itself, it's OK if whatever T2 is defined as refers
10808 // to T1.
10809 if (!nt->is_alias())
10810 return TRAVERSE_SKIP_COMPONENTS;
10813 // Check if there are recursive inherited interface aliases.
10814 Interface_type* ift = type->interface_type();
10815 if (ift != NULL)
10817 const Typed_identifier_list* methods = ift->local_methods();
10818 if (methods == NULL)
10819 return TRAVERSE_CONTINUE;
10820 for (Typed_identifier_list::const_iterator p = methods->begin();
10821 p != methods->end();
10822 ++p)
10823 if (p->name().empty() && p->type()->named_type() == this->find_type_)
10825 this->found_ = true;
10826 return TRAVERSE_EXIT;
10830 return TRAVERSE_CONTINUE;
10833 // Verify that a named type does not refer to itself.
10835 bool
10836 Named_type::do_verify()
10838 if (this->is_verified_)
10839 return true;
10840 this->is_verified_ = true;
10842 if (this->is_error_)
10843 return false;
10845 if (this->is_alias_)
10847 Find_alias find(this);
10848 Type::traverse(this->type_, &find);
10849 if (find.found())
10851 go_error_at(this->location_, "invalid recursive alias %qs",
10852 this->message_name().c_str());
10853 this->is_error_ = true;
10854 return false;
10858 Find_type_use find(this);
10859 Type::traverse(this->type_, &find);
10860 if (find.found())
10862 go_error_at(this->location_, "invalid recursive type %qs",
10863 this->message_name().c_str());
10864 this->is_error_ = true;
10865 return false;
10868 // Check whether any of the local methods overloads an existing
10869 // struct field or interface method. We don't need to check the
10870 // list of methods against itself: that is handled by the Bindings
10871 // code.
10872 if (this->local_methods_ != NULL)
10874 Struct_type* st = this->type_->struct_type();
10875 if (st != NULL)
10877 for (Bindings::const_declarations_iterator p =
10878 this->local_methods_->begin_declarations();
10879 p != this->local_methods_->end_declarations();
10880 ++p)
10882 const std::string& name(p->first);
10883 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10885 go_error_at(p->second->location(),
10886 "method %qs redeclares struct field name",
10887 Gogo::message_name(name).c_str());
10893 return true;
10896 // Return whether this type is or contains a pointer.
10898 bool
10899 Named_type::do_has_pointer() const
10901 // A type that is not in the heap has no pointers that we care about.
10902 if (!this->in_heap_)
10903 return false;
10905 if (this->seen_)
10906 return false;
10907 this->seen_ = true;
10908 bool ret = this->type_->has_pointer();
10909 this->seen_ = false;
10910 return ret;
10913 // Return whether comparisons for this type can use the identity
10914 // function.
10916 bool
10917 Named_type::do_compare_is_identity(Gogo* gogo)
10919 // We don't use this->seen_ here because compare_is_identity may
10920 // call base() later, and that will mess up if seen_ is set here.
10921 if (this->seen_in_compare_is_identity_)
10922 return false;
10923 this->seen_in_compare_is_identity_ = true;
10924 bool ret = this->type_->compare_is_identity(gogo);
10925 this->seen_in_compare_is_identity_ = false;
10926 return ret;
10929 // Return whether this type is reflexive--whether it is always equal
10930 // to itself.
10932 bool
10933 Named_type::do_is_reflexive()
10935 if (this->seen_in_compare_is_identity_)
10936 return false;
10937 this->seen_in_compare_is_identity_ = true;
10938 bool ret = this->type_->is_reflexive();
10939 this->seen_in_compare_is_identity_ = false;
10940 return ret;
10943 // Return whether this type needs a key update when used as a map key.
10945 bool
10946 Named_type::do_needs_key_update()
10948 if (this->seen_in_compare_is_identity_)
10949 return true;
10950 this->seen_in_compare_is_identity_ = true;
10951 bool ret = this->type_->needs_key_update();
10952 this->seen_in_compare_is_identity_ = false;
10953 return ret;
10956 // Return whether this type is permitted in the heap.
10957 bool
10958 Named_type::do_in_heap() const
10960 if (!this->in_heap_)
10961 return false;
10962 if (this->seen_)
10963 return true;
10964 this->seen_ = true;
10965 bool ret = this->type_->in_heap();
10966 this->seen_ = false;
10967 return ret;
10970 // Return a hash code. This is used for method lookup. We simply
10971 // hash on the name itself.
10973 unsigned int
10974 Named_type::do_hash_for_method(Gogo* gogo, int) const
10976 if (this->is_error_)
10977 return 0;
10979 // Aliases are handled in Type::hash_for_method.
10980 go_assert(!this->is_alias_);
10982 const std::string& name(this->named_object()->name());
10983 unsigned int ret = Gogo::hash_string(name, 0);
10985 // GOGO will be NULL here when called from Type_hash_identical.
10986 // That is OK because that is only used for internal hash tables
10987 // where we are going to be comparing named types for equality. In
10988 // other cases, which are cases where the runtime is going to
10989 // compare hash codes to see if the types are the same, we need to
10990 // include the pkgpath in the hash.
10991 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10993 const Package* package = this->named_object()->package();
10994 if (package == NULL)
10995 ret = Gogo::hash_string(gogo->pkgpath(), ret);
10996 else
10997 ret = Gogo::hash_string(package->pkgpath(), ret);
11000 return ret;
11003 // Convert a named type to the backend representation. In order to
11004 // get dependencies right, we fill in a dummy structure for this type,
11005 // then convert all the dependencies, then complete this type. When
11006 // this function is complete, the size of the type is known.
11008 void
11009 Named_type::convert(Gogo* gogo)
11011 if (this->is_error_ || this->is_converted_)
11012 return;
11014 this->create_placeholder(gogo);
11016 // If we are called to turn unsafe.Sizeof into a constant, we may
11017 // not have verified the type yet. We have to make sure it is
11018 // verified, since that sets the list of dependencies.
11019 this->verify();
11021 // Convert all the dependencies. If they refer indirectly back to
11022 // this type, they will pick up the intermediate representation we just
11023 // created.
11024 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
11025 p != this->dependencies_.end();
11026 ++p)
11027 (*p)->convert(gogo);
11029 // Complete this type.
11030 Btype* bt = this->named_btype_;
11031 Type* base = this->type_->base();
11032 switch (base->classification())
11034 case TYPE_VOID:
11035 case TYPE_BOOLEAN:
11036 case TYPE_INTEGER:
11037 case TYPE_FLOAT:
11038 case TYPE_COMPLEX:
11039 case TYPE_STRING:
11040 case TYPE_NIL:
11041 break;
11043 case TYPE_MAP:
11044 case TYPE_CHANNEL:
11045 break;
11047 case TYPE_FUNCTION:
11048 case TYPE_POINTER:
11049 // The size of these types is already correct. We don't worry
11050 // about filling them in until later, when we also track
11051 // circular references.
11052 break;
11054 case TYPE_STRUCT:
11056 std::vector<Backend::Btyped_identifier> bfields;
11057 get_backend_struct_fields(gogo, base->struct_type(), true, &bfields);
11058 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
11059 bt = gogo->backend()->error_type();
11061 break;
11063 case TYPE_ARRAY:
11064 // Slice types were completed in create_placeholder.
11065 if (!base->is_slice_type())
11067 Btype* bet = base->array_type()->get_backend_element(gogo, true);
11068 Bexpression* blen = base->array_type()->get_backend_length(gogo);
11069 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
11070 bt = gogo->backend()->error_type();
11072 break;
11074 case TYPE_INTERFACE:
11075 // Interface types were completed in create_placeholder.
11076 break;
11078 case TYPE_ERROR:
11079 return;
11081 default:
11082 case TYPE_SINK:
11083 case TYPE_CALL_MULTIPLE_RESULT:
11084 case TYPE_NAMED:
11085 case TYPE_FORWARD:
11086 go_unreachable();
11089 this->named_btype_ = bt;
11090 this->is_converted_ = true;
11091 this->is_placeholder_ = false;
11094 // Create the placeholder for a named type. This is the first step in
11095 // converting to the backend representation.
11097 void
11098 Named_type::create_placeholder(Gogo* gogo)
11100 if (this->is_error_)
11101 this->named_btype_ = gogo->backend()->error_type();
11103 if (this->named_btype_ != NULL)
11104 return;
11106 // Create the structure for this type. Note that because we call
11107 // base() here, we don't attempt to represent a named type defined
11108 // as another named type. Instead both named types will point to
11109 // different base representations.
11110 Type* base = this->type_->base();
11111 Btype* bt;
11112 bool set_name = true;
11113 switch (base->classification())
11115 case TYPE_ERROR:
11116 this->is_error_ = true;
11117 this->named_btype_ = gogo->backend()->error_type();
11118 return;
11120 case TYPE_VOID:
11121 case TYPE_BOOLEAN:
11122 case TYPE_INTEGER:
11123 case TYPE_FLOAT:
11124 case TYPE_COMPLEX:
11125 case TYPE_STRING:
11126 case TYPE_NIL:
11127 // These are simple basic types, we can just create them
11128 // directly.
11129 bt = Type::get_named_base_btype(gogo, base);
11130 break;
11132 case TYPE_MAP:
11133 case TYPE_CHANNEL:
11134 // All maps and channels have the same backend representation.
11135 bt = Type::get_named_base_btype(gogo, base);
11136 break;
11138 case TYPE_FUNCTION:
11139 case TYPE_POINTER:
11141 bool for_function = base->classification() == TYPE_FUNCTION;
11142 bt = gogo->backend()->placeholder_pointer_type(this->name(),
11143 this->location_,
11144 for_function);
11145 set_name = false;
11147 break;
11149 case TYPE_STRUCT:
11150 bt = gogo->backend()->placeholder_struct_type(this->name(),
11151 this->location_);
11152 this->is_placeholder_ = true;
11153 set_name = false;
11154 break;
11156 case TYPE_ARRAY:
11157 if (base->is_slice_type())
11158 bt = gogo->backend()->placeholder_struct_type(this->name(),
11159 this->location_);
11160 else
11162 bt = gogo->backend()->placeholder_array_type(this->name(),
11163 this->location_);
11164 this->is_placeholder_ = true;
11166 set_name = false;
11167 break;
11169 case TYPE_INTERFACE:
11170 if (base->interface_type()->is_empty())
11171 bt = Interface_type::get_backend_empty_interface_type(gogo);
11172 else
11174 bt = gogo->backend()->placeholder_struct_type(this->name(),
11175 this->location_);
11176 set_name = false;
11178 break;
11180 default:
11181 case TYPE_SINK:
11182 case TYPE_CALL_MULTIPLE_RESULT:
11183 case TYPE_NAMED:
11184 case TYPE_FORWARD:
11185 go_unreachable();
11188 if (set_name)
11189 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
11191 this->named_btype_ = bt;
11193 if (base->is_slice_type())
11195 // We do not record slices as dependencies of other types,
11196 // because we can fill them in completely here with the final
11197 // size.
11198 std::vector<Backend::Btyped_identifier> bfields;
11199 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
11200 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
11201 this->named_btype_ = gogo->backend()->error_type();
11203 else if (base->interface_type() != NULL
11204 && !base->interface_type()->is_empty())
11206 // We do not record interfaces as dependencies of other types,
11207 // because we can fill them in completely here with the final
11208 // size.
11209 std::vector<Backend::Btyped_identifier> bfields;
11210 get_backend_interface_fields(gogo, base->interface_type(), true,
11211 &bfields);
11212 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
11213 this->named_btype_ = gogo->backend()->error_type();
11217 // Get the backend representation for a named type.
11219 Btype*
11220 Named_type::do_get_backend(Gogo* gogo)
11222 if (this->is_error_)
11223 return gogo->backend()->error_type();
11225 Btype* bt = this->named_btype_;
11227 if (!gogo->named_types_are_converted())
11229 // We have not completed converting named types. NAMED_BTYPE_
11230 // is a placeholder and we shouldn't do anything further.
11231 if (bt != NULL)
11232 return bt;
11234 // We don't build dependencies for types whose sizes do not
11235 // change or are not relevant, so we may see them here while
11236 // converting types.
11237 this->create_placeholder(gogo);
11238 bt = this->named_btype_;
11239 go_assert(bt != NULL);
11240 return bt;
11243 // We are not converting types. This should only be called if the
11244 // type has already been converted.
11245 if (!this->is_converted_)
11247 go_assert(saw_errors());
11248 return gogo->backend()->error_type();
11251 go_assert(bt != NULL);
11253 // Complete the backend representation.
11254 Type* base = this->type_->base();
11255 Btype* bt1;
11256 switch (base->classification())
11258 case TYPE_ERROR:
11259 return gogo->backend()->error_type();
11261 case TYPE_VOID:
11262 case TYPE_BOOLEAN:
11263 case TYPE_INTEGER:
11264 case TYPE_FLOAT:
11265 case TYPE_COMPLEX:
11266 case TYPE_STRING:
11267 case TYPE_NIL:
11268 case TYPE_MAP:
11269 case TYPE_CHANNEL:
11270 return bt;
11272 case TYPE_STRUCT:
11273 if (!this->seen_in_get_backend_)
11275 this->seen_in_get_backend_ = true;
11276 base->struct_type()->finish_backend_fields(gogo);
11277 this->seen_in_get_backend_ = false;
11279 return bt;
11281 case TYPE_ARRAY:
11282 if (!this->seen_in_get_backend_)
11284 this->seen_in_get_backend_ = true;
11285 base->array_type()->finish_backend_element(gogo);
11286 this->seen_in_get_backend_ = false;
11288 return bt;
11290 case TYPE_INTERFACE:
11291 if (!this->seen_in_get_backend_)
11293 this->seen_in_get_backend_ = true;
11294 base->interface_type()->finish_backend_methods(gogo);
11295 this->seen_in_get_backend_ = false;
11297 return bt;
11299 case TYPE_FUNCTION:
11300 // Don't build a circular data structure. GENERIC can't handle
11301 // it.
11302 if (this->seen_in_get_backend_)
11303 return gogo->backend()->circular_pointer_type(bt, true);
11304 this->seen_in_get_backend_ = true;
11305 bt1 = Type::get_named_base_btype(gogo, base);
11306 this->seen_in_get_backend_ = false;
11307 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11308 bt = gogo->backend()->error_type();
11309 return bt;
11311 case TYPE_POINTER:
11312 // Don't build a circular data structure. GENERIC can't handle
11313 // it.
11314 if (this->seen_in_get_backend_)
11315 return gogo->backend()->circular_pointer_type(bt, false);
11316 this->seen_in_get_backend_ = true;
11317 bt1 = Type::get_named_base_btype(gogo, base);
11318 this->seen_in_get_backend_ = false;
11319 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11320 bt = gogo->backend()->error_type();
11321 return bt;
11323 default:
11324 case TYPE_SINK:
11325 case TYPE_CALL_MULTIPLE_RESULT:
11326 case TYPE_NAMED:
11327 case TYPE_FORWARD:
11328 go_unreachable();
11331 go_unreachable();
11334 // Build a type descriptor for a named type.
11336 Expression*
11337 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11339 if (this->is_error_)
11340 return Expression::make_error(this->location_);
11342 // We shouldn't see unnamed type aliases here. They should have
11343 // been removed by the call to unalias in Type::type_descriptor_pointer.
11344 // We can see named type aliases via Type::named_type_descriptor.
11345 go_assert(name != NULL || !this->is_alias_);
11347 // If NAME is not NULL, then we don't really want the type
11348 // descriptor for this type; we want the descriptor for the
11349 // underlying type, giving it the name NAME.
11350 return this->named_type_descriptor(gogo, this->type_,
11351 name == NULL ? this : name);
11354 // Add to the reflection string. This is used mostly for the name of
11355 // the type used in a type descriptor, not for actual reflection
11356 // strings.
11358 void
11359 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
11361 this->append_reflection_type_name(gogo, false, ret);
11364 // Add to the reflection string. For an alias we normally use the
11365 // real name, but if USE_ALIAS is true we use the alias name itself.
11367 void
11368 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
11369 std::string* ret) const
11371 if (this->is_error_)
11372 return;
11373 if (this->is_alias_ && !use_alias)
11375 if (this->seen_alias_)
11376 return;
11377 this->seen_alias_ = true;
11378 this->append_reflection(this->type_, gogo, ret);
11379 this->seen_alias_ = false;
11380 return;
11382 if (!this->is_builtin())
11384 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
11385 // make a unique reflection string, so that the type
11386 // canonicalization in the reflect package will work. In order
11387 // to be compatible with the gc compiler, we put tabs into the
11388 // package path, so that the reflect methods can discard it.
11389 const Package* package = this->named_object_->package();
11390 ret->push_back('\t');
11391 ret->append(package != NULL
11392 ? package->pkgpath_symbol()
11393 : gogo->pkgpath_symbol());
11394 ret->push_back('\t');
11395 ret->append(package != NULL
11396 ? package->package_name()
11397 : gogo->package_name());
11398 ret->push_back('.');
11400 if (this->in_function_ != NULL)
11402 ret->push_back('\t');
11403 const Typed_identifier* rcvr =
11404 this->in_function_->func_value()->type()->receiver();
11405 if (rcvr != NULL)
11407 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11408 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
11409 ret->push_back('.');
11411 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
11412 ret->push_back('$');
11413 if (this->in_function_index_ > 0)
11415 char buf[30];
11416 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11417 ret->append(buf);
11418 ret->push_back('$');
11420 ret->push_back('\t');
11422 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
11425 // Import a named type. This is only used for export format versions
11426 // before version 3.
11428 void
11429 Named_type::import_named_type(Import* imp, Named_type** ptype)
11431 imp->require_c_string("type ");
11432 Type *type = imp->read_type();
11433 *ptype = type->named_type();
11434 go_assert(*ptype != NULL);
11435 imp->require_semicolon_if_old_version();
11436 imp->require_c_string("\n");
11439 // Export the type when it is referenced by another type. In this
11440 // case Export::export_type will already have issued the name. The
11441 // output always ends with a newline, since that is convenient if
11442 // there are methods.
11444 void
11445 Named_type::do_export(Export* exp) const
11447 exp->write_type(this->type_);
11448 exp->write_c_string("\n");
11450 // To save space, we only export the methods directly attached to
11451 // this type.
11452 Bindings* methods = this->local_methods_;
11453 if (methods == NULL)
11454 return;
11456 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
11457 p != methods->end_definitions();
11458 ++p)
11460 exp->write_c_string(" ");
11461 (*p)->export_named_object(exp);
11464 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
11465 p != methods->end_declarations();
11466 ++p)
11468 if (p->second->is_function_declaration())
11470 exp->write_c_string(" ");
11471 p->second->export_named_object(exp);
11476 // Make a named type.
11478 Named_type*
11479 Type::make_named_type(Named_object* named_object, Type* type,
11480 Location location)
11482 return new Named_type(named_object, type, location);
11485 // Finalize the methods for TYPE. It will be a named type or a struct
11486 // type. This sets *ALL_METHODS to the list of methods, and builds
11487 // all required stubs.
11489 void
11490 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
11491 Methods** all_methods)
11493 *all_methods = new Methods();
11494 std::vector<const Named_type*> seen;
11495 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
11496 if ((*all_methods)->empty())
11498 delete *all_methods;
11499 *all_methods = NULL;
11501 Type::build_stub_methods(gogo, type, *all_methods, location);
11502 if (type->is_direct_iface_type() || !type->in_heap())
11503 Type::build_direct_iface_stub_methods(gogo, type, *all_methods, location);
11506 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11507 // build up the struct field indexes as we go. DEPTH is the depth of
11508 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11509 // adding these methods for an anonymous field with pointer type.
11510 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11511 // calls the real method. TYPES_SEEN is used to avoid infinite
11512 // recursion.
11514 void
11515 Type::add_methods_for_type(const Type* type,
11516 const Method::Field_indexes* field_indexes,
11517 unsigned int depth,
11518 bool is_embedded_pointer,
11519 bool needs_stub_method,
11520 std::vector<const Named_type*>* seen,
11521 Methods* methods)
11523 // Pointer types may not have methods.
11524 if (type->points_to() != NULL)
11525 return;
11527 const Named_type* nt = type->named_type();
11528 if (nt != NULL)
11530 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11531 p != seen->end();
11532 ++p)
11534 if (*p == nt)
11535 return;
11538 seen->push_back(nt);
11540 Type::add_local_methods_for_type(nt, field_indexes, depth,
11541 is_embedded_pointer, needs_stub_method,
11542 methods);
11545 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11546 is_embedded_pointer, needs_stub_method,
11547 seen, methods);
11549 // If we are called with depth > 0, then we are looking at an
11550 // anonymous field of a struct. If such a field has interface type,
11551 // then we need to add the interface methods. We don't want to add
11552 // them when depth == 0, because we will already handle them
11553 // following the usual rules for an interface type.
11554 if (depth > 0)
11555 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11557 if (nt != NULL)
11558 seen->pop_back();
11561 // Add the local methods for the named type NT to *METHODS. The
11562 // parameters are as for add_methods_to_type.
11564 void
11565 Type::add_local_methods_for_type(const Named_type* nt,
11566 const Method::Field_indexes* field_indexes,
11567 unsigned int depth,
11568 bool is_embedded_pointer,
11569 bool needs_stub_method,
11570 Methods* methods)
11572 const Bindings* local_methods = nt->local_methods();
11573 if (local_methods == NULL)
11574 return;
11576 for (Bindings::const_declarations_iterator p =
11577 local_methods->begin_declarations();
11578 p != local_methods->end_declarations();
11579 ++p)
11581 Named_object* no = p->second;
11582 bool is_value_method = (is_embedded_pointer
11583 || !Type::method_expects_pointer(no));
11584 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11585 (needs_stub_method || depth > 0));
11586 if (!methods->insert(no->name(), m))
11587 delete m;
11591 // Add the embedded methods for TYPE to *METHODS. These are the
11592 // methods attached to anonymous fields. The parameters are as for
11593 // add_methods_to_type.
11595 void
11596 Type::add_embedded_methods_for_type(const Type* type,
11597 const Method::Field_indexes* field_indexes,
11598 unsigned int depth,
11599 bool is_embedded_pointer,
11600 bool needs_stub_method,
11601 std::vector<const Named_type*>* seen,
11602 Methods* methods)
11604 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11605 // struct.
11606 const Struct_type* st = type->struct_type();
11607 if (st == NULL)
11608 return;
11610 const Struct_field_list* fields = st->fields();
11611 if (fields == NULL)
11612 return;
11614 unsigned int i = 0;
11615 for (Struct_field_list::const_iterator pf = fields->begin();
11616 pf != fields->end();
11617 ++pf, ++i)
11619 if (!pf->is_anonymous())
11620 continue;
11622 Type* ftype = pf->type();
11623 bool is_pointer = false;
11624 if (ftype->points_to() != NULL)
11626 ftype = ftype->points_to();
11627 is_pointer = true;
11629 Named_type* fnt = ftype->named_type();
11630 if (fnt == NULL)
11632 // This is an error, but it will be diagnosed elsewhere.
11633 continue;
11636 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11637 sub_field_indexes->next = field_indexes;
11638 sub_field_indexes->field_index = i;
11640 Methods tmp_methods;
11641 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11642 (is_embedded_pointer || is_pointer),
11643 (needs_stub_method
11644 || is_pointer
11645 || i > 0),
11646 seen,
11647 &tmp_methods);
11648 // Check if there are promoted methods that conflict with field names and
11649 // don't add them to the method map.
11650 for (Methods::const_iterator p = tmp_methods.begin();
11651 p != tmp_methods.end();
11652 ++p)
11654 bool found = false;
11655 for (Struct_field_list::const_iterator fp = fields->begin();
11656 fp != fields->end();
11657 ++fp)
11659 if (fp->field_name() == p->first)
11661 found = true;
11662 break;
11665 if (!found &&
11666 !methods->insert(p->first, p->second))
11667 delete p->second;
11672 // If TYPE is an interface type, then add its method to *METHODS.
11673 // This is for interface methods attached to an anonymous field. The
11674 // parameters are as for add_methods_for_type.
11676 void
11677 Type::add_interface_methods_for_type(const Type* type,
11678 const Method::Field_indexes* field_indexes,
11679 unsigned int depth,
11680 Methods* methods)
11682 const Interface_type* it = type->interface_type();
11683 if (it == NULL)
11684 return;
11686 const Typed_identifier_list* imethods = it->methods();
11687 if (imethods == NULL)
11688 return;
11690 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11691 pm != imethods->end();
11692 ++pm)
11694 Function_type* fntype = pm->type()->function_type();
11695 if (fntype == NULL)
11697 // This is an error, but it should be reported elsewhere
11698 // when we look at the methods for IT.
11699 continue;
11701 go_assert(!fntype->is_method());
11702 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11703 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11704 field_indexes, depth);
11705 if (!methods->insert(pm->name(), m))
11706 delete m;
11710 // Build stub methods for TYPE as needed. METHODS is the set of
11711 // methods for the type. A stub method may be needed when a type
11712 // inherits a method from an anonymous field. When we need the
11713 // address of the method, as in a type descriptor, we need to build a
11714 // little stub which does the required field dereferences and jumps to
11715 // the real method. LOCATION is the location of the type definition.
11717 void
11718 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11719 Location location)
11721 if (methods == NULL)
11722 return;
11723 for (Methods::const_iterator p = methods->begin();
11724 p != methods->end();
11725 ++p)
11727 Method* m = p->second;
11728 if (m->is_ambiguous() || !m->needs_stub_method())
11729 continue;
11731 const std::string& name(p->first);
11733 // Build a stub method.
11735 const Function_type* fntype = m->type();
11737 static unsigned int counter;
11738 char buf[100];
11739 snprintf(buf, sizeof buf, "$this%u", counter);
11740 ++counter;
11742 Type* receiver_type = const_cast<Type*>(type);
11743 if (!m->is_value_method())
11744 receiver_type = Type::make_pointer_type(receiver_type);
11745 Location receiver_location = m->receiver_location();
11746 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11747 receiver_location);
11749 const Typed_identifier_list* fnparams = fntype->parameters();
11750 Typed_identifier_list* stub_params;
11751 if (fnparams == NULL || fnparams->empty())
11752 stub_params = NULL;
11753 else
11755 // We give each stub parameter a unique name.
11756 stub_params = new Typed_identifier_list();
11757 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11758 pp != fnparams->end();
11759 ++pp)
11761 char pbuf[100];
11762 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11763 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11764 pp->location()));
11765 ++counter;
11769 const Typed_identifier_list* fnresults = fntype->results();
11770 Typed_identifier_list* stub_results;
11771 if (fnresults == NULL || fnresults->empty())
11772 stub_results = NULL;
11773 else
11775 // We create the result parameters without any names, since
11776 // we won't refer to them.
11777 stub_results = new Typed_identifier_list();
11778 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11779 pr != fnresults->end();
11780 ++pr)
11781 stub_results->push_back(Typed_identifier("", pr->type(),
11782 pr->location()));
11785 Function_type* stub_type = Type::make_function_type(receiver,
11786 stub_params,
11787 stub_results,
11788 fntype->location());
11789 if (fntype->is_varargs())
11790 stub_type->set_is_varargs();
11792 // We only create the function in the package which creates the
11793 // type.
11794 const Package* package;
11795 if (type->named_type() == NULL)
11796 package = NULL;
11797 else
11798 package = type->named_type()->named_object()->package();
11799 std::string stub_name = gogo->stub_method_name(package, name);
11800 Named_object* stub;
11801 if (package != NULL)
11802 stub = Named_object::make_function_declaration(stub_name, package,
11803 stub_type, location);
11804 else
11806 stub = gogo->start_function(stub_name, stub_type, false,
11807 fntype->location());
11808 Type::build_one_stub_method(gogo, m, buf, receiver_type, stub_params,
11809 fntype->is_varargs(), stub_results,
11810 location);
11811 gogo->finish_function(fntype->location());
11813 if (type->named_type() == NULL && stub->is_function())
11814 stub->func_value()->set_is_unnamed_type_stub_method();
11815 if (m->nointerface() && stub->is_function())
11816 stub->func_value()->set_nointerface();
11819 m->set_stub_object(stub);
11823 // Build a stub method which adjusts the receiver as required to call
11824 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11825 // PARAMS is the list of function parameters.
11827 void
11828 Type::build_one_stub_method(Gogo* gogo, Method* method,
11829 const char* receiver_name,
11830 const Type* receiver_type,
11831 const Typed_identifier_list* params,
11832 bool is_varargs,
11833 const Typed_identifier_list* results,
11834 Location location)
11836 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11837 go_assert(receiver_object != NULL);
11839 Expression* expr = Expression::make_var_reference(receiver_object, location);
11840 const Type* expr_type = receiver_type;
11841 expr = Type::apply_field_indexes(expr, method->field_indexes(), location,
11842 &expr_type);
11843 if (expr_type->points_to() == NULL)
11844 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11846 Expression_list* arguments;
11847 if (params == NULL || params->empty())
11848 arguments = NULL;
11849 else
11851 arguments = new Expression_list();
11852 for (Typed_identifier_list::const_iterator p = params->begin();
11853 p != params->end();
11854 ++p)
11856 Named_object* param = gogo->lookup(p->name(), NULL);
11857 go_assert(param != NULL);
11858 Expression* param_ref = Expression::make_var_reference(param,
11859 location);
11860 arguments->push_back(param_ref);
11864 Expression* func = method->bind_method(expr, location);
11865 go_assert(func != NULL);
11866 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11867 location);
11868 Type::add_return_from_results(gogo, call, results, location);
11871 // Build direct interface stub methods for TYPE as needed. METHODS
11872 // is the set of methods for the type. LOCATION is the location of
11873 // the type definition.
11875 // This is for an interface holding a pointer to the type and invoking
11876 // a value method. The interface data is the pointer, and is passed
11877 // to the stub, which dereferences it and passes to the actual method.
11879 void
11880 Type::build_direct_iface_stub_methods(Gogo* gogo, const Type* type,
11881 Methods* methods, Location loc)
11883 if (methods == NULL)
11884 return;
11886 bool is_direct_iface = type->is_direct_iface_type();
11887 bool in_heap = type->in_heap();
11888 for (Methods::const_iterator p = methods->begin();
11889 p != methods->end();
11890 ++p)
11892 Method* m = p->second;
11894 // We need a direct-iface stub for a value method for a
11895 // direct-iface type, and for a pointer method for a not-in-heap
11896 // type.
11897 bool need_stub = false;
11898 if (is_direct_iface && m->is_value_method())
11899 need_stub = true;
11900 if (!in_heap && !m->is_value_method())
11901 need_stub = true;
11902 if (!need_stub || m->is_ambiguous())
11903 continue;
11905 Type* receiver_type = const_cast<Type*>(type);
11906 receiver_type = Type::make_pointer_type(receiver_type);
11907 const std::string& name(p->first);
11908 Function_type* fntype = m->type();
11910 static unsigned int counter;
11911 char buf[100];
11912 snprintf(buf, sizeof buf, "$ptr%u", counter);
11913 ++counter;
11914 Typed_identifier* receiver =
11915 new Typed_identifier(buf, receiver_type, m->receiver_location());
11917 const Typed_identifier_list* params = fntype->parameters();
11918 Typed_identifier_list* stub_params;
11919 if (params == NULL || params->empty())
11920 stub_params = NULL;
11921 else
11923 // We give each stub parameter a unique name.
11924 stub_params = new Typed_identifier_list();
11925 for (Typed_identifier_list::const_iterator pp = params->begin();
11926 pp != params->end();
11927 ++pp)
11929 char pbuf[100];
11930 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11931 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11932 pp->location()));
11933 ++counter;
11937 const Typed_identifier_list* fnresults = fntype->results();
11938 Typed_identifier_list* stub_results;
11939 if (fnresults == NULL || fnresults->empty())
11940 stub_results = NULL;
11941 else
11943 // We create the result parameters without any names, since
11944 // we won't refer to them.
11945 stub_results = new Typed_identifier_list();
11946 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11947 pr != fnresults->end();
11948 ++pr)
11949 stub_results->push_back(Typed_identifier("", pr->type(),
11950 pr->location()));
11953 Function_type* stub_type = Type::make_function_type(receiver,
11954 stub_params,
11955 stub_results,
11956 fntype->location());
11957 if (fntype->is_varargs())
11958 stub_type->set_is_varargs();
11960 // We only create the function in the package which creates the
11961 // type.
11962 const Package* package;
11963 if (type->named_type() == NULL)
11964 package = NULL;
11965 else
11966 package = type->named_type()->named_object()->package();
11968 std::string stub_name = gogo->stub_method_name(package, name) + "2";
11969 Named_object* stub;
11970 if (package != NULL)
11971 stub = Named_object::make_function_declaration(stub_name, package,
11972 stub_type, loc);
11973 else
11975 stub = gogo->start_function(stub_name, stub_type, false,
11976 fntype->location());
11977 Type::build_one_iface_stub_method(gogo, m, buf, stub_params,
11978 fntype->is_varargs(), stub_results,
11979 loc);
11980 gogo->finish_function(fntype->location());
11982 if (type->named_type() == NULL && stub->is_function())
11983 stub->func_value()->set_is_unnamed_type_stub_method();
11984 if (m->nointerface() && stub->is_function())
11985 stub->func_value()->set_nointerface();
11988 m->set_iface_stub_object(stub);
11992 // Build a stub method for METHOD of direct interface type T.
11993 // RECEIVER_NAME is the name we used for the receiver.
11994 // PARAMS is the list of function parameters.
11996 // The stub looks like
11998 // func ($ptr *T, PARAMS) {
11999 // (*$ptr).METHOD(PARAMS)
12000 // }
12002 void
12003 Type::build_one_iface_stub_method(Gogo* gogo, Method* method,
12004 const char* receiver_name,
12005 const Typed_identifier_list* params,
12006 bool is_varargs,
12007 const Typed_identifier_list* results,
12008 Location loc)
12010 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
12011 go_assert(receiver_object != NULL);
12013 Expression* expr = Expression::make_var_reference(receiver_object, loc);
12014 expr = Expression::make_dereference(expr,
12015 Expression::NIL_CHECK_DEFAULT,
12016 loc);
12018 Expression_list* arguments;
12019 if (params == NULL || params->empty())
12020 arguments = NULL;
12021 else
12023 arguments = new Expression_list();
12024 for (Typed_identifier_list::const_iterator p = params->begin();
12025 p != params->end();
12026 ++p)
12028 Named_object* param = gogo->lookup(p->name(), NULL);
12029 go_assert(param != NULL);
12030 Expression* param_ref = Expression::make_var_reference(param,
12031 loc);
12032 arguments->push_back(param_ref);
12036 Expression* func = method->bind_method(expr, loc);
12037 go_assert(func != NULL);
12038 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
12039 loc);
12040 Type::add_return_from_results(gogo, call, results, loc);
12043 // Build and add a return statement from a call expression and a list
12044 // of result parameters. All we need to know is the number of
12045 // results.
12047 void
12048 Type::add_return_from_results(Gogo* gogo, Call_expression* call,
12049 const Typed_identifier_list* results,
12050 Location loc)
12052 Statement* s;
12053 if (results == NULL || results->empty())
12054 s = Statement::make_statement(call, true);
12055 else
12057 Expression_list* vals = new Expression_list();
12058 size_t rc = results->size();
12059 if (rc == 1)
12060 vals->push_back(call);
12061 else
12063 for (size_t i = 0; i < rc; ++i)
12064 vals->push_back(Expression::make_call_result(call, i));
12066 s = Statement::make_return_statement(vals, loc);
12069 gogo->add_statement(s);
12072 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
12073 // in reverse order. *PEXPR_TYPE maintains the type of EXPR; we use
12074 // this to avoid calling EXPR->type() before the lowering pass.
12076 Expression*
12077 Type::apply_field_indexes(Expression* expr,
12078 const Method::Field_indexes* field_indexes,
12079 Location location,
12080 const Type** pexpr_type)
12082 if (field_indexes == NULL)
12083 return expr;
12084 expr = Type::apply_field_indexes(expr, field_indexes->next, location,
12085 pexpr_type);
12086 const Type* expr_type = *pexpr_type;
12087 const Struct_type* stype = expr_type->deref()->struct_type();
12088 go_assert(stype != NULL
12089 && field_indexes->field_index < stype->field_count());
12090 if (expr_type->struct_type() == NULL)
12092 go_assert(expr_type->points_to()->struct_type() == stype);
12093 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
12094 location);
12096 *pexpr_type = stype->field(field_indexes->field_index)->type();
12097 return Expression::make_field_reference(expr, field_indexes->field_index,
12098 location);
12101 // Return whether NO is a method for which the receiver is a pointer.
12103 bool
12104 Type::method_expects_pointer(const Named_object* no)
12106 const Function_type *fntype;
12107 if (no->is_function())
12108 fntype = no->func_value()->type();
12109 else if (no->is_function_declaration())
12110 fntype = no->func_declaration_value()->type();
12111 else
12112 go_unreachable();
12113 return fntype->receiver()->type()->points_to() != NULL;
12116 // Given a set of methods for a type, METHODS, return the method NAME,
12117 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
12118 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
12119 // but is ambiguous (and return NULL).
12121 Method*
12122 Type::method_function(const Methods* methods, const std::string& name,
12123 bool* is_ambiguous)
12125 if (is_ambiguous != NULL)
12126 *is_ambiguous = false;
12127 if (methods == NULL)
12128 return NULL;
12129 Methods::const_iterator p = methods->find(name);
12130 if (p == methods->end())
12131 return NULL;
12132 Method* m = p->second;
12133 if (m->is_ambiguous())
12135 if (is_ambiguous != NULL)
12136 *is_ambiguous = true;
12137 return NULL;
12139 return m;
12142 // Return a pointer to the interface method table for TYPE for the
12143 // interface INTERFACE.
12145 Expression*
12146 Type::interface_method_table(Type* type,
12147 Interface_type *interface,
12148 bool is_pointer,
12149 Interface_method_tables** method_tables,
12150 Interface_method_tables** pointer_tables)
12152 go_assert(!interface->is_empty());
12154 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
12156 if (*pimt == NULL)
12157 *pimt = new Interface_method_tables(5);
12159 std::pair<Interface_type*, Expression*> val(interface, NULL);
12160 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
12162 Location loc = Linemap::predeclared_location();
12163 if (ins.second)
12165 // This is a new entry in the hash table.
12166 go_assert(ins.first->second == NULL);
12167 ins.first->second =
12168 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
12170 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
12173 // Look for field or method NAME for TYPE. Return an Expression for
12174 // the field or method bound to EXPR. If there is no such field or
12175 // method, give an appropriate error and return an error expression.
12177 Expression*
12178 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
12179 const std::string& name,
12180 Location location)
12182 if (type->deref()->is_error_type())
12183 return Expression::make_error(location);
12185 const Named_type* nt = type->deref()->named_type();
12186 const Struct_type* st = type->deref()->struct_type();
12187 const Interface_type* it = type->interface_type();
12189 // If this is a pointer to a pointer, then it is possible that the
12190 // pointed-to type has methods.
12191 bool dereferenced = false;
12192 if (nt == NULL
12193 && st == NULL
12194 && it == NULL
12195 && type->points_to() != NULL
12196 && type->points_to()->points_to() != NULL)
12198 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
12199 location);
12200 type = type->points_to();
12201 if (type->deref()->is_error_type())
12202 return Expression::make_error(location);
12203 nt = type->points_to()->named_type();
12204 st = type->points_to()->struct_type();
12205 dereferenced = true;
12208 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
12209 || expr->is_addressable());
12210 std::vector<const Named_type*> seen;
12211 bool is_method = false;
12212 bool found_pointer_method = false;
12213 std::string ambig1;
12214 std::string ambig2;
12215 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
12216 &seen, NULL, &is_method,
12217 &found_pointer_method, &ambig1, &ambig2))
12219 Expression* ret;
12220 if (!is_method)
12222 go_assert(st != NULL);
12223 if (type->struct_type() == NULL)
12225 if (dereferenced)
12227 go_error_at(location, "pointer type has no field %qs",
12228 Gogo::message_name(name).c_str());
12229 return Expression::make_error(location);
12231 go_assert(type->points_to() != NULL);
12232 expr = Expression::make_dereference(expr,
12233 Expression::NIL_CHECK_DEFAULT,
12234 location);
12235 go_assert(expr->type()->struct_type() == st);
12237 ret = st->field_reference(expr, name, location);
12238 if (ret == NULL)
12240 go_error_at(location, "type has no field %qs",
12241 Gogo::message_name(name).c_str());
12242 return Expression::make_error(location);
12245 else if (it != NULL && it->find_method(name) != NULL)
12246 ret = Expression::make_interface_field_reference(expr, name,
12247 location);
12248 else
12250 Method* m;
12251 if (nt != NULL)
12252 m = nt->method_function(name, NULL);
12253 else if (st != NULL)
12254 m = st->method_function(name, NULL);
12255 else
12256 go_unreachable();
12257 go_assert(m != NULL);
12258 if (dereferenced)
12260 go_error_at(location,
12261 "calling method %qs requires explicit dereference",
12262 Gogo::message_name(name).c_str());
12263 return Expression::make_error(location);
12265 if (!m->is_value_method() && expr->type()->points_to() == NULL)
12266 expr = Expression::make_unary(OPERATOR_AND, expr, location);
12267 ret = m->bind_method(expr, location);
12269 go_assert(ret != NULL);
12270 return ret;
12272 else
12274 if (Gogo::is_erroneous_name(name))
12276 // An error was already reported.
12278 else if (!ambig1.empty())
12279 go_error_at(location, "%qs is ambiguous via %qs and %qs",
12280 Gogo::message_name(name).c_str(), ambig1.c_str(),
12281 ambig2.c_str());
12282 else if (found_pointer_method)
12283 go_error_at(location, "method requires a pointer receiver");
12284 else if (it != NULL && it->is_empty())
12285 go_error_at(location,
12286 "reference to method %qs in interface with no methods",
12287 Gogo::message_name(name).c_str());
12288 else if (it == NULL && type->deref()->interface_type() != NULL)
12289 go_error_at(location,
12290 ("reference to method %qs in type that is "
12291 "pointer to interface, not interface"),
12292 Gogo::message_name(name).c_str());
12293 else if (nt == NULL && st == NULL && it == NULL)
12294 go_error_at(location,
12295 ("reference to field %qs in object which "
12296 "has no fields or methods"),
12297 Gogo::message_name(name).c_str());
12298 else
12300 bool is_unexported;
12301 // The test for 'a' and 'z' is to handle builtin names,
12302 // which are not hidden.
12303 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
12304 is_unexported = false;
12305 else
12307 std::string unpacked = Gogo::unpack_hidden_name(name);
12308 seen.clear();
12309 is_unexported = Type::is_unexported_field_or_method(gogo, type,
12310 unpacked,
12311 &seen);
12313 if (is_unexported)
12314 go_error_at(location, "reference to unexported field or method %qs",
12315 Gogo::message_name(name).c_str());
12316 else
12317 go_error_at(location, "reference to undefined field or method %qs",
12318 Gogo::message_name(name).c_str());
12320 return Expression::make_error(location);
12324 // Look in TYPE for a field or method named NAME, return true if one
12325 // is found. This looks through embedded anonymous fields and handles
12326 // ambiguity. If a method is found, sets *IS_METHOD to true;
12327 // otherwise, if a field is found, set it to false. If
12328 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
12329 // whose address can not be taken. SEEN is used to avoid infinite
12330 // recursion on invalid types.
12332 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
12333 // method we couldn't use because it requires a pointer. LEVEL is
12334 // used for recursive calls, and can be NULL for a non-recursive call.
12335 // When this function returns false because it finds that the name is
12336 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
12337 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
12338 // will be unchanged.
12340 // This function just returns whether or not there is a field or
12341 // method, and whether it is a field or method. It doesn't build an
12342 // expression to refer to it. If it is a method, we then look in the
12343 // list of all methods for the type. If it is a field, the search has
12344 // to be done again, looking only for fields, and building up the
12345 // expression as we go.
12347 bool
12348 Type::find_field_or_method(const Type* type,
12349 const std::string& name,
12350 bool receiver_can_be_pointer,
12351 std::vector<const Named_type*>* seen,
12352 int* level,
12353 bool* is_method,
12354 bool* found_pointer_method,
12355 std::string* ambig1,
12356 std::string* ambig2)
12358 // Named types can have locally defined methods.
12359 const Named_type* nt = type->unalias()->named_type();
12360 if (nt == NULL && type->points_to() != NULL)
12361 nt = type->points_to()->unalias()->named_type();
12362 if (nt != NULL)
12364 Named_object* no = nt->find_local_method(name);
12365 if (no != NULL)
12367 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
12369 *is_method = true;
12370 return true;
12373 // Record that we have found a pointer method in order to
12374 // give a better error message if we don't find anything
12375 // else.
12376 *found_pointer_method = true;
12379 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12380 p != seen->end();
12381 ++p)
12383 if (*p == nt)
12385 // We've already seen this type when searching for methods.
12386 return false;
12391 // Interface types can have methods.
12392 const Interface_type* it = type->interface_type();
12393 if (it != NULL && it->find_method(name) != NULL)
12395 *is_method = true;
12396 return true;
12399 // Struct types can have fields. They can also inherit fields and
12400 // methods from anonymous fields.
12401 const Struct_type* st = type->deref()->struct_type();
12402 if (st == NULL)
12403 return false;
12404 const Struct_field_list* fields = st->fields();
12405 if (fields == NULL)
12406 return false;
12408 if (nt != NULL)
12409 seen->push_back(nt);
12411 int found_level = 0;
12412 bool found_is_method = false;
12413 std::string found_ambig1;
12414 std::string found_ambig2;
12415 const Struct_field* found_parent = NULL;
12416 for (Struct_field_list::const_iterator pf = fields->begin();
12417 pf != fields->end();
12418 ++pf)
12420 if (pf->is_field_name(name))
12422 *is_method = false;
12423 if (nt != NULL)
12424 seen->pop_back();
12425 return true;
12428 if (!pf->is_anonymous())
12429 continue;
12431 if (pf->type()->deref()->is_error_type()
12432 || pf->type()->deref()->is_undefined())
12433 continue;
12435 Named_type* fnt = pf->type()->named_type();
12436 if (fnt == NULL)
12437 fnt = pf->type()->deref()->named_type();
12438 go_assert(fnt != NULL);
12440 // Methods with pointer receivers on embedded field are
12441 // inherited by the pointer to struct, and also by the struct
12442 // type if the field itself is a pointer.
12443 bool can_be_pointer = (receiver_can_be_pointer
12444 || pf->type()->points_to() != NULL);
12445 int sublevel = level == NULL ? 1 : *level + 1;
12446 bool sub_is_method;
12447 std::string subambig1;
12448 std::string subambig2;
12449 bool subfound = Type::find_field_or_method(fnt,
12450 name,
12451 can_be_pointer,
12452 seen,
12453 &sublevel,
12454 &sub_is_method,
12455 found_pointer_method,
12456 &subambig1,
12457 &subambig2);
12458 if (!subfound)
12460 if (!subambig1.empty())
12462 // The name was found via this field, but is ambiguous.
12463 // if the ambiguity is lower or at the same level as
12464 // anything else we have already found, then we want to
12465 // pass the ambiguity back to the caller.
12466 if (found_level == 0 || sublevel <= found_level)
12468 found_ambig1 = (Gogo::message_name(pf->field_name())
12469 + '.' + subambig1);
12470 found_ambig2 = (Gogo::message_name(pf->field_name())
12471 + '.' + subambig2);
12472 found_level = sublevel;
12476 else
12478 // The name was found via this field. Use the level to see
12479 // if we want to use this one, or whether it introduces an
12480 // ambiguity.
12481 if (found_level == 0 || sublevel < found_level)
12483 found_level = sublevel;
12484 found_is_method = sub_is_method;
12485 found_ambig1.clear();
12486 found_ambig2.clear();
12487 found_parent = &*pf;
12489 else if (sublevel > found_level)
12491 else if (found_ambig1.empty())
12493 // We found an ambiguity.
12494 go_assert(found_parent != NULL);
12495 found_ambig1 = Gogo::message_name(found_parent->field_name());
12496 found_ambig2 = Gogo::message_name(pf->field_name());
12498 else
12500 // We found an ambiguity, but we already know of one.
12501 // Just report the earlier one.
12506 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
12507 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
12508 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
12509 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
12511 if (nt != NULL)
12512 seen->pop_back();
12514 if (found_level == 0)
12515 return false;
12516 else if (found_is_method
12517 && type->named_type() != NULL
12518 && type->points_to() != NULL)
12520 // If this is a method inherited from a struct field in a named pointer
12521 // type, it is invalid to automatically dereference the pointer to the
12522 // struct to find this method.
12523 if (level != NULL)
12524 *level = found_level;
12525 *is_method = true;
12526 return false;
12528 else if (!found_ambig1.empty())
12530 go_assert(!found_ambig1.empty());
12531 ambig1->assign(found_ambig1);
12532 ambig2->assign(found_ambig2);
12533 if (level != NULL)
12534 *level = found_level;
12535 return false;
12537 else
12539 if (level != NULL)
12540 *level = found_level;
12541 *is_method = found_is_method;
12542 return true;
12546 // Return whether NAME is an unexported field or method for TYPE.
12548 bool
12549 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
12550 const std::string& name,
12551 std::vector<const Named_type*>* seen)
12553 const Named_type* nt = type->named_type();
12554 if (nt == NULL)
12555 nt = type->deref()->named_type();
12556 if (nt != NULL)
12558 if (nt->is_unexported_local_method(gogo, name))
12559 return true;
12561 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12562 p != seen->end();
12563 ++p)
12565 if (*p == nt)
12567 // We've already seen this type.
12568 return false;
12573 const Interface_type* it = type->interface_type();
12574 if (it != NULL && it->is_unexported_method(gogo, name))
12575 return true;
12577 type = type->deref();
12579 const Struct_type* st = type->struct_type();
12580 if (st != NULL && st->is_unexported_local_field(gogo, name))
12581 return true;
12583 if (st == NULL)
12584 return false;
12586 const Struct_field_list* fields = st->fields();
12587 if (fields == NULL)
12588 return false;
12590 if (nt != NULL)
12591 seen->push_back(nt);
12593 for (Struct_field_list::const_iterator pf = fields->begin();
12594 pf != fields->end();
12595 ++pf)
12597 if (pf->is_anonymous()
12598 && !pf->type()->deref()->is_error_type()
12599 && !pf->type()->deref()->is_undefined())
12601 Named_type* subtype = pf->type()->named_type();
12602 if (subtype == NULL)
12603 subtype = pf->type()->deref()->named_type();
12604 if (subtype == NULL)
12606 // This is an error, but it will be diagnosed elsewhere.
12607 continue;
12609 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
12611 if (nt != NULL)
12612 seen->pop_back();
12613 return true;
12618 if (nt != NULL)
12619 seen->pop_back();
12621 return false;
12624 // Class Forward_declaration.
12626 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
12627 : Type(TYPE_FORWARD),
12628 named_object_(named_object->resolve()), warned_(false)
12630 go_assert(this->named_object_->is_unknown()
12631 || this->named_object_->is_type_declaration());
12634 // Return the named object.
12636 Named_object*
12637 Forward_declaration_type::named_object()
12639 return this->named_object_->resolve();
12642 const Named_object*
12643 Forward_declaration_type::named_object() const
12645 return this->named_object_->resolve();
12648 // Return the name of the forward declared type.
12650 const std::string&
12651 Forward_declaration_type::name() const
12653 return this->named_object()->name();
12656 // Warn about a use of a type which has been declared but not defined.
12658 void
12659 Forward_declaration_type::warn() const
12661 Named_object* no = this->named_object_->resolve();
12662 if (no->is_unknown())
12664 // The name was not defined anywhere.
12665 if (!this->warned_)
12667 go_error_at(this->named_object_->location(),
12668 "use of undefined type %qs",
12669 no->message_name().c_str());
12670 this->warned_ = true;
12673 else if (no->is_type_declaration())
12675 // The name was seen as a type, but the type was never defined.
12676 if (no->type_declaration_value()->using_type())
12678 go_error_at(this->named_object_->location(),
12679 "use of undefined type %qs",
12680 no->message_name().c_str());
12681 this->warned_ = true;
12684 else
12686 // The name was defined, but not as a type.
12687 if (!this->warned_)
12689 go_error_at(this->named_object_->location(), "expected type");
12690 this->warned_ = true;
12695 // Get the base type of a declaration. This gives an error if the
12696 // type has not yet been defined.
12698 Type*
12699 Forward_declaration_type::real_type()
12701 if (this->is_defined())
12703 Named_type* nt = this->named_object()->type_value();
12704 if (!nt->is_valid())
12705 return Type::make_error_type();
12706 return this->named_object()->type_value();
12708 else
12710 this->warn();
12711 return Type::make_error_type();
12715 const Type*
12716 Forward_declaration_type::real_type() const
12718 if (this->is_defined())
12720 const Named_type* nt = this->named_object()->type_value();
12721 if (!nt->is_valid())
12722 return Type::make_error_type();
12723 return this->named_object()->type_value();
12725 else
12727 this->warn();
12728 return Type::make_error_type();
12732 // Return whether the base type is defined.
12734 bool
12735 Forward_declaration_type::is_defined() const
12737 return this->named_object()->is_type();
12740 // Add a method. This is used when methods are defined before the
12741 // type.
12743 Named_object*
12744 Forward_declaration_type::add_method(const std::string& name,
12745 Function* function)
12747 Named_object* no = this->named_object();
12748 if (no->is_unknown())
12749 no->declare_as_type();
12750 return no->type_declaration_value()->add_method(name, function);
12753 // Add a method declaration. This is used when methods are declared
12754 // before the type.
12756 Named_object*
12757 Forward_declaration_type::add_method_declaration(const std::string& name,
12758 Package* package,
12759 Function_type* type,
12760 Location location)
12762 Named_object* no = this->named_object();
12763 if (no->is_unknown())
12764 no->declare_as_type();
12765 Type_declaration* td = no->type_declaration_value();
12766 return td->add_method_declaration(name, package, type, location);
12769 // Add an already created object as a method.
12771 void
12772 Forward_declaration_type::add_existing_method(Named_object* nom)
12774 Named_object* no = this->named_object();
12775 if (no->is_unknown())
12776 no->declare_as_type();
12777 no->type_declaration_value()->add_existing_method(nom);
12780 // Traversal.
12783 Forward_declaration_type::do_traverse(Traverse* traverse)
12785 if (this->is_defined()
12786 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12787 return TRAVERSE_EXIT;
12788 return TRAVERSE_CONTINUE;
12791 // Verify the type.
12793 bool
12794 Forward_declaration_type::do_verify()
12796 if (!this->is_defined() && !this->is_nil_constant_as_type())
12798 this->warn();
12799 return false;
12801 return true;
12804 // Get the backend representation for the type.
12806 Btype*
12807 Forward_declaration_type::do_get_backend(Gogo* gogo)
12809 if (this->is_defined())
12810 return Type::get_named_base_btype(gogo, this->real_type());
12812 if (this->warned_)
12813 return gogo->backend()->error_type();
12815 // We represent an undefined type as a struct with no fields. That
12816 // should work fine for the backend, since the same case can arise
12817 // in C.
12818 std::vector<Backend::Btyped_identifier> fields;
12819 Btype* bt = gogo->backend()->struct_type(fields);
12820 return gogo->backend()->named_type(this->name(), bt,
12821 this->named_object()->location());
12824 // Build a type descriptor for a forwarded type.
12826 Expression*
12827 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12829 Location ploc = Linemap::predeclared_location();
12830 if (!this->is_defined())
12831 return Expression::make_error(ploc);
12832 else
12834 Type* t = this->real_type();
12835 if (name != NULL)
12836 return this->named_type_descriptor(gogo, t, name);
12837 else
12838 return Expression::make_error(this->named_object_->location());
12842 // The reflection string.
12844 void
12845 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12847 this->append_reflection(this->real_type(), gogo, ret);
12850 // Export a forward declaration. This can happen when a defined type
12851 // refers to a type which is only declared (and is presumably defined
12852 // in some other file in the same package).
12854 void
12855 Forward_declaration_type::do_export(Export*) const
12857 // If there is a base type, that should be exported instead of this.
12858 go_assert(!this->is_defined());
12860 // We don't output anything.
12863 // Make a forward declaration.
12865 Type*
12866 Type::make_forward_declaration(Named_object* named_object)
12868 return new Forward_declaration_type(named_object);
12871 // Class Typed_identifier_list.
12873 // Sort the entries by name.
12875 struct Typed_identifier_list_sort
12877 public:
12878 bool
12879 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12881 return (Gogo::unpack_hidden_name(t1.name())
12882 < Gogo::unpack_hidden_name(t2.name()));
12886 void
12887 Typed_identifier_list::sort_by_name()
12889 std::sort(this->entries_.begin(), this->entries_.end(),
12890 Typed_identifier_list_sort());
12893 // Traverse types.
12896 Typed_identifier_list::traverse(Traverse* traverse) const
12898 for (Typed_identifier_list::const_iterator p = this->begin();
12899 p != this->end();
12900 ++p)
12902 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12903 return TRAVERSE_EXIT;
12905 return TRAVERSE_CONTINUE;
12908 // Copy the list.
12910 Typed_identifier_list*
12911 Typed_identifier_list::copy() const
12913 Typed_identifier_list* ret = new Typed_identifier_list();
12914 for (Typed_identifier_list::const_iterator p = this->begin();
12915 p != this->end();
12916 ++p)
12917 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12918 return ret;