compiler: clean up unresolved placeholders for pointer types
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob91d6091f54496031eba8a383ad722c2c3a0a9d82
1 // types.cc -- Go frontend types.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <ostream>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "operator.h"
16 #include "expressions.h"
17 #include "statements.h"
18 #include "export.h"
19 #include "import.h"
20 #include "backend.h"
21 #include "types.h"
23 // Forward declarations so that we don't have to make types.h #include
24 // backend.h.
26 static void
27 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
28 bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 std::vector<Backend::Btyped_identifier>* bfields);
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 bool use_placeholder,
38 std::vector<Backend::Btyped_identifier>* bfields);
40 // Class Type.
42 Type::Type(Type_classification classification)
43 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44 gc_symbol_var_(NULL)
48 Type::~Type()
52 // Get the base type for a type--skip names and forward declarations.
54 Type*
55 Type::base()
57 switch (this->classification_)
59 case TYPE_NAMED:
60 return this->named_type()->named_base();
61 case TYPE_FORWARD:
62 return this->forward_declaration_type()->real_type()->base();
63 default:
64 return this;
68 const Type*
69 Type::base() const
71 switch (this->classification_)
73 case TYPE_NAMED:
74 return this->named_type()->named_base();
75 case TYPE_FORWARD:
76 return this->forward_declaration_type()->real_type()->base();
77 default:
78 return this;
82 // Skip defined forward declarations.
84 Type*
85 Type::forwarded()
87 Type* t = this;
88 Forward_declaration_type* ftype = t->forward_declaration_type();
89 while (ftype != NULL && ftype->is_defined())
91 t = ftype->real_type();
92 ftype = t->forward_declaration_type();
94 return t;
97 const Type*
98 Type::forwarded() const
100 const Type* t = this;
101 const Forward_declaration_type* ftype = t->forward_declaration_type();
102 while (ftype != NULL && ftype->is_defined())
104 t = ftype->real_type();
105 ftype = t->forward_declaration_type();
107 return t;
110 // If this is a named type, return it. Otherwise, return NULL.
112 Named_type*
113 Type::named_type()
115 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
118 const Named_type*
119 Type::named_type() const
121 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
124 // Return true if this type is not defined.
126 bool
127 Type::is_undefined() const
129 return this->forwarded()->forward_declaration_type() != NULL;
132 // Return true if this is a basic type: a type which is not composed
133 // of other types, and is not void.
135 bool
136 Type::is_basic_type() const
138 switch (this->classification_)
140 case TYPE_INTEGER:
141 case TYPE_FLOAT:
142 case TYPE_COMPLEX:
143 case TYPE_BOOLEAN:
144 case TYPE_STRING:
145 case TYPE_NIL:
146 return true;
148 case TYPE_ERROR:
149 case TYPE_VOID:
150 case TYPE_FUNCTION:
151 case TYPE_POINTER:
152 case TYPE_STRUCT:
153 case TYPE_ARRAY:
154 case TYPE_MAP:
155 case TYPE_CHANNEL:
156 case TYPE_INTERFACE:
157 return false;
159 case TYPE_NAMED:
160 case TYPE_FORWARD:
161 return this->base()->is_basic_type();
163 default:
164 go_unreachable();
168 // Return true if this is an abstract type.
170 bool
171 Type::is_abstract() const
173 switch (this->classification())
175 case TYPE_INTEGER:
176 return this->integer_type()->is_abstract();
177 case TYPE_FLOAT:
178 return this->float_type()->is_abstract();
179 case TYPE_COMPLEX:
180 return this->complex_type()->is_abstract();
181 case TYPE_STRING:
182 return this->is_abstract_string_type();
183 case TYPE_BOOLEAN:
184 return this->is_abstract_boolean_type();
185 default:
186 return false;
190 // Return a non-abstract version of an abstract type.
192 Type*
193 Type::make_non_abstract_type()
195 go_assert(this->is_abstract());
196 switch (this->classification())
198 case TYPE_INTEGER:
199 if (this->integer_type()->is_rune())
200 return Type::lookup_integer_type("int32");
201 else
202 return Type::lookup_integer_type("int");
203 case TYPE_FLOAT:
204 return Type::lookup_float_type("float64");
205 case TYPE_COMPLEX:
206 return Type::lookup_complex_type("complex128");
207 case TYPE_STRING:
208 return Type::lookup_string_type();
209 case TYPE_BOOLEAN:
210 return Type::lookup_bool_type();
211 default:
212 go_unreachable();
216 // Return true if this is an error type. Don't give an error if we
217 // try to dereference an undefined forwarding type, as this is called
218 // in the parser when the type may legitimately be undefined.
220 bool
221 Type::is_error_type() const
223 const Type* t = this->forwarded();
224 // Note that we return false for an undefined forward type.
225 switch (t->classification_)
227 case TYPE_ERROR:
228 return true;
229 case TYPE_NAMED:
230 return t->named_type()->is_named_error_type();
231 default:
232 return false;
236 // If this is a pointer type, return the type to which it points.
237 // Otherwise, return NULL.
239 Type*
240 Type::points_to() const
242 const Pointer_type* ptype = this->convert<const Pointer_type,
243 TYPE_POINTER>();
244 return ptype == NULL ? NULL : ptype->points_to();
247 // Return whether this is a slice type.
249 bool
250 Type::is_slice_type() const
252 return this->array_type() != NULL && this->array_type()->length() == NULL;
255 // Return whether this is the predeclared constant nil being used as a
256 // type.
258 bool
259 Type::is_nil_constant_as_type() const
261 const Type* t = this->forwarded();
262 if (t->forward_declaration_type() != NULL)
264 const Named_object* no = t->forward_declaration_type()->named_object();
265 if (no->is_unknown())
266 no = no->unknown_value()->real_named_object();
267 if (no != NULL
268 && no->is_const()
269 && no->const_value()->expr()->is_nil_expression())
270 return true;
272 return false;
275 // Traverse a type.
278 Type::traverse(Type* type, Traverse* traverse)
280 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
281 || (traverse->traverse_mask()
282 & Traverse::traverse_expressions) != 0);
283 if (traverse->remember_type(type))
285 // We have already traversed this type.
286 return TRAVERSE_CONTINUE;
288 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
290 int t = traverse->type(type);
291 if (t == TRAVERSE_EXIT)
292 return TRAVERSE_EXIT;
293 else if (t == TRAVERSE_SKIP_COMPONENTS)
294 return TRAVERSE_CONTINUE;
296 // An array type has an expression which we need to traverse if
297 // traverse_expressions is set.
298 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
299 return TRAVERSE_EXIT;
300 return TRAVERSE_CONTINUE;
303 // Default implementation for do_traverse for child class.
306 Type::do_traverse(Traverse*)
308 return TRAVERSE_CONTINUE;
311 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
312 // then return true for all erroneous types; this is used to avoid
313 // cascading errors. If REASON is not NULL, optionally set *REASON to
314 // the reason the types are not identical.
316 bool
317 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
318 std::string* reason)
320 return Type::are_identical_cmp_tags(t1, t2, COMPARE_TAGS,
321 errors_are_identical, reason);
324 // Like are_identical, but with a CMP_TAGS parameter.
326 bool
327 Type::are_identical_cmp_tags(const Type* t1, const Type* t2, Cmp_tags cmp_tags,
328 bool errors_are_identical, std::string* reason)
330 if (t1 == NULL || t2 == NULL)
332 // Something is wrong.
333 return errors_are_identical ? true : t1 == t2;
336 // Skip defined forward declarations.
337 t1 = t1->forwarded();
338 t2 = t2->forwarded();
340 // Ignore aliases for purposes of type identity.
341 while (t1->named_type() != NULL && t1->named_type()->is_alias())
342 t1 = t1->named_type()->real_type()->forwarded();
343 while (t2->named_type() != NULL && t2->named_type()->is_alias())
344 t2 = t2->named_type()->real_type()->forwarded();
346 if (t1 == t2)
347 return true;
349 // An undefined forward declaration is an error.
350 if (t1->forward_declaration_type() != NULL
351 || t2->forward_declaration_type() != NULL)
352 return errors_are_identical;
354 // Avoid cascading errors with error types.
355 if (t1->is_error_type() || t2->is_error_type())
357 if (errors_are_identical)
358 return true;
359 return t1->is_error_type() && t2->is_error_type();
362 // Get a good reason for the sink type. Note that the sink type on
363 // the left hand side of an assignment is handled in are_assignable.
364 if (t1->is_sink_type() || t2->is_sink_type())
366 if (reason != NULL)
367 *reason = "invalid use of _";
368 return false;
371 // A named type is only identical to itself.
372 if (t1->named_type() != NULL || t2->named_type() != NULL)
373 return false;
375 // Check type shapes.
376 if (t1->classification() != t2->classification())
377 return false;
379 switch (t1->classification())
381 case TYPE_VOID:
382 case TYPE_BOOLEAN:
383 case TYPE_STRING:
384 case TYPE_NIL:
385 // These types are always identical.
386 return true;
388 case TYPE_INTEGER:
389 return t1->integer_type()->is_identical(t2->integer_type());
391 case TYPE_FLOAT:
392 return t1->float_type()->is_identical(t2->float_type());
394 case TYPE_COMPLEX:
395 return t1->complex_type()->is_identical(t2->complex_type());
397 case TYPE_FUNCTION:
398 return t1->function_type()->is_identical(t2->function_type(),
399 false,
400 cmp_tags,
401 errors_are_identical,
402 reason);
404 case TYPE_POINTER:
405 return Type::are_identical_cmp_tags(t1->points_to(), t2->points_to(),
406 cmp_tags, errors_are_identical,
407 reason);
409 case TYPE_STRUCT:
410 return t1->struct_type()->is_identical(t2->struct_type(), cmp_tags,
411 errors_are_identical);
413 case TYPE_ARRAY:
414 return t1->array_type()->is_identical(t2->array_type(), cmp_tags,
415 errors_are_identical);
417 case TYPE_MAP:
418 return t1->map_type()->is_identical(t2->map_type(), cmp_tags,
419 errors_are_identical);
421 case TYPE_CHANNEL:
422 return t1->channel_type()->is_identical(t2->channel_type(), cmp_tags,
423 errors_are_identical);
425 case TYPE_INTERFACE:
426 return t1->interface_type()->is_identical(t2->interface_type(), cmp_tags,
427 errors_are_identical);
429 case TYPE_CALL_MULTIPLE_RESULT:
430 if (reason != NULL)
431 *reason = "invalid use of multiple-value function call";
432 return false;
434 default:
435 go_unreachable();
439 // Return true if it's OK to have a binary operation with types LHS
440 // and RHS. This is not used for shifts or comparisons.
442 bool
443 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
445 if (Type::are_identical(lhs, rhs, true, NULL))
446 return true;
448 // A constant of abstract bool type may be mixed with any bool type.
449 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
450 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
451 return true;
453 // A constant of abstract string type may be mixed with any string
454 // type.
455 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
456 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
457 return true;
459 lhs = lhs->base();
460 rhs = rhs->base();
462 // A constant of abstract integer, float, or complex type may be
463 // mixed with an integer, float, or complex type.
464 if ((rhs->is_abstract()
465 && (rhs->integer_type() != NULL
466 || rhs->float_type() != NULL
467 || rhs->complex_type() != NULL)
468 && (lhs->integer_type() != NULL
469 || lhs->float_type() != NULL
470 || lhs->complex_type() != NULL))
471 || (lhs->is_abstract()
472 && (lhs->integer_type() != NULL
473 || lhs->float_type() != NULL
474 || lhs->complex_type() != NULL)
475 && (rhs->integer_type() != NULL
476 || rhs->float_type() != NULL
477 || rhs->complex_type() != NULL)))
478 return true;
480 // The nil type may be compared to a pointer, an interface type, a
481 // slice type, a channel type, a map type, or a function type.
482 if (lhs->is_nil_type()
483 && (rhs->points_to() != NULL
484 || rhs->interface_type() != NULL
485 || rhs->is_slice_type()
486 || rhs->map_type() != NULL
487 || rhs->channel_type() != NULL
488 || rhs->function_type() != NULL))
489 return true;
490 if (rhs->is_nil_type()
491 && (lhs->points_to() != NULL
492 || lhs->interface_type() != NULL
493 || lhs->is_slice_type()
494 || lhs->map_type() != NULL
495 || lhs->channel_type() != NULL
496 || lhs->function_type() != NULL))
497 return true;
499 return false;
502 // Return true if a value with type T1 may be compared with a value of
503 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
505 bool
506 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
507 const Type *t2, std::string *reason)
509 if (t1 != t2
510 && !Type::are_assignable(t1, t2, NULL)
511 && !Type::are_assignable(t2, t1, NULL))
513 if (reason != NULL)
514 *reason = "incompatible types in binary expression";
515 return false;
518 if (!is_equality_op)
520 if (t1->integer_type() == NULL
521 && t1->float_type() == NULL
522 && !t1->is_string_type())
524 if (reason != NULL)
525 *reason = _("invalid comparison of non-ordered type");
526 return false;
529 else if (t1->is_slice_type()
530 || t1->map_type() != NULL
531 || t1->function_type() != NULL
532 || t2->is_slice_type()
533 || t2->map_type() != NULL
534 || t2->function_type() != NULL)
536 if (!t1->is_nil_type() && !t2->is_nil_type())
538 if (reason != NULL)
540 if (t1->is_slice_type() || t2->is_slice_type())
541 *reason = _("slice can only be compared to nil");
542 else if (t1->map_type() != NULL || t2->map_type() != NULL)
543 *reason = _("map can only be compared to nil");
544 else
545 *reason = _("func can only be compared to nil");
547 // Match 6g error messages.
548 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
550 char buf[200];
551 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
552 reason->c_str());
553 *reason = buf;
556 return false;
559 else
561 if (!t1->is_boolean_type()
562 && t1->integer_type() == NULL
563 && t1->float_type() == NULL
564 && t1->complex_type() == NULL
565 && !t1->is_string_type()
566 && t1->points_to() == NULL
567 && t1->channel_type() == NULL
568 && t1->interface_type() == NULL
569 && t1->struct_type() == NULL
570 && t1->array_type() == NULL
571 && !t1->is_nil_type())
573 if (reason != NULL)
574 *reason = _("invalid comparison of non-comparable type");
575 return false;
578 if (t1->named_type() != NULL)
579 return t1->named_type()->named_type_is_comparable(reason);
580 else if (t2->named_type() != NULL)
581 return t2->named_type()->named_type_is_comparable(reason);
582 else if (t1->struct_type() != NULL)
584 if (t1->struct_type()->is_struct_incomparable())
586 if (reason != NULL)
587 *reason = _("invalid comparison of generated struct");
588 return false;
590 const Struct_field_list* fields = t1->struct_type()->fields();
591 for (Struct_field_list::const_iterator p = fields->begin();
592 p != fields->end();
593 ++p)
595 if (!p->type()->is_comparable())
597 if (reason != NULL)
598 *reason = _("invalid comparison of non-comparable struct");
599 return false;
603 else if (t1->array_type() != NULL)
605 if (t1->array_type()->is_array_incomparable())
607 if (reason != NULL)
608 *reason = _("invalid comparison of generated array");
609 return false;
611 if (t1->array_type()->length()->is_nil_expression()
612 || !t1->array_type()->element_type()->is_comparable())
614 if (reason != NULL)
615 *reason = _("invalid comparison of non-comparable array");
616 return false;
621 return true;
624 // Return true if a value with type RHS may be assigned to a variable
625 // with type LHS. If REASON is not NULL, set *REASON to the reason
626 // the types are not assignable.
628 bool
629 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
631 // Do some checks first. Make sure the types are defined.
632 if (rhs != NULL && !rhs->is_undefined())
634 if (rhs->is_void_type())
636 if (reason != NULL)
637 *reason = "non-value used as value";
638 return false;
640 if (rhs->is_call_multiple_result_type())
642 if (reason != NULL)
643 reason->assign(_("multiple-value function call in "
644 "single-value context"));
645 return false;
649 // Any value may be assigned to the blank identifier.
650 if (lhs != NULL
651 && !lhs->is_undefined()
652 && lhs->is_sink_type())
653 return true;
655 // Identical types are assignable.
656 if (Type::are_identical(lhs, rhs, true, reason))
657 return true;
659 // The types are assignable if they have identical underlying types
660 // and either LHS or RHS is not a named type.
661 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
662 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
663 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
664 return true;
666 // The types are assignable if LHS is an interface type and RHS
667 // implements the required methods.
668 const Interface_type* lhs_interface_type = lhs->interface_type();
669 if (lhs_interface_type != NULL)
671 if (lhs_interface_type->implements_interface(rhs, reason))
672 return true;
673 const Interface_type* rhs_interface_type = rhs->interface_type();
674 if (rhs_interface_type != NULL
675 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
676 reason))
677 return true;
680 // The type are assignable if RHS is a bidirectional channel type,
681 // LHS is a channel type, they have identical element types, and
682 // either LHS or RHS is not a named type.
683 if (lhs->channel_type() != NULL
684 && rhs->channel_type() != NULL
685 && rhs->channel_type()->may_send()
686 && rhs->channel_type()->may_receive()
687 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
688 && Type::are_identical(lhs->channel_type()->element_type(),
689 rhs->channel_type()->element_type(),
690 true,
691 reason))
692 return true;
694 // The nil type may be assigned to a pointer, function, slice, map,
695 // channel, or interface type.
696 if (rhs->is_nil_type()
697 && (lhs->points_to() != NULL
698 || lhs->function_type() != NULL
699 || lhs->is_slice_type()
700 || lhs->map_type() != NULL
701 || lhs->channel_type() != NULL
702 || lhs->interface_type() != NULL))
703 return true;
705 // An untyped numeric constant may be assigned to a numeric type if
706 // it is representable in that type.
707 if ((rhs->is_abstract()
708 && (rhs->integer_type() != NULL
709 || rhs->float_type() != NULL
710 || rhs->complex_type() != NULL))
711 && (lhs->integer_type() != NULL
712 || lhs->float_type() != NULL
713 || lhs->complex_type() != NULL))
714 return true;
716 // Give some better error messages.
717 if (reason != NULL && reason->empty())
719 if (rhs->interface_type() != NULL)
720 reason->assign(_("need explicit conversion"));
721 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
723 size_t len = (lhs->named_type()->name().length()
724 + rhs->named_type()->name().length()
725 + 100);
726 char* buf = new char[len];
727 snprintf(buf, len, _("cannot use type %s as type %s"),
728 rhs->named_type()->message_name().c_str(),
729 lhs->named_type()->message_name().c_str());
730 reason->assign(buf);
731 delete[] buf;
735 return false;
738 // Return true if a value with type RHS may be converted to type LHS.
739 // If REASON is not NULL, set *REASON to the reason the types are not
740 // convertible.
742 bool
743 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
745 // The types are convertible if they are assignable.
746 if (Type::are_assignable(lhs, rhs, reason))
747 return true;
749 // A pointer to a regular type may not be converted to a pointer to
750 // a type that may not live in the heap, except when converting to
751 // unsafe.Pointer.
752 if (lhs->points_to() != NULL
753 && rhs->points_to() != NULL
754 && !rhs->points_to()->in_heap()
755 && lhs->points_to()->in_heap()
756 && !lhs->is_unsafe_pointer_type())
758 if (reason != NULL)
759 reason->assign(_("conversion from notinheap type to normal type"));
760 return false;
763 // The types are convertible if they have identical underlying
764 // types, ignoring struct field tags.
765 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
766 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
767 true, reason))
768 return true;
770 // The types are convertible if they are both unnamed pointer types
771 // and their pointer base types have identical underlying types,
772 // ignoring struct field tags.
773 if (lhs->named_type() == NULL
774 && rhs->named_type() == NULL
775 && lhs->points_to() != NULL
776 && rhs->points_to() != NULL
777 && (lhs->points_to()->named_type() != NULL
778 || rhs->points_to()->named_type() != NULL)
779 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
780 rhs->points_to()->base(),
781 IGNORE_TAGS,
782 true,
783 reason))
784 return true;
786 // Integer and floating point types are convertible to each other.
787 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
788 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
789 return true;
791 // Complex types are convertible to each other.
792 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
793 return true;
795 // An integer, or []byte, or []rune, may be converted to a string.
796 if (lhs->is_string_type())
798 if (rhs->integer_type() != NULL)
799 return true;
800 if (rhs->is_slice_type())
802 const Type* e = rhs->array_type()->element_type()->forwarded();
803 if (e->integer_type() != NULL
804 && (e->integer_type()->is_byte()
805 || e->integer_type()->is_rune()))
806 return true;
810 // A string may be converted to []byte or []rune.
811 if (rhs->is_string_type() && lhs->is_slice_type())
813 const Type* e = lhs->array_type()->element_type()->forwarded();
814 if (e->integer_type() != NULL
815 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
816 return true;
819 // An unsafe.Pointer type may be converted to any pointer type or to
820 // a type whose underlying type is uintptr, and vice-versa.
821 if (lhs->is_unsafe_pointer_type()
822 && (rhs->points_to() != NULL
823 || (rhs->integer_type() != NULL
824 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
825 return true;
826 if (rhs->is_unsafe_pointer_type()
827 && (lhs->points_to() != NULL
828 || (lhs->integer_type() != NULL
829 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
830 return true;
832 // Give a better error message.
833 if (reason != NULL)
835 if (reason->empty())
836 *reason = "invalid type conversion";
837 else
839 std::string s = "invalid type conversion (";
840 s += *reason;
841 s += ')';
842 *reason = s;
846 return false;
849 // Return a hash code for the type to be used for method lookup.
851 unsigned int
852 Type::hash_for_method(Gogo* gogo) const
854 if (this->named_type() != NULL && this->named_type()->is_alias())
855 return this->named_type()->real_type()->hash_for_method(gogo);
856 unsigned int ret = 0;
857 if (this->classification_ != TYPE_FORWARD)
858 ret += this->classification_;
859 return ret + this->do_hash_for_method(gogo);
862 // Default implementation of do_hash_for_method. This is appropriate
863 // for types with no subfields.
865 unsigned int
866 Type::do_hash_for_method(Gogo*) const
868 return 0;
871 // Return a hash code for a string, given a starting hash.
873 unsigned int
874 Type::hash_string(const std::string& s, unsigned int h)
876 const char* p = s.data();
877 size_t len = s.length();
878 for (; len > 0; --len)
880 h ^= *p++;
881 h*= 16777619;
883 return h;
886 // A hash table mapping unnamed types to the backend representation of
887 // those types.
889 Type::Type_btypes Type::type_btypes;
891 // Return the backend representation for this type.
893 Btype*
894 Type::get_backend(Gogo* gogo)
896 if (this->btype_ != NULL)
897 return this->btype_;
899 if (this->forward_declaration_type() != NULL
900 || this->named_type() != NULL)
901 return this->get_btype_without_hash(gogo);
903 if (this->is_error_type())
904 return gogo->backend()->error_type();
906 // To avoid confusing the backend, translate all identical Go types
907 // to the same backend representation. We use a hash table to do
908 // that. There is no need to use the hash table for named types, as
909 // named types are only identical to themselves.
911 std::pair<Type*, Type_btype_entry> val;
912 val.first = this;
913 val.second.btype = NULL;
914 val.second.is_placeholder = false;
915 std::pair<Type_btypes::iterator, bool> ins =
916 Type::type_btypes.insert(val);
917 if (!ins.second && ins.first->second.btype != NULL)
919 // Note that GOGO can be NULL here, but only when the GCC
920 // middle-end is asking for a frontend type. That will only
921 // happen for simple types, which should never require
922 // placeholders.
923 if (!ins.first->second.is_placeholder)
924 this->btype_ = ins.first->second.btype;
925 else if (gogo->named_types_are_converted())
927 this->finish_backend(gogo, ins.first->second.btype);
928 ins.first->second.is_placeholder = false;
931 return ins.first->second.btype;
934 Btype* bt = this->get_btype_without_hash(gogo);
936 if (ins.first->second.btype == NULL)
938 ins.first->second.btype = bt;
939 ins.first->second.is_placeholder = false;
941 else
943 // We have already created a backend representation for this
944 // type. This can happen when an unnamed type is defined using
945 // a named type which in turns uses an identical unnamed type.
946 // Use the representation we created earlier and ignore the one we just
947 // built.
948 if (this->btype_ == bt)
949 this->btype_ = ins.first->second.btype;
950 bt = ins.first->second.btype;
953 return bt;
956 // Return the backend representation for a type without looking in the
957 // hash table for identical types. This is used for named types,
958 // since a named type is never identical to any other type.
960 Btype*
961 Type::get_btype_without_hash(Gogo* gogo)
963 if (this->btype_ == NULL)
965 Btype* bt = this->do_get_backend(gogo);
967 // For a recursive function or pointer type, we will temporarily
968 // return a circular pointer type during the recursion. We
969 // don't want to record that for a forwarding type, as it may
970 // confuse us later.
971 if (this->forward_declaration_type() != NULL
972 && gogo->backend()->is_circular_pointer_type(bt))
973 return bt;
975 if (gogo == NULL || !gogo->named_types_are_converted())
976 return bt;
978 this->btype_ = bt;
980 return this->btype_;
983 // Get the backend representation of a type without forcing the
984 // creation of the backend representation of all supporting types.
985 // This will return a backend type that has the correct size but may
986 // be incomplete. E.g., a pointer will just be a placeholder pointer,
987 // and will not contain the final representation of the type to which
988 // it points. This is used while converting all named types to the
989 // backend representation, to avoid problems with indirect references
990 // to types which are not yet complete. When this is called, the
991 // sizes of all direct references (e.g., a struct field) should be
992 // known, but the sizes of indirect references (e.g., the type to
993 // which a pointer points) may not.
995 Btype*
996 Type::get_backend_placeholder(Gogo* gogo)
998 if (gogo->named_types_are_converted())
999 return this->get_backend(gogo);
1000 if (this->btype_ != NULL)
1001 return this->btype_;
1003 Btype* bt;
1004 switch (this->classification_)
1006 case TYPE_ERROR:
1007 case TYPE_VOID:
1008 case TYPE_BOOLEAN:
1009 case TYPE_INTEGER:
1010 case TYPE_FLOAT:
1011 case TYPE_COMPLEX:
1012 case TYPE_STRING:
1013 case TYPE_NIL:
1014 // These are simple types that can just be created directly.
1015 return this->get_backend(gogo);
1017 case TYPE_MAP:
1018 case TYPE_CHANNEL:
1019 // All maps and channels have the same backend representation.
1020 return this->get_backend(gogo);
1022 case TYPE_NAMED:
1023 case TYPE_FORWARD:
1024 // Named types keep track of their own dependencies and manage
1025 // their own placeholders.
1026 return this->get_backend(gogo);
1028 case TYPE_INTERFACE:
1029 if (this->interface_type()->is_empty())
1030 return Interface_type::get_backend_empty_interface_type(gogo);
1031 break;
1033 default:
1034 break;
1037 std::pair<Type*, Type_btype_entry> val;
1038 val.first = this;
1039 val.second.btype = NULL;
1040 val.second.is_placeholder = false;
1041 std::pair<Type_btypes::iterator, bool> ins =
1042 Type::type_btypes.insert(val);
1043 if (!ins.second && ins.first->second.btype != NULL)
1044 return ins.first->second.btype;
1046 switch (this->classification_)
1048 case TYPE_FUNCTION:
1050 // A Go function type is a pointer to a struct type.
1051 Location loc = this->function_type()->location();
1052 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1054 break;
1056 case TYPE_POINTER:
1058 Location loc = Linemap::unknown_location();
1059 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1061 break;
1063 case TYPE_STRUCT:
1064 // We don't have to make the struct itself be a placeholder. We
1065 // are promised that we know the sizes of the struct fields.
1066 // But we may have to use a placeholder for any particular
1067 // struct field.
1069 std::vector<Backend::Btyped_identifier> bfields;
1070 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1071 true, &bfields);
1072 bt = gogo->backend()->struct_type(bfields);
1074 break;
1076 case TYPE_ARRAY:
1077 if (this->is_slice_type())
1079 std::vector<Backend::Btyped_identifier> bfields;
1080 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1081 bt = gogo->backend()->struct_type(bfields);
1083 else
1085 Btype* element = this->array_type()->get_backend_element(gogo, true);
1086 Bexpression* len = this->array_type()->get_backend_length(gogo);
1087 bt = gogo->backend()->array_type(element, len);
1089 break;
1091 case TYPE_INTERFACE:
1093 go_assert(!this->interface_type()->is_empty());
1094 std::vector<Backend::Btyped_identifier> bfields;
1095 get_backend_interface_fields(gogo, this->interface_type(), true,
1096 &bfields);
1097 bt = gogo->backend()->struct_type(bfields);
1099 break;
1101 case TYPE_SINK:
1102 case TYPE_CALL_MULTIPLE_RESULT:
1103 /* Note that various classifications were handled in the earlier
1104 switch. */
1105 default:
1106 go_unreachable();
1109 if (ins.first->second.btype == NULL)
1111 ins.first->second.btype = bt;
1112 ins.first->second.is_placeholder = true;
1114 else
1116 // A placeholder for this type got created along the way. Use
1117 // that one and ignore the one we just built.
1118 bt = ins.first->second.btype;
1121 return bt;
1124 // Complete the backend representation. This is called for a type
1125 // using a placeholder type.
1127 void
1128 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1130 switch (this->classification_)
1132 case TYPE_ERROR:
1133 case TYPE_VOID:
1134 case TYPE_BOOLEAN:
1135 case TYPE_INTEGER:
1136 case TYPE_FLOAT:
1137 case TYPE_COMPLEX:
1138 case TYPE_STRING:
1139 case TYPE_NIL:
1140 go_unreachable();
1142 case TYPE_FUNCTION:
1144 Btype* bt = this->do_get_backend(gogo);
1145 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1146 go_assert(saw_errors());
1148 break;
1150 case TYPE_POINTER:
1152 Btype* bt = this->do_get_backend(gogo);
1153 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1154 go_assert(saw_errors());
1156 break;
1158 case TYPE_STRUCT:
1159 // The struct type itself is done, but we have to make sure that
1160 // all the field types are converted.
1161 this->struct_type()->finish_backend_fields(gogo);
1162 break;
1164 case TYPE_ARRAY:
1165 // The array type itself is done, but make sure the element type
1166 // is converted.
1167 this->array_type()->finish_backend_element(gogo);
1168 break;
1170 case TYPE_MAP:
1171 case TYPE_CHANNEL:
1172 go_unreachable();
1174 case TYPE_INTERFACE:
1175 // The interface type itself is done, but make sure the method
1176 // types are converted.
1177 this->interface_type()->finish_backend_methods(gogo);
1178 break;
1180 case TYPE_NAMED:
1181 case TYPE_FORWARD:
1182 go_unreachable();
1184 case TYPE_SINK:
1185 case TYPE_CALL_MULTIPLE_RESULT:
1186 default:
1187 go_unreachable();
1190 this->btype_ = placeholder;
1193 // Return a pointer to the type descriptor for this type.
1195 Bexpression*
1196 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1198 Type* t = this->forwarded();
1199 while (t->named_type() != NULL && t->named_type()->is_alias())
1200 t = t->named_type()->real_type()->forwarded();
1201 if (t->type_descriptor_var_ == NULL)
1203 t->make_type_descriptor_var(gogo);
1204 go_assert(t->type_descriptor_var_ != NULL);
1206 Bexpression* var_expr =
1207 gogo->backend()->var_expression(t->type_descriptor_var_,
1208 VE_rvalue, location);
1209 Bexpression* var_addr =
1210 gogo->backend()->address_expression(var_expr, location);
1211 Type* td_type = Type::make_type_descriptor_type();
1212 Btype* td_btype = td_type->get_backend(gogo);
1213 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1214 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1217 // A mapping from unnamed types to type descriptor variables.
1219 Type::Type_descriptor_vars Type::type_descriptor_vars;
1221 // Build the type descriptor for this type.
1223 void
1224 Type::make_type_descriptor_var(Gogo* gogo)
1226 go_assert(this->type_descriptor_var_ == NULL);
1228 Named_type* nt = this->named_type();
1230 // We can have multiple instances of unnamed types, but we only want
1231 // to emit the type descriptor once. We use a hash table. This is
1232 // not necessary for named types, as they are unique, and we store
1233 // the type descriptor in the type itself.
1234 Bvariable** phash = NULL;
1235 if (nt == NULL)
1237 Bvariable* bvnull = NULL;
1238 std::pair<Type_descriptor_vars::iterator, bool> ins =
1239 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1240 if (!ins.second)
1242 // We've already built a type descriptor for this type.
1243 this->type_descriptor_var_ = ins.first->second;
1244 return;
1246 phash = &ins.first->second;
1249 // The type descriptor symbol for the unsafe.Pointer type is defined in
1250 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1251 // symbol if necessary.
1252 if (this->is_unsafe_pointer_type())
1254 Location bloc = Linemap::predeclared_location();
1256 Type* td_type = Type::make_type_descriptor_type();
1257 Btype* td_btype = td_type->get_backend(gogo);
1258 const char *name = "__go_tdn_unsafe.Pointer";
1259 std::string asm_name(go_selectively_encode_id(name));
1260 this->type_descriptor_var_ =
1261 gogo->backend()->immutable_struct_reference(name, asm_name,
1262 td_btype,
1263 bloc);
1265 if (phash != NULL)
1266 *phash = this->type_descriptor_var_;
1267 return;
1270 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1272 // Build the contents of the type descriptor.
1273 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1275 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1277 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1279 const Package* dummy;
1280 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1282 std::string asm_name(go_selectively_encode_id(var_name));
1283 this->type_descriptor_var_ =
1284 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1285 initializer_btype,
1286 loc);
1287 if (phash != NULL)
1288 *phash = this->type_descriptor_var_;
1289 return;
1292 // See if this type descriptor can appear in multiple packages.
1293 bool is_common = false;
1294 if (nt != NULL)
1296 // We create the descriptor for a builtin type whenever we need
1297 // it.
1298 is_common = nt->is_builtin();
1300 else
1302 // This is an unnamed type. The descriptor could be defined in
1303 // any package where it is needed, and the linker will pick one
1304 // descriptor to keep.
1305 is_common = true;
1308 // We are going to build the type descriptor in this package. We
1309 // must create the variable before we convert the initializer to the
1310 // backend representation, because the initializer may refer to the
1311 // type descriptor of this type. By setting type_descriptor_var_ we
1312 // ensure that type_descriptor_pointer will work if called while
1313 // converting INITIALIZER.
1315 std::string asm_name(go_selectively_encode_id(var_name));
1316 this->type_descriptor_var_ =
1317 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1318 initializer_btype, loc);
1319 if (phash != NULL)
1320 *phash = this->type_descriptor_var_;
1322 Translate_context context(gogo, NULL, NULL, NULL);
1323 context.set_is_const();
1324 Bexpression* binitializer = initializer->get_backend(&context);
1326 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1327 var_name, false, is_common,
1328 initializer_btype, loc,
1329 binitializer);
1332 // Return the name of the type descriptor variable. If NT is not
1333 // NULL, use it to get the name. Otherwise this is an unnamed type.
1335 std::string
1336 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1338 if (nt == NULL)
1339 return "__go_td_" + this->mangled_name(gogo);
1341 Named_object* no = nt->named_object();
1342 unsigned int index;
1343 const Named_object* in_function = nt->in_function(&index);
1344 std::string ret = "__go_tdn_";
1345 if (nt->is_builtin())
1346 go_assert(in_function == NULL);
1347 else
1349 const std::string& pkgpath(no->package() == NULL
1350 ? gogo->pkgpath_symbol()
1351 : no->package()->pkgpath_symbol());
1352 ret.append(pkgpath);
1353 ret.append(1, '.');
1354 if (in_function != NULL)
1356 const Typed_identifier* rcvr =
1357 in_function->func_value()->type()->receiver();
1358 if (rcvr != NULL)
1360 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1361 ret.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1362 ret.append(1, '.');
1364 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1365 ret.append(1, '.');
1366 if (index > 0)
1368 char buf[30];
1369 snprintf(buf, sizeof buf, "%u", index);
1370 ret.append(buf);
1371 ret.append(1, '.');
1376 std::string mname(Gogo::mangle_possibly_hidden_name(no->name()));
1377 ret.append(mname);
1379 return ret;
1382 // Return true if this type descriptor is defined in a different
1383 // package. If this returns true it sets *PACKAGE to the package.
1385 bool
1386 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1387 const Package** package)
1389 if (nt != NULL)
1391 if (nt->named_object()->package() != NULL)
1393 // This is a named type defined in a different package. The
1394 // type descriptor should be defined in that package.
1395 *package = nt->named_object()->package();
1396 return true;
1399 else
1401 if (this->points_to() != NULL
1402 && this->points_to()->named_type() != NULL
1403 && this->points_to()->named_type()->named_object()->package() != NULL)
1405 // This is an unnamed pointer to a named type defined in a
1406 // different package. The descriptor should be defined in
1407 // that package.
1408 *package = this->points_to()->named_type()->named_object()->package();
1409 return true;
1412 return false;
1415 // Return a composite literal for a type descriptor.
1417 Expression*
1418 Type::type_descriptor(Gogo* gogo, Type* type)
1420 return type->do_type_descriptor(gogo, NULL);
1423 // Return a composite literal for a type descriptor with a name.
1425 Expression*
1426 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1428 go_assert(name != NULL && type->named_type() != name);
1429 return type->do_type_descriptor(gogo, name);
1432 // Make a builtin struct type from a list of fields. The fields are
1433 // pairs of a name and a type.
1435 Struct_type*
1436 Type::make_builtin_struct_type(int nfields, ...)
1438 va_list ap;
1439 va_start(ap, nfields);
1441 Location bloc = Linemap::predeclared_location();
1442 Struct_field_list* sfl = new Struct_field_list();
1443 for (int i = 0; i < nfields; i++)
1445 const char* field_name = va_arg(ap, const char *);
1446 Type* type = va_arg(ap, Type*);
1447 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1450 va_end(ap);
1452 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1453 ret->set_is_struct_incomparable();
1454 return ret;
1457 // A list of builtin named types.
1459 std::vector<Named_type*> Type::named_builtin_types;
1461 // Make a builtin named type.
1463 Named_type*
1464 Type::make_builtin_named_type(const char* name, Type* type)
1466 Location bloc = Linemap::predeclared_location();
1467 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1468 Named_type* ret = no->type_value();
1469 Type::named_builtin_types.push_back(ret);
1470 return ret;
1473 // Convert the named builtin types.
1475 void
1476 Type::convert_builtin_named_types(Gogo* gogo)
1478 for (std::vector<Named_type*>::const_iterator p =
1479 Type::named_builtin_types.begin();
1480 p != Type::named_builtin_types.end();
1481 ++p)
1483 bool r = (*p)->verify();
1484 go_assert(r);
1485 (*p)->convert(gogo);
1489 // Return the type of a type descriptor. We should really tie this to
1490 // runtime.Type rather than copying it. This must match the struct "_type"
1491 // declared in libgo/go/runtime/type.go.
1493 Type*
1494 Type::make_type_descriptor_type()
1496 static Type* ret;
1497 if (ret == NULL)
1499 Location bloc = Linemap::predeclared_location();
1501 Type* uint8_type = Type::lookup_integer_type("uint8");
1502 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1503 Type* uint32_type = Type::lookup_integer_type("uint32");
1504 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1505 Type* string_type = Type::lookup_string_type();
1506 Type* pointer_string_type = Type::make_pointer_type(string_type);
1508 // This is an unnamed version of unsafe.Pointer. Perhaps we
1509 // should use the named version instead, although that would
1510 // require us to create the unsafe package if it has not been
1511 // imported. It probably doesn't matter.
1512 Type* void_type = Type::make_void_type();
1513 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1515 Typed_identifier_list *params = new Typed_identifier_list();
1516 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1517 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1519 Typed_identifier_list* results = new Typed_identifier_list();
1520 results->push_back(Typed_identifier("", uintptr_type, bloc));
1522 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1523 bloc);
1525 params = new Typed_identifier_list();
1526 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1527 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1529 results = new Typed_identifier_list();
1530 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1532 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1533 bloc);
1535 // Forward declaration for the type descriptor type.
1536 Named_object* named_type_descriptor_type =
1537 Named_object::make_type_declaration("_type", NULL, bloc);
1538 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1539 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1541 // The type of a method on a concrete type.
1542 Struct_type* method_type =
1543 Type::make_builtin_struct_type(5,
1544 "name", pointer_string_type,
1545 "pkgPath", pointer_string_type,
1546 "mtyp", pointer_type_descriptor_type,
1547 "typ", pointer_type_descriptor_type,
1548 "tfn", unsafe_pointer_type);
1549 Named_type* named_method_type =
1550 Type::make_builtin_named_type("method", method_type);
1552 // Information for types with a name or methods.
1553 Type* slice_named_method_type =
1554 Type::make_array_type(named_method_type, NULL);
1555 Struct_type* uncommon_type =
1556 Type::make_builtin_struct_type(3,
1557 "name", pointer_string_type,
1558 "pkgPath", pointer_string_type,
1559 "methods", slice_named_method_type);
1560 Named_type* named_uncommon_type =
1561 Type::make_builtin_named_type("uncommonType", uncommon_type);
1563 Type* pointer_uncommon_type =
1564 Type::make_pointer_type(named_uncommon_type);
1566 // The type descriptor type.
1568 Struct_type* type_descriptor_type =
1569 Type::make_builtin_struct_type(12,
1570 "size", uintptr_type,
1571 "ptrdata", uintptr_type,
1572 "hash", uint32_type,
1573 "kind", uint8_type,
1574 "align", uint8_type,
1575 "fieldAlign", uint8_type,
1576 "hashfn", hash_fntype,
1577 "equalfn", equal_fntype,
1578 "gcdata", pointer_uint8_type,
1579 "string", pointer_string_type,
1580 "", pointer_uncommon_type,
1581 "ptrToThis",
1582 pointer_type_descriptor_type);
1584 Named_type* named = Type::make_builtin_named_type("_type",
1585 type_descriptor_type);
1587 named_type_descriptor_type->set_type_value(named);
1589 ret = named;
1592 return ret;
1595 // Make the type of a pointer to a type descriptor as represented in
1596 // Go.
1598 Type*
1599 Type::make_type_descriptor_ptr_type()
1601 static Type* ret;
1602 if (ret == NULL)
1603 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1604 return ret;
1607 // Return the alignment required by the memequalN function. N is a
1608 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1609 // in libgo/go/runtime/alg.go.
1611 int64_t
1612 Type::memequal_align(Gogo* gogo, int size)
1614 const char* tn;
1615 switch (size)
1617 case 16:
1618 tn = "int16";
1619 break;
1620 case 32:
1621 tn = "int32";
1622 break;
1623 case 64:
1624 tn = "int64";
1625 break;
1626 case 128:
1627 // The code uses [2]int64, which must have the same alignment as
1628 // int64.
1629 tn = "int64";
1630 break;
1631 default:
1632 go_unreachable();
1635 Type* t = Type::lookup_integer_type(tn);
1637 int64_t ret;
1638 if (!t->backend_type_align(gogo, &ret))
1639 go_unreachable();
1640 return ret;
1643 // Return whether this type needs specially built type functions.
1644 // This returns true for types that are comparable and either can not
1645 // use an identity comparison, or are a non-standard size.
1647 bool
1648 Type::needs_specific_type_functions(Gogo* gogo)
1650 Named_type* nt = this->named_type();
1651 if (nt != NULL && nt->is_alias())
1652 return false;
1653 if (!this->is_comparable())
1654 return false;
1655 if (!this->compare_is_identity(gogo))
1656 return true;
1658 // We create a few predeclared types for type descriptors; they are
1659 // really just for the backend and don't need hash or equality
1660 // functions.
1661 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1662 return false;
1664 int64_t size, align;
1665 if (!this->backend_type_size(gogo, &size)
1666 || !this->backend_type_align(gogo, &align))
1668 go_assert(saw_errors());
1669 return false;
1671 // This switch matches the one in Type::type_functions.
1672 switch (size)
1674 case 0:
1675 case 1:
1676 case 2:
1677 return align < Type::memequal_align(gogo, 16);
1678 case 4:
1679 return align < Type::memequal_align(gogo, 32);
1680 case 8:
1681 return align < Type::memequal_align(gogo, 64);
1682 case 16:
1683 return align < Type::memequal_align(gogo, 128);
1684 default:
1685 return true;
1689 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1690 // hash code for this type and which compare whether two values of
1691 // this type are equal. If NAME is not NULL it is the name of this
1692 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1693 // functions, for convenience; they may be NULL.
1695 void
1696 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1697 Function_type* equal_fntype, Named_object** hash_fn,
1698 Named_object** equal_fn)
1700 // If this loop leaves NAME as NULL, then the type does not have a
1701 // name after all.
1702 while (name != NULL && name->is_alias())
1703 name = name->real_type()->named_type();
1705 if (!this->is_comparable())
1707 *hash_fn = NULL;
1708 *equal_fn = NULL;
1709 return;
1712 if (hash_fntype == NULL || equal_fntype == NULL)
1714 Location bloc = Linemap::predeclared_location();
1716 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1717 Type* void_type = Type::make_void_type();
1718 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1720 if (hash_fntype == NULL)
1722 Typed_identifier_list* params = new Typed_identifier_list();
1723 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1724 bloc));
1725 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1727 Typed_identifier_list* results = new Typed_identifier_list();
1728 results->push_back(Typed_identifier("", uintptr_type, bloc));
1730 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1732 if (equal_fntype == NULL)
1734 Typed_identifier_list* params = new Typed_identifier_list();
1735 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1736 bloc));
1737 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1738 bloc));
1740 Typed_identifier_list* results = new Typed_identifier_list();
1741 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1742 bloc));
1744 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1748 const char* hash_fnname;
1749 const char* equal_fnname;
1750 if (this->compare_is_identity(gogo))
1752 int64_t size, align;
1753 if (!this->backend_type_size(gogo, &size)
1754 || !this->backend_type_align(gogo, &align))
1756 go_assert(saw_errors());
1757 return;
1759 bool build_functions = false;
1760 // This switch matches the one in Type::needs_specific_type_functions.
1761 // The alignment tests are because of the memequal functions,
1762 // which assume that the values are aligned as required for an
1763 // integer of that size.
1764 switch (size)
1766 case 0:
1767 hash_fnname = "runtime.memhash0";
1768 equal_fnname = "runtime.memequal0";
1769 break;
1770 case 1:
1771 hash_fnname = "runtime.memhash8";
1772 equal_fnname = "runtime.memequal8";
1773 break;
1774 case 2:
1775 if (align < Type::memequal_align(gogo, 16))
1776 build_functions = true;
1777 else
1779 hash_fnname = "runtime.memhash16";
1780 equal_fnname = "runtime.memequal16";
1782 break;
1783 case 4:
1784 if (align < Type::memequal_align(gogo, 32))
1785 build_functions = true;
1786 else
1788 hash_fnname = "runtime.memhash32";
1789 equal_fnname = "runtime.memequal32";
1791 break;
1792 case 8:
1793 if (align < Type::memequal_align(gogo, 64))
1794 build_functions = true;
1795 else
1797 hash_fnname = "runtime.memhash64";
1798 equal_fnname = "runtime.memequal64";
1800 break;
1801 case 16:
1802 if (align < Type::memequal_align(gogo, 128))
1803 build_functions = true;
1804 else
1806 hash_fnname = "runtime.memhash128";
1807 equal_fnname = "runtime.memequal128";
1809 break;
1810 default:
1811 build_functions = true;
1812 break;
1814 if (build_functions)
1816 // We don't have a built-in function for a type of this size
1817 // and alignment. Build a function to use that calls the
1818 // generic hash/equality functions for identity, passing the size.
1819 this->specific_type_functions(gogo, name, size, hash_fntype,
1820 equal_fntype, hash_fn, equal_fn);
1821 return;
1824 else
1826 switch (this->base()->classification())
1828 case Type::TYPE_ERROR:
1829 case Type::TYPE_VOID:
1830 case Type::TYPE_NIL:
1831 case Type::TYPE_FUNCTION:
1832 case Type::TYPE_MAP:
1833 // For these types is_comparable should have returned false.
1834 go_unreachable();
1836 case Type::TYPE_BOOLEAN:
1837 case Type::TYPE_INTEGER:
1838 case Type::TYPE_POINTER:
1839 case Type::TYPE_CHANNEL:
1840 // For these types compare_is_identity should have returned true.
1841 go_unreachable();
1843 case Type::TYPE_FLOAT:
1844 switch (this->float_type()->bits())
1846 case 32:
1847 hash_fnname = "runtime.f32hash";
1848 equal_fnname = "runtime.f32equal";
1849 break;
1850 case 64:
1851 hash_fnname = "runtime.f64hash";
1852 equal_fnname = "runtime.f64equal";
1853 break;
1854 default:
1855 go_unreachable();
1857 break;
1859 case Type::TYPE_COMPLEX:
1860 switch (this->complex_type()->bits())
1862 case 64:
1863 hash_fnname = "runtime.c64hash";
1864 equal_fnname = "runtime.c64equal";
1865 break;
1866 case 128:
1867 hash_fnname = "runtime.c128hash";
1868 equal_fnname = "runtime.c128equal";
1869 break;
1870 default:
1871 go_unreachable();
1873 break;
1875 case Type::TYPE_STRING:
1876 hash_fnname = "runtime.strhash";
1877 equal_fnname = "runtime.strequal";
1878 break;
1880 case Type::TYPE_STRUCT:
1882 // This is a struct which can not be compared using a
1883 // simple identity function. We need to build a function
1884 // for comparison.
1885 this->specific_type_functions(gogo, name, -1, hash_fntype,
1886 equal_fntype, hash_fn, equal_fn);
1887 return;
1890 case Type::TYPE_ARRAY:
1891 if (this->is_slice_type())
1893 // Type::is_compatible_for_comparison should have
1894 // returned false.
1895 go_unreachable();
1897 else
1899 // This is an array which can not be compared using a
1900 // simple identity function. We need to build a
1901 // function for comparison.
1902 this->specific_type_functions(gogo, name, -1, hash_fntype,
1903 equal_fntype, hash_fn, equal_fn);
1904 return;
1906 break;
1908 case Type::TYPE_INTERFACE:
1909 if (this->interface_type()->is_empty())
1911 hash_fnname = "runtime.nilinterhash";
1912 equal_fnname = "runtime.nilinterequal";
1914 else
1916 hash_fnname = "runtime.interhash";
1917 equal_fnname = "runtime.interequal";
1919 break;
1921 case Type::TYPE_NAMED:
1922 case Type::TYPE_FORWARD:
1923 go_unreachable();
1925 default:
1926 go_unreachable();
1931 Location bloc = Linemap::predeclared_location();
1932 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1933 hash_fntype, bloc);
1934 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1935 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1936 equal_fntype, bloc);
1937 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1940 // A hash table mapping types to the specific hash functions.
1942 Type::Type_functions Type::type_functions_table;
1944 // Handle a type function which is specific to a type: if SIZE == -1,
1945 // this is a struct or array that can not use an identity comparison.
1946 // Otherwise, it is a type that uses an identity comparison but is not
1947 // one of the standard supported sizes.
1949 void
1950 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1951 Function_type* hash_fntype,
1952 Function_type* equal_fntype,
1953 Named_object** hash_fn,
1954 Named_object** equal_fn)
1956 Hash_equal_fn fnull(NULL, NULL);
1957 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1958 std::pair<Type_functions::iterator, bool> ins =
1959 Type::type_functions_table.insert(val);
1960 if (!ins.second)
1962 // We already have functions for this type
1963 *hash_fn = ins.first->second.first;
1964 *equal_fn = ins.first->second.second;
1965 return;
1968 std::string base_name;
1969 if (name == NULL)
1971 // Mangled names can have '.' if they happen to refer to named
1972 // types in some way. That's fine if this is simply a named
1973 // type, but otherwise it will confuse the code that builds
1974 // function identifiers. Remove '.' when necessary.
1975 base_name = this->mangled_name(gogo);
1976 size_t i;
1977 while ((i = base_name.find('.')) != std::string::npos)
1978 base_name[i] = '$';
1979 base_name = gogo->pack_hidden_name(base_name, false);
1981 else
1983 // This name is already hidden or not as appropriate.
1984 base_name = name->name();
1985 unsigned int index;
1986 const Named_object* in_function = name->in_function(&index);
1987 if (in_function != NULL)
1989 base_name.append(1, '$');
1990 const Typed_identifier* rcvr =
1991 in_function->func_value()->type()->receiver();
1992 if (rcvr != NULL)
1994 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1995 base_name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1996 base_name.append(1, '$');
1998 base_name.append(Gogo::unpack_hidden_name(in_function->name()));
1999 if (index > 0)
2001 char buf[30];
2002 snprintf(buf, sizeof buf, "%u", index);
2003 base_name += '$';
2004 base_name += buf;
2008 std::string hash_name = base_name + "$hash";
2009 std::string equal_name = base_name + "$equal";
2011 Location bloc = Linemap::predeclared_location();
2013 const Package* package = NULL;
2014 bool is_defined_elsewhere =
2015 this->type_descriptor_defined_elsewhere(name, &package);
2016 if (is_defined_elsewhere)
2018 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2019 hash_fntype, bloc);
2020 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2021 equal_fntype, bloc);
2023 else
2025 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2026 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2027 bloc);
2030 ins.first->second.first = *hash_fn;
2031 ins.first->second.second = *equal_fn;
2033 if (!is_defined_elsewhere)
2035 if (gogo->in_global_scope())
2036 this->write_specific_type_functions(gogo, name, size, hash_name,
2037 hash_fntype, equal_name,
2038 equal_fntype);
2039 else
2040 gogo->queue_specific_type_function(this, name, size, hash_name,
2041 hash_fntype, equal_name,
2042 equal_fntype);
2046 // Write the hash and equality functions for a type which needs to be
2047 // written specially.
2049 void
2050 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2051 const std::string& hash_name,
2052 Function_type* hash_fntype,
2053 const std::string& equal_name,
2054 Function_type* equal_fntype)
2056 Location bloc = Linemap::predeclared_location();
2058 if (gogo->specific_type_functions_are_written())
2060 go_assert(saw_errors());
2061 return;
2064 go_assert(this->is_comparable());
2066 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2067 bloc);
2068 hash_fn->func_value()->set_is_type_specific_function();
2069 gogo->start_block(bloc);
2071 if (size != -1)
2072 this->write_identity_hash(gogo, size);
2073 else if (name != NULL && name->real_type()->named_type() != NULL)
2074 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2075 else if (this->struct_type() != NULL)
2076 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2077 equal_fntype);
2078 else if (this->array_type() != NULL)
2079 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2080 equal_fntype);
2081 else
2082 go_unreachable();
2084 Block* b = gogo->finish_block(bloc);
2085 gogo->add_block(b, bloc);
2086 gogo->lower_block(hash_fn, b);
2087 gogo->finish_function(bloc);
2089 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2090 false, bloc);
2091 equal_fn->func_value()->set_is_type_specific_function();
2092 gogo->start_block(bloc);
2094 if (size != -1)
2095 this->write_identity_equal(gogo, size);
2096 else if (name != NULL && name->real_type()->named_type() != NULL)
2097 this->write_named_equal(gogo, name);
2098 else if (this->struct_type() != NULL)
2099 this->struct_type()->write_equal_function(gogo, name);
2100 else if (this->array_type() != NULL)
2101 this->array_type()->write_equal_function(gogo, name);
2102 else
2103 go_unreachable();
2105 b = gogo->finish_block(bloc);
2106 gogo->add_block(b, bloc);
2107 gogo->lower_block(equal_fn, b);
2108 gogo->finish_function(bloc);
2110 // Build the function descriptors for the type descriptor to refer to.
2111 hash_fn->func_value()->descriptor(gogo, hash_fn);
2112 equal_fn->func_value()->descriptor(gogo, equal_fn);
2115 // Write a hash function for a type that can use an identity hash but
2116 // is not one of the standard supported sizes. For example, this
2117 // would be used for the type [3]byte. This builds a return statement
2118 // that returns a call to the memhash function, passing the key and
2119 // seed from the function arguments (already constructed before this
2120 // is called), and the constant size.
2122 void
2123 Type::write_identity_hash(Gogo* gogo, int64_t size)
2125 Location bloc = Linemap::predeclared_location();
2127 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2128 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2130 Typed_identifier_list* params = new Typed_identifier_list();
2131 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2132 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2133 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2135 Typed_identifier_list* results = new Typed_identifier_list();
2136 results->push_back(Typed_identifier("", uintptr_type, bloc));
2138 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2139 results, bloc);
2141 Named_object* memhash =
2142 Named_object::make_function_declaration("runtime.memhash", NULL,
2143 memhash_fntype, bloc);
2144 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2146 Named_object* key_arg = gogo->lookup("key", NULL);
2147 go_assert(key_arg != NULL);
2148 Named_object* seed_arg = gogo->lookup("seed", NULL);
2149 go_assert(seed_arg != NULL);
2151 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2152 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2153 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2154 bloc);
2155 Expression_list* args = new Expression_list();
2156 args->push_back(key_ref);
2157 args->push_back(seed_ref);
2158 args->push_back(size_arg);
2159 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2160 Expression* call = Expression::make_call(func, args, false, bloc);
2162 Expression_list* vals = new Expression_list();
2163 vals->push_back(call);
2164 Statement* s = Statement::make_return_statement(vals, bloc);
2165 gogo->add_statement(s);
2168 // Write an equality function for a type that can use an identity
2169 // equality comparison but is not one of the standard supported sizes.
2170 // For example, this would be used for the type [3]byte. This builds
2171 // a return statement that returns a call to the memequal function,
2172 // passing the two keys from the function arguments (already
2173 // constructed before this is called), and the constant size.
2175 void
2176 Type::write_identity_equal(Gogo* gogo, int64_t size)
2178 Location bloc = Linemap::predeclared_location();
2180 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2181 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2183 Typed_identifier_list* params = new Typed_identifier_list();
2184 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2185 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2186 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2188 Typed_identifier_list* results = new Typed_identifier_list();
2189 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2191 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2192 results, bloc);
2194 Named_object* memequal =
2195 Named_object::make_function_declaration("runtime.memequal", NULL,
2196 memequal_fntype, bloc);
2197 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2199 Named_object* key1_arg = gogo->lookup("key1", NULL);
2200 go_assert(key1_arg != NULL);
2201 Named_object* key2_arg = gogo->lookup("key2", NULL);
2202 go_assert(key2_arg != NULL);
2204 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2205 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2206 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2207 bloc);
2208 Expression_list* args = new Expression_list();
2209 args->push_back(key1_ref);
2210 args->push_back(key2_ref);
2211 args->push_back(size_arg);
2212 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2213 Expression* call = Expression::make_call(func, args, false, bloc);
2215 Expression_list* vals = new Expression_list();
2216 vals->push_back(call);
2217 Statement* s = Statement::make_return_statement(vals, bloc);
2218 gogo->add_statement(s);
2221 // Write a hash function that simply calls the hash function for a
2222 // named type. This is used when one named type is defined as
2223 // another. This ensures that this case works when the other named
2224 // type is defined in another package and relies on calling hash
2225 // functions defined only in that package.
2227 void
2228 Type::write_named_hash(Gogo* gogo, Named_type* name,
2229 Function_type* hash_fntype, Function_type* equal_fntype)
2231 Location bloc = Linemap::predeclared_location();
2233 Named_type* base_type = name->real_type()->named_type();
2234 while (base_type->is_alias())
2236 base_type = base_type->real_type()->named_type();
2237 go_assert(base_type != NULL);
2239 go_assert(base_type != NULL);
2241 // The pointer to the type we are going to hash. This is an
2242 // unsafe.Pointer.
2243 Named_object* key_arg = gogo->lookup("key", NULL);
2244 go_assert(key_arg != NULL);
2246 // The seed argument to the hash function.
2247 Named_object* seed_arg = gogo->lookup("seed", NULL);
2248 go_assert(seed_arg != NULL);
2250 Named_object* hash_fn;
2251 Named_object* equal_fn;
2252 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2253 &hash_fn, &equal_fn);
2255 // Call the hash function for the base type.
2256 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2257 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2258 Expression_list* args = new Expression_list();
2259 args->push_back(key_ref);
2260 args->push_back(seed_ref);
2261 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2262 Expression* call = Expression::make_call(func, args, false, bloc);
2264 // Return the hash of the base type.
2265 Expression_list* vals = new Expression_list();
2266 vals->push_back(call);
2267 Statement* s = Statement::make_return_statement(vals, bloc);
2268 gogo->add_statement(s);
2271 // Write an equality function that simply calls the equality function
2272 // for a named type. This is used when one named type is defined as
2273 // another. This ensures that this case works when the other named
2274 // type is defined in another package and relies on calling equality
2275 // functions defined only in that package.
2277 void
2278 Type::write_named_equal(Gogo* gogo, Named_type* name)
2280 Location bloc = Linemap::predeclared_location();
2282 // The pointers to the types we are going to compare. These have
2283 // type unsafe.Pointer.
2284 Named_object* key1_arg = gogo->lookup("key1", NULL);
2285 Named_object* key2_arg = gogo->lookup("key2", NULL);
2286 go_assert(key1_arg != NULL && key2_arg != NULL);
2288 Named_type* base_type = name->real_type()->named_type();
2289 go_assert(base_type != NULL);
2291 // Build temporaries with the base type.
2292 Type* pt = Type::make_pointer_type(base_type);
2294 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2295 ref = Expression::make_cast(pt, ref, bloc);
2296 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2297 gogo->add_statement(p1);
2299 ref = Expression::make_var_reference(key2_arg, bloc);
2300 ref = Expression::make_cast(pt, ref, bloc);
2301 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2302 gogo->add_statement(p2);
2304 // Compare the values for equality.
2305 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2306 t1 = Expression::make_unary(OPERATOR_MULT, t1, bloc);
2308 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2309 t2 = Expression::make_unary(OPERATOR_MULT, t2, bloc);
2311 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2313 // Return the equality comparison.
2314 Expression_list* vals = new Expression_list();
2315 vals->push_back(cond);
2316 Statement* s = Statement::make_return_statement(vals, bloc);
2317 gogo->add_statement(s);
2320 // Return a composite literal for the type descriptor for a plain type
2321 // of kind RUNTIME_TYPE_KIND named NAME.
2323 Expression*
2324 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2325 Named_type* name, const Methods* methods,
2326 bool only_value_methods)
2328 Location bloc = Linemap::predeclared_location();
2330 Type* td_type = Type::make_type_descriptor_type();
2331 const Struct_field_list* fields = td_type->struct_type()->fields();
2333 Expression_list* vals = new Expression_list();
2334 vals->reserve(12);
2336 if (!this->has_pointer())
2337 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2338 if (this->points_to() != NULL)
2339 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2340 int64_t ptrsize;
2341 int64_t ptrdata;
2342 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2343 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2345 Struct_field_list::const_iterator p = fields->begin();
2346 go_assert(p->is_field_name("size"));
2347 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2348 vals->push_back(Expression::make_type_info(this, type_info));
2350 ++p;
2351 go_assert(p->is_field_name("ptrdata"));
2352 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2353 vals->push_back(Expression::make_type_info(this, type_info));
2355 ++p;
2356 go_assert(p->is_field_name("hash"));
2357 unsigned int h;
2358 if (name != NULL)
2359 h = name->hash_for_method(gogo);
2360 else
2361 h = this->hash_for_method(gogo);
2362 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2364 ++p;
2365 go_assert(p->is_field_name("kind"));
2366 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2367 bloc));
2369 ++p;
2370 go_assert(p->is_field_name("align"));
2371 type_info = Expression::TYPE_INFO_ALIGNMENT;
2372 vals->push_back(Expression::make_type_info(this, type_info));
2374 ++p;
2375 go_assert(p->is_field_name("fieldAlign"));
2376 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2377 vals->push_back(Expression::make_type_info(this, type_info));
2379 ++p;
2380 go_assert(p->is_field_name("hashfn"));
2381 Function_type* hash_fntype = p->type()->function_type();
2383 ++p;
2384 go_assert(p->is_field_name("equalfn"));
2385 Function_type* equal_fntype = p->type()->function_type();
2387 Named_object* hash_fn;
2388 Named_object* equal_fn;
2389 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2390 &equal_fn);
2391 if (hash_fn == NULL)
2392 vals->push_back(Expression::make_cast(hash_fntype,
2393 Expression::make_nil(bloc),
2394 bloc));
2395 else
2396 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2397 if (equal_fn == NULL)
2398 vals->push_back(Expression::make_cast(equal_fntype,
2399 Expression::make_nil(bloc),
2400 bloc));
2401 else
2402 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2404 ++p;
2405 go_assert(p->is_field_name("gcdata"));
2406 vals->push_back(Expression::make_gc_symbol(this));
2408 ++p;
2409 go_assert(p->is_field_name("string"));
2410 Expression* s = Expression::make_string((name != NULL
2411 ? name->reflection(gogo)
2412 : this->reflection(gogo)),
2413 bloc);
2414 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2416 ++p;
2417 go_assert(p->is_field_name("uncommonType"));
2418 if (name == NULL && methods == NULL)
2419 vals->push_back(Expression::make_nil(bloc));
2420 else
2422 if (methods == NULL)
2423 methods = name->methods();
2424 vals->push_back(this->uncommon_type_constructor(gogo,
2425 p->type()->deref(),
2426 name, methods,
2427 only_value_methods));
2430 ++p;
2431 go_assert(p->is_field_name("ptrToThis"));
2432 if (name == NULL && methods == NULL)
2433 vals->push_back(Expression::make_nil(bloc));
2434 else
2436 Type* pt;
2437 if (name != NULL)
2438 pt = Type::make_pointer_type(name);
2439 else
2440 pt = Type::make_pointer_type(this);
2441 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2444 ++p;
2445 go_assert(p == fields->end());
2447 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2450 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2451 // length used by the gc toolchain, and also appears in
2452 // libgo/go/reflect/type.go.
2454 static const int64_t max_ptrmask_bytes = 2048;
2456 // Return a pointer to the Garbage Collection information for this type.
2458 Bexpression*
2459 Type::gc_symbol_pointer(Gogo* gogo)
2461 Type* t = this->forwarded();
2462 while (t->named_type() != NULL && t->named_type()->is_alias())
2463 t = t->named_type()->real_type()->forwarded();
2465 if (!t->has_pointer())
2466 return gogo->backend()->nil_pointer_expression();
2468 if (t->gc_symbol_var_ == NULL)
2470 t->make_gc_symbol_var(gogo);
2471 go_assert(t->gc_symbol_var_ != NULL);
2473 Location bloc = Linemap::predeclared_location();
2474 Bexpression* var_expr =
2475 gogo->backend()->var_expression(t->gc_symbol_var_, VE_rvalue, bloc);
2476 Bexpression* addr_expr =
2477 gogo->backend()->address_expression(var_expr, bloc);
2479 Type* uint8_type = Type::lookup_integer_type("uint8");
2480 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2481 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2482 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2485 // A mapping from unnamed types to GC symbol variables.
2487 Type::GC_symbol_vars Type::gc_symbol_vars;
2489 // Build the GC symbol for this type.
2491 void
2492 Type::make_gc_symbol_var(Gogo* gogo)
2494 go_assert(this->gc_symbol_var_ == NULL);
2496 Named_type* nt = this->named_type();
2498 // We can have multiple instances of unnamed types and similar to type
2499 // descriptors, we only want to the emit the GC data once, so we use a
2500 // hash table.
2501 Bvariable** phash = NULL;
2502 if (nt == NULL)
2504 Bvariable* bvnull = NULL;
2505 std::pair<GC_symbol_vars::iterator, bool> ins =
2506 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2507 if (!ins.second)
2509 // We've already built a gc symbol for this type.
2510 this->gc_symbol_var_ = ins.first->second;
2511 return;
2513 phash = &ins.first->second;
2516 int64_t ptrsize;
2517 int64_t ptrdata;
2518 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2520 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2521 if (phash != NULL)
2522 *phash = this->gc_symbol_var_;
2523 return;
2526 std::string sym_name = this->type_descriptor_var_name(gogo, nt) + "$gc";
2528 // Build the contents of the gc symbol.
2529 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2530 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2532 // If the type descriptor for this type is defined somewhere else, so is the
2533 // GC symbol.
2534 const Package* dummy;
2535 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2537 std::string asm_name(go_selectively_encode_id(sym_name));
2538 this->gc_symbol_var_ =
2539 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2540 sym_btype);
2541 if (phash != NULL)
2542 *phash = this->gc_symbol_var_;
2543 return;
2546 // See if this gc symbol can appear in multiple packages.
2547 bool is_common = false;
2548 if (nt != NULL)
2550 // We create the symbol for a builtin type whenever we need
2551 // it.
2552 is_common = nt->is_builtin();
2554 else
2556 // This is an unnamed type. The descriptor could be defined in
2557 // any package where it is needed, and the linker will pick one
2558 // descriptor to keep.
2559 is_common = true;
2562 // Since we are building the GC symbol in this package, we must create the
2563 // variable before converting the initializer to its backend representation
2564 // because the initializer may refer to the GC symbol for this type.
2565 std::string asm_name(go_selectively_encode_id(sym_name));
2566 this->gc_symbol_var_ =
2567 gogo->backend()->implicit_variable(sym_name, asm_name,
2568 sym_btype, false, true, is_common, 0);
2569 if (phash != NULL)
2570 *phash = this->gc_symbol_var_;
2572 Translate_context context(gogo, NULL, NULL, NULL);
2573 context.set_is_const();
2574 Bexpression* sym_binit = sym_init->get_backend(&context);
2575 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2576 sym_btype, false, true, is_common,
2577 sym_binit);
2580 // Return whether this type needs a GC program, and set *PTRDATA to
2581 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2582 // pointer.
2584 bool
2585 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2587 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2588 if (!voidptr->backend_type_size(gogo, ptrsize))
2589 go_unreachable();
2591 if (!this->backend_type_ptrdata(gogo, ptrdata))
2593 go_assert(saw_errors());
2594 return false;
2597 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2600 // A simple class used to build a GC ptrmask for a type.
2602 class Ptrmask
2604 public:
2605 Ptrmask(size_t count)
2606 : bits_((count + 7) / 8, 0)
2609 void
2610 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2612 std::string
2613 symname() const;
2615 Expression*
2616 constructor(Gogo* gogo) const;
2618 private:
2619 void
2620 set(size_t index)
2621 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2623 // The actual bits.
2624 std::vector<unsigned char> bits_;
2627 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2628 // counts in bytes. PTRSIZE is the size of a pointer on the target
2629 // system.
2631 void
2632 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2634 switch (type->base()->classification())
2636 default:
2637 case Type::TYPE_NIL:
2638 case Type::TYPE_CALL_MULTIPLE_RESULT:
2639 case Type::TYPE_NAMED:
2640 case Type::TYPE_FORWARD:
2641 go_unreachable();
2643 case Type::TYPE_ERROR:
2644 case Type::TYPE_VOID:
2645 case Type::TYPE_BOOLEAN:
2646 case Type::TYPE_INTEGER:
2647 case Type::TYPE_FLOAT:
2648 case Type::TYPE_COMPLEX:
2649 case Type::TYPE_SINK:
2650 break;
2652 case Type::TYPE_FUNCTION:
2653 case Type::TYPE_POINTER:
2654 case Type::TYPE_MAP:
2655 case Type::TYPE_CHANNEL:
2656 // These types are all a single pointer.
2657 go_assert((offset % ptrsize) == 0);
2658 this->set(offset / ptrsize);
2659 break;
2661 case Type::TYPE_STRING:
2662 // A string starts with a single pointer.
2663 go_assert((offset % ptrsize) == 0);
2664 this->set(offset / ptrsize);
2665 break;
2667 case Type::TYPE_INTERFACE:
2668 // An interface is two pointers.
2669 go_assert((offset % ptrsize) == 0);
2670 this->set(offset / ptrsize);
2671 this->set((offset / ptrsize) + 1);
2672 break;
2674 case Type::TYPE_STRUCT:
2676 if (!type->has_pointer())
2677 return;
2679 const Struct_field_list* fields = type->struct_type()->fields();
2680 int64_t soffset = 0;
2681 for (Struct_field_list::const_iterator pf = fields->begin();
2682 pf != fields->end();
2683 ++pf)
2685 int64_t field_align;
2686 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2688 go_assert(saw_errors());
2689 return;
2691 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2693 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2695 int64_t field_size;
2696 if (!pf->type()->backend_type_size(gogo, &field_size))
2698 go_assert(saw_errors());
2699 return;
2701 soffset += field_size;
2704 break;
2706 case Type::TYPE_ARRAY:
2707 if (type->is_slice_type())
2709 // A slice starts with a single pointer.
2710 go_assert((offset % ptrsize) == 0);
2711 this->set(offset / ptrsize);
2712 break;
2714 else
2716 if (!type->has_pointer())
2717 return;
2719 int64_t len;
2720 if (!type->array_type()->int_length(&len))
2722 go_assert(saw_errors());
2723 return;
2726 Type* element_type = type->array_type()->element_type();
2727 int64_t ele_size;
2728 if (!element_type->backend_type_size(gogo, &ele_size))
2730 go_assert(saw_errors());
2731 return;
2734 int64_t eoffset = 0;
2735 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2736 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2737 break;
2742 // Return a symbol name for this ptrmask. This is used to coalesce
2743 // identical ptrmasks, which are common. The symbol name must use
2744 // only characters that are valid in symbols. It's nice if it's
2745 // short. We convert it to a base64 string.
2747 std::string
2748 Ptrmask::symname() const
2750 const char chars[65] =
2751 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
2752 go_assert(chars[64] == '\0');
2753 std::string ret;
2754 unsigned int b = 0;
2755 int remaining = 0;
2756 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2757 p != this->bits_.end();
2758 ++p)
2760 b |= *p << remaining;
2761 remaining += 8;
2762 while (remaining >= 6)
2764 ret += chars[b & 0x3f];
2765 b >>= 6;
2766 remaining -= 6;
2769 while (remaining > 0)
2771 ret += chars[b & 0x3f];
2772 b >>= 6;
2773 remaining -= 6;
2775 return ret;
2778 // Return a constructor for this ptrmask. This will be used to
2779 // initialize the runtime ptrmask value.
2781 Expression*
2782 Ptrmask::constructor(Gogo* gogo) const
2784 Location bloc = Linemap::predeclared_location();
2785 Type* byte_type = gogo->lookup_global("byte")->type_value();
2786 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2787 bloc);
2788 Array_type* at = Type::make_array_type(byte_type, len);
2789 Expression_list* vals = new Expression_list();
2790 vals->reserve(this->bits_.size());
2791 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2792 p != this->bits_.end();
2793 ++p)
2794 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2795 return Expression::make_array_composite_literal(at, vals, bloc);
2798 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2799 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2801 // Return a ptrmask variable for a type. For a type descriptor this
2802 // is only used for variables that are small enough to not need a
2803 // gcprog, but for a global variable this is used for a variable of
2804 // any size. PTRDATA is the number of bytes of the type that contain
2805 // pointer data. PTRSIZE is the size of a pointer on the target
2806 // system.
2808 Bvariable*
2809 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2811 Ptrmask ptrmask(ptrdata / ptrsize);
2812 if (ptrdata >= ptrsize)
2813 ptrmask.set_from(gogo, this, ptrsize, 0);
2814 else
2816 // This can happen in error cases. Just build an empty gcbits.
2817 go_assert(saw_errors());
2819 std::string sym_name = "runtime.gcbits." + ptrmask.symname();
2820 Bvariable* bvnull = NULL;
2821 std::pair<GC_gcbits_vars::iterator, bool> ins =
2822 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2823 if (!ins.second)
2825 // We've already built a GC symbol for this set of gcbits.
2826 return ins.first->second;
2829 Expression* val = ptrmask.constructor(gogo);
2830 Translate_context context(gogo, NULL, NULL, NULL);
2831 context.set_is_const();
2832 Bexpression* bval = val->get_backend(&context);
2834 std::string asm_name(go_selectively_encode_id(sym_name));
2835 Btype *btype = val->type()->get_backend(gogo);
2836 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2837 btype, false, true,
2838 true, 0);
2839 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2840 true, true, bval);
2841 ins.first->second = ret;
2842 return ret;
2845 // A GCProg is used to build a program for the garbage collector.
2846 // This is used for types with a lot of pointer data, to reduce the
2847 // size of the data in the compiled program. The program is expanded
2848 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2850 class GCProg
2852 public:
2853 GCProg()
2854 : bytes_(), index_(0), nb_(0)
2857 // The number of bits described so far.
2858 int64_t
2859 bit_index() const
2860 { return this->index_; }
2862 void
2863 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2865 void
2866 end();
2868 Expression*
2869 constructor(Gogo* gogo) const;
2871 private:
2872 void
2873 ptr(int64_t);
2875 bool
2876 should_repeat(int64_t, int64_t);
2878 void
2879 repeat(int64_t, int64_t);
2881 void
2882 zero_until(int64_t);
2884 void
2885 lit(unsigned char);
2887 void
2888 varint(int64_t);
2890 void
2891 flushlit();
2893 // Add a byte to the program.
2894 void
2895 byte(unsigned char x)
2896 { this->bytes_.push_back(x); }
2898 // The maximum number of bytes of literal bits.
2899 static const int max_literal = 127;
2901 // The program.
2902 std::vector<unsigned char> bytes_;
2903 // The index of the last bit described.
2904 int64_t index_;
2905 // The current set of literal bits.
2906 unsigned char b_[max_literal];
2907 // The current number of literal bits.
2908 int nb_;
2911 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2912 // counts in bytes. PTRSIZE is the size of a pointer on the target
2913 // system.
2915 void
2916 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2918 switch (type->base()->classification())
2920 default:
2921 case Type::TYPE_NIL:
2922 case Type::TYPE_CALL_MULTIPLE_RESULT:
2923 case Type::TYPE_NAMED:
2924 case Type::TYPE_FORWARD:
2925 go_unreachable();
2927 case Type::TYPE_ERROR:
2928 case Type::TYPE_VOID:
2929 case Type::TYPE_BOOLEAN:
2930 case Type::TYPE_INTEGER:
2931 case Type::TYPE_FLOAT:
2932 case Type::TYPE_COMPLEX:
2933 case Type::TYPE_SINK:
2934 break;
2936 case Type::TYPE_FUNCTION:
2937 case Type::TYPE_POINTER:
2938 case Type::TYPE_MAP:
2939 case Type::TYPE_CHANNEL:
2940 // These types are all a single pointer.
2941 go_assert((offset % ptrsize) == 0);
2942 this->ptr(offset / ptrsize);
2943 break;
2945 case Type::TYPE_STRING:
2946 // A string starts with a single pointer.
2947 go_assert((offset % ptrsize) == 0);
2948 this->ptr(offset / ptrsize);
2949 break;
2951 case Type::TYPE_INTERFACE:
2952 // An interface is two pointers.
2953 go_assert((offset % ptrsize) == 0);
2954 this->ptr(offset / ptrsize);
2955 this->ptr((offset / ptrsize) + 1);
2956 break;
2958 case Type::TYPE_STRUCT:
2960 if (!type->has_pointer())
2961 return;
2963 const Struct_field_list* fields = type->struct_type()->fields();
2964 int64_t soffset = 0;
2965 for (Struct_field_list::const_iterator pf = fields->begin();
2966 pf != fields->end();
2967 ++pf)
2969 int64_t field_align;
2970 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2972 go_assert(saw_errors());
2973 return;
2975 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2977 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2979 int64_t field_size;
2980 if (!pf->type()->backend_type_size(gogo, &field_size))
2982 go_assert(saw_errors());
2983 return;
2985 soffset += field_size;
2988 break;
2990 case Type::TYPE_ARRAY:
2991 if (type->is_slice_type())
2993 // A slice starts with a single pointer.
2994 go_assert((offset % ptrsize) == 0);
2995 this->ptr(offset / ptrsize);
2996 break;
2998 else
3000 if (!type->has_pointer())
3001 return;
3003 int64_t len;
3004 if (!type->array_type()->int_length(&len))
3006 go_assert(saw_errors());
3007 return;
3010 Type* element_type = type->array_type()->element_type();
3012 // Flatten array of array to a big array by multiplying counts.
3013 while (element_type->array_type() != NULL
3014 && !element_type->is_slice_type())
3016 int64_t ele_len;
3017 if (!element_type->array_type()->int_length(&ele_len))
3019 go_assert(saw_errors());
3020 return;
3023 len *= ele_len;
3024 element_type = element_type->array_type()->element_type();
3027 int64_t ele_size;
3028 if (!element_type->backend_type_size(gogo, &ele_size))
3030 go_assert(saw_errors());
3031 return;
3034 go_assert(len > 0 && ele_size > 0);
3036 if (!this->should_repeat(ele_size / ptrsize, len))
3038 // Cheaper to just emit the bits.
3039 int64_t eoffset = 0;
3040 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3041 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3043 else
3045 go_assert((offset % ptrsize) == 0);
3046 go_assert((ele_size % ptrsize) == 0);
3047 this->set_from(gogo, element_type, ptrsize, offset);
3048 this->zero_until((offset + ele_size) / ptrsize);
3049 this->repeat(ele_size / ptrsize, len - 1);
3052 break;
3057 // Emit a 1 into the bit stream of a GC program at the given bit index.
3059 void
3060 GCProg::ptr(int64_t index)
3062 go_assert(index >= this->index_);
3063 this->zero_until(index);
3064 this->lit(1);
3067 // Return whether it is worthwhile to use a repeat to describe c
3068 // elements of n bits each, compared to just emitting c copies of the
3069 // n-bit description.
3071 bool
3072 GCProg::should_repeat(int64_t n, int64_t c)
3074 // Repeat if there is more than 1 item and if the total data doesn't
3075 // fit into four bytes.
3076 return c > 1 && c * n > 4 * 8;
3079 // Emit an instruction to repeat the description of the last n words c
3080 // times (including the initial description, so c + 1 times in total).
3082 void
3083 GCProg::repeat(int64_t n, int64_t c)
3085 if (n == 0 || c == 0)
3086 return;
3087 this->flushlit();
3088 if (n < 128)
3089 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3090 else
3092 this->byte(0x80);
3093 this->varint(n);
3095 this->varint(c);
3096 this->index_ += n * c;
3099 // Add zeros to the bit stream up to the given index.
3101 void
3102 GCProg::zero_until(int64_t index)
3104 go_assert(index >= this->index_);
3105 int64_t skip = index - this->index_;
3106 if (skip == 0)
3107 return;
3108 if (skip < 4 * 8)
3110 for (int64_t i = 0; i < skip; ++i)
3111 this->lit(0);
3112 return;
3114 this->lit(0);
3115 this->flushlit();
3116 this->repeat(1, skip - 1);
3119 // Add a single literal bit to the program.
3121 void
3122 GCProg::lit(unsigned char x)
3124 if (this->nb_ == GCProg::max_literal)
3125 this->flushlit();
3126 this->b_[this->nb_] = x;
3127 ++this->nb_;
3128 ++this->index_;
3131 // Emit the varint encoding of x.
3133 void
3134 GCProg::varint(int64_t x)
3136 go_assert(x >= 0);
3137 while (x >= 0x80)
3139 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3140 x >>= 7;
3142 this->byte(static_cast<unsigned char>(x & 0x7f));
3145 // Flush any pending literal bits.
3147 void
3148 GCProg::flushlit()
3150 if (this->nb_ == 0)
3151 return;
3152 this->byte(static_cast<unsigned char>(this->nb_));
3153 unsigned char bits = 0;
3154 for (int i = 0; i < this->nb_; ++i)
3156 bits |= this->b_[i] << (i % 8);
3157 if ((i + 1) % 8 == 0)
3159 this->byte(bits);
3160 bits = 0;
3163 if (this->nb_ % 8 != 0)
3164 this->byte(bits);
3165 this->nb_ = 0;
3168 // Mark the end of a GC program.
3170 void
3171 GCProg::end()
3173 this->flushlit();
3174 this->byte(0);
3177 // Return an Expression for the bytes in a GC program.
3179 Expression*
3180 GCProg::constructor(Gogo* gogo) const
3182 Location bloc = Linemap::predeclared_location();
3184 // The first four bytes are the length of the program in target byte
3185 // order. Build a struct whose first type is uint32 to make this
3186 // work.
3188 Type* uint32_type = Type::lookup_integer_type("uint32");
3190 Type* byte_type = gogo->lookup_global("byte")->type_value();
3191 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3192 bloc);
3193 Array_type* at = Type::make_array_type(byte_type, len);
3195 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3196 "bytes", at);
3198 Expression_list* vals = new Expression_list();
3199 vals->reserve(this->bytes_.size());
3200 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3201 p != this->bytes_.end();
3202 ++p)
3203 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3204 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3206 vals = new Expression_list();
3207 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3208 bloc));
3209 vals->push_back(bytes);
3211 return Expression::make_struct_composite_literal(st, vals, bloc);
3214 // Return a composite literal for the garbage collection program for
3215 // this type. This is only used for types that are too large to use a
3216 // ptrmask.
3218 Expression*
3219 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3221 Location bloc = Linemap::predeclared_location();
3223 GCProg prog;
3224 prog.set_from(gogo, this, ptrsize, 0);
3225 int64_t offset = prog.bit_index() * ptrsize;
3226 prog.end();
3228 int64_t type_size;
3229 if (!this->backend_type_size(gogo, &type_size))
3231 go_assert(saw_errors());
3232 return Expression::make_error(bloc);
3235 go_assert(offset >= ptrdata && offset <= type_size);
3237 return prog.constructor(gogo);
3240 // Return a composite literal for the uncommon type information for
3241 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3242 // struct. If name is not NULL, it is the name of the type. If
3243 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3244 // is true if only value methods should be included. At least one of
3245 // NAME and METHODS must not be NULL.
3247 Expression*
3248 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3249 Named_type* name, const Methods* methods,
3250 bool only_value_methods) const
3252 Location bloc = Linemap::predeclared_location();
3254 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3256 Expression_list* vals = new Expression_list();
3257 vals->reserve(3);
3259 Struct_field_list::const_iterator p = fields->begin();
3260 go_assert(p->is_field_name("name"));
3262 ++p;
3263 go_assert(p->is_field_name("pkgPath"));
3265 if (name == NULL)
3267 vals->push_back(Expression::make_nil(bloc));
3268 vals->push_back(Expression::make_nil(bloc));
3270 else
3272 Named_object* no = name->named_object();
3273 std::string n = Gogo::unpack_hidden_name(no->name());
3274 Expression* s = Expression::make_string(n, bloc);
3275 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3277 if (name->is_builtin())
3278 vals->push_back(Expression::make_nil(bloc));
3279 else
3281 const Package* package = no->package();
3282 const std::string& pkgpath(package == NULL
3283 ? gogo->pkgpath()
3284 : package->pkgpath());
3285 s = Expression::make_string(pkgpath, bloc);
3286 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3290 ++p;
3291 go_assert(p->is_field_name("methods"));
3292 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3293 only_value_methods));
3295 ++p;
3296 go_assert(p == fields->end());
3298 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3299 vals, bloc);
3300 return Expression::make_unary(OPERATOR_AND, r, bloc);
3303 // Sort methods by name.
3305 class Sort_methods
3307 public:
3308 bool
3309 operator()(const std::pair<std::string, const Method*>& m1,
3310 const std::pair<std::string, const Method*>& m2) const
3312 return (Gogo::unpack_hidden_name(m1.first)
3313 < Gogo::unpack_hidden_name(m2.first));
3317 // Return a composite literal for the type method table for this type.
3318 // METHODS_TYPE is the type of the table, and is a slice type.
3319 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3320 // then only value methods are used.
3322 Expression*
3323 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3324 const Methods* methods,
3325 bool only_value_methods) const
3327 Location bloc = Linemap::predeclared_location();
3329 std::vector<std::pair<std::string, const Method*> > smethods;
3330 if (methods != NULL)
3332 smethods.reserve(methods->count());
3333 for (Methods::const_iterator p = methods->begin();
3334 p != methods->end();
3335 ++p)
3337 if (p->second->is_ambiguous())
3338 continue;
3339 if (only_value_methods && !p->second->is_value_method())
3340 continue;
3342 // This is where we implement the magic //go:nointerface
3343 // comment. If we saw that comment, we don't add this
3344 // method to the type descriptor.
3345 if (p->second->nointerface())
3346 continue;
3348 smethods.push_back(std::make_pair(p->first, p->second));
3352 if (smethods.empty())
3353 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3355 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3357 Type* method_type = methods_type->array_type()->element_type();
3359 Expression_list* vals = new Expression_list();
3360 vals->reserve(smethods.size());
3361 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3362 = smethods.begin();
3363 p != smethods.end();
3364 ++p)
3365 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3366 p->second, only_value_methods));
3368 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3371 // Return a composite literal for a single method. METHOD_TYPE is the
3372 // type of the entry. METHOD_NAME is the name of the method and M is
3373 // the method information.
3375 Expression*
3376 Type::method_constructor(Gogo*, Type* method_type,
3377 const std::string& method_name,
3378 const Method* m,
3379 bool only_value_methods) const
3381 Location bloc = Linemap::predeclared_location();
3383 const Struct_field_list* fields = method_type->struct_type()->fields();
3385 Expression_list* vals = new Expression_list();
3386 vals->reserve(5);
3388 Struct_field_list::const_iterator p = fields->begin();
3389 go_assert(p->is_field_name("name"));
3390 const std::string n = Gogo::unpack_hidden_name(method_name);
3391 Expression* s = Expression::make_string(n, bloc);
3392 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3394 ++p;
3395 go_assert(p->is_field_name("pkgPath"));
3396 if (!Gogo::is_hidden_name(method_name))
3397 vals->push_back(Expression::make_nil(bloc));
3398 else
3400 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3401 bloc);
3402 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3405 Named_object* no = (m->needs_stub_method()
3406 ? m->stub_object()
3407 : m->named_object());
3409 Function_type* mtype;
3410 if (no->is_function())
3411 mtype = no->func_value()->type();
3412 else
3413 mtype = no->func_declaration_value()->type();
3414 go_assert(mtype->is_method());
3415 Type* nonmethod_type = mtype->copy_without_receiver();
3417 ++p;
3418 go_assert(p->is_field_name("mtyp"));
3419 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3421 ++p;
3422 go_assert(p->is_field_name("typ"));
3423 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3424 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3425 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3427 ++p;
3428 go_assert(p->is_field_name("tfn"));
3429 vals->push_back(Expression::make_func_code_reference(no, bloc));
3431 ++p;
3432 go_assert(p == fields->end());
3434 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3437 // Return a composite literal for the type descriptor of a plain type.
3438 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3439 // NULL, it is the name to use as well as the list of methods.
3441 Expression*
3442 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3443 Named_type* name)
3445 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3446 name, NULL, true);
3449 // Return the type reflection string for this type.
3451 std::string
3452 Type::reflection(Gogo* gogo) const
3454 std::string ret;
3456 // The do_reflection virtual function should set RET to the
3457 // reflection string.
3458 this->do_reflection(gogo, &ret);
3460 return ret;
3463 // Return a mangled name for the type.
3465 std::string
3466 Type::mangled_name(Gogo* gogo) const
3468 std::string ret;
3470 // The do_mangled_name virtual function should set RET to the
3471 // mangled name. For a composite type it should append a code for
3472 // the composition and then call do_mangled_name on the components.
3473 this->do_mangled_name(gogo, &ret);
3475 return ret;
3478 // Return whether the backend size of the type is known.
3480 bool
3481 Type::is_backend_type_size_known(Gogo* gogo)
3483 switch (this->classification_)
3485 case TYPE_ERROR:
3486 case TYPE_VOID:
3487 case TYPE_BOOLEAN:
3488 case TYPE_INTEGER:
3489 case TYPE_FLOAT:
3490 case TYPE_COMPLEX:
3491 case TYPE_STRING:
3492 case TYPE_FUNCTION:
3493 case TYPE_POINTER:
3494 case TYPE_NIL:
3495 case TYPE_MAP:
3496 case TYPE_CHANNEL:
3497 case TYPE_INTERFACE:
3498 return true;
3500 case TYPE_STRUCT:
3502 const Struct_field_list* fields = this->struct_type()->fields();
3503 for (Struct_field_list::const_iterator pf = fields->begin();
3504 pf != fields->end();
3505 ++pf)
3506 if (!pf->type()->is_backend_type_size_known(gogo))
3507 return false;
3508 return true;
3511 case TYPE_ARRAY:
3513 const Array_type* at = this->array_type();
3514 if (at->length() == NULL)
3515 return true;
3516 else
3518 Numeric_constant nc;
3519 if (!at->length()->numeric_constant_value(&nc))
3520 return false;
3521 mpz_t ival;
3522 if (!nc.to_int(&ival))
3523 return false;
3524 mpz_clear(ival);
3525 return at->element_type()->is_backend_type_size_known(gogo);
3529 case TYPE_NAMED:
3530 this->named_type()->convert(gogo);
3531 return this->named_type()->is_named_backend_type_size_known();
3533 case TYPE_FORWARD:
3535 Forward_declaration_type* fdt = this->forward_declaration_type();
3536 return fdt->real_type()->is_backend_type_size_known(gogo);
3539 case TYPE_SINK:
3540 case TYPE_CALL_MULTIPLE_RESULT:
3541 go_unreachable();
3543 default:
3544 go_unreachable();
3548 // If the size of the type can be determined, set *PSIZE to the size
3549 // in bytes and return true. Otherwise, return false. This queries
3550 // the backend.
3552 bool
3553 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3555 if (!this->is_backend_type_size_known(gogo))
3556 return false;
3557 if (this->is_error_type())
3558 return false;
3559 Btype* bt = this->get_backend_placeholder(gogo);
3560 *psize = gogo->backend()->type_size(bt);
3561 if (*psize == -1)
3563 if (this->named_type() != NULL)
3564 go_error_at(this->named_type()->location(),
3565 "type %s larger than address space",
3566 Gogo::message_name(this->named_type()->name()).c_str());
3567 else
3568 go_error_at(Linemap::unknown_location(),
3569 "type %s larger than address space",
3570 this->reflection(gogo).c_str());
3572 // Make this an error type to avoid knock-on errors.
3573 this->classification_ = TYPE_ERROR;
3574 return false;
3576 return true;
3579 // If the alignment of the type can be determined, set *PALIGN to
3580 // the alignment in bytes and return true. Otherwise, return false.
3582 bool
3583 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3585 if (!this->is_backend_type_size_known(gogo))
3586 return false;
3587 Btype* bt = this->get_backend_placeholder(gogo);
3588 *palign = gogo->backend()->type_alignment(bt);
3589 return true;
3592 // Like backend_type_align, but return the alignment when used as a
3593 // field.
3595 bool
3596 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3598 if (!this->is_backend_type_size_known(gogo))
3599 return false;
3600 Btype* bt = this->get_backend_placeholder(gogo);
3601 *palign = gogo->backend()->type_field_alignment(bt);
3602 return true;
3605 // Get the ptrdata value for a type. This is the size of the prefix
3606 // of the type that contains all pointers. Store the ptrdata in
3607 // *PPTRDATA and return whether we found it.
3609 bool
3610 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3612 *pptrdata = 0;
3614 if (!this->has_pointer())
3615 return true;
3617 if (!this->is_backend_type_size_known(gogo))
3618 return false;
3620 switch (this->classification_)
3622 case TYPE_ERROR:
3623 return true;
3625 case TYPE_FUNCTION:
3626 case TYPE_POINTER:
3627 case TYPE_MAP:
3628 case TYPE_CHANNEL:
3629 // These types are nothing but a pointer.
3630 return this->backend_type_size(gogo, pptrdata);
3632 case TYPE_INTERFACE:
3633 // An interface is a struct of two pointers.
3634 return this->backend_type_size(gogo, pptrdata);
3636 case TYPE_STRING:
3638 // A string is a struct whose first field is a pointer, and
3639 // whose second field is not.
3640 Type* uint8_type = Type::lookup_integer_type("uint8");
3641 Type* ptr = Type::make_pointer_type(uint8_type);
3642 return ptr->backend_type_size(gogo, pptrdata);
3645 case TYPE_NAMED:
3646 case TYPE_FORWARD:
3647 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3649 case TYPE_STRUCT:
3651 const Struct_field_list* fields = this->struct_type()->fields();
3652 int64_t offset = 0;
3653 const Struct_field *ptr = NULL;
3654 int64_t ptr_offset = 0;
3655 for (Struct_field_list::const_iterator pf = fields->begin();
3656 pf != fields->end();
3657 ++pf)
3659 int64_t field_align;
3660 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3661 return false;
3662 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3664 if (pf->type()->has_pointer())
3666 ptr = &*pf;
3667 ptr_offset = offset;
3670 int64_t field_size;
3671 if (!pf->type()->backend_type_size(gogo, &field_size))
3672 return false;
3673 offset += field_size;
3676 if (ptr != NULL)
3678 int64_t ptr_ptrdata;
3679 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3680 return false;
3681 *pptrdata = ptr_offset + ptr_ptrdata;
3683 return true;
3686 case TYPE_ARRAY:
3687 if (this->is_slice_type())
3689 // A slice is a struct whose first field is a pointer, and
3690 // whose remaining fields are not.
3691 Type* element_type = this->array_type()->element_type();
3692 Type* ptr = Type::make_pointer_type(element_type);
3693 return ptr->backend_type_size(gogo, pptrdata);
3695 else
3697 Numeric_constant nc;
3698 if (!this->array_type()->length()->numeric_constant_value(&nc))
3699 return false;
3700 int64_t len;
3701 if (!nc.to_memory_size(&len))
3702 return false;
3704 Type* element_type = this->array_type()->element_type();
3705 int64_t ele_size;
3706 int64_t ele_ptrdata;
3707 if (!element_type->backend_type_size(gogo, &ele_size)
3708 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3709 return false;
3710 go_assert(ele_size > 0 && ele_ptrdata > 0);
3712 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3713 return true;
3716 default:
3717 case TYPE_VOID:
3718 case TYPE_BOOLEAN:
3719 case TYPE_INTEGER:
3720 case TYPE_FLOAT:
3721 case TYPE_COMPLEX:
3722 case TYPE_SINK:
3723 case TYPE_NIL:
3724 case TYPE_CALL_MULTIPLE_RESULT:
3725 go_unreachable();
3729 // Get the ptrdata value to store in a type descriptor. This is
3730 // normally the same as backend_type_ptrdata, but for a type that is
3731 // large enough to use a gcprog we may need to store a different value
3732 // if it ends with an array. If the gcprog uses a repeat descriptor
3733 // for the array, and if the array element ends with non-pointer data,
3734 // then the gcprog will produce a value that describes the complete
3735 // array where the backend ptrdata will omit the non-pointer elements
3736 // of the final array element. This is a subtle difference but the
3737 // run time code checks it to verify that it has expanded a gcprog as
3738 // expected.
3740 bool
3741 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3743 int64_t backend_ptrdata;
3744 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3745 return false;
3747 int64_t ptrsize;
3748 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3750 *pptrdata = backend_ptrdata;
3751 return true;
3754 GCProg prog;
3755 prog.set_from(gogo, this, ptrsize, 0);
3756 int64_t offset = prog.bit_index() * ptrsize;
3758 go_assert(offset >= backend_ptrdata);
3759 *pptrdata = offset;
3760 return true;
3763 // Default function to export a type.
3765 void
3766 Type::do_export(Export*) const
3768 go_unreachable();
3771 // Import a type.
3773 Type*
3774 Type::import_type(Import* imp)
3776 if (imp->match_c_string("("))
3777 return Function_type::do_import(imp);
3778 else if (imp->match_c_string("*"))
3779 return Pointer_type::do_import(imp);
3780 else if (imp->match_c_string("struct "))
3781 return Struct_type::do_import(imp);
3782 else if (imp->match_c_string("["))
3783 return Array_type::do_import(imp);
3784 else if (imp->match_c_string("map "))
3785 return Map_type::do_import(imp);
3786 else if (imp->match_c_string("chan "))
3787 return Channel_type::do_import(imp);
3788 else if (imp->match_c_string("interface"))
3789 return Interface_type::do_import(imp);
3790 else
3792 go_error_at(imp->location(), "import error: expected type");
3793 return Type::make_error_type();
3797 // A type used to indicate a parsing error. This exists to simplify
3798 // later error detection.
3800 class Error_type : public Type
3802 public:
3803 Error_type()
3804 : Type(TYPE_ERROR)
3807 protected:
3808 bool
3809 do_compare_is_identity(Gogo*)
3810 { return false; }
3812 Btype*
3813 do_get_backend(Gogo* gogo)
3814 { return gogo->backend()->error_type(); }
3816 Expression*
3817 do_type_descriptor(Gogo*, Named_type*)
3818 { return Expression::make_error(Linemap::predeclared_location()); }
3820 void
3821 do_reflection(Gogo*, std::string*) const
3822 { go_assert(saw_errors()); }
3824 void
3825 do_mangled_name(Gogo*, std::string* ret) const
3826 { ret->push_back('E'); }
3829 Type*
3830 Type::make_error_type()
3832 static Error_type singleton_error_type;
3833 return &singleton_error_type;
3836 // The void type.
3838 class Void_type : public Type
3840 public:
3841 Void_type()
3842 : Type(TYPE_VOID)
3845 protected:
3846 bool
3847 do_compare_is_identity(Gogo*)
3848 { return false; }
3850 Btype*
3851 do_get_backend(Gogo* gogo)
3852 { return gogo->backend()->void_type(); }
3854 Expression*
3855 do_type_descriptor(Gogo*, Named_type*)
3856 { go_unreachable(); }
3858 void
3859 do_reflection(Gogo*, std::string*) const
3862 void
3863 do_mangled_name(Gogo*, std::string* ret) const
3864 { ret->push_back('v'); }
3867 Type*
3868 Type::make_void_type()
3870 static Void_type singleton_void_type;
3871 return &singleton_void_type;
3874 // The boolean type.
3876 class Boolean_type : public Type
3878 public:
3879 Boolean_type()
3880 : Type(TYPE_BOOLEAN)
3883 protected:
3884 bool
3885 do_compare_is_identity(Gogo*)
3886 { return true; }
3888 Btype*
3889 do_get_backend(Gogo* gogo)
3890 { return gogo->backend()->bool_type(); }
3892 Expression*
3893 do_type_descriptor(Gogo*, Named_type* name);
3895 // We should not be asked for the reflection string of a basic type.
3896 void
3897 do_reflection(Gogo*, std::string* ret) const
3898 { ret->append("bool"); }
3900 void
3901 do_mangled_name(Gogo*, std::string* ret) const
3902 { ret->push_back('b'); }
3905 // Make the type descriptor.
3907 Expression*
3908 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3910 if (name != NULL)
3911 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3912 else
3914 Named_object* no = gogo->lookup_global("bool");
3915 go_assert(no != NULL);
3916 return Type::type_descriptor(gogo, no->type_value());
3920 Type*
3921 Type::make_boolean_type()
3923 static Boolean_type boolean_type;
3924 return &boolean_type;
3927 // The named type "bool".
3929 static Named_type* named_bool_type;
3931 // Get the named type "bool".
3933 Named_type*
3934 Type::lookup_bool_type()
3936 return named_bool_type;
3939 // Make the named type "bool".
3941 Named_type*
3942 Type::make_named_bool_type()
3944 Type* bool_type = Type::make_boolean_type();
3945 Named_object* named_object =
3946 Named_object::make_type("bool", NULL, bool_type,
3947 Linemap::predeclared_location());
3948 Named_type* named_type = named_object->type_value();
3949 named_bool_type = named_type;
3950 return named_type;
3953 // Class Integer_type.
3955 Integer_type::Named_integer_types Integer_type::named_integer_types;
3957 // Create a new integer type. Non-abstract integer types always have
3958 // names.
3960 Named_type*
3961 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3962 int bits, int runtime_type_kind)
3964 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3965 runtime_type_kind);
3966 std::string sname(name);
3967 Named_object* named_object =
3968 Named_object::make_type(sname, NULL, integer_type,
3969 Linemap::predeclared_location());
3970 Named_type* named_type = named_object->type_value();
3971 std::pair<Named_integer_types::iterator, bool> ins =
3972 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3973 go_assert(ins.second);
3974 return named_type;
3977 // Look up an existing integer type.
3979 Named_type*
3980 Integer_type::lookup_integer_type(const char* name)
3982 Named_integer_types::const_iterator p =
3983 Integer_type::named_integer_types.find(name);
3984 go_assert(p != Integer_type::named_integer_types.end());
3985 return p->second;
3988 // Create a new abstract integer type.
3990 Integer_type*
3991 Integer_type::create_abstract_integer_type()
3993 static Integer_type* abstract_type;
3994 if (abstract_type == NULL)
3996 Type* int_type = Type::lookup_integer_type("int");
3997 abstract_type = new Integer_type(true, false,
3998 int_type->integer_type()->bits(),
3999 RUNTIME_TYPE_KIND_INT);
4001 return abstract_type;
4004 // Create a new abstract character type.
4006 Integer_type*
4007 Integer_type::create_abstract_character_type()
4009 static Integer_type* abstract_type;
4010 if (abstract_type == NULL)
4012 abstract_type = new Integer_type(true, false, 32,
4013 RUNTIME_TYPE_KIND_INT32);
4014 abstract_type->set_is_rune();
4016 return abstract_type;
4019 // Integer type compatibility.
4021 bool
4022 Integer_type::is_identical(const Integer_type* t) const
4024 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
4025 return false;
4026 return this->is_abstract_ == t->is_abstract_;
4029 // Hash code.
4031 unsigned int
4032 Integer_type::do_hash_for_method(Gogo*) const
4034 return ((this->bits_ << 4)
4035 + ((this->is_unsigned_ ? 1 : 0) << 8)
4036 + ((this->is_abstract_ ? 1 : 0) << 9));
4039 // Convert an Integer_type to the backend representation.
4041 Btype*
4042 Integer_type::do_get_backend(Gogo* gogo)
4044 if (this->is_abstract_)
4046 go_assert(saw_errors());
4047 return gogo->backend()->error_type();
4049 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4052 // The type descriptor for an integer type. Integer types are always
4053 // named.
4055 Expression*
4056 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4058 go_assert(name != NULL || saw_errors());
4059 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4062 // We should not be asked for the reflection string of a basic type.
4064 void
4065 Integer_type::do_reflection(Gogo*, std::string*) const
4067 go_assert(saw_errors());
4070 // Mangled name.
4072 void
4073 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
4075 char buf[100];
4076 snprintf(buf, sizeof buf, "i%s%s%de",
4077 this->is_abstract_ ? "a" : "",
4078 this->is_unsigned_ ? "u" : "",
4079 this->bits_);
4080 ret->append(buf);
4083 // Make an integer type.
4085 Named_type*
4086 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4087 int runtime_type_kind)
4089 return Integer_type::create_integer_type(name, is_unsigned, bits,
4090 runtime_type_kind);
4093 // Make an abstract integer type.
4095 Integer_type*
4096 Type::make_abstract_integer_type()
4098 return Integer_type::create_abstract_integer_type();
4101 // Make an abstract character type.
4103 Integer_type*
4104 Type::make_abstract_character_type()
4106 return Integer_type::create_abstract_character_type();
4109 // Look up an integer type.
4111 Named_type*
4112 Type::lookup_integer_type(const char* name)
4114 return Integer_type::lookup_integer_type(name);
4117 // Class Float_type.
4119 Float_type::Named_float_types Float_type::named_float_types;
4121 // Create a new float type. Non-abstract float types always have
4122 // names.
4124 Named_type*
4125 Float_type::create_float_type(const char* name, int bits,
4126 int runtime_type_kind)
4128 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4129 std::string sname(name);
4130 Named_object* named_object =
4131 Named_object::make_type(sname, NULL, float_type,
4132 Linemap::predeclared_location());
4133 Named_type* named_type = named_object->type_value();
4134 std::pair<Named_float_types::iterator, bool> ins =
4135 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4136 go_assert(ins.second);
4137 return named_type;
4140 // Look up an existing float type.
4142 Named_type*
4143 Float_type::lookup_float_type(const char* name)
4145 Named_float_types::const_iterator p =
4146 Float_type::named_float_types.find(name);
4147 go_assert(p != Float_type::named_float_types.end());
4148 return p->second;
4151 // Create a new abstract float type.
4153 Float_type*
4154 Float_type::create_abstract_float_type()
4156 static Float_type* abstract_type;
4157 if (abstract_type == NULL)
4158 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4159 return abstract_type;
4162 // Whether this type is identical with T.
4164 bool
4165 Float_type::is_identical(const Float_type* t) const
4167 if (this->bits_ != t->bits_)
4168 return false;
4169 return this->is_abstract_ == t->is_abstract_;
4172 // Hash code.
4174 unsigned int
4175 Float_type::do_hash_for_method(Gogo*) const
4177 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4180 // Convert to the backend representation.
4182 Btype*
4183 Float_type::do_get_backend(Gogo* gogo)
4185 return gogo->backend()->float_type(this->bits_);
4188 // The type descriptor for a float type. Float types are always named.
4190 Expression*
4191 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4193 go_assert(name != NULL || saw_errors());
4194 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4197 // We should not be asked for the reflection string of a basic type.
4199 void
4200 Float_type::do_reflection(Gogo*, std::string*) const
4202 go_assert(saw_errors());
4205 // Mangled name.
4207 void
4208 Float_type::do_mangled_name(Gogo*, std::string* ret) const
4210 char buf[100];
4211 snprintf(buf, sizeof buf, "f%s%de",
4212 this->is_abstract_ ? "a" : "",
4213 this->bits_);
4214 ret->append(buf);
4217 // Make a floating point type.
4219 Named_type*
4220 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4222 return Float_type::create_float_type(name, bits, runtime_type_kind);
4225 // Make an abstract float type.
4227 Float_type*
4228 Type::make_abstract_float_type()
4230 return Float_type::create_abstract_float_type();
4233 // Look up a float type.
4235 Named_type*
4236 Type::lookup_float_type(const char* name)
4238 return Float_type::lookup_float_type(name);
4241 // Class Complex_type.
4243 Complex_type::Named_complex_types Complex_type::named_complex_types;
4245 // Create a new complex type. Non-abstract complex types always have
4246 // names.
4248 Named_type*
4249 Complex_type::create_complex_type(const char* name, int bits,
4250 int runtime_type_kind)
4252 Complex_type* complex_type = new Complex_type(false, bits,
4253 runtime_type_kind);
4254 std::string sname(name);
4255 Named_object* named_object =
4256 Named_object::make_type(sname, NULL, complex_type,
4257 Linemap::predeclared_location());
4258 Named_type* named_type = named_object->type_value();
4259 std::pair<Named_complex_types::iterator, bool> ins =
4260 Complex_type::named_complex_types.insert(std::make_pair(sname,
4261 named_type));
4262 go_assert(ins.second);
4263 return named_type;
4266 // Look up an existing complex type.
4268 Named_type*
4269 Complex_type::lookup_complex_type(const char* name)
4271 Named_complex_types::const_iterator p =
4272 Complex_type::named_complex_types.find(name);
4273 go_assert(p != Complex_type::named_complex_types.end());
4274 return p->second;
4277 // Create a new abstract complex type.
4279 Complex_type*
4280 Complex_type::create_abstract_complex_type()
4282 static Complex_type* abstract_type;
4283 if (abstract_type == NULL)
4284 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4285 return abstract_type;
4288 // Whether this type is identical with T.
4290 bool
4291 Complex_type::is_identical(const Complex_type *t) const
4293 if (this->bits_ != t->bits_)
4294 return false;
4295 return this->is_abstract_ == t->is_abstract_;
4298 // Hash code.
4300 unsigned int
4301 Complex_type::do_hash_for_method(Gogo*) const
4303 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4306 // Convert to the backend representation.
4308 Btype*
4309 Complex_type::do_get_backend(Gogo* gogo)
4311 return gogo->backend()->complex_type(this->bits_);
4314 // The type descriptor for a complex type. Complex types are always
4315 // named.
4317 Expression*
4318 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4320 go_assert(name != NULL || saw_errors());
4321 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4324 // We should not be asked for the reflection string of a basic type.
4326 void
4327 Complex_type::do_reflection(Gogo*, std::string*) const
4329 go_assert(saw_errors());
4332 // Mangled name.
4334 void
4335 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
4337 char buf[100];
4338 snprintf(buf, sizeof buf, "c%s%de",
4339 this->is_abstract_ ? "a" : "",
4340 this->bits_);
4341 ret->append(buf);
4344 // Make a complex type.
4346 Named_type*
4347 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4349 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4352 // Make an abstract complex type.
4354 Complex_type*
4355 Type::make_abstract_complex_type()
4357 return Complex_type::create_abstract_complex_type();
4360 // Look up a complex type.
4362 Named_type*
4363 Type::lookup_complex_type(const char* name)
4365 return Complex_type::lookup_complex_type(name);
4368 // Class String_type.
4370 // Convert String_type to the backend representation. A string is a
4371 // struct with two fields: a pointer to the characters and a length.
4373 Btype*
4374 String_type::do_get_backend(Gogo* gogo)
4376 static Btype* backend_string_type;
4377 if (backend_string_type == NULL)
4379 std::vector<Backend::Btyped_identifier> fields(2);
4381 Type* b = gogo->lookup_global("byte")->type_value();
4382 Type* pb = Type::make_pointer_type(b);
4384 // We aren't going to get back to this field to finish the
4385 // backend representation, so force it to be finished now.
4386 if (!gogo->named_types_are_converted())
4388 Btype* bt = pb->get_backend_placeholder(gogo);
4389 pb->finish_backend(gogo, bt);
4392 fields[0].name = "__data";
4393 fields[0].btype = pb->get_backend(gogo);
4394 fields[0].location = Linemap::predeclared_location();
4396 Type* int_type = Type::lookup_integer_type("int");
4397 fields[1].name = "__length";
4398 fields[1].btype = int_type->get_backend(gogo);
4399 fields[1].location = fields[0].location;
4401 backend_string_type = gogo->backend()->struct_type(fields);
4403 return backend_string_type;
4406 // The type descriptor for the string type.
4408 Expression*
4409 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4411 if (name != NULL)
4412 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4413 else
4415 Named_object* no = gogo->lookup_global("string");
4416 go_assert(no != NULL);
4417 return Type::type_descriptor(gogo, no->type_value());
4421 // We should not be asked for the reflection string of a basic type.
4423 void
4424 String_type::do_reflection(Gogo*, std::string* ret) const
4426 ret->append("string");
4429 // Mangled name of a string type.
4431 void
4432 String_type::do_mangled_name(Gogo*, std::string* ret) const
4434 ret->push_back('z');
4437 // Make a string type.
4439 Type*
4440 Type::make_string_type()
4442 static String_type string_type;
4443 return &string_type;
4446 // The named type "string".
4448 static Named_type* named_string_type;
4450 // Get the named type "string".
4452 Named_type*
4453 Type::lookup_string_type()
4455 return named_string_type;
4458 // Make the named type string.
4460 Named_type*
4461 Type::make_named_string_type()
4463 Type* string_type = Type::make_string_type();
4464 Named_object* named_object =
4465 Named_object::make_type("string", NULL, string_type,
4466 Linemap::predeclared_location());
4467 Named_type* named_type = named_object->type_value();
4468 named_string_type = named_type;
4469 return named_type;
4472 // The sink type. This is the type of the blank identifier _. Any
4473 // type may be assigned to it.
4475 class Sink_type : public Type
4477 public:
4478 Sink_type()
4479 : Type(TYPE_SINK)
4482 protected:
4483 bool
4484 do_compare_is_identity(Gogo*)
4485 { return false; }
4487 Btype*
4488 do_get_backend(Gogo*)
4489 { go_unreachable(); }
4491 Expression*
4492 do_type_descriptor(Gogo*, Named_type*)
4493 { go_unreachable(); }
4495 void
4496 do_reflection(Gogo*, std::string*) const
4497 { go_unreachable(); }
4499 void
4500 do_mangled_name(Gogo*, std::string*) const
4501 { go_unreachable(); }
4504 // Make the sink type.
4506 Type*
4507 Type::make_sink_type()
4509 static Sink_type sink_type;
4510 return &sink_type;
4513 // Class Function_type.
4515 // Traversal.
4518 Function_type::do_traverse(Traverse* traverse)
4520 if (this->receiver_ != NULL
4521 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4522 return TRAVERSE_EXIT;
4523 if (this->parameters_ != NULL
4524 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4525 return TRAVERSE_EXIT;
4526 if (this->results_ != NULL
4527 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4528 return TRAVERSE_EXIT;
4529 return TRAVERSE_CONTINUE;
4532 // Returns whether T is a valid redeclaration of this type. If this
4533 // returns false, and REASON is not NULL, *REASON may be set to a
4534 // brief explanation of why it returned false.
4536 bool
4537 Function_type::is_valid_redeclaration(const Function_type* t,
4538 std::string* reason) const
4540 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4541 return false;
4543 // A redeclaration of a function is required to use the same names
4544 // for the receiver and parameters.
4545 if (this->receiver() != NULL
4546 && this->receiver()->name() != t->receiver()->name())
4548 if (reason != NULL)
4549 *reason = "receiver name changed";
4550 return false;
4553 const Typed_identifier_list* parms1 = this->parameters();
4554 const Typed_identifier_list* parms2 = t->parameters();
4555 if (parms1 != NULL)
4557 Typed_identifier_list::const_iterator p1 = parms1->begin();
4558 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4559 p2 != parms2->end();
4560 ++p2, ++p1)
4562 if (p1->name() != p2->name())
4564 if (reason != NULL)
4565 *reason = "parameter name changed";
4566 return false;
4569 // This is called at parse time, so we may have unknown
4570 // types.
4571 Type* t1 = p1->type()->forwarded();
4572 Type* t2 = p2->type()->forwarded();
4573 if (t1 != t2
4574 && t1->forward_declaration_type() != NULL
4575 && (t2->forward_declaration_type() == NULL
4576 || (t1->forward_declaration_type()->named_object()
4577 != t2->forward_declaration_type()->named_object())))
4578 return false;
4582 const Typed_identifier_list* results1 = this->results();
4583 const Typed_identifier_list* results2 = t->results();
4584 if (results1 != NULL)
4586 Typed_identifier_list::const_iterator res1 = results1->begin();
4587 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4588 res2 != results2->end();
4589 ++res2, ++res1)
4591 if (res1->name() != res2->name())
4593 if (reason != NULL)
4594 *reason = "result name changed";
4595 return false;
4598 // This is called at parse time, so we may have unknown
4599 // types.
4600 Type* t1 = res1->type()->forwarded();
4601 Type* t2 = res2->type()->forwarded();
4602 if (t1 != t2
4603 && t1->forward_declaration_type() != NULL
4604 && (t2->forward_declaration_type() == NULL
4605 || (t1->forward_declaration_type()->named_object()
4606 != t2->forward_declaration_type()->named_object())))
4607 return false;
4611 return true;
4614 // Check whether T is the same as this type.
4616 bool
4617 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4618 Cmp_tags cmp_tags, bool errors_are_identical,
4619 std::string* reason) const
4621 if (!ignore_receiver)
4623 const Typed_identifier* r1 = this->receiver();
4624 const Typed_identifier* r2 = t->receiver();
4625 if ((r1 != NULL) != (r2 != NULL))
4627 if (reason != NULL)
4628 *reason = _("different receiver types");
4629 return false;
4631 if (r1 != NULL)
4633 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4634 errors_are_identical, reason))
4636 if (reason != NULL && !reason->empty())
4637 *reason = "receiver: " + *reason;
4638 return false;
4643 const Typed_identifier_list* parms1 = this->parameters();
4644 const Typed_identifier_list* parms2 = t->parameters();
4645 if ((parms1 != NULL) != (parms2 != NULL))
4647 if (reason != NULL)
4648 *reason = _("different number of parameters");
4649 return false;
4651 if (parms1 != NULL)
4653 Typed_identifier_list::const_iterator p1 = parms1->begin();
4654 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4655 p2 != parms2->end();
4656 ++p2, ++p1)
4658 if (p1 == parms1->end())
4660 if (reason != NULL)
4661 *reason = _("different number of parameters");
4662 return false;
4665 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4666 errors_are_identical, NULL))
4668 if (reason != NULL)
4669 *reason = _("different parameter types");
4670 return false;
4673 if (p1 != parms1->end())
4675 if (reason != NULL)
4676 *reason = _("different number of parameters");
4677 return false;
4681 if (this->is_varargs() != t->is_varargs())
4683 if (reason != NULL)
4684 *reason = _("different varargs");
4685 return false;
4688 const Typed_identifier_list* results1 = this->results();
4689 const Typed_identifier_list* results2 = t->results();
4690 if ((results1 != NULL) != (results2 != NULL))
4692 if (reason != NULL)
4693 *reason = _("different number of results");
4694 return false;
4696 if (results1 != NULL)
4698 Typed_identifier_list::const_iterator res1 = results1->begin();
4699 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4700 res2 != results2->end();
4701 ++res2, ++res1)
4703 if (res1 == results1->end())
4705 if (reason != NULL)
4706 *reason = _("different number of results");
4707 return false;
4710 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4711 cmp_tags, errors_are_identical,
4712 NULL))
4714 if (reason != NULL)
4715 *reason = _("different result types");
4716 return false;
4719 if (res1 != results1->end())
4721 if (reason != NULL)
4722 *reason = _("different number of results");
4723 return false;
4727 return true;
4730 // Hash code.
4732 unsigned int
4733 Function_type::do_hash_for_method(Gogo* gogo) const
4735 unsigned int ret = 0;
4736 // We ignore the receiver type for hash codes, because we need to
4737 // get the same hash code for a method in an interface and a method
4738 // declared for a type. The former will not have a receiver.
4739 if (this->parameters_ != NULL)
4741 int shift = 1;
4742 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4743 p != this->parameters_->end();
4744 ++p, ++shift)
4745 ret += p->type()->hash_for_method(gogo) << shift;
4747 if (this->results_ != NULL)
4749 int shift = 2;
4750 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4751 p != this->results_->end();
4752 ++p, ++shift)
4753 ret += p->type()->hash_for_method(gogo) << shift;
4755 if (this->is_varargs_)
4756 ret += 1;
4757 ret <<= 4;
4758 return ret;
4761 // Hash result parameters.
4763 unsigned int
4764 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4766 unsigned int hash = 0;
4767 for (Typed_identifier_list::const_iterator p = t->begin();
4768 p != t->end();
4769 ++p)
4771 hash <<= 2;
4772 hash = Type::hash_string(p->name(), hash);
4773 hash += p->type()->hash_for_method(NULL);
4775 return hash;
4778 // Compare result parameters so that can map identical result
4779 // parameters to a single struct type.
4781 bool
4782 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4783 const Typed_identifier_list* b) const
4785 if (a->size() != b->size())
4786 return false;
4787 Typed_identifier_list::const_iterator pa = a->begin();
4788 for (Typed_identifier_list::const_iterator pb = b->begin();
4789 pb != b->end();
4790 ++pa, ++pb)
4792 if (pa->name() != pb->name()
4793 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4794 return false;
4796 return true;
4799 // Hash from results to a backend struct type.
4801 Function_type::Results_structs Function_type::results_structs;
4803 // Get the backend representation for a function type.
4805 Btype*
4806 Function_type::get_backend_fntype(Gogo* gogo)
4808 if (this->fnbtype_ == NULL)
4810 Backend::Btyped_identifier breceiver;
4811 if (this->receiver_ != NULL)
4813 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4815 // We always pass the address of the receiver parameter, in
4816 // order to make interface calls work with unknown types.
4817 Type* rtype = this->receiver_->type();
4818 if (rtype->points_to() == NULL)
4819 rtype = Type::make_pointer_type(rtype);
4820 breceiver.btype = rtype->get_backend(gogo);
4821 breceiver.location = this->receiver_->location();
4824 std::vector<Backend::Btyped_identifier> bparameters;
4825 if (this->parameters_ != NULL)
4827 bparameters.resize(this->parameters_->size());
4828 size_t i = 0;
4829 for (Typed_identifier_list::const_iterator p =
4830 this->parameters_->begin(); p != this->parameters_->end();
4831 ++p, ++i)
4833 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4834 bparameters[i].btype = p->type()->get_backend(gogo);
4835 bparameters[i].location = p->location();
4837 go_assert(i == bparameters.size());
4840 std::vector<Backend::Btyped_identifier> bresults;
4841 Btype* bresult_struct = NULL;
4842 if (this->results_ != NULL)
4844 bresults.resize(this->results_->size());
4845 size_t i = 0;
4846 for (Typed_identifier_list::const_iterator p =
4847 this->results_->begin();
4848 p != this->results_->end();
4849 ++p, ++i)
4851 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4852 bresults[i].btype = p->type()->get_backend(gogo);
4853 bresults[i].location = p->location();
4855 go_assert(i == bresults.size());
4857 if (this->results_->size() > 1)
4859 // Use the same results struct for all functions that
4860 // return the same set of results. This is useful to
4861 // unify calls to interface methods with other calls.
4862 std::pair<Typed_identifier_list*, Btype*> val;
4863 val.first = this->results_;
4864 val.second = NULL;
4865 std::pair<Results_structs::iterator, bool> ins =
4866 Function_type::results_structs.insert(val);
4867 if (ins.second)
4869 // Build a new struct type.
4870 Struct_field_list* sfl = new Struct_field_list;
4871 for (Typed_identifier_list::const_iterator p =
4872 this->results_->begin();
4873 p != this->results_->end();
4874 ++p)
4876 Typed_identifier tid = *p;
4877 if (tid.name().empty())
4878 tid = Typed_identifier("UNNAMED", tid.type(),
4879 tid.location());
4880 sfl->push_back(Struct_field(tid));
4882 Struct_type* st = Type::make_struct_type(sfl,
4883 this->location());
4884 st->set_is_struct_incomparable();
4885 ins.first->second = st->get_backend(gogo);
4887 bresult_struct = ins.first->second;
4891 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4892 bresults, bresult_struct,
4893 this->location());
4897 return this->fnbtype_;
4900 // Get the backend representation for a Go function type.
4902 Btype*
4903 Function_type::do_get_backend(Gogo* gogo)
4905 // When we do anything with a function value other than call it, it
4906 // is represented as a pointer to a struct whose first field is the
4907 // actual function. So that is what we return as the type of a Go
4908 // function.
4910 Location loc = this->location();
4911 Btype* struct_type =
4912 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4913 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4915 std::vector<Backend::Btyped_identifier> fields(1);
4916 fields[0].name = "code";
4917 fields[0].btype = this->get_backend_fntype(gogo);
4918 fields[0].location = loc;
4919 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4920 return gogo->backend()->error_type();
4921 return ptr_struct_type;
4924 // The type of a function type descriptor.
4926 Type*
4927 Function_type::make_function_type_descriptor_type()
4929 static Type* ret;
4930 if (ret == NULL)
4932 Type* tdt = Type::make_type_descriptor_type();
4933 Type* ptdt = Type::make_type_descriptor_ptr_type();
4935 Type* bool_type = Type::lookup_bool_type();
4937 Type* slice_type = Type::make_array_type(ptdt, NULL);
4939 Struct_type* s = Type::make_builtin_struct_type(4,
4940 "", tdt,
4941 "dotdotdot", bool_type,
4942 "in", slice_type,
4943 "out", slice_type);
4945 ret = Type::make_builtin_named_type("FuncType", s);
4948 return ret;
4951 // The type descriptor for a function type.
4953 Expression*
4954 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4956 Location bloc = Linemap::predeclared_location();
4958 Type* ftdt = Function_type::make_function_type_descriptor_type();
4960 const Struct_field_list* fields = ftdt->struct_type()->fields();
4962 Expression_list* vals = new Expression_list();
4963 vals->reserve(4);
4965 Struct_field_list::const_iterator p = fields->begin();
4966 go_assert(p->is_field_name("_type"));
4967 vals->push_back(this->type_descriptor_constructor(gogo,
4968 RUNTIME_TYPE_KIND_FUNC,
4969 name, NULL, true));
4971 ++p;
4972 go_assert(p->is_field_name("dotdotdot"));
4973 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4975 ++p;
4976 go_assert(p->is_field_name("in"));
4977 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4978 this->parameters()));
4980 ++p;
4981 go_assert(p->is_field_name("out"));
4982 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4983 this->results()));
4985 ++p;
4986 go_assert(p == fields->end());
4988 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4991 // Return a composite literal for the parameters or results of a type
4992 // descriptor.
4994 Expression*
4995 Function_type::type_descriptor_params(Type* params_type,
4996 const Typed_identifier* receiver,
4997 const Typed_identifier_list* params)
4999 Location bloc = Linemap::predeclared_location();
5001 if (receiver == NULL && params == NULL)
5002 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
5004 Expression_list* vals = new Expression_list();
5005 vals->reserve((params == NULL ? 0 : params->size())
5006 + (receiver != NULL ? 1 : 0));
5008 if (receiver != NULL)
5009 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
5011 if (params != NULL)
5013 for (Typed_identifier_list::const_iterator p = params->begin();
5014 p != params->end();
5015 ++p)
5016 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
5019 return Expression::make_slice_composite_literal(params_type, vals, bloc);
5022 // The reflection string.
5024 void
5025 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
5027 // FIXME: Turn this off until we straighten out the type of the
5028 // struct field used in a go statement which calls a method.
5029 // go_assert(this->receiver_ == NULL);
5031 ret->append("func");
5033 if (this->receiver_ != NULL)
5035 ret->push_back('(');
5036 this->append_reflection(this->receiver_->type(), gogo, ret);
5037 ret->push_back(')');
5040 ret->push_back('(');
5041 const Typed_identifier_list* params = this->parameters();
5042 if (params != NULL)
5044 bool is_varargs = this->is_varargs_;
5045 for (Typed_identifier_list::const_iterator p = params->begin();
5046 p != params->end();
5047 ++p)
5049 if (p != params->begin())
5050 ret->append(", ");
5051 if (!is_varargs || p + 1 != params->end())
5052 this->append_reflection(p->type(), gogo, ret);
5053 else
5055 ret->append("...");
5056 this->append_reflection(p->type()->array_type()->element_type(),
5057 gogo, ret);
5061 ret->push_back(')');
5063 const Typed_identifier_list* results = this->results();
5064 if (results != NULL && !results->empty())
5066 if (results->size() == 1)
5067 ret->push_back(' ');
5068 else
5069 ret->append(" (");
5070 for (Typed_identifier_list::const_iterator p = results->begin();
5071 p != results->end();
5072 ++p)
5074 if (p != results->begin())
5075 ret->append(", ");
5076 this->append_reflection(p->type(), gogo, ret);
5078 if (results->size() > 1)
5079 ret->push_back(')');
5083 // Mangled name.
5085 void
5086 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5088 ret->push_back('F');
5090 if (this->receiver_ != NULL)
5092 ret->push_back('m');
5093 this->append_mangled_name(this->receiver_->type(), gogo, ret);
5096 const Typed_identifier_list* params = this->parameters();
5097 if (params != NULL)
5099 ret->push_back('p');
5100 for (Typed_identifier_list::const_iterator p = params->begin();
5101 p != params->end();
5102 ++p)
5103 this->append_mangled_name(p->type(), gogo, ret);
5104 if (this->is_varargs_)
5105 ret->push_back('V');
5106 ret->push_back('e');
5109 const Typed_identifier_list* results = this->results();
5110 if (results != NULL)
5112 ret->push_back('r');
5113 for (Typed_identifier_list::const_iterator p = results->begin();
5114 p != results->end();
5115 ++p)
5116 this->append_mangled_name(p->type(), gogo, ret);
5117 ret->push_back('e');
5120 ret->push_back('e');
5123 // Export a function type.
5125 void
5126 Function_type::do_export(Export* exp) const
5128 // We don't write out the receiver. The only function types which
5129 // should have a receiver are the ones associated with explicitly
5130 // defined methods. For those the receiver type is written out by
5131 // Function::export_func.
5133 exp->write_c_string("(");
5134 bool first = true;
5135 if (this->parameters_ != NULL)
5137 bool is_varargs = this->is_varargs_;
5138 for (Typed_identifier_list::const_iterator p =
5139 this->parameters_->begin();
5140 p != this->parameters_->end();
5141 ++p)
5143 if (first)
5144 first = false;
5145 else
5146 exp->write_c_string(", ");
5147 exp->write_name(p->name());
5148 exp->write_c_string(" ");
5149 if (!is_varargs || p + 1 != this->parameters_->end())
5150 exp->write_type(p->type());
5151 else
5153 exp->write_c_string("...");
5154 exp->write_type(p->type()->array_type()->element_type());
5158 exp->write_c_string(")");
5160 const Typed_identifier_list* results = this->results_;
5161 if (results != NULL)
5163 exp->write_c_string(" ");
5164 if (results->size() == 1 && results->begin()->name().empty())
5165 exp->write_type(results->begin()->type());
5166 else
5168 first = true;
5169 exp->write_c_string("(");
5170 for (Typed_identifier_list::const_iterator p = results->begin();
5171 p != results->end();
5172 ++p)
5174 if (first)
5175 first = false;
5176 else
5177 exp->write_c_string(", ");
5178 exp->write_name(p->name());
5179 exp->write_c_string(" ");
5180 exp->write_type(p->type());
5182 exp->write_c_string(")");
5187 // Import a function type.
5189 Function_type*
5190 Function_type::do_import(Import* imp)
5192 imp->require_c_string("(");
5193 Typed_identifier_list* parameters;
5194 bool is_varargs = false;
5195 if (imp->peek_char() == ')')
5196 parameters = NULL;
5197 else
5199 parameters = new Typed_identifier_list();
5200 while (true)
5202 std::string name = imp->read_name();
5203 imp->require_c_string(" ");
5205 if (imp->match_c_string("..."))
5207 imp->advance(3);
5208 is_varargs = true;
5211 Type* ptype = imp->read_type();
5212 if (is_varargs)
5213 ptype = Type::make_array_type(ptype, NULL);
5214 parameters->push_back(Typed_identifier(name, ptype,
5215 imp->location()));
5216 if (imp->peek_char() != ',')
5217 break;
5218 go_assert(!is_varargs);
5219 imp->require_c_string(", ");
5222 imp->require_c_string(")");
5224 Typed_identifier_list* results;
5225 if (imp->peek_char() != ' ')
5226 results = NULL;
5227 else
5229 imp->advance(1);
5230 results = new Typed_identifier_list;
5231 if (imp->peek_char() != '(')
5233 Type* rtype = imp->read_type();
5234 results->push_back(Typed_identifier("", rtype, imp->location()));
5236 else
5238 imp->advance(1);
5239 while (true)
5241 std::string name = imp->read_name();
5242 imp->require_c_string(" ");
5243 Type* rtype = imp->read_type();
5244 results->push_back(Typed_identifier(name, rtype,
5245 imp->location()));
5246 if (imp->peek_char() != ',')
5247 break;
5248 imp->require_c_string(", ");
5250 imp->require_c_string(")");
5254 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5255 imp->location());
5256 if (is_varargs)
5257 ret->set_is_varargs();
5258 return ret;
5261 // Make a copy of a function type without a receiver.
5263 Function_type*
5264 Function_type::copy_without_receiver() const
5266 go_assert(this->is_method());
5267 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5268 this->results_,
5269 this->location_);
5270 if (this->is_varargs())
5271 ret->set_is_varargs();
5272 if (this->is_builtin())
5273 ret->set_is_builtin();
5274 return ret;
5277 // Make a copy of a function type with a receiver.
5279 Function_type*
5280 Function_type::copy_with_receiver(Type* receiver_type) const
5282 go_assert(!this->is_method());
5283 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5284 this->location_);
5285 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5286 this->results_,
5287 this->location_);
5288 if (this->is_varargs_)
5289 ret->set_is_varargs();
5290 return ret;
5293 // Make a copy of a function type with the receiver as the first
5294 // parameter.
5296 Function_type*
5297 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5299 go_assert(this->is_method());
5300 Typed_identifier_list* new_params = new Typed_identifier_list();
5301 Type* rtype = this->receiver_->type();
5302 if (want_pointer_receiver)
5303 rtype = Type::make_pointer_type(rtype);
5304 Typed_identifier receiver(this->receiver_->name(), rtype,
5305 this->receiver_->location());
5306 new_params->push_back(receiver);
5307 const Typed_identifier_list* orig_params = this->parameters_;
5308 if (orig_params != NULL && !orig_params->empty())
5310 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5311 p != orig_params->end();
5312 ++p)
5313 new_params->push_back(*p);
5315 return Type::make_function_type(NULL, new_params, this->results_,
5316 this->location_);
5319 // Make a copy of a function type ignoring any receiver and adding a
5320 // closure parameter.
5322 Function_type*
5323 Function_type::copy_with_names() const
5325 Typed_identifier_list* new_params = new Typed_identifier_list();
5326 const Typed_identifier_list* orig_params = this->parameters_;
5327 if (orig_params != NULL && !orig_params->empty())
5329 static int count;
5330 char buf[50];
5331 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5332 p != orig_params->end();
5333 ++p)
5335 snprintf(buf, sizeof buf, "pt.%u", count);
5336 ++count;
5337 new_params->push_back(Typed_identifier(buf, p->type(),
5338 p->location()));
5342 const Typed_identifier_list* orig_results = this->results_;
5343 Typed_identifier_list* new_results;
5344 if (orig_results == NULL || orig_results->empty())
5345 new_results = NULL;
5346 else
5348 new_results = new Typed_identifier_list();
5349 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5350 p != orig_results->end();
5351 ++p)
5352 new_results->push_back(Typed_identifier("", p->type(),
5353 p->location()));
5356 return Type::make_function_type(NULL, new_params, new_results,
5357 this->location());
5360 // Make a function type.
5362 Function_type*
5363 Type::make_function_type(Typed_identifier* receiver,
5364 Typed_identifier_list* parameters,
5365 Typed_identifier_list* results,
5366 Location location)
5368 return new Function_type(receiver, parameters, results, location);
5371 // Make a backend function type.
5373 Backend_function_type*
5374 Type::make_backend_function_type(Typed_identifier* receiver,
5375 Typed_identifier_list* parameters,
5376 Typed_identifier_list* results,
5377 Location location)
5379 return new Backend_function_type(receiver, parameters, results, location);
5382 // Class Pointer_type.
5384 // Traversal.
5387 Pointer_type::do_traverse(Traverse* traverse)
5389 return Type::traverse(this->to_type_, traverse);
5392 // Hash code.
5394 unsigned int
5395 Pointer_type::do_hash_for_method(Gogo* gogo) const
5397 return this->to_type_->hash_for_method(gogo) << 4;
5400 // Get the backend representation for a pointer type.
5402 Btype*
5403 Pointer_type::do_get_backend(Gogo* gogo)
5405 Btype* to_btype = this->to_type_->get_backend(gogo);
5406 return gogo->backend()->pointer_type(to_btype);
5409 // The type of a pointer type descriptor.
5411 Type*
5412 Pointer_type::make_pointer_type_descriptor_type()
5414 static Type* ret;
5415 if (ret == NULL)
5417 Type* tdt = Type::make_type_descriptor_type();
5418 Type* ptdt = Type::make_type_descriptor_ptr_type();
5420 Struct_type* s = Type::make_builtin_struct_type(2,
5421 "", tdt,
5422 "elem", ptdt);
5424 ret = Type::make_builtin_named_type("PtrType", s);
5427 return ret;
5430 // The type descriptor for a pointer type.
5432 Expression*
5433 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5435 if (this->is_unsafe_pointer_type())
5437 go_assert(name != NULL);
5438 return this->plain_type_descriptor(gogo,
5439 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5440 name);
5442 else
5444 Location bloc = Linemap::predeclared_location();
5446 const Methods* methods;
5447 Type* deref = this->points_to();
5448 if (deref->named_type() != NULL)
5449 methods = deref->named_type()->methods();
5450 else if (deref->struct_type() != NULL)
5451 methods = deref->struct_type()->methods();
5452 else
5453 methods = NULL;
5455 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5457 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5459 Expression_list* vals = new Expression_list();
5460 vals->reserve(2);
5462 Struct_field_list::const_iterator p = fields->begin();
5463 go_assert(p->is_field_name("_type"));
5464 vals->push_back(this->type_descriptor_constructor(gogo,
5465 RUNTIME_TYPE_KIND_PTR,
5466 name, methods, false));
5468 ++p;
5469 go_assert(p->is_field_name("elem"));
5470 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5472 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5476 // Reflection string.
5478 void
5479 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5481 ret->push_back('*');
5482 this->append_reflection(this->to_type_, gogo, ret);
5485 void
5486 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5488 ret->push_back('p');
5489 this->append_mangled_name(this->to_type_, gogo, ret);
5492 // Export.
5494 void
5495 Pointer_type::do_export(Export* exp) const
5497 exp->write_c_string("*");
5498 if (this->is_unsafe_pointer_type())
5499 exp->write_c_string("any");
5500 else
5501 exp->write_type(this->to_type_);
5504 // Import.
5506 Pointer_type*
5507 Pointer_type::do_import(Import* imp)
5509 imp->require_c_string("*");
5510 if (imp->match_c_string("any"))
5512 imp->advance(3);
5513 return Type::make_pointer_type(Type::make_void_type());
5515 Type* to = imp->read_type();
5516 return Type::make_pointer_type(to);
5519 // Cache of pointer types. Key is "to" type, value is pointer type
5520 // that points to key.
5522 Type::Pointer_type_table Type::pointer_types;
5524 // Make a pointer type.
5526 Pointer_type*
5527 Type::make_pointer_type(Type* to_type)
5529 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5530 if (p != pointer_types.end())
5531 return p->second;
5532 Pointer_type* ret = new Pointer_type(to_type);
5533 pointer_types[to_type] = ret;
5534 return ret;
5537 // This helper is invoked immediately after named types have been
5538 // converted, to clean up any unresolved pointer types remaining in
5539 // the pointer type cache.
5541 // The motivation for this routine: occasionally the compiler creates
5542 // some specific pointer type as part of a lowering operation (ex:
5543 // pointer-to-void), then Type::backend_type_size() is invoked on the
5544 // type (which creates a Btype placeholder for it), that placeholder
5545 // passed somewhere along the line to the back end, but since there is
5546 // no reference to the type in user code, there is never a call to
5547 // Type::finish_backend for the type (hence the Btype remains as an
5548 // unresolved placeholder). Calling this routine will clean up such
5549 // instances.
5551 void
5552 Type::finish_pointer_types(Gogo* gogo)
5554 for (Pointer_type_table::const_iterator i = pointer_types.begin();
5555 i != pointer_types.end();
5556 ++i)
5558 Pointer_type* pt = i->second;
5559 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5560 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5562 pt->finish_backend(gogo, tbti->second.btype);
5563 tbti->second.is_placeholder = false;
5568 // The nil type. We use a special type for nil because it is not the
5569 // same as any other type. In C term nil has type void*, but there is
5570 // no such type in Go.
5572 class Nil_type : public Type
5574 public:
5575 Nil_type()
5576 : Type(TYPE_NIL)
5579 protected:
5580 bool
5581 do_compare_is_identity(Gogo*)
5582 { return false; }
5584 Btype*
5585 do_get_backend(Gogo* gogo)
5586 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
5588 Expression*
5589 do_type_descriptor(Gogo*, Named_type*)
5590 { go_unreachable(); }
5592 void
5593 do_reflection(Gogo*, std::string*) const
5594 { go_unreachable(); }
5596 void
5597 do_mangled_name(Gogo*, std::string* ret) const
5598 { ret->push_back('n'); }
5601 // Make the nil type.
5603 Type*
5604 Type::make_nil_type()
5606 static Nil_type singleton_nil_type;
5607 return &singleton_nil_type;
5610 // The type of a function call which returns multiple values. This is
5611 // really a struct, but we don't want to confuse a function call which
5612 // returns a struct with a function call which returns multiple
5613 // values.
5615 class Call_multiple_result_type : public Type
5617 public:
5618 Call_multiple_result_type(Call_expression* call)
5619 : Type(TYPE_CALL_MULTIPLE_RESULT),
5620 call_(call)
5623 protected:
5624 bool
5625 do_has_pointer() const
5626 { return false; }
5628 bool
5629 do_compare_is_identity(Gogo*)
5630 { return false; }
5632 Btype*
5633 do_get_backend(Gogo* gogo)
5635 go_assert(saw_errors());
5636 return gogo->backend()->error_type();
5639 Expression*
5640 do_type_descriptor(Gogo*, Named_type*)
5642 go_assert(saw_errors());
5643 return Expression::make_error(Linemap::unknown_location());
5646 void
5647 do_reflection(Gogo*, std::string*) const
5648 { go_assert(saw_errors()); }
5650 void
5651 do_mangled_name(Gogo*, std::string*) const
5652 { go_assert(saw_errors()); }
5654 private:
5655 // The expression being called.
5656 Call_expression* call_;
5659 // Make a call result type.
5661 Type*
5662 Type::make_call_multiple_result_type(Call_expression* call)
5664 return new Call_multiple_result_type(call);
5667 // Class Struct_field.
5669 // Get the name of a field.
5671 const std::string&
5672 Struct_field::field_name() const
5674 const std::string& name(this->typed_identifier_.name());
5675 if (!name.empty())
5676 return name;
5677 else
5679 // This is called during parsing, before anything is lowered, so
5680 // we have to be pretty careful to avoid dereferencing an
5681 // unknown type name.
5682 Type* t = this->typed_identifier_.type();
5683 Type* dt = t;
5684 if (t->classification() == Type::TYPE_POINTER)
5686 // Very ugly.
5687 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5688 dt = ptype->points_to();
5690 if (dt->forward_declaration_type() != NULL)
5691 return dt->forward_declaration_type()->name();
5692 else if (dt->named_type() != NULL)
5694 // Note that this can be an alias name.
5695 return dt->named_type()->name();
5697 else if (t->is_error_type() || dt->is_error_type())
5699 static const std::string error_string = "*error*";
5700 return error_string;
5702 else
5704 // Avoid crashing in the erroneous case where T is named but
5705 // DT is not.
5706 go_assert(t != dt);
5707 if (t->forward_declaration_type() != NULL)
5708 return t->forward_declaration_type()->name();
5709 else if (t->named_type() != NULL)
5710 return t->named_type()->name();
5711 else
5712 go_unreachable();
5717 // Return whether this field is named NAME.
5719 bool
5720 Struct_field::is_field_name(const std::string& name) const
5722 const std::string& me(this->typed_identifier_.name());
5723 if (!me.empty())
5724 return me == name;
5725 else
5727 Type* t = this->typed_identifier_.type();
5728 if (t->points_to() != NULL)
5729 t = t->points_to();
5730 Named_type* nt = t->named_type();
5731 if (nt != NULL && nt->name() == name)
5732 return true;
5734 // This is a horrible hack caused by the fact that we don't pack
5735 // the names of builtin types. FIXME.
5736 if (!this->is_imported_
5737 && nt != NULL
5738 && nt->is_builtin()
5739 && nt->name() == Gogo::unpack_hidden_name(name))
5740 return true;
5742 return false;
5746 // Return whether this field is an unexported field named NAME.
5748 bool
5749 Struct_field::is_unexported_field_name(Gogo* gogo,
5750 const std::string& name) const
5752 const std::string& field_name(this->field_name());
5753 if (Gogo::is_hidden_name(field_name)
5754 && name == Gogo::unpack_hidden_name(field_name)
5755 && gogo->pack_hidden_name(name, false) != field_name)
5756 return true;
5758 // Check for the name of a builtin type. This is like the test in
5759 // is_field_name, only there we return false if this->is_imported_,
5760 // and here we return true.
5761 if (this->is_imported_ && this->is_anonymous())
5763 Type* t = this->typed_identifier_.type();
5764 if (t->points_to() != NULL)
5765 t = t->points_to();
5766 Named_type* nt = t->named_type();
5767 if (nt != NULL
5768 && nt->is_builtin()
5769 && nt->name() == Gogo::unpack_hidden_name(name))
5770 return true;
5773 return false;
5776 // Return whether this field is an embedded built-in type.
5778 bool
5779 Struct_field::is_embedded_builtin(Gogo* gogo) const
5781 const std::string& name(this->field_name());
5782 // We know that a field is an embedded type if it is anonymous.
5783 // We can decide if it is a built-in type by checking to see if it is
5784 // registered globally under the field's name.
5785 // This allows us to distinguish between embedded built-in types and
5786 // embedded types that are aliases to built-in types.
5787 return (this->is_anonymous()
5788 && !Gogo::is_hidden_name(name)
5789 && gogo->lookup_global(name.c_str()) != NULL);
5792 // Class Struct_type.
5794 // A hash table used to find identical unnamed structs so that they
5795 // share method tables.
5797 Struct_type::Identical_structs Struct_type::identical_structs;
5799 // A hash table used to merge method sets for identical unnamed
5800 // structs.
5802 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5804 // Traversal.
5807 Struct_type::do_traverse(Traverse* traverse)
5809 Struct_field_list* fields = this->fields_;
5810 if (fields != NULL)
5812 for (Struct_field_list::iterator p = fields->begin();
5813 p != fields->end();
5814 ++p)
5816 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5817 return TRAVERSE_EXIT;
5820 return TRAVERSE_CONTINUE;
5823 // Verify that the struct type is complete and valid.
5825 bool
5826 Struct_type::do_verify()
5828 Struct_field_list* fields = this->fields_;
5829 if (fields == NULL)
5830 return true;
5831 for (Struct_field_list::iterator p = fields->begin();
5832 p != fields->end();
5833 ++p)
5835 Type* t = p->type();
5836 if (p->is_anonymous())
5838 if (t->named_type() != NULL && t->points_to() != NULL)
5840 go_error_at(p->location(), "embedded type may not be a pointer");
5841 p->set_type(Type::make_error_type());
5843 else if (t->points_to() != NULL
5844 && t->points_to()->interface_type() != NULL)
5846 go_error_at(p->location(),
5847 "embedded type may not be pointer to interface");
5848 p->set_type(Type::make_error_type());
5852 return true;
5855 // Whether this contains a pointer.
5857 bool
5858 Struct_type::do_has_pointer() const
5860 const Struct_field_list* fields = this->fields();
5861 if (fields == NULL)
5862 return false;
5863 for (Struct_field_list::const_iterator p = fields->begin();
5864 p != fields->end();
5865 ++p)
5867 if (p->type()->has_pointer())
5868 return true;
5870 return false;
5873 // Whether this type is identical to T.
5875 bool
5876 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5877 bool errors_are_identical) const
5879 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5880 return false;
5881 const Struct_field_list* fields1 = this->fields();
5882 const Struct_field_list* fields2 = t->fields();
5883 if (fields1 == NULL || fields2 == NULL)
5884 return fields1 == fields2;
5885 Struct_field_list::const_iterator pf2 = fields2->begin();
5886 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5887 pf1 != fields1->end();
5888 ++pf1, ++pf2)
5890 if (pf2 == fields2->end())
5891 return false;
5892 if (pf1->field_name() != pf2->field_name())
5893 return false;
5894 if (pf1->is_anonymous() != pf2->is_anonymous()
5895 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5896 errors_are_identical, NULL))
5897 return false;
5898 if (cmp_tags == COMPARE_TAGS)
5900 if (!pf1->has_tag())
5902 if (pf2->has_tag())
5903 return false;
5905 else
5907 if (!pf2->has_tag())
5908 return false;
5909 if (pf1->tag() != pf2->tag())
5910 return false;
5914 if (pf2 != fields2->end())
5915 return false;
5916 return true;
5919 // Whether comparisons of this struct type are simple identity
5920 // comparisons.
5922 bool
5923 Struct_type::do_compare_is_identity(Gogo* gogo)
5925 const Struct_field_list* fields = this->fields_;
5926 if (fields == NULL)
5927 return true;
5928 int64_t offset = 0;
5929 for (Struct_field_list::const_iterator pf = fields->begin();
5930 pf != fields->end();
5931 ++pf)
5933 if (Gogo::is_sink_name(pf->field_name()))
5934 return false;
5936 if (!pf->type()->compare_is_identity(gogo))
5937 return false;
5939 int64_t field_align;
5940 if (!pf->type()->backend_type_align(gogo, &field_align))
5941 return false;
5942 if ((offset & (field_align - 1)) != 0)
5944 // This struct has padding. We don't guarantee that that
5945 // padding is zero-initialized for a stack variable, so we
5946 // can't use memcmp to compare struct values.
5947 return false;
5950 int64_t field_size;
5951 if (!pf->type()->backend_type_size(gogo, &field_size))
5952 return false;
5953 offset += field_size;
5956 int64_t struct_size;
5957 if (!this->backend_type_size(gogo, &struct_size))
5958 return false;
5959 if (offset != struct_size)
5961 // Trailing padding may not be zero when on the stack.
5962 return false;
5965 return true;
5968 // Return whether this struct type is reflexive--whether a value of
5969 // this type is always equal to itself.
5971 bool
5972 Struct_type::do_is_reflexive()
5974 const Struct_field_list* fields = this->fields_;
5975 if (fields == NULL)
5976 return true;
5977 for (Struct_field_list::const_iterator pf = fields->begin();
5978 pf != fields->end();
5979 ++pf)
5981 if (!pf->type()->is_reflexive())
5982 return false;
5984 return true;
5987 // Return whether this struct type needs a key update when used as a
5988 // map key.
5990 bool
5991 Struct_type::do_needs_key_update()
5993 const Struct_field_list* fields = this->fields_;
5994 if (fields == NULL)
5995 return false;
5996 for (Struct_field_list::const_iterator pf = fields->begin();
5997 pf != fields->end();
5998 ++pf)
6000 if (pf->type()->needs_key_update())
6001 return true;
6003 return false;
6006 // Return whether this struct type is permitted to be in the heap.
6008 bool
6009 Struct_type::do_in_heap()
6011 const Struct_field_list* fields = this->fields_;
6012 if (fields == NULL)
6013 return true;
6014 for (Struct_field_list::const_iterator pf = fields->begin();
6015 pf != fields->end();
6016 ++pf)
6018 if (!pf->type()->in_heap())
6019 return false;
6021 return true;
6024 // Build identity and hash functions for this struct.
6026 // Hash code.
6028 unsigned int
6029 Struct_type::do_hash_for_method(Gogo* gogo) const
6031 unsigned int ret = 0;
6032 if (this->fields() != NULL)
6034 for (Struct_field_list::const_iterator pf = this->fields()->begin();
6035 pf != this->fields()->end();
6036 ++pf)
6037 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
6039 ret <<= 2;
6040 if (this->is_struct_incomparable_)
6041 ret <<= 1;
6042 return ret;
6045 // Find the local field NAME.
6047 const Struct_field*
6048 Struct_type::find_local_field(const std::string& name,
6049 unsigned int *pindex) const
6051 const Struct_field_list* fields = this->fields_;
6052 if (fields == NULL)
6053 return NULL;
6054 unsigned int i = 0;
6055 for (Struct_field_list::const_iterator pf = fields->begin();
6056 pf != fields->end();
6057 ++pf, ++i)
6059 if (pf->is_field_name(name))
6061 if (pindex != NULL)
6062 *pindex = i;
6063 return &*pf;
6066 return NULL;
6069 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
6071 Field_reference_expression*
6072 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
6073 Location location) const
6075 unsigned int depth;
6076 return this->field_reference_depth(struct_expr, name, location, NULL,
6077 &depth);
6080 // Return an expression for a field, along with the depth at which it
6081 // was found.
6083 Field_reference_expression*
6084 Struct_type::field_reference_depth(Expression* struct_expr,
6085 const std::string& name,
6086 Location location,
6087 Saw_named_type* saw,
6088 unsigned int* depth) const
6090 const Struct_field_list* fields = this->fields_;
6091 if (fields == NULL)
6092 return NULL;
6094 // Look for a field with this name.
6095 unsigned int i = 0;
6096 for (Struct_field_list::const_iterator pf = fields->begin();
6097 pf != fields->end();
6098 ++pf, ++i)
6100 if (pf->is_field_name(name))
6102 *depth = 0;
6103 return Expression::make_field_reference(struct_expr, i, location);
6107 // Look for an anonymous field which contains a field with this
6108 // name.
6109 unsigned int found_depth = 0;
6110 Field_reference_expression* ret = NULL;
6111 i = 0;
6112 for (Struct_field_list::const_iterator pf = fields->begin();
6113 pf != fields->end();
6114 ++pf, ++i)
6116 if (!pf->is_anonymous())
6117 continue;
6119 Struct_type* st = pf->type()->deref()->struct_type();
6120 if (st == NULL)
6121 continue;
6123 Saw_named_type* hold_saw = saw;
6124 Saw_named_type saw_here;
6125 Named_type* nt = pf->type()->named_type();
6126 if (nt == NULL)
6127 nt = pf->type()->deref()->named_type();
6128 if (nt != NULL)
6130 Saw_named_type* q;
6131 for (q = saw; q != NULL; q = q->next)
6133 if (q->nt == nt)
6135 // If this is an error, it will be reported
6136 // elsewhere.
6137 break;
6140 if (q != NULL)
6141 continue;
6142 saw_here.next = saw;
6143 saw_here.nt = nt;
6144 saw = &saw_here;
6147 // Look for a reference using a NULL struct expression. If we
6148 // find one, fill in the struct expression with a reference to
6149 // this field.
6150 unsigned int subdepth;
6151 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6152 location,
6153 saw,
6154 &subdepth);
6156 saw = hold_saw;
6158 if (sub == NULL)
6159 continue;
6161 if (ret == NULL || subdepth < found_depth)
6163 if (ret != NULL)
6164 delete ret;
6165 ret = sub;
6166 found_depth = subdepth;
6167 Expression* here = Expression::make_field_reference(struct_expr, i,
6168 location);
6169 if (pf->type()->points_to() != NULL)
6170 here = Expression::make_unary(OPERATOR_MULT, here, location);
6171 while (sub->expr() != NULL)
6173 sub = sub->expr()->deref()->field_reference_expression();
6174 go_assert(sub != NULL);
6176 sub->set_struct_expression(here);
6177 sub->set_implicit(true);
6179 else if (subdepth > found_depth)
6180 delete sub;
6181 else
6183 // We do not handle ambiguity here--it should be handled by
6184 // Type::bind_field_or_method.
6185 delete sub;
6186 found_depth = 0;
6187 ret = NULL;
6191 if (ret != NULL)
6192 *depth = found_depth + 1;
6194 return ret;
6197 // Return the total number of fields, including embedded fields.
6199 unsigned int
6200 Struct_type::total_field_count() const
6202 if (this->fields_ == NULL)
6203 return 0;
6204 unsigned int ret = 0;
6205 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6206 pf != this->fields_->end();
6207 ++pf)
6209 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6210 ++ret;
6211 else
6212 ret += pf->type()->struct_type()->total_field_count();
6214 return ret;
6217 // Return whether NAME is an unexported field, for better error reporting.
6219 bool
6220 Struct_type::is_unexported_local_field(Gogo* gogo,
6221 const std::string& name) const
6223 const Struct_field_list* fields = this->fields_;
6224 if (fields != NULL)
6226 for (Struct_field_list::const_iterator pf = fields->begin();
6227 pf != fields->end();
6228 ++pf)
6229 if (pf->is_unexported_field_name(gogo, name))
6230 return true;
6232 return false;
6235 // Finalize the methods of an unnamed struct.
6237 void
6238 Struct_type::finalize_methods(Gogo* gogo)
6240 if (this->all_methods_ != NULL)
6241 return;
6243 // It is possible to have multiple identical structs that have
6244 // methods. We want them to share method tables. Otherwise we will
6245 // emit identical methods more than once, which is bad since they
6246 // will even have the same names.
6247 std::pair<Identical_structs::iterator, bool> ins =
6248 Struct_type::identical_structs.insert(std::make_pair(this, this));
6249 if (!ins.second)
6251 // An identical struct was already entered into the hash table.
6252 // Note that finalize_methods is, fortunately, not recursive.
6253 this->all_methods_ = ins.first->second->all_methods_;
6254 return;
6257 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6260 // Return the method NAME, or NULL if there isn't one or if it is
6261 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6262 // ambiguous.
6264 Method*
6265 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6267 return Type::method_function(this->all_methods_, name, is_ambiguous);
6270 // Return a pointer to the interface method table for this type for
6271 // the interface INTERFACE. IS_POINTER is true if this is for a
6272 // pointer to THIS.
6274 Expression*
6275 Struct_type::interface_method_table(Interface_type* interface,
6276 bool is_pointer)
6278 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6279 val(this, NULL);
6280 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6281 Struct_type::struct_method_tables.insert(val);
6283 Struct_method_table_pair* smtp;
6284 if (!ins.second)
6285 smtp = ins.first->second;
6286 else
6288 smtp = new Struct_method_table_pair();
6289 smtp->first = NULL;
6290 smtp->second = NULL;
6291 ins.first->second = smtp;
6294 return Type::interface_method_table(this, interface, is_pointer,
6295 &smtp->first, &smtp->second);
6298 // Convert struct fields to the backend representation. This is not
6299 // declared in types.h so that types.h doesn't have to #include
6300 // backend.h.
6302 static void
6303 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6304 bool use_placeholder,
6305 std::vector<Backend::Btyped_identifier>* bfields)
6307 bfields->resize(fields->size());
6308 size_t i = 0;
6309 for (Struct_field_list::const_iterator p = fields->begin();
6310 p != fields->end();
6311 ++p, ++i)
6313 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6314 (*bfields)[i].btype = (use_placeholder
6315 ? p->type()->get_backend_placeholder(gogo)
6316 : p->type()->get_backend(gogo));
6317 (*bfields)[i].location = p->location();
6319 go_assert(i == fields->size());
6322 // Get the backend representation for a struct type.
6324 Btype*
6325 Struct_type::do_get_backend(Gogo* gogo)
6327 std::vector<Backend::Btyped_identifier> bfields;
6328 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6329 return gogo->backend()->struct_type(bfields);
6332 // Finish the backend representation of the fields of a struct.
6334 void
6335 Struct_type::finish_backend_fields(Gogo* gogo)
6337 const Struct_field_list* fields = this->fields_;
6338 if (fields != NULL)
6340 for (Struct_field_list::const_iterator p = fields->begin();
6341 p != fields->end();
6342 ++p)
6343 p->type()->get_backend(gogo);
6347 // The type of a struct type descriptor.
6349 Type*
6350 Struct_type::make_struct_type_descriptor_type()
6352 static Type* ret;
6353 if (ret == NULL)
6355 Type* tdt = Type::make_type_descriptor_type();
6356 Type* ptdt = Type::make_type_descriptor_ptr_type();
6358 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6359 Type* string_type = Type::lookup_string_type();
6360 Type* pointer_string_type = Type::make_pointer_type(string_type);
6362 Struct_type* sf =
6363 Type::make_builtin_struct_type(5,
6364 "name", pointer_string_type,
6365 "pkgPath", pointer_string_type,
6366 "typ", ptdt,
6367 "tag", pointer_string_type,
6368 "offset", uintptr_type);
6369 Type* nsf = Type::make_builtin_named_type("structField", sf);
6371 Type* slice_type = Type::make_array_type(nsf, NULL);
6373 Struct_type* s = Type::make_builtin_struct_type(2,
6374 "", tdt,
6375 "fields", slice_type);
6377 ret = Type::make_builtin_named_type("StructType", s);
6380 return ret;
6383 // Build a type descriptor for a struct type.
6385 Expression*
6386 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6388 Location bloc = Linemap::predeclared_location();
6390 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6392 const Struct_field_list* fields = stdt->struct_type()->fields();
6394 Expression_list* vals = new Expression_list();
6395 vals->reserve(2);
6397 const Methods* methods = this->methods();
6398 // A named struct should not have methods--the methods should attach
6399 // to the named type.
6400 go_assert(methods == NULL || name == NULL);
6402 Struct_field_list::const_iterator ps = fields->begin();
6403 go_assert(ps->is_field_name("_type"));
6404 vals->push_back(this->type_descriptor_constructor(gogo,
6405 RUNTIME_TYPE_KIND_STRUCT,
6406 name, methods, true));
6408 ++ps;
6409 go_assert(ps->is_field_name("fields"));
6411 Expression_list* elements = new Expression_list();
6412 elements->reserve(this->fields_->size());
6413 Type* element_type = ps->type()->array_type()->element_type();
6414 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6415 pf != this->fields_->end();
6416 ++pf)
6418 const Struct_field_list* f = element_type->struct_type()->fields();
6420 Expression_list* fvals = new Expression_list();
6421 fvals->reserve(5);
6423 Struct_field_list::const_iterator q = f->begin();
6424 go_assert(q->is_field_name("name"));
6425 if (pf->is_anonymous())
6426 fvals->push_back(Expression::make_nil(bloc));
6427 else
6429 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6430 Expression* s = Expression::make_string(n, bloc);
6431 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6434 ++q;
6435 go_assert(q->is_field_name("pkgPath"));
6436 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6437 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6438 fvals->push_back(Expression::make_nil(bloc));
6439 else
6441 std::string n;
6442 if (is_embedded_builtin)
6443 n = gogo->package_name();
6444 else
6445 n = Gogo::hidden_name_pkgpath(pf->field_name());
6446 Expression* s = Expression::make_string(n, bloc);
6447 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6450 ++q;
6451 go_assert(q->is_field_name("typ"));
6452 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6454 ++q;
6455 go_assert(q->is_field_name("tag"));
6456 if (!pf->has_tag())
6457 fvals->push_back(Expression::make_nil(bloc));
6458 else
6460 Expression* s = Expression::make_string(pf->tag(), bloc);
6461 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6464 ++q;
6465 go_assert(q->is_field_name("offset"));
6466 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
6468 Expression* v = Expression::make_struct_composite_literal(element_type,
6469 fvals, bloc);
6470 elements->push_back(v);
6473 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6474 elements, bloc));
6476 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6479 // Write the hash function for a struct which can not use the identity
6480 // function.
6482 void
6483 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6484 Function_type* hash_fntype,
6485 Function_type* equal_fntype)
6487 Location bloc = Linemap::predeclared_location();
6489 // The pointer to the struct that we are going to hash. This is an
6490 // argument to the hash function we are implementing here.
6491 Named_object* key_arg = gogo->lookup("key", NULL);
6492 go_assert(key_arg != NULL);
6493 Type* key_arg_type = key_arg->var_value()->type();
6495 // The seed argument to the hash function.
6496 Named_object* seed_arg = gogo->lookup("seed", NULL);
6497 go_assert(seed_arg != NULL);
6499 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6501 // Make a temporary to hold the return value, initialized to the seed.
6502 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6503 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6504 bloc);
6505 gogo->add_statement(retval);
6507 // Make a temporary to hold the key as a uintptr.
6508 ref = Expression::make_var_reference(key_arg, bloc);
6509 ref = Expression::make_cast(uintptr_type, ref, bloc);
6510 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6511 bloc);
6512 gogo->add_statement(key);
6514 // Loop over the struct fields.
6515 const Struct_field_list* fields = this->fields_;
6516 for (Struct_field_list::const_iterator pf = fields->begin();
6517 pf != fields->end();
6518 ++pf)
6520 if (Gogo::is_sink_name(pf->field_name()))
6521 continue;
6523 // Get a pointer to the value of this field.
6524 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6525 ref = Expression::make_temporary_reference(key, bloc);
6526 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6527 bloc);
6528 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6530 // Get the hash function to use for the type of this field.
6531 Named_object* hash_fn;
6532 Named_object* equal_fn;
6533 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6534 equal_fntype, &hash_fn, &equal_fn);
6536 // Call the hash function for the field, passing retval as the seed.
6537 ref = Expression::make_temporary_reference(retval, bloc);
6538 Expression_list* args = new Expression_list();
6539 args->push_back(subkey);
6540 args->push_back(ref);
6541 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6542 Expression* call = Expression::make_call(func, args, false, bloc);
6544 // Set retval to the result.
6545 Temporary_reference_expression* tref =
6546 Expression::make_temporary_reference(retval, bloc);
6547 tref->set_is_lvalue();
6548 Statement* s = Statement::make_assignment(tref, call, bloc);
6549 gogo->add_statement(s);
6552 // Return retval to the caller of the hash function.
6553 Expression_list* vals = new Expression_list();
6554 ref = Expression::make_temporary_reference(retval, bloc);
6555 vals->push_back(ref);
6556 Statement* s = Statement::make_return_statement(vals, bloc);
6557 gogo->add_statement(s);
6560 // Write the equality function for a struct which can not use the
6561 // identity function.
6563 void
6564 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6566 Location bloc = Linemap::predeclared_location();
6568 // The pointers to the structs we are going to compare.
6569 Named_object* key1_arg = gogo->lookup("key1", NULL);
6570 Named_object* key2_arg = gogo->lookup("key2", NULL);
6571 go_assert(key1_arg != NULL && key2_arg != NULL);
6573 // Build temporaries with the right types.
6574 Type* pt = Type::make_pointer_type(name != NULL
6575 ? static_cast<Type*>(name)
6576 : static_cast<Type*>(this));
6578 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6579 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6580 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6581 gogo->add_statement(p1);
6583 ref = Expression::make_var_reference(key2_arg, bloc);
6584 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6585 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6586 gogo->add_statement(p2);
6588 const Struct_field_list* fields = this->fields_;
6589 unsigned int field_index = 0;
6590 for (Struct_field_list::const_iterator pf = fields->begin();
6591 pf != fields->end();
6592 ++pf, ++field_index)
6594 if (Gogo::is_sink_name(pf->field_name()))
6595 continue;
6597 // Compare one field in both P1 and P2.
6598 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6599 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
6600 f1 = Expression::make_field_reference(f1, field_index, bloc);
6602 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6603 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
6604 f2 = Expression::make_field_reference(f2, field_index, bloc);
6606 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6608 // If the values are not equal, return false.
6609 gogo->start_block(bloc);
6610 Expression_list* vals = new Expression_list();
6611 vals->push_back(Expression::make_boolean(false, bloc));
6612 Statement* s = Statement::make_return_statement(vals, bloc);
6613 gogo->add_statement(s);
6614 Block* then_block = gogo->finish_block(bloc);
6616 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6617 gogo->add_statement(s);
6620 // All the fields are equal, so return true.
6621 Expression_list* vals = new Expression_list();
6622 vals->push_back(Expression::make_boolean(true, bloc));
6623 Statement* s = Statement::make_return_statement(vals, bloc);
6624 gogo->add_statement(s);
6627 // Reflection string.
6629 void
6630 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6632 ret->append("struct {");
6634 for (Struct_field_list::const_iterator p = this->fields_->begin();
6635 p != this->fields_->end();
6636 ++p)
6638 if (p != this->fields_->begin())
6639 ret->push_back(';');
6640 ret->push_back(' ');
6641 if (p->is_anonymous())
6642 ret->push_back('?');
6643 else
6644 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6645 ret->push_back(' ');
6646 if (p->is_anonymous()
6647 && p->type()->named_type() != NULL
6648 && p->type()->named_type()->is_alias())
6649 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6650 else
6651 this->append_reflection(p->type(), gogo, ret);
6653 if (p->has_tag())
6655 const std::string& tag(p->tag());
6656 ret->append(" \"");
6657 for (std::string::const_iterator p = tag.begin();
6658 p != tag.end();
6659 ++p)
6661 if (*p == '\0')
6662 ret->append("\\x00");
6663 else if (*p == '\n')
6664 ret->append("\\n");
6665 else if (*p == '\t')
6666 ret->append("\\t");
6667 else if (*p == '"')
6668 ret->append("\\\"");
6669 else if (*p == '\\')
6670 ret->append("\\\\");
6671 else
6672 ret->push_back(*p);
6674 ret->push_back('"');
6678 if (!this->fields_->empty())
6679 ret->push_back(' ');
6681 ret->push_back('}');
6684 // Mangled name.
6686 void
6687 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6689 ret->push_back('S');
6691 const Struct_field_list* fields = this->fields_;
6692 if (fields != NULL)
6694 for (Struct_field_list::const_iterator p = fields->begin();
6695 p != fields->end();
6696 ++p)
6698 if (p->is_anonymous())
6699 ret->append("0_");
6700 else
6703 std::string n(Gogo::mangle_possibly_hidden_name(p->field_name()));
6704 char buf[20];
6705 snprintf(buf, sizeof buf, "%u_",
6706 static_cast<unsigned int>(n.length()));
6707 ret->append(buf);
6708 ret->append(n);
6711 // For an anonymous field with an alias type, the field name
6712 // is the alias name.
6713 if (p->is_anonymous()
6714 && p->type()->named_type() != NULL
6715 && p->type()->named_type()->is_alias())
6716 p->type()->named_type()->append_mangled_type_name(gogo, true, ret);
6717 else
6718 this->append_mangled_name(p->type(), gogo, ret);
6719 if (p->has_tag())
6721 const std::string& tag(p->tag());
6722 std::string out;
6723 for (std::string::const_iterator p = tag.begin();
6724 p != tag.end();
6725 ++p)
6727 if (ISALNUM(*p) || *p == '_')
6728 out.push_back(*p);
6729 else
6731 char buf[20];
6732 snprintf(buf, sizeof buf, ".%x.",
6733 static_cast<unsigned int>(*p));
6734 out.append(buf);
6737 char buf[20];
6738 snprintf(buf, sizeof buf, "T%u_",
6739 static_cast<unsigned int>(out.length()));
6740 ret->append(buf);
6741 ret->append(out);
6746 if (this->is_struct_incomparable_)
6747 ret->push_back('x');
6749 ret->push_back('e');
6752 // If the offset of field INDEX in the backend implementation can be
6753 // determined, set *POFFSET to the offset in bytes and return true.
6754 // Otherwise, return false.
6756 bool
6757 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6758 int64_t* poffset)
6760 if (!this->is_backend_type_size_known(gogo))
6761 return false;
6762 Btype* bt = this->get_backend_placeholder(gogo);
6763 *poffset = gogo->backend()->type_field_offset(bt, index);
6764 return true;
6767 // Export.
6769 void
6770 Struct_type::do_export(Export* exp) const
6772 exp->write_c_string("struct { ");
6773 const Struct_field_list* fields = this->fields_;
6774 go_assert(fields != NULL);
6775 for (Struct_field_list::const_iterator p = fields->begin();
6776 p != fields->end();
6777 ++p)
6779 if (p->is_anonymous())
6780 exp->write_string("? ");
6781 else
6783 exp->write_string(p->field_name());
6784 exp->write_c_string(" ");
6786 exp->write_type(p->type());
6788 if (p->has_tag())
6790 exp->write_c_string(" ");
6791 Expression* expr =
6792 Expression::make_string(p->tag(), Linemap::predeclared_location());
6793 expr->export_expression(exp);
6794 delete expr;
6797 exp->write_c_string("; ");
6799 exp->write_c_string("}");
6802 // Import.
6804 Struct_type*
6805 Struct_type::do_import(Import* imp)
6807 imp->require_c_string("struct { ");
6808 Struct_field_list* fields = new Struct_field_list;
6809 if (imp->peek_char() != '}')
6811 while (true)
6813 std::string name;
6814 if (imp->match_c_string("? "))
6815 imp->advance(2);
6816 else
6818 name = imp->read_identifier();
6819 imp->require_c_string(" ");
6821 Type* ftype = imp->read_type();
6823 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6824 sf.set_is_imported();
6826 if (imp->peek_char() == ' ')
6828 imp->advance(1);
6829 Expression* expr = Expression::import_expression(imp);
6830 String_expression* sexpr = expr->string_expression();
6831 go_assert(sexpr != NULL);
6832 sf.set_tag(sexpr->val());
6833 delete sexpr;
6836 imp->require_c_string("; ");
6837 fields->push_back(sf);
6838 if (imp->peek_char() == '}')
6839 break;
6842 imp->require_c_string("}");
6844 return Type::make_struct_type(fields, imp->location());
6847 // Whether we can write this struct type to a C header file.
6848 // We can't if any of the fields are structs defined in a different package.
6850 bool
6851 Struct_type::can_write_to_c_header(
6852 std::vector<const Named_object*>* requires,
6853 std::vector<const Named_object*>* declare) const
6855 const Struct_field_list* fields = this->fields_;
6856 if (fields == NULL || fields->empty())
6857 return false;
6858 int sinks = 0;
6859 for (Struct_field_list::const_iterator p = fields->begin();
6860 p != fields->end();
6861 ++p)
6863 if (p->is_anonymous())
6864 return false;
6865 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6866 return false;
6867 if (Gogo::message_name(p->field_name()) == "_")
6868 sinks++;
6870 if (sinks > 1)
6871 return false;
6872 return true;
6875 // Whether we can write the type T to a C header file.
6877 bool
6878 Struct_type::can_write_type_to_c_header(
6879 const Type* t,
6880 std::vector<const Named_object*>* requires,
6881 std::vector<const Named_object*>* declare) const
6883 t = t->forwarded();
6884 switch (t->classification())
6886 case TYPE_ERROR:
6887 case TYPE_FORWARD:
6888 return false;
6890 case TYPE_VOID:
6891 case TYPE_BOOLEAN:
6892 case TYPE_INTEGER:
6893 case TYPE_FLOAT:
6894 case TYPE_COMPLEX:
6895 case TYPE_STRING:
6896 case TYPE_FUNCTION:
6897 case TYPE_MAP:
6898 case TYPE_CHANNEL:
6899 case TYPE_INTERFACE:
6900 return true;
6902 case TYPE_POINTER:
6903 // Don't try to handle a pointer to an array.
6904 if (t->points_to()->array_type() != NULL
6905 && !t->points_to()->is_slice_type())
6906 return false;
6908 if (t->points_to()->named_type() != NULL
6909 && t->points_to()->struct_type() != NULL)
6910 declare->push_back(t->points_to()->named_type()->named_object());
6911 return true;
6913 case TYPE_STRUCT:
6914 return t->struct_type()->can_write_to_c_header(requires, declare);
6916 case TYPE_ARRAY:
6917 if (t->is_slice_type())
6918 return true;
6919 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6920 requires, declare);
6922 case TYPE_NAMED:
6924 const Named_object* no = t->named_type()->named_object();
6925 if (no->package() != NULL)
6927 if (t->is_unsafe_pointer_type())
6928 return true;
6929 return false;
6931 if (t->struct_type() != NULL)
6933 requires->push_back(no);
6934 return t->struct_type()->can_write_to_c_header(requires, declare);
6936 return this->can_write_type_to_c_header(t->base(), requires, declare);
6939 case TYPE_CALL_MULTIPLE_RESULT:
6940 case TYPE_NIL:
6941 case TYPE_SINK:
6942 default:
6943 go_unreachable();
6947 // Write this struct to a C header file.
6949 void
6950 Struct_type::write_to_c_header(std::ostream& os) const
6952 const Struct_field_list* fields = this->fields_;
6953 for (Struct_field_list::const_iterator p = fields->begin();
6954 p != fields->end();
6955 ++p)
6957 os << '\t';
6958 this->write_field_to_c_header(os, p->field_name(), p->type());
6959 os << ';' << std::endl;
6963 // Write the type of a struct field to a C header file.
6965 void
6966 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6967 const Type *t) const
6969 bool print_name = true;
6970 t = t->forwarded();
6971 switch (t->classification())
6973 case TYPE_VOID:
6974 os << "void";
6975 break;
6977 case TYPE_BOOLEAN:
6978 os << "_Bool";
6979 break;
6981 case TYPE_INTEGER:
6983 const Integer_type* it = t->integer_type();
6984 if (it->is_unsigned())
6985 os << 'u';
6986 os << "int" << it->bits() << "_t";
6988 break;
6990 case TYPE_FLOAT:
6991 switch (t->float_type()->bits())
6993 case 32:
6994 os << "float";
6995 break;
6996 case 64:
6997 os << "double";
6998 break;
6999 default:
7000 go_unreachable();
7002 break;
7004 case TYPE_COMPLEX:
7005 switch (t->complex_type()->bits())
7007 case 64:
7008 os << "float _Complex";
7009 break;
7010 case 128:
7011 os << "double _Complex";
7012 break;
7013 default:
7014 go_unreachable();
7016 break;
7018 case TYPE_STRING:
7019 os << "String";
7020 break;
7022 case TYPE_FUNCTION:
7023 os << "FuncVal*";
7024 break;
7026 case TYPE_POINTER:
7028 std::vector<const Named_object*> requires;
7029 std::vector<const Named_object*> declare;
7030 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
7031 &declare))
7032 os << "void*";
7033 else
7035 this->write_field_to_c_header(os, "", t->points_to());
7036 os << '*';
7039 break;
7041 case TYPE_MAP:
7042 os << "Map*";
7043 break;
7045 case TYPE_CHANNEL:
7046 os << "Chan*";
7047 break;
7049 case TYPE_INTERFACE:
7050 if (t->interface_type()->is_empty())
7051 os << "Eface";
7052 else
7053 os << "Iface";
7054 break;
7056 case TYPE_STRUCT:
7057 os << "struct {" << std::endl;
7058 t->struct_type()->write_to_c_header(os);
7059 os << "\t}";
7060 break;
7062 case TYPE_ARRAY:
7063 if (t->is_slice_type())
7064 os << "Slice";
7065 else
7067 const Type *ele = t;
7068 std::vector<const Type*> array_types;
7069 while (ele->array_type() != NULL && !ele->is_slice_type())
7071 array_types.push_back(ele);
7072 ele = ele->array_type()->element_type();
7074 this->write_field_to_c_header(os, "", ele);
7075 os << ' ' << Gogo::message_name(name);
7076 print_name = false;
7077 while (!array_types.empty())
7079 ele = array_types.back();
7080 array_types.pop_back();
7081 os << '[';
7082 Numeric_constant nc;
7083 if (!ele->array_type()->length()->numeric_constant_value(&nc))
7084 go_unreachable();
7085 mpz_t val;
7086 if (!nc.to_int(&val))
7087 go_unreachable();
7088 char* s = mpz_get_str(NULL, 10, val);
7089 os << s;
7090 free(s);
7091 mpz_clear(val);
7092 os << ']';
7095 break;
7097 case TYPE_NAMED:
7099 const Named_object* no = t->named_type()->named_object();
7100 if (t->struct_type() != NULL)
7101 os << "struct " << no->message_name();
7102 else if (t->is_unsafe_pointer_type())
7103 os << "void*";
7104 else if (t == Type::lookup_integer_type("uintptr"))
7105 os << "uintptr_t";
7106 else
7108 this->write_field_to_c_header(os, name, t->base());
7109 print_name = false;
7112 break;
7114 case TYPE_ERROR:
7115 case TYPE_FORWARD:
7116 case TYPE_CALL_MULTIPLE_RESULT:
7117 case TYPE_NIL:
7118 case TYPE_SINK:
7119 default:
7120 go_unreachable();
7123 if (print_name && !name.empty())
7124 os << ' ' << Gogo::message_name(name);
7127 // Make a struct type.
7129 Struct_type*
7130 Type::make_struct_type(Struct_field_list* fields,
7131 Location location)
7133 return new Struct_type(fields, location);
7136 // Class Array_type.
7138 // Store the length of an array as an int64_t into *PLEN. Return
7139 // false if the length can not be determined. This will assert if
7140 // called for a slice.
7142 bool
7143 Array_type::int_length(int64_t* plen)
7145 go_assert(this->length_ != NULL);
7146 Numeric_constant nc;
7147 if (!this->length_->numeric_constant_value(&nc))
7148 return false;
7149 return nc.to_memory_size(plen);
7152 // Whether two array types are identical.
7154 bool
7155 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
7156 bool errors_are_identical) const
7158 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
7159 cmp_tags, errors_are_identical, NULL))
7160 return false;
7162 if (this->is_array_incomparable_ != t->is_array_incomparable_)
7163 return false;
7165 Expression* l1 = this->length();
7166 Expression* l2 = t->length();
7168 // Slices of the same element type are identical.
7169 if (l1 == NULL && l2 == NULL)
7170 return true;
7172 // Arrays of the same element type are identical if they have the
7173 // same length.
7174 if (l1 != NULL && l2 != NULL)
7176 if (l1 == l2)
7177 return true;
7179 // Try to determine the lengths. If we can't, assume the arrays
7180 // are not identical.
7181 bool ret = false;
7182 Numeric_constant nc1, nc2;
7183 if (l1->numeric_constant_value(&nc1)
7184 && l2->numeric_constant_value(&nc2))
7186 mpz_t v1;
7187 if (nc1.to_int(&v1))
7189 mpz_t v2;
7190 if (nc2.to_int(&v2))
7192 ret = mpz_cmp(v1, v2) == 0;
7193 mpz_clear(v2);
7195 mpz_clear(v1);
7198 return ret;
7201 // Otherwise the arrays are not identical.
7202 return false;
7205 // Traversal.
7208 Array_type::do_traverse(Traverse* traverse)
7210 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7211 return TRAVERSE_EXIT;
7212 if (this->length_ != NULL
7213 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7214 return TRAVERSE_EXIT;
7215 return TRAVERSE_CONTINUE;
7218 // Check that the length is valid.
7220 bool
7221 Array_type::verify_length()
7223 if (this->length_ == NULL)
7224 return true;
7226 Type_context context(Type::lookup_integer_type("int"), false);
7227 this->length_->determine_type(&context);
7229 if (!this->length_->is_constant())
7231 go_error_at(this->length_->location(), "array bound is not constant");
7232 return false;
7235 Numeric_constant nc;
7236 if (!this->length_->numeric_constant_value(&nc))
7238 if (this->length_->type()->integer_type() != NULL
7239 || this->length_->type()->float_type() != NULL)
7240 go_error_at(this->length_->location(), "array bound is not constant");
7241 else
7242 go_error_at(this->length_->location(), "array bound is not numeric");
7243 return false;
7246 Type* int_type = Type::lookup_integer_type("int");
7247 unsigned int tbits = int_type->integer_type()->bits();
7248 unsigned long val;
7249 switch (nc.to_unsigned_long(&val))
7251 case Numeric_constant::NC_UL_VALID:
7252 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7254 go_error_at(this->length_->location(), "array bound overflows");
7255 return false;
7257 break;
7258 case Numeric_constant::NC_UL_NOTINT:
7259 go_error_at(this->length_->location(), "array bound truncated to integer");
7260 return false;
7261 case Numeric_constant::NC_UL_NEGATIVE:
7262 go_error_at(this->length_->location(), "negative array bound");
7263 return false;
7264 case Numeric_constant::NC_UL_BIG:
7266 mpz_t val;
7267 if (!nc.to_int(&val))
7268 go_unreachable();
7269 unsigned int bits = mpz_sizeinbase(val, 2);
7270 mpz_clear(val);
7271 if (bits >= tbits)
7273 go_error_at(this->length_->location(), "array bound overflows");
7274 return false;
7277 break;
7278 default:
7279 go_unreachable();
7282 return true;
7285 // Verify the type.
7287 bool
7288 Array_type::do_verify()
7290 if (this->element_type()->is_error_type())
7291 return false;
7292 if (!this->verify_length())
7293 this->length_ = Expression::make_error(this->length_->location());
7294 return true;
7297 // Whether the type contains pointers. This is always true for a
7298 // slice. For an array it is true if the element type has pointers
7299 // and the length is greater than zero.
7301 bool
7302 Array_type::do_has_pointer() const
7304 if (this->length_ == NULL)
7305 return true;
7306 if (!this->element_type_->has_pointer())
7307 return false;
7309 Numeric_constant nc;
7310 if (!this->length_->numeric_constant_value(&nc))
7312 // Error reported elsewhere.
7313 return false;
7316 unsigned long val;
7317 switch (nc.to_unsigned_long(&val))
7319 case Numeric_constant::NC_UL_VALID:
7320 return val > 0;
7321 case Numeric_constant::NC_UL_BIG:
7322 return true;
7323 default:
7324 // Error reported elsewhere.
7325 return false;
7329 // Whether we can use memcmp to compare this array.
7331 bool
7332 Array_type::do_compare_is_identity(Gogo* gogo)
7334 if (this->length_ == NULL)
7335 return false;
7337 // Check for [...], which indicates that this is not a real type.
7338 if (this->length_->is_nil_expression())
7339 return false;
7341 if (!this->element_type_->compare_is_identity(gogo))
7342 return false;
7344 // If there is any padding, then we can't use memcmp.
7345 int64_t size;
7346 int64_t align;
7347 if (!this->element_type_->backend_type_size(gogo, &size)
7348 || !this->element_type_->backend_type_align(gogo, &align))
7349 return false;
7350 if ((size & (align - 1)) != 0)
7351 return false;
7353 return true;
7356 // Array type hash code.
7358 unsigned int
7359 Array_type::do_hash_for_method(Gogo* gogo) const
7361 unsigned int ret;
7363 // There is no very convenient way to get a hash code for the
7364 // length.
7365 ret = this->element_type_->hash_for_method(gogo) + 1;
7366 if (this->is_array_incomparable_)
7367 ret <<= 1;
7368 return ret;
7371 // Write the hash function for an array which can not use the identify
7372 // function.
7374 void
7375 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7376 Function_type* hash_fntype,
7377 Function_type* equal_fntype)
7379 Location bloc = Linemap::predeclared_location();
7381 // The pointer to the array that we are going to hash. This is an
7382 // argument to the hash function we are implementing here.
7383 Named_object* key_arg = gogo->lookup("key", NULL);
7384 go_assert(key_arg != NULL);
7385 Type* key_arg_type = key_arg->var_value()->type();
7387 // The seed argument to the hash function.
7388 Named_object* seed_arg = gogo->lookup("seed", NULL);
7389 go_assert(seed_arg != NULL);
7391 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7393 // Make a temporary to hold the return value, initialized to the seed.
7394 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7395 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7396 bloc);
7397 gogo->add_statement(retval);
7399 // Make a temporary to hold the key as a uintptr.
7400 ref = Expression::make_var_reference(key_arg, bloc);
7401 ref = Expression::make_cast(uintptr_type, ref, bloc);
7402 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7403 bloc);
7404 gogo->add_statement(key);
7406 // Loop over the array elements.
7407 // for i = range a
7408 Type* int_type = Type::lookup_integer_type("int");
7409 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7410 gogo->add_statement(index);
7412 Expression* iref = Expression::make_temporary_reference(index, bloc);
7413 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7414 Type* pt = Type::make_pointer_type(name != NULL
7415 ? static_cast<Type*>(name)
7416 : static_cast<Type*>(this));
7417 aref = Expression::make_cast(pt, aref, bloc);
7418 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7419 NULL,
7420 aref,
7421 bloc);
7423 gogo->start_block(bloc);
7425 // Get the hash function for the element type.
7426 Named_object* hash_fn;
7427 Named_object* equal_fn;
7428 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7429 hash_fntype, equal_fntype, &hash_fn,
7430 &equal_fn);
7432 // Get a pointer to this element in the loop.
7433 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7434 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7436 // Get the size of each element.
7437 Expression* ele_size = Expression::make_type_info(this->element_type_,
7438 Expression::TYPE_INFO_SIZE);
7440 // Get the hash of this element, passing retval as the seed.
7441 ref = Expression::make_temporary_reference(retval, bloc);
7442 Expression_list* args = new Expression_list();
7443 args->push_back(subkey);
7444 args->push_back(ref);
7445 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7446 Expression* call = Expression::make_call(func, args, false, bloc);
7448 // Set retval to the result.
7449 Temporary_reference_expression* tref =
7450 Expression::make_temporary_reference(retval, bloc);
7451 tref->set_is_lvalue();
7452 Statement* s = Statement::make_assignment(tref, call, bloc);
7453 gogo->add_statement(s);
7455 // Increase the element pointer.
7456 tref = Expression::make_temporary_reference(key, bloc);
7457 tref->set_is_lvalue();
7458 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7459 bloc);
7460 Block* statements = gogo->finish_block(bloc);
7462 for_range->add_statements(statements);
7463 gogo->add_statement(for_range);
7465 // Return retval to the caller of the hash function.
7466 Expression_list* vals = new Expression_list();
7467 ref = Expression::make_temporary_reference(retval, bloc);
7468 vals->push_back(ref);
7469 s = Statement::make_return_statement(vals, bloc);
7470 gogo->add_statement(s);
7473 // Write the equality function for an array which can not use the
7474 // identity function.
7476 void
7477 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7479 Location bloc = Linemap::predeclared_location();
7481 // The pointers to the arrays we are going to compare.
7482 Named_object* key1_arg = gogo->lookup("key1", NULL);
7483 Named_object* key2_arg = gogo->lookup("key2", NULL);
7484 go_assert(key1_arg != NULL && key2_arg != NULL);
7486 // Build temporaries for the keys with the right types.
7487 Type* pt = Type::make_pointer_type(name != NULL
7488 ? static_cast<Type*>(name)
7489 : static_cast<Type*>(this));
7491 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7492 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7493 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7494 gogo->add_statement(p1);
7496 ref = Expression::make_var_reference(key2_arg, bloc);
7497 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7498 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7499 gogo->add_statement(p2);
7501 // Loop over the array elements.
7502 // for i = range a
7503 Type* int_type = Type::lookup_integer_type("int");
7504 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7505 gogo->add_statement(index);
7507 Expression* iref = Expression::make_temporary_reference(index, bloc);
7508 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7509 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7510 NULL,
7511 aref,
7512 bloc);
7514 gogo->start_block(bloc);
7516 // Compare element in P1 and P2.
7517 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7518 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
7519 ref = Expression::make_temporary_reference(index, bloc);
7520 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7522 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7523 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
7524 ref = Expression::make_temporary_reference(index, bloc);
7525 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7527 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7529 // If the elements are not equal, return false.
7530 gogo->start_block(bloc);
7531 Expression_list* vals = new Expression_list();
7532 vals->push_back(Expression::make_boolean(false, bloc));
7533 Statement* s = Statement::make_return_statement(vals, bloc);
7534 gogo->add_statement(s);
7535 Block* then_block = gogo->finish_block(bloc);
7537 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7538 gogo->add_statement(s);
7540 Block* statements = gogo->finish_block(bloc);
7542 for_range->add_statements(statements);
7543 gogo->add_statement(for_range);
7545 // All the elements are equal, so return true.
7546 vals = new Expression_list();
7547 vals->push_back(Expression::make_boolean(true, bloc));
7548 s = Statement::make_return_statement(vals, bloc);
7549 gogo->add_statement(s);
7552 // Get the backend representation of the fields of a slice. This is
7553 // not declared in types.h so that types.h doesn't have to #include
7554 // backend.h.
7556 // We use int for the count and capacity fields. This matches 6g.
7557 // The language more or less assumes that we can't allocate space of a
7558 // size which does not fit in int.
7560 static void
7561 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7562 std::vector<Backend::Btyped_identifier>* bfields)
7564 bfields->resize(3);
7566 Type* pet = Type::make_pointer_type(type->element_type());
7567 Btype* pbet = (use_placeholder
7568 ? pet->get_backend_placeholder(gogo)
7569 : pet->get_backend(gogo));
7570 Location ploc = Linemap::predeclared_location();
7572 Backend::Btyped_identifier* p = &(*bfields)[0];
7573 p->name = "__values";
7574 p->btype = pbet;
7575 p->location = ploc;
7577 Type* int_type = Type::lookup_integer_type("int");
7579 p = &(*bfields)[1];
7580 p->name = "__count";
7581 p->btype = int_type->get_backend(gogo);
7582 p->location = ploc;
7584 p = &(*bfields)[2];
7585 p->name = "__capacity";
7586 p->btype = int_type->get_backend(gogo);
7587 p->location = ploc;
7590 // Get the backend representation for the type of this array. A fixed array is
7591 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7592 // just like an array in C. An open array is a struct with three
7593 // fields: a data pointer, the length, and the capacity.
7595 Btype*
7596 Array_type::do_get_backend(Gogo* gogo)
7598 if (this->length_ == NULL)
7600 std::vector<Backend::Btyped_identifier> bfields;
7601 get_backend_slice_fields(gogo, this, false, &bfields);
7602 return gogo->backend()->struct_type(bfields);
7604 else
7606 Btype* element = this->get_backend_element(gogo, false);
7607 Bexpression* len = this->get_backend_length(gogo);
7608 return gogo->backend()->array_type(element, len);
7612 // Return the backend representation of the element type.
7614 Btype*
7615 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7617 if (use_placeholder)
7618 return this->element_type_->get_backend_placeholder(gogo);
7619 else
7620 return this->element_type_->get_backend(gogo);
7623 // Return the backend representation of the length. The length may be
7624 // computed using a function call, so we must only evaluate it once.
7626 Bexpression*
7627 Array_type::get_backend_length(Gogo* gogo)
7629 go_assert(this->length_ != NULL);
7630 if (this->blength_ == NULL)
7632 Numeric_constant nc;
7633 mpz_t val;
7634 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7636 if (mpz_sgn(val) < 0)
7638 this->blength_ = gogo->backend()->error_expression();
7639 return this->blength_;
7641 Type* t = nc.type();
7642 if (t == NULL)
7643 t = Type::lookup_integer_type("int");
7644 else if (t->is_abstract())
7645 t = t->make_non_abstract_type();
7646 Btype* btype = t->get_backend(gogo);
7647 this->blength_ =
7648 gogo->backend()->integer_constant_expression(btype, val);
7649 mpz_clear(val);
7651 else
7653 // Make up a translation context for the array length
7654 // expression. FIXME: This won't work in general.
7655 Translate_context context(gogo, NULL, NULL, NULL);
7656 this->blength_ = this->length_->get_backend(&context);
7658 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7659 this->blength_ =
7660 gogo->backend()->convert_expression(ibtype, this->blength_,
7661 this->length_->location());
7664 return this->blength_;
7667 // Finish backend representation of the array.
7669 void
7670 Array_type::finish_backend_element(Gogo* gogo)
7672 Type* et = this->array_type()->element_type();
7673 et->get_backend(gogo);
7674 if (this->is_slice_type())
7676 // This relies on the fact that we always use the same
7677 // structure for a pointer to any given type.
7678 Type* pet = Type::make_pointer_type(et);
7679 pet->get_backend(gogo);
7683 // Return an expression for a pointer to the values in ARRAY.
7685 Expression*
7686 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7688 if (this->length() != NULL)
7690 // Fixed array.
7691 go_assert(array->type()->array_type() != NULL);
7692 Type* etype = array->type()->array_type()->element_type();
7693 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7694 return Expression::make_cast(Type::make_pointer_type(etype), array,
7695 array->location());
7698 // Slice.
7700 if (is_lvalue)
7702 Temporary_reference_expression* tref =
7703 array->temporary_reference_expression();
7704 Var_expression* ve = array->var_expression();
7705 if (tref != NULL)
7707 tref = tref->copy()->temporary_reference_expression();
7708 tref->set_is_lvalue();
7709 array = tref;
7711 else if (ve != NULL)
7713 ve = new Var_expression(ve->named_object(), ve->location());
7714 ve->set_in_lvalue_pos();
7715 array = ve;
7719 return Expression::make_slice_info(array,
7720 Expression::SLICE_INFO_VALUE_POINTER,
7721 array->location());
7724 // Return an expression for the length of the array ARRAY which has this
7725 // type.
7727 Expression*
7728 Array_type::get_length(Gogo*, Expression* array) const
7730 if (this->length_ != NULL)
7731 return this->length_;
7733 // This is a slice. We need to read the length field.
7734 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7735 array->location());
7738 // Return an expression for the capacity of the array ARRAY which has this
7739 // type.
7741 Expression*
7742 Array_type::get_capacity(Gogo*, Expression* array) const
7744 if (this->length_ != NULL)
7745 return this->length_;
7747 // This is a slice. We need to read the capacity field.
7748 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7749 array->location());
7752 // Export.
7754 void
7755 Array_type::do_export(Export* exp) const
7757 exp->write_c_string("[");
7758 if (this->length_ != NULL)
7759 this->length_->export_expression(exp);
7760 exp->write_c_string("] ");
7761 exp->write_type(this->element_type_);
7764 // Import.
7766 Array_type*
7767 Array_type::do_import(Import* imp)
7769 imp->require_c_string("[");
7770 Expression* length;
7771 if (imp->peek_char() == ']')
7772 length = NULL;
7773 else
7774 length = Expression::import_expression(imp);
7775 imp->require_c_string("] ");
7776 Type* element_type = imp->read_type();
7777 return Type::make_array_type(element_type, length);
7780 // The type of an array type descriptor.
7782 Type*
7783 Array_type::make_array_type_descriptor_type()
7785 static Type* ret;
7786 if (ret == NULL)
7788 Type* tdt = Type::make_type_descriptor_type();
7789 Type* ptdt = Type::make_type_descriptor_ptr_type();
7791 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7793 Struct_type* sf =
7794 Type::make_builtin_struct_type(4,
7795 "", tdt,
7796 "elem", ptdt,
7797 "slice", ptdt,
7798 "len", uintptr_type);
7800 ret = Type::make_builtin_named_type("ArrayType", sf);
7803 return ret;
7806 // The type of an slice type descriptor.
7808 Type*
7809 Array_type::make_slice_type_descriptor_type()
7811 static Type* ret;
7812 if (ret == NULL)
7814 Type* tdt = Type::make_type_descriptor_type();
7815 Type* ptdt = Type::make_type_descriptor_ptr_type();
7817 Struct_type* sf =
7818 Type::make_builtin_struct_type(2,
7819 "", tdt,
7820 "elem", ptdt);
7822 ret = Type::make_builtin_named_type("SliceType", sf);
7825 return ret;
7828 // Build a type descriptor for an array/slice type.
7830 Expression*
7831 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7833 if (this->length_ != NULL)
7834 return this->array_type_descriptor(gogo, name);
7835 else
7836 return this->slice_type_descriptor(gogo, name);
7839 // Build a type descriptor for an array type.
7841 Expression*
7842 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7844 Location bloc = Linemap::predeclared_location();
7846 Type* atdt = Array_type::make_array_type_descriptor_type();
7848 const Struct_field_list* fields = atdt->struct_type()->fields();
7850 Expression_list* vals = new Expression_list();
7851 vals->reserve(3);
7853 Struct_field_list::const_iterator p = fields->begin();
7854 go_assert(p->is_field_name("_type"));
7855 vals->push_back(this->type_descriptor_constructor(gogo,
7856 RUNTIME_TYPE_KIND_ARRAY,
7857 name, NULL, true));
7859 ++p;
7860 go_assert(p->is_field_name("elem"));
7861 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7863 ++p;
7864 go_assert(p->is_field_name("slice"));
7865 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7866 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7868 ++p;
7869 go_assert(p->is_field_name("len"));
7870 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7872 ++p;
7873 go_assert(p == fields->end());
7875 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7878 // Build a type descriptor for a slice type.
7880 Expression*
7881 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7883 Location bloc = Linemap::predeclared_location();
7885 Type* stdt = Array_type::make_slice_type_descriptor_type();
7887 const Struct_field_list* fields = stdt->struct_type()->fields();
7889 Expression_list* vals = new Expression_list();
7890 vals->reserve(2);
7892 Struct_field_list::const_iterator p = fields->begin();
7893 go_assert(p->is_field_name("_type"));
7894 vals->push_back(this->type_descriptor_constructor(gogo,
7895 RUNTIME_TYPE_KIND_SLICE,
7896 name, NULL, true));
7898 ++p;
7899 go_assert(p->is_field_name("elem"));
7900 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7902 ++p;
7903 go_assert(p == fields->end());
7905 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7908 // Reflection string.
7910 void
7911 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7913 ret->push_back('[');
7914 if (this->length_ != NULL)
7916 Numeric_constant nc;
7917 if (!this->length_->numeric_constant_value(&nc))
7919 go_assert(saw_errors());
7920 return;
7922 mpz_t val;
7923 if (!nc.to_int(&val))
7925 go_assert(saw_errors());
7926 return;
7928 char* s = mpz_get_str(NULL, 10, val);
7929 ret->append(s);
7930 free(s);
7931 mpz_clear(val);
7933 ret->push_back(']');
7935 this->append_reflection(this->element_type_, gogo, ret);
7938 // Mangled name.
7940 void
7941 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7943 ret->push_back('A');
7944 this->append_mangled_name(this->element_type_, gogo, ret);
7945 if (this->length_ != NULL)
7947 Numeric_constant nc;
7948 if (!this->length_->numeric_constant_value(&nc))
7950 go_assert(saw_errors());
7951 return;
7953 mpz_t val;
7954 if (!nc.to_int(&val))
7956 go_assert(saw_errors());
7957 return;
7959 char *s = mpz_get_str(NULL, 10, val);
7960 ret->append(s);
7961 free(s);
7962 mpz_clear(val);
7963 if (this->is_array_incomparable_)
7964 ret->push_back('x');
7966 ret->push_back('e');
7969 // Make an array type.
7971 Array_type*
7972 Type::make_array_type(Type* element_type, Expression* length)
7974 return new Array_type(element_type, length);
7977 // Class Map_type.
7979 Named_object* Map_type::zero_value;
7980 int64_t Map_type::zero_value_size;
7981 int64_t Map_type::zero_value_align;
7983 // If this map requires the "fat" functions, return the pointer to
7984 // pass as the zero value to those functions. Otherwise, in the
7985 // normal case, return NULL. The map requires the "fat" functions if
7986 // the value size is larger than max_zero_size bytes. max_zero_size
7987 // must match maxZero in libgo/go/runtime/hashmap.go.
7989 Expression*
7990 Map_type::fat_zero_value(Gogo* gogo)
7992 int64_t valsize;
7993 if (!this->val_type_->backend_type_size(gogo, &valsize))
7995 go_assert(saw_errors());
7996 return NULL;
7998 if (valsize <= Map_type::max_zero_size)
7999 return NULL;
8001 if (Map_type::zero_value_size < valsize)
8002 Map_type::zero_value_size = valsize;
8004 int64_t valalign;
8005 if (!this->val_type_->backend_type_align(gogo, &valalign))
8007 go_assert(saw_errors());
8008 return NULL;
8011 if (Map_type::zero_value_align < valalign)
8012 Map_type::zero_value_align = valalign;
8014 Location bloc = Linemap::predeclared_location();
8016 if (Map_type::zero_value == NULL)
8018 // The final type will be set in backend_zero_value.
8019 Type* uint8_type = Type::lookup_integer_type("uint8");
8020 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
8021 Array_type* array_type = Type::make_array_type(uint8_type, size);
8022 array_type->set_is_array_incomparable();
8023 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
8024 Map_type::zero_value = Named_object::make_variable("go$zerovalue", NULL,
8025 var);
8028 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
8029 z = Expression::make_unary(OPERATOR_AND, z, bloc);
8030 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8031 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
8032 return z;
8035 // Return whether VAR is the map zero value.
8037 bool
8038 Map_type::is_zero_value(Variable* var)
8040 return (Map_type::zero_value != NULL
8041 && Map_type::zero_value->var_value() == var);
8044 // Return the backend representation for the zero value.
8046 Bvariable*
8047 Map_type::backend_zero_value(Gogo* gogo)
8049 Location bloc = Linemap::predeclared_location();
8051 go_assert(Map_type::zero_value != NULL);
8053 Type* uint8_type = Type::lookup_integer_type("uint8");
8054 Btype* buint8_type = uint8_type->get_backend(gogo);
8056 Type* int_type = Type::lookup_integer_type("int");
8058 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
8059 int_type, bloc);
8060 Translate_context context(gogo, NULL, NULL, NULL);
8061 Bexpression* blength = e->get_backend(&context);
8063 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
8065 std::string zname = Map_type::zero_value->name();
8066 std::string asm_name(go_selectively_encode_id(zname));
8067 Bvariable* zvar =
8068 gogo->backend()->implicit_variable(zname, asm_name,
8069 barray_type, false, true, true,
8070 Map_type::zero_value_align);
8071 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
8072 false, true, true, NULL);
8073 return zvar;
8076 // Traversal.
8079 Map_type::do_traverse(Traverse* traverse)
8081 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
8082 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
8083 return TRAVERSE_EXIT;
8084 return TRAVERSE_CONTINUE;
8087 // Check that the map type is OK.
8089 bool
8090 Map_type::do_verify()
8092 // The runtime support uses "map[void]void".
8093 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
8094 go_error_at(this->location_, "invalid map key type");
8095 if (!this->key_type_->in_heap())
8096 go_error_at(this->location_, "go:notinheap map key not allowed");
8097 if (!this->val_type_->in_heap())
8098 go_error_at(this->location_, "go:notinheap map value not allowed");
8099 return true;
8102 // Whether two map types are identical.
8104 bool
8105 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
8106 bool errors_are_identical) const
8108 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
8109 cmp_tags, errors_are_identical, NULL)
8110 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
8111 cmp_tags, errors_are_identical,
8112 NULL));
8115 // Hash code.
8117 unsigned int
8118 Map_type::do_hash_for_method(Gogo* gogo) const
8120 return (this->key_type_->hash_for_method(gogo)
8121 + this->val_type_->hash_for_method(gogo)
8122 + 2);
8125 // Get the backend representation for a map type. A map type is
8126 // represented as a pointer to a struct. The struct is hmap in
8127 // runtime/hashmap.go.
8129 Btype*
8130 Map_type::do_get_backend(Gogo* gogo)
8132 static Btype* backend_map_type;
8133 if (backend_map_type == NULL)
8135 std::vector<Backend::Btyped_identifier> bfields(9);
8137 Location bloc = Linemap::predeclared_location();
8139 Type* int_type = Type::lookup_integer_type("int");
8140 bfields[0].name = "count";
8141 bfields[0].btype = int_type->get_backend(gogo);
8142 bfields[0].location = bloc;
8144 Type* uint8_type = Type::lookup_integer_type("uint8");
8145 bfields[1].name = "flags";
8146 bfields[1].btype = uint8_type->get_backend(gogo);
8147 bfields[1].location = bloc;
8149 bfields[2].name = "B";
8150 bfields[2].btype = bfields[1].btype;
8151 bfields[2].location = bloc;
8153 Type* uint16_type = Type::lookup_integer_type("uint16");
8154 bfields[3].name = "noverflow";
8155 bfields[3].btype = uint16_type->get_backend(gogo);
8156 bfields[3].location = bloc;
8158 Type* uint32_type = Type::lookup_integer_type("uint32");
8159 bfields[4].name = "hash0";
8160 bfields[4].btype = uint32_type->get_backend(gogo);
8161 bfields[4].location = bloc;
8163 Btype* bvt = gogo->backend()->void_type();
8164 Btype* bpvt = gogo->backend()->pointer_type(bvt);
8165 bfields[5].name = "buckets";
8166 bfields[5].btype = bpvt;
8167 bfields[5].location = bloc;
8169 bfields[6].name = "oldbuckets";
8170 bfields[6].btype = bpvt;
8171 bfields[6].location = bloc;
8173 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8174 bfields[7].name = "nevacuate";
8175 bfields[7].btype = uintptr_type->get_backend(gogo);
8176 bfields[7].location = bloc;
8178 bfields[8].name = "overflow";
8179 bfields[8].btype = bpvt;
8180 bfields[8].location = bloc;
8182 Btype *bt = gogo->backend()->struct_type(bfields);
8183 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
8184 backend_map_type = gogo->backend()->pointer_type(bt);
8186 return backend_map_type;
8189 // The type of a map type descriptor.
8191 Type*
8192 Map_type::make_map_type_descriptor_type()
8194 static Type* ret;
8195 if (ret == NULL)
8197 Type* tdt = Type::make_type_descriptor_type();
8198 Type* ptdt = Type::make_type_descriptor_ptr_type();
8199 Type* uint8_type = Type::lookup_integer_type("uint8");
8200 Type* uint16_type = Type::lookup_integer_type("uint16");
8201 Type* bool_type = Type::lookup_bool_type();
8203 Struct_type* sf =
8204 Type::make_builtin_struct_type(12,
8205 "", tdt,
8206 "key", ptdt,
8207 "elem", ptdt,
8208 "bucket", ptdt,
8209 "hmap", ptdt,
8210 "keysize", uint8_type,
8211 "indirectkey", bool_type,
8212 "valuesize", uint8_type,
8213 "indirectvalue", bool_type,
8214 "bucketsize", uint16_type,
8215 "reflexivekey", bool_type,
8216 "needkeyupdate", bool_type);
8218 ret = Type::make_builtin_named_type("MapType", sf);
8221 return ret;
8224 // Build a type descriptor for a map type.
8226 Expression*
8227 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8229 Location bloc = Linemap::predeclared_location();
8231 Type* mtdt = Map_type::make_map_type_descriptor_type();
8232 Type* uint8_type = Type::lookup_integer_type("uint8");
8233 Type* uint16_type = Type::lookup_integer_type("uint16");
8235 int64_t keysize;
8236 if (!this->key_type_->backend_type_size(gogo, &keysize))
8238 go_error_at(this->location_, "error determining map key type size");
8239 return Expression::make_error(this->location_);
8242 int64_t valsize;
8243 if (!this->val_type_->backend_type_size(gogo, &valsize))
8245 go_error_at(this->location_, "error determining map value type size");
8246 return Expression::make_error(this->location_);
8249 int64_t ptrsize;
8250 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8252 go_assert(saw_errors());
8253 return Expression::make_error(this->location_);
8256 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8257 if (bucket_type == NULL)
8259 go_assert(saw_errors());
8260 return Expression::make_error(this->location_);
8263 int64_t bucketsize;
8264 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8266 go_assert(saw_errors());
8267 return Expression::make_error(this->location_);
8270 const Struct_field_list* fields = mtdt->struct_type()->fields();
8272 Expression_list* vals = new Expression_list();
8273 vals->reserve(12);
8275 Struct_field_list::const_iterator p = fields->begin();
8276 go_assert(p->is_field_name("_type"));
8277 vals->push_back(this->type_descriptor_constructor(gogo,
8278 RUNTIME_TYPE_KIND_MAP,
8279 name, NULL, true));
8281 ++p;
8282 go_assert(p->is_field_name("key"));
8283 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8285 ++p;
8286 go_assert(p->is_field_name("elem"));
8287 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8289 ++p;
8290 go_assert(p->is_field_name("bucket"));
8291 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8293 ++p;
8294 go_assert(p->is_field_name("hmap"));
8295 Type* hmap_type = this->hmap_type(bucket_type);
8296 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8298 ++p;
8299 go_assert(p->is_field_name("keysize"));
8300 if (keysize > Map_type::max_key_size)
8301 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8302 else
8303 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8305 ++p;
8306 go_assert(p->is_field_name("indirectkey"));
8307 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8308 bloc));
8310 ++p;
8311 go_assert(p->is_field_name("valuesize"));
8312 if (valsize > Map_type::max_val_size)
8313 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8314 else
8315 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8317 ++p;
8318 go_assert(p->is_field_name("indirectvalue"));
8319 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8320 bloc));
8322 ++p;
8323 go_assert(p->is_field_name("bucketsize"));
8324 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8325 bloc));
8327 ++p;
8328 go_assert(p->is_field_name("reflexivekey"));
8329 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8330 bloc));
8332 ++p;
8333 go_assert(p->is_field_name("needkeyupdate"));
8334 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8335 bloc));
8337 ++p;
8338 go_assert(p == fields->end());
8340 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8343 // Return the bucket type to use for a map type. This must correspond
8344 // to libgo/go/runtime/hashmap.go.
8346 Type*
8347 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8349 if (this->bucket_type_ != NULL)
8350 return this->bucket_type_;
8352 Type* key_type = this->key_type_;
8353 if (keysize > Map_type::max_key_size)
8354 key_type = Type::make_pointer_type(key_type);
8356 Type* val_type = this->val_type_;
8357 if (valsize > Map_type::max_val_size)
8358 val_type = Type::make_pointer_type(val_type);
8360 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8361 NULL, this->location_);
8363 Type* uint8_type = Type::lookup_integer_type("uint8");
8364 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8365 topbits_type->set_is_array_incomparable();
8366 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8367 keys_type->set_is_array_incomparable();
8368 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8369 values_type->set_is_array_incomparable();
8371 // If keys and values have no pointers, the map implementation can
8372 // keep a list of overflow pointers on the side so that buckets can
8373 // be marked as having no pointers. Arrange for the bucket to have
8374 // no pointers by changing the type of the overflow field to uintptr
8375 // in this case. See comment on the hmap.overflow field in
8376 // libgo/go/runtime/hashmap.go.
8377 Type* overflow_type;
8378 if (!key_type->has_pointer() && !val_type->has_pointer())
8379 overflow_type = Type::lookup_integer_type("uintptr");
8380 else
8382 // This should really be a pointer to the bucket type itself,
8383 // but that would require us to construct a Named_type for it to
8384 // give it a way to refer to itself. Since nothing really cares
8385 // (except perhaps for someone using a debugger) just use an
8386 // unsafe pointer.
8387 overflow_type = Type::make_pointer_type(Type::make_void_type());
8390 // Make sure the overflow pointer is the last memory in the struct,
8391 // because the runtime assumes it can use size-ptrSize as the offset
8392 // of the overflow pointer. We double-check that property below
8393 // once the offsets and size are computed.
8395 int64_t topbits_field_size, topbits_field_align;
8396 int64_t keys_field_size, keys_field_align;
8397 int64_t values_field_size, values_field_align;
8398 int64_t overflow_field_size, overflow_field_align;
8399 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8400 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8401 || !keys_type->backend_type_size(gogo, &keys_field_size)
8402 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8403 || !values_type->backend_type_size(gogo, &values_field_size)
8404 || !values_type->backend_type_field_align(gogo, &values_field_align)
8405 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8406 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8408 go_assert(saw_errors());
8409 return NULL;
8412 Struct_type* ret;
8413 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8414 values_field_align);
8415 if (max_align <= overflow_field_align)
8416 ret = make_builtin_struct_type(4,
8417 "topbits", topbits_type,
8418 "keys", keys_type,
8419 "values", values_type,
8420 "overflow", overflow_type);
8421 else
8423 size_t off = topbits_field_size;
8424 off = ((off + keys_field_align - 1)
8425 &~ static_cast<size_t>(keys_field_align - 1));
8426 off += keys_field_size;
8427 off = ((off + values_field_align - 1)
8428 &~ static_cast<size_t>(values_field_align - 1));
8429 off += values_field_size;
8431 int64_t padded_overflow_field_size =
8432 ((overflow_field_size + max_align - 1)
8433 &~ static_cast<size_t>(max_align - 1));
8435 size_t ovoff = off;
8436 ovoff = ((ovoff + max_align - 1)
8437 &~ static_cast<size_t>(max_align - 1));
8438 size_t pad = (ovoff - off
8439 + padded_overflow_field_size - overflow_field_size);
8441 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8442 this->location_);
8443 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8444 pad_type->set_is_array_incomparable();
8446 ret = make_builtin_struct_type(5,
8447 "topbits", topbits_type,
8448 "keys", keys_type,
8449 "values", values_type,
8450 "pad", pad_type,
8451 "overflow", overflow_type);
8454 // Verify that the overflow field is just before the end of the
8455 // bucket type.
8457 Btype* btype = ret->get_backend(gogo);
8458 int64_t offset = gogo->backend()->type_field_offset(btype,
8459 ret->field_count() - 1);
8460 int64_t size;
8461 if (!ret->backend_type_size(gogo, &size))
8463 go_assert(saw_errors());
8464 return NULL;
8467 int64_t ptr_size;
8468 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8470 go_assert(saw_errors());
8471 return NULL;
8474 go_assert(offset + ptr_size == size);
8476 ret->set_is_struct_incomparable();
8478 this->bucket_type_ = ret;
8479 return ret;
8482 // Return the hashmap type for a map type.
8484 Type*
8485 Map_type::hmap_type(Type* bucket_type)
8487 if (this->hmap_type_ != NULL)
8488 return this->hmap_type_;
8490 Type* int_type = Type::lookup_integer_type("int");
8491 Type* uint8_type = Type::lookup_integer_type("uint8");
8492 Type* uint32_type = Type::lookup_integer_type("uint32");
8493 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8494 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8496 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8498 Struct_type* ret = make_builtin_struct_type(8,
8499 "count", int_type,
8500 "flags", uint8_type,
8501 "B", uint8_type,
8502 "hash0", uint32_type,
8503 "buckets", ptr_bucket_type,
8504 "oldbuckets", ptr_bucket_type,
8505 "nevacuate", uintptr_type,
8506 "overflow", void_ptr_type);
8507 ret->set_is_struct_incomparable();
8508 this->hmap_type_ = ret;
8509 return ret;
8512 // Return the iterator type for a map type. This is the type of the
8513 // value used when doing a range over a map.
8515 Type*
8516 Map_type::hiter_type(Gogo* gogo)
8518 if (this->hiter_type_ != NULL)
8519 return this->hiter_type_;
8521 int64_t keysize, valsize;
8522 if (!this->key_type_->backend_type_size(gogo, &keysize)
8523 || !this->val_type_->backend_type_size(gogo, &valsize))
8525 go_assert(saw_errors());
8526 return NULL;
8529 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8530 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8531 Type* uint8_type = Type::lookup_integer_type("uint8");
8532 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8533 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8534 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8535 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8536 Type* hmap_type = this->hmap_type(bucket_type);
8537 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8538 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8540 Struct_type* ret = make_builtin_struct_type(12,
8541 "key", key_ptr_type,
8542 "val", val_ptr_type,
8543 "t", uint8_ptr_type,
8544 "h", hmap_ptr_type,
8545 "buckets", bucket_ptr_type,
8546 "bptr", bucket_ptr_type,
8547 "overflow0", void_ptr_type,
8548 "overflow1", void_ptr_type,
8549 "startBucket", uintptr_type,
8550 "stuff", uintptr_type,
8551 "bucket", uintptr_type,
8552 "checkBucket", uintptr_type);
8553 ret->set_is_struct_incomparable();
8554 this->hiter_type_ = ret;
8555 return ret;
8558 // Reflection string for a map.
8560 void
8561 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8563 ret->append("map[");
8564 this->append_reflection(this->key_type_, gogo, ret);
8565 ret->append("]");
8566 this->append_reflection(this->val_type_, gogo, ret);
8569 // Mangled name for a map.
8571 void
8572 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8574 ret->push_back('M');
8575 this->append_mangled_name(this->key_type_, gogo, ret);
8576 ret->append("__");
8577 this->append_mangled_name(this->val_type_, gogo, ret);
8580 // Export a map type.
8582 void
8583 Map_type::do_export(Export* exp) const
8585 exp->write_c_string("map [");
8586 exp->write_type(this->key_type_);
8587 exp->write_c_string("] ");
8588 exp->write_type(this->val_type_);
8591 // Import a map type.
8593 Map_type*
8594 Map_type::do_import(Import* imp)
8596 imp->require_c_string("map [");
8597 Type* key_type = imp->read_type();
8598 imp->require_c_string("] ");
8599 Type* val_type = imp->read_type();
8600 return Type::make_map_type(key_type, val_type, imp->location());
8603 // Make a map type.
8605 Map_type*
8606 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8608 return new Map_type(key_type, val_type, location);
8611 // Class Channel_type.
8613 // Verify.
8615 bool
8616 Channel_type::do_verify()
8618 // We have no location for this error, but this is not something the
8619 // ordinary user will see.
8620 if (!this->element_type_->in_heap())
8621 go_error_at(Linemap::unknown_location(),
8622 "chan of go:notinheap type not allowed");
8623 return true;
8626 // Hash code.
8628 unsigned int
8629 Channel_type::do_hash_for_method(Gogo* gogo) const
8631 unsigned int ret = 0;
8632 if (this->may_send_)
8633 ret += 1;
8634 if (this->may_receive_)
8635 ret += 2;
8636 if (this->element_type_ != NULL)
8637 ret += this->element_type_->hash_for_method(gogo) << 2;
8638 return ret << 3;
8641 // Whether this type is the same as T.
8643 bool
8644 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8645 bool errors_are_identical) const
8647 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8648 cmp_tags, errors_are_identical, NULL))
8649 return false;
8650 return (this->may_send_ == t->may_send_
8651 && this->may_receive_ == t->may_receive_);
8654 // Return the backend representation for a channel type. A channel is a pointer
8655 // to a __go_channel struct. The __go_channel struct is defined in
8656 // libgo/runtime/channel.h.
8658 Btype*
8659 Channel_type::do_get_backend(Gogo* gogo)
8661 static Btype* backend_channel_type;
8662 if (backend_channel_type == NULL)
8664 std::vector<Backend::Btyped_identifier> bfields;
8665 Btype* bt = gogo->backend()->struct_type(bfields);
8666 bt = gogo->backend()->named_type("__go_channel", bt,
8667 Linemap::predeclared_location());
8668 backend_channel_type = gogo->backend()->pointer_type(bt);
8670 return backend_channel_type;
8673 // Build a type descriptor for a channel type.
8675 Type*
8676 Channel_type::make_chan_type_descriptor_type()
8678 static Type* ret;
8679 if (ret == NULL)
8681 Type* tdt = Type::make_type_descriptor_type();
8682 Type* ptdt = Type::make_type_descriptor_ptr_type();
8684 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8686 Struct_type* sf =
8687 Type::make_builtin_struct_type(3,
8688 "", tdt,
8689 "elem", ptdt,
8690 "dir", uintptr_type);
8692 ret = Type::make_builtin_named_type("ChanType", sf);
8695 return ret;
8698 // Build a type descriptor for a map type.
8700 Expression*
8701 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8703 Location bloc = Linemap::predeclared_location();
8705 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8707 const Struct_field_list* fields = ctdt->struct_type()->fields();
8709 Expression_list* vals = new Expression_list();
8710 vals->reserve(3);
8712 Struct_field_list::const_iterator p = fields->begin();
8713 go_assert(p->is_field_name("_type"));
8714 vals->push_back(this->type_descriptor_constructor(gogo,
8715 RUNTIME_TYPE_KIND_CHAN,
8716 name, NULL, true));
8718 ++p;
8719 go_assert(p->is_field_name("elem"));
8720 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8722 ++p;
8723 go_assert(p->is_field_name("dir"));
8724 // These bits must match the ones in libgo/runtime/go-type.h.
8725 int val = 0;
8726 if (this->may_receive_)
8727 val |= 1;
8728 if (this->may_send_)
8729 val |= 2;
8730 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8732 ++p;
8733 go_assert(p == fields->end());
8735 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8738 // Reflection string.
8740 void
8741 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8743 if (!this->may_send_)
8744 ret->append("<-");
8745 ret->append("chan");
8746 if (!this->may_receive_)
8747 ret->append("<-");
8748 ret->push_back(' ');
8749 this->append_reflection(this->element_type_, gogo, ret);
8752 // Mangled name.
8754 void
8755 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8757 ret->push_back('C');
8758 this->append_mangled_name(this->element_type_, gogo, ret);
8759 if (this->may_send_)
8760 ret->push_back('s');
8761 if (this->may_receive_)
8762 ret->push_back('r');
8763 ret->push_back('e');
8766 // Export.
8768 void
8769 Channel_type::do_export(Export* exp) const
8771 exp->write_c_string("chan ");
8772 if (this->may_send_ && !this->may_receive_)
8773 exp->write_c_string("-< ");
8774 else if (this->may_receive_ && !this->may_send_)
8775 exp->write_c_string("<- ");
8776 exp->write_type(this->element_type_);
8779 // Import.
8781 Channel_type*
8782 Channel_type::do_import(Import* imp)
8784 imp->require_c_string("chan ");
8786 bool may_send;
8787 bool may_receive;
8788 if (imp->match_c_string("-< "))
8790 imp->advance(3);
8791 may_send = true;
8792 may_receive = false;
8794 else if (imp->match_c_string("<- "))
8796 imp->advance(3);
8797 may_receive = true;
8798 may_send = false;
8800 else
8802 may_send = true;
8803 may_receive = true;
8806 Type* element_type = imp->read_type();
8808 return Type::make_channel_type(may_send, may_receive, element_type);
8811 // Return the type to manage a select statement with ncases case
8812 // statements. A value of this type is allocated on the stack. This
8813 // must match the type hselect in libgo/go/runtime/select.go.
8815 Type*
8816 Channel_type::select_type(int ncases)
8818 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8819 Type* uint16_type = Type::lookup_integer_type("uint16");
8821 static Struct_type* scase_type;
8822 if (scase_type == NULL)
8824 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8825 Type* uint64_type = Type::lookup_integer_type("uint64");
8826 scase_type =
8827 Type::make_builtin_struct_type(7,
8828 "elem", unsafe_pointer_type,
8829 "chan", unsafe_pointer_type,
8830 "pc", uintptr_type,
8831 "kind", uint16_type,
8832 "index", uint16_type,
8833 "receivedp", unsafe_pointer_type,
8834 "releasetime", uint64_type);
8835 scase_type->set_is_struct_incomparable();
8838 Expression* ncases_expr =
8839 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8840 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8841 scases->set_is_array_incomparable();
8842 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8843 order->set_is_array_incomparable();
8845 Struct_type* ret =
8846 Type::make_builtin_struct_type(7,
8847 "tcase", uint16_type,
8848 "ncase", uint16_type,
8849 "pollorder", unsafe_pointer_type,
8850 "lockorder", unsafe_pointer_type,
8851 "scase", scases,
8852 "lockorderarr", order,
8853 "pollorderarr", order);
8854 ret->set_is_struct_incomparable();
8855 return ret;
8858 // Make a new channel type.
8860 Channel_type*
8861 Type::make_channel_type(bool send, bool receive, Type* element_type)
8863 return new Channel_type(send, receive, element_type);
8866 // Class Interface_type.
8868 // Return the list of methods.
8870 const Typed_identifier_list*
8871 Interface_type::methods() const
8873 go_assert(this->methods_are_finalized_ || saw_errors());
8874 return this->all_methods_;
8877 // Return the number of methods.
8879 size_t
8880 Interface_type::method_count() const
8882 go_assert(this->methods_are_finalized_ || saw_errors());
8883 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8886 // Traversal.
8889 Interface_type::do_traverse(Traverse* traverse)
8891 Typed_identifier_list* methods = (this->methods_are_finalized_
8892 ? this->all_methods_
8893 : this->parse_methods_);
8894 if (methods == NULL)
8895 return TRAVERSE_CONTINUE;
8896 return methods->traverse(traverse);
8899 // Finalize the methods. This handles interface inheritance.
8901 void
8902 Interface_type::finalize_methods()
8904 if (this->methods_are_finalized_)
8905 return;
8906 this->methods_are_finalized_ = true;
8907 if (this->parse_methods_ == NULL)
8908 return;
8910 this->all_methods_ = new Typed_identifier_list();
8911 this->all_methods_->reserve(this->parse_methods_->size());
8912 Typed_identifier_list inherit;
8913 for (Typed_identifier_list::const_iterator pm =
8914 this->parse_methods_->begin();
8915 pm != this->parse_methods_->end();
8916 ++pm)
8918 const Typed_identifier* p = &*pm;
8919 if (p->name().empty())
8920 inherit.push_back(*p);
8921 else if (this->find_method(p->name()) == NULL)
8922 this->all_methods_->push_back(*p);
8923 else
8924 go_error_at(p->location(), "duplicate method %qs",
8925 Gogo::message_name(p->name()).c_str());
8928 std::vector<Named_type*> seen;
8929 seen.reserve(inherit.size());
8930 bool issued_recursive_error = false;
8931 while (!inherit.empty())
8933 Type* t = inherit.back().type();
8934 Location tl = inherit.back().location();
8935 inherit.pop_back();
8937 Interface_type* it = t->interface_type();
8938 if (it == NULL)
8940 if (!t->is_error())
8941 go_error_at(tl, "interface contains embedded non-interface");
8942 continue;
8944 if (it == this)
8946 if (!issued_recursive_error)
8948 go_error_at(tl, "invalid recursive interface");
8949 issued_recursive_error = true;
8951 continue;
8954 Named_type* nt = t->named_type();
8955 if (nt != NULL && it->parse_methods_ != NULL)
8957 std::vector<Named_type*>::const_iterator q;
8958 for (q = seen.begin(); q != seen.end(); ++q)
8960 if (*q == nt)
8962 go_error_at(tl, "inherited interface loop");
8963 break;
8966 if (q != seen.end())
8967 continue;
8968 seen.push_back(nt);
8971 const Typed_identifier_list* imethods = it->parse_methods_;
8972 if (imethods == NULL)
8973 continue;
8974 for (Typed_identifier_list::const_iterator q = imethods->begin();
8975 q != imethods->end();
8976 ++q)
8978 if (q->name().empty())
8979 inherit.push_back(*q);
8980 else if (this->find_method(q->name()) == NULL)
8981 this->all_methods_->push_back(Typed_identifier(q->name(),
8982 q->type(), tl));
8983 else
8984 go_error_at(tl, "inherited method %qs is ambiguous",
8985 Gogo::message_name(q->name()).c_str());
8989 if (!this->all_methods_->empty())
8990 this->all_methods_->sort_by_name();
8991 else
8993 delete this->all_methods_;
8994 this->all_methods_ = NULL;
8998 // Return the method NAME, or NULL.
9000 const Typed_identifier*
9001 Interface_type::find_method(const std::string& name) const
9003 go_assert(this->methods_are_finalized_);
9004 if (this->all_methods_ == NULL)
9005 return NULL;
9006 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9007 p != this->all_methods_->end();
9008 ++p)
9009 if (p->name() == name)
9010 return &*p;
9011 return NULL;
9014 // Return the method index.
9016 size_t
9017 Interface_type::method_index(const std::string& name) const
9019 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
9020 size_t ret = 0;
9021 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9022 p != this->all_methods_->end();
9023 ++p, ++ret)
9024 if (p->name() == name)
9025 return ret;
9026 go_unreachable();
9029 // Return whether NAME is an unexported method, for better error
9030 // reporting.
9032 bool
9033 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
9035 go_assert(this->methods_are_finalized_);
9036 if (this->all_methods_ == NULL)
9037 return false;
9038 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9039 p != this->all_methods_->end();
9040 ++p)
9042 const std::string& method_name(p->name());
9043 if (Gogo::is_hidden_name(method_name)
9044 && name == Gogo::unpack_hidden_name(method_name)
9045 && gogo->pack_hidden_name(name, false) != method_name)
9046 return true;
9048 return false;
9051 // Whether this type is identical with T.
9053 bool
9054 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
9055 bool errors_are_identical) const
9057 // If methods have not been finalized, then we are asking whether
9058 // func redeclarations are the same. This is an error, so for
9059 // simplicity we say they are never the same.
9060 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
9061 return false;
9063 // We require the same methods with the same types. The methods
9064 // have already been sorted.
9065 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
9066 return this->all_methods_ == t->all_methods_;
9068 if (this->assume_identical(this, t) || t->assume_identical(t, this))
9069 return true;
9071 Assume_identical* hold_ai = this->assume_identical_;
9072 Assume_identical ai;
9073 ai.t1 = this;
9074 ai.t2 = t;
9075 ai.next = hold_ai;
9076 this->assume_identical_ = &ai;
9078 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
9079 Typed_identifier_list::const_iterator p2;
9080 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
9082 if (p1 == this->all_methods_->end())
9083 break;
9084 if (p1->name() != p2->name()
9085 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
9086 errors_are_identical, NULL))
9087 break;
9090 this->assume_identical_ = hold_ai;
9092 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
9095 // Return true if T1 and T2 are assumed to be identical during a type
9096 // comparison.
9098 bool
9099 Interface_type::assume_identical(const Interface_type* t1,
9100 const Interface_type* t2) const
9102 for (Assume_identical* p = this->assume_identical_;
9103 p != NULL;
9104 p = p->next)
9105 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
9106 return true;
9107 return false;
9110 // Whether we can assign the interface type T to this type. The types
9111 // are known to not be identical. An interface assignment is only
9112 // permitted if T is known to implement all methods in THIS.
9113 // Otherwise a type guard is required.
9115 bool
9116 Interface_type::is_compatible_for_assign(const Interface_type* t,
9117 std::string* reason) const
9119 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
9120 if (this->all_methods_ == NULL)
9121 return true;
9122 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9123 p != this->all_methods_->end();
9124 ++p)
9126 const Typed_identifier* m = t->find_method(p->name());
9127 if (m == NULL)
9129 if (reason != NULL)
9131 char buf[200];
9132 snprintf(buf, sizeof buf,
9133 _("need explicit conversion; missing method %s%s%s"),
9134 go_open_quote(), Gogo::message_name(p->name()).c_str(),
9135 go_close_quote());
9136 reason->assign(buf);
9138 return false;
9141 std::string subreason;
9142 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
9144 if (reason != NULL)
9146 std::string n = Gogo::message_name(p->name());
9147 size_t len = 100 + n.length() + subreason.length();
9148 char* buf = new char[len];
9149 if (subreason.empty())
9150 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9151 go_open_quote(), n.c_str(), go_close_quote());
9152 else
9153 snprintf(buf, len,
9154 _("incompatible type for method %s%s%s (%s)"),
9155 go_open_quote(), n.c_str(), go_close_quote(),
9156 subreason.c_str());
9157 reason->assign(buf);
9158 delete[] buf;
9160 return false;
9164 return true;
9167 // Hash code.
9169 unsigned int
9170 Interface_type::do_hash_for_method(Gogo*) const
9172 go_assert(this->methods_are_finalized_);
9173 unsigned int ret = 0;
9174 if (this->all_methods_ != NULL)
9176 for (Typed_identifier_list::const_iterator p =
9177 this->all_methods_->begin();
9178 p != this->all_methods_->end();
9179 ++p)
9181 ret = Type::hash_string(p->name(), ret);
9182 // We don't use the method type in the hash, to avoid
9183 // infinite recursion if an interface method uses a type
9184 // which is an interface which inherits from the interface
9185 // itself.
9186 // type T interface { F() interface {T}}
9187 ret <<= 1;
9190 return ret;
9193 // Return true if T implements the interface. If it does not, and
9194 // REASON is not NULL, set *REASON to a useful error message.
9196 bool
9197 Interface_type::implements_interface(const Type* t, std::string* reason) const
9199 go_assert(this->methods_are_finalized_);
9200 if (this->all_methods_ == NULL)
9201 return true;
9203 bool is_pointer = false;
9204 const Named_type* nt = t->named_type();
9205 const Struct_type* st = t->struct_type();
9206 // If we start with a named type, we don't dereference it to find
9207 // methods.
9208 if (nt == NULL)
9210 const Type* pt = t->points_to();
9211 if (pt != NULL)
9213 // If T is a pointer to a named type, then we need to look at
9214 // the type to which it points.
9215 is_pointer = true;
9216 nt = pt->named_type();
9217 st = pt->struct_type();
9221 // If we have a named type, get the methods from it rather than from
9222 // any struct type.
9223 if (nt != NULL)
9224 st = NULL;
9226 // Only named and struct types have methods.
9227 if (nt == NULL && st == NULL)
9229 if (reason != NULL)
9231 if (t->points_to() != NULL
9232 && t->points_to()->interface_type() != NULL)
9233 reason->assign(_("pointer to interface type has no methods"));
9234 else
9235 reason->assign(_("type has no methods"));
9237 return false;
9240 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
9242 if (reason != NULL)
9244 if (t->points_to() != NULL
9245 && t->points_to()->interface_type() != NULL)
9246 reason->assign(_("pointer to interface type has no methods"));
9247 else
9248 reason->assign(_("type has no methods"));
9250 return false;
9253 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9254 p != this->all_methods_->end();
9255 ++p)
9257 bool is_ambiguous = false;
9258 Method* m = (nt != NULL
9259 ? nt->method_function(p->name(), &is_ambiguous)
9260 : st->method_function(p->name(), &is_ambiguous));
9261 if (m == NULL)
9263 if (reason != NULL)
9265 std::string n = Gogo::message_name(p->name());
9266 size_t len = n.length() + 100;
9267 char* buf = new char[len];
9268 if (is_ambiguous)
9269 snprintf(buf, len, _("ambiguous method %s%s%s"),
9270 go_open_quote(), n.c_str(), go_close_quote());
9271 else
9272 snprintf(buf, len, _("missing method %s%s%s"),
9273 go_open_quote(), n.c_str(), go_close_quote());
9274 reason->assign(buf);
9275 delete[] buf;
9277 return false;
9280 Function_type *p_fn_type = p->type()->function_type();
9281 Function_type* m_fn_type = m->type()->function_type();
9282 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9283 std::string subreason;
9284 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9285 &subreason))
9287 if (reason != NULL)
9289 std::string n = Gogo::message_name(p->name());
9290 size_t len = 100 + n.length() + subreason.length();
9291 char* buf = new char[len];
9292 if (subreason.empty())
9293 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9294 go_open_quote(), n.c_str(), go_close_quote());
9295 else
9296 snprintf(buf, len,
9297 _("incompatible type for method %s%s%s (%s)"),
9298 go_open_quote(), n.c_str(), go_close_quote(),
9299 subreason.c_str());
9300 reason->assign(buf);
9301 delete[] buf;
9303 return false;
9306 if (!is_pointer && !m->is_value_method())
9308 if (reason != NULL)
9310 std::string n = Gogo::message_name(p->name());
9311 size_t len = 100 + n.length();
9312 char* buf = new char[len];
9313 snprintf(buf, len,
9314 _("method %s%s%s requires a pointer receiver"),
9315 go_open_quote(), n.c_str(), go_close_quote());
9316 reason->assign(buf);
9317 delete[] buf;
9319 return false;
9322 // If the magic //go:nointerface comment was used, the method
9323 // may not be used to implement interfaces.
9324 if (m->nointerface())
9326 if (reason != NULL)
9328 std::string n = Gogo::message_name(p->name());
9329 size_t len = 100 + n.length();
9330 char* buf = new char[len];
9331 snprintf(buf, len,
9332 _("method %s%s%s is marked go:nointerface"),
9333 go_open_quote(), n.c_str(), go_close_quote());
9334 reason->assign(buf);
9335 delete[] buf;
9337 return false;
9341 return true;
9344 // Return the backend representation of the empty interface type. We
9345 // use the same struct for all empty interfaces.
9347 Btype*
9348 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9350 static Btype* empty_interface_type;
9351 if (empty_interface_type == NULL)
9353 std::vector<Backend::Btyped_identifier> bfields(2);
9355 Location bloc = Linemap::predeclared_location();
9357 Type* pdt = Type::make_type_descriptor_ptr_type();
9358 bfields[0].name = "__type_descriptor";
9359 bfields[0].btype = pdt->get_backend(gogo);
9360 bfields[0].location = bloc;
9362 Type* vt = Type::make_pointer_type(Type::make_void_type());
9363 bfields[1].name = "__object";
9364 bfields[1].btype = vt->get_backend(gogo);
9365 bfields[1].location = bloc;
9367 empty_interface_type = gogo->backend()->struct_type(bfields);
9369 return empty_interface_type;
9372 // Return a pointer to the backend representation of the method table.
9374 Btype*
9375 Interface_type::get_backend_methods(Gogo* gogo)
9377 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9378 return this->bmethods_;
9380 Location loc = this->location();
9382 std::vector<Backend::Btyped_identifier>
9383 mfields(this->all_methods_->size() + 1);
9385 Type* pdt = Type::make_type_descriptor_ptr_type();
9386 mfields[0].name = "__type_descriptor";
9387 mfields[0].btype = pdt->get_backend(gogo);
9388 mfields[0].location = loc;
9390 std::string last_name = "";
9391 size_t i = 1;
9392 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9393 p != this->all_methods_->end();
9394 ++p, ++i)
9396 // The type of the method in Go only includes the parameters.
9397 // The actual method also has a receiver, which is always a
9398 // pointer. We need to add that pointer type here in order to
9399 // generate the correct type for the backend.
9400 Function_type* ft = p->type()->function_type();
9401 go_assert(ft->receiver() == NULL);
9403 const Typed_identifier_list* params = ft->parameters();
9404 Typed_identifier_list* mparams = new Typed_identifier_list();
9405 if (params != NULL)
9406 mparams->reserve(params->size() + 1);
9407 Type* vt = Type::make_pointer_type(Type::make_void_type());
9408 mparams->push_back(Typed_identifier("", vt, ft->location()));
9409 if (params != NULL)
9411 for (Typed_identifier_list::const_iterator pp = params->begin();
9412 pp != params->end();
9413 ++pp)
9414 mparams->push_back(*pp);
9417 Typed_identifier_list* mresults = (ft->results() == NULL
9418 ? NULL
9419 : ft->results()->copy());
9420 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9421 ft->location());
9423 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9424 mfields[i].btype = mft->get_backend_fntype(gogo);
9425 mfields[i].location = loc;
9427 // Sanity check: the names should be sorted.
9428 go_assert(Gogo::unpack_hidden_name(p->name())
9429 > Gogo::unpack_hidden_name(last_name));
9430 last_name = p->name();
9433 Btype* st = gogo->backend()->struct_type(mfields);
9434 Btype* ret = gogo->backend()->pointer_type(st);
9436 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
9437 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
9438 this->bmethods_ = ret;
9439 this->bmethods_is_placeholder_ = false;
9440 return ret;
9443 // Return a placeholder for the pointer to the backend methods table.
9445 Btype*
9446 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9448 if (this->bmethods_ == NULL)
9450 Location loc = this->location();
9451 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
9452 false);
9453 this->bmethods_is_placeholder_ = true;
9455 return this->bmethods_;
9458 // Return the fields of a non-empty interface type. This is not
9459 // declared in types.h so that types.h doesn't have to #include
9460 // backend.h.
9462 static void
9463 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9464 bool use_placeholder,
9465 std::vector<Backend::Btyped_identifier>* bfields)
9467 Location loc = type->location();
9469 bfields->resize(2);
9471 (*bfields)[0].name = "__methods";
9472 (*bfields)[0].btype = (use_placeholder
9473 ? type->get_backend_methods_placeholder(gogo)
9474 : type->get_backend_methods(gogo));
9475 (*bfields)[0].location = loc;
9477 Type* vt = Type::make_pointer_type(Type::make_void_type());
9478 (*bfields)[1].name = "__object";
9479 (*bfields)[1].btype = vt->get_backend(gogo);
9480 (*bfields)[1].location = Linemap::predeclared_location();
9483 // Return the backend representation for an interface type. An interface is a
9484 // pointer to a struct. The struct has three fields. The first field is a
9485 // pointer to the type descriptor for the dynamic type of the object.
9486 // The second field is a pointer to a table of methods for the
9487 // interface to be used with the object. The third field is the value
9488 // of the object itself.
9490 Btype*
9491 Interface_type::do_get_backend(Gogo* gogo)
9493 if (this->is_empty())
9494 return Interface_type::get_backend_empty_interface_type(gogo);
9495 else
9497 if (this->interface_btype_ != NULL)
9498 return this->interface_btype_;
9499 this->interface_btype_ =
9500 gogo->backend()->placeholder_struct_type("", this->location_);
9501 std::vector<Backend::Btyped_identifier> bfields;
9502 get_backend_interface_fields(gogo, this, false, &bfields);
9503 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9504 bfields))
9505 this->interface_btype_ = gogo->backend()->error_type();
9506 return this->interface_btype_;
9510 // Finish the backend representation of the methods.
9512 void
9513 Interface_type::finish_backend_methods(Gogo* gogo)
9515 if (!this->is_empty())
9517 const Typed_identifier_list* methods = this->methods();
9518 if (methods != NULL)
9520 for (Typed_identifier_list::const_iterator p = methods->begin();
9521 p != methods->end();
9522 ++p)
9523 p->type()->get_backend(gogo);
9526 // Getting the backend methods now will set the placeholder
9527 // pointer.
9528 this->get_backend_methods(gogo);
9532 // The type of an interface type descriptor.
9534 Type*
9535 Interface_type::make_interface_type_descriptor_type()
9537 static Type* ret;
9538 if (ret == NULL)
9540 Type* tdt = Type::make_type_descriptor_type();
9541 Type* ptdt = Type::make_type_descriptor_ptr_type();
9543 Type* string_type = Type::lookup_string_type();
9544 Type* pointer_string_type = Type::make_pointer_type(string_type);
9546 Struct_type* sm =
9547 Type::make_builtin_struct_type(3,
9548 "name", pointer_string_type,
9549 "pkgPath", pointer_string_type,
9550 "typ", ptdt);
9552 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9554 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9556 Struct_type* s = Type::make_builtin_struct_type(2,
9557 "", tdt,
9558 "methods", slice_nsm);
9560 ret = Type::make_builtin_named_type("InterfaceType", s);
9563 return ret;
9566 // Build a type descriptor for an interface type.
9568 Expression*
9569 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9571 Location bloc = Linemap::predeclared_location();
9573 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9575 const Struct_field_list* ifields = itdt->struct_type()->fields();
9577 Expression_list* ivals = new Expression_list();
9578 ivals->reserve(2);
9580 Struct_field_list::const_iterator pif = ifields->begin();
9581 go_assert(pif->is_field_name("_type"));
9582 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9583 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9584 true));
9586 ++pif;
9587 go_assert(pif->is_field_name("methods"));
9589 Expression_list* methods = new Expression_list();
9590 if (this->all_methods_ != NULL)
9592 Type* elemtype = pif->type()->array_type()->element_type();
9594 methods->reserve(this->all_methods_->size());
9595 for (Typed_identifier_list::const_iterator pm =
9596 this->all_methods_->begin();
9597 pm != this->all_methods_->end();
9598 ++pm)
9600 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9602 Expression_list* mvals = new Expression_list();
9603 mvals->reserve(3);
9605 Struct_field_list::const_iterator pmf = mfields->begin();
9606 go_assert(pmf->is_field_name("name"));
9607 std::string s = Gogo::unpack_hidden_name(pm->name());
9608 Expression* e = Expression::make_string(s, bloc);
9609 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9611 ++pmf;
9612 go_assert(pmf->is_field_name("pkgPath"));
9613 if (!Gogo::is_hidden_name(pm->name()))
9614 mvals->push_back(Expression::make_nil(bloc));
9615 else
9617 s = Gogo::hidden_name_pkgpath(pm->name());
9618 e = Expression::make_string(s, bloc);
9619 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9622 ++pmf;
9623 go_assert(pmf->is_field_name("typ"));
9624 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9626 ++pmf;
9627 go_assert(pmf == mfields->end());
9629 e = Expression::make_struct_composite_literal(elemtype, mvals,
9630 bloc);
9631 methods->push_back(e);
9635 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9636 methods, bloc));
9638 ++pif;
9639 go_assert(pif == ifields->end());
9641 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9644 // Reflection string.
9646 void
9647 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9649 ret->append("interface {");
9650 const Typed_identifier_list* methods = this->parse_methods_;
9651 if (methods != NULL)
9653 ret->push_back(' ');
9654 for (Typed_identifier_list::const_iterator p = methods->begin();
9655 p != methods->end();
9656 ++p)
9658 if (p != methods->begin())
9659 ret->append("; ");
9660 if (p->name().empty())
9661 this->append_reflection(p->type(), gogo, ret);
9662 else
9664 if (!Gogo::is_hidden_name(p->name()))
9665 ret->append(p->name());
9666 else if (gogo->pkgpath_from_option())
9667 ret->append(p->name().substr(1));
9668 else
9670 // If no -fgo-pkgpath option, backward compatibility
9671 // for how this used to work before -fgo-pkgpath was
9672 // introduced.
9673 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9674 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9675 ret->push_back('.');
9676 ret->append(Gogo::unpack_hidden_name(p->name()));
9678 std::string sub = p->type()->reflection(gogo);
9679 go_assert(sub.compare(0, 4, "func") == 0);
9680 sub = sub.substr(4);
9681 ret->append(sub);
9684 ret->push_back(' ');
9686 ret->append("}");
9689 // Mangled name.
9691 void
9692 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9694 go_assert(this->methods_are_finalized_);
9696 ret->push_back('I');
9698 const Typed_identifier_list* methods = this->all_methods_;
9699 if (methods != NULL && !this->seen_)
9701 this->seen_ = true;
9702 for (Typed_identifier_list::const_iterator p = methods->begin();
9703 p != methods->end();
9704 ++p)
9706 if (!p->name().empty())
9708 std::string n(Gogo::mangle_possibly_hidden_name(p->name()));
9709 char buf[20];
9710 snprintf(buf, sizeof buf, "%u_",
9711 static_cast<unsigned int>(n.length()));
9712 ret->append(buf);
9713 ret->append(n);
9715 this->append_mangled_name(p->type(), gogo, ret);
9717 this->seen_ = false;
9720 ret->push_back('e');
9723 // Export.
9725 void
9726 Interface_type::do_export(Export* exp) const
9728 exp->write_c_string("interface { ");
9730 const Typed_identifier_list* methods = this->parse_methods_;
9731 if (methods != NULL)
9733 for (Typed_identifier_list::const_iterator pm = methods->begin();
9734 pm != methods->end();
9735 ++pm)
9737 if (pm->name().empty())
9739 exp->write_c_string("? ");
9740 exp->write_type(pm->type());
9742 else
9744 exp->write_string(pm->name());
9745 exp->write_c_string(" (");
9747 const Function_type* fntype = pm->type()->function_type();
9749 bool first = true;
9750 const Typed_identifier_list* parameters = fntype->parameters();
9751 if (parameters != NULL)
9753 bool is_varargs = fntype->is_varargs();
9754 for (Typed_identifier_list::const_iterator pp =
9755 parameters->begin();
9756 pp != parameters->end();
9757 ++pp)
9759 if (first)
9760 first = false;
9761 else
9762 exp->write_c_string(", ");
9763 exp->write_name(pp->name());
9764 exp->write_c_string(" ");
9765 if (!is_varargs || pp + 1 != parameters->end())
9766 exp->write_type(pp->type());
9767 else
9769 exp->write_c_string("...");
9770 Type *pptype = pp->type();
9771 exp->write_type(pptype->array_type()->element_type());
9776 exp->write_c_string(")");
9778 const Typed_identifier_list* results = fntype->results();
9779 if (results != NULL)
9781 exp->write_c_string(" ");
9782 if (results->size() == 1 && results->begin()->name().empty())
9783 exp->write_type(results->begin()->type());
9784 else
9786 first = true;
9787 exp->write_c_string("(");
9788 for (Typed_identifier_list::const_iterator p =
9789 results->begin();
9790 p != results->end();
9791 ++p)
9793 if (first)
9794 first = false;
9795 else
9796 exp->write_c_string(", ");
9797 exp->write_name(p->name());
9798 exp->write_c_string(" ");
9799 exp->write_type(p->type());
9801 exp->write_c_string(")");
9806 exp->write_c_string("; ");
9810 exp->write_c_string("}");
9813 // Import an interface type.
9815 Interface_type*
9816 Interface_type::do_import(Import* imp)
9818 imp->require_c_string("interface { ");
9820 Typed_identifier_list* methods = new Typed_identifier_list;
9821 while (imp->peek_char() != '}')
9823 std::string name = imp->read_identifier();
9825 if (name == "?")
9827 imp->require_c_string(" ");
9828 Type* t = imp->read_type();
9829 methods->push_back(Typed_identifier("", t, imp->location()));
9830 imp->require_c_string("; ");
9831 continue;
9834 imp->require_c_string(" (");
9836 Typed_identifier_list* parameters;
9837 bool is_varargs = false;
9838 if (imp->peek_char() == ')')
9839 parameters = NULL;
9840 else
9842 parameters = new Typed_identifier_list;
9843 while (true)
9845 std::string name = imp->read_name();
9846 imp->require_c_string(" ");
9848 if (imp->match_c_string("..."))
9850 imp->advance(3);
9851 is_varargs = true;
9854 Type* ptype = imp->read_type();
9855 if (is_varargs)
9856 ptype = Type::make_array_type(ptype, NULL);
9857 parameters->push_back(Typed_identifier(name, ptype,
9858 imp->location()));
9859 if (imp->peek_char() != ',')
9860 break;
9861 go_assert(!is_varargs);
9862 imp->require_c_string(", ");
9865 imp->require_c_string(")");
9867 Typed_identifier_list* results;
9868 if (imp->peek_char() != ' ')
9869 results = NULL;
9870 else
9872 results = new Typed_identifier_list;
9873 imp->advance(1);
9874 if (imp->peek_char() != '(')
9876 Type* rtype = imp->read_type();
9877 results->push_back(Typed_identifier("", rtype, imp->location()));
9879 else
9881 imp->advance(1);
9882 while (true)
9884 std::string name = imp->read_name();
9885 imp->require_c_string(" ");
9886 Type* rtype = imp->read_type();
9887 results->push_back(Typed_identifier(name, rtype,
9888 imp->location()));
9889 if (imp->peek_char() != ',')
9890 break;
9891 imp->require_c_string(", ");
9893 imp->require_c_string(")");
9897 Function_type* fntype = Type::make_function_type(NULL, parameters,
9898 results,
9899 imp->location());
9900 if (is_varargs)
9901 fntype->set_is_varargs();
9902 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9904 imp->require_c_string("; ");
9907 imp->require_c_string("}");
9909 if (methods->empty())
9911 delete methods;
9912 methods = NULL;
9915 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9916 ret->package_ = imp->package();
9917 return ret;
9920 // Make an interface type.
9922 Interface_type*
9923 Type::make_interface_type(Typed_identifier_list* methods,
9924 Location location)
9926 return new Interface_type(methods, location);
9929 // Make an empty interface type.
9931 Interface_type*
9932 Type::make_empty_interface_type(Location location)
9934 Interface_type* ret = new Interface_type(NULL, location);
9935 ret->finalize_methods();
9936 return ret;
9939 // Class Method.
9941 // Bind a method to an object.
9943 Expression*
9944 Method::bind_method(Expression* expr, Location location) const
9946 if (this->stub_ == NULL)
9948 // When there is no stub object, the binding is determined by
9949 // the child class.
9950 return this->do_bind_method(expr, location);
9952 return Expression::make_bound_method(expr, this, this->stub_, location);
9955 // Return the named object associated with a method. This may only be
9956 // called after methods are finalized.
9958 Named_object*
9959 Method::named_object() const
9961 if (this->stub_ != NULL)
9962 return this->stub_;
9963 return this->do_named_object();
9966 // Class Named_method.
9968 // The type of the method.
9970 Function_type*
9971 Named_method::do_type() const
9973 if (this->named_object_->is_function())
9974 return this->named_object_->func_value()->type();
9975 else if (this->named_object_->is_function_declaration())
9976 return this->named_object_->func_declaration_value()->type();
9977 else
9978 go_unreachable();
9981 // Return the location of the method receiver.
9983 Location
9984 Named_method::do_receiver_location() const
9986 return this->do_type()->receiver()->location();
9989 // Bind a method to an object.
9991 Expression*
9992 Named_method::do_bind_method(Expression* expr, Location location) const
9994 Named_object* no = this->named_object_;
9995 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9996 no, location);
9997 // If this is not a local method, and it does not use a stub, then
9998 // the real method expects a different type. We need to cast the
9999 // first argument.
10000 if (this->depth() > 0 && !this->needs_stub_method())
10002 Function_type* ftype = this->do_type();
10003 go_assert(ftype->is_method());
10004 Type* frtype = ftype->receiver()->type();
10005 bme->set_first_argument_type(frtype);
10007 return bme;
10010 // Return whether this method should not participate in interfaces.
10012 bool
10013 Named_method::do_nointerface() const
10015 Named_object* no = this->named_object_;
10016 return no->is_function() && no->func_value()->nointerface();
10019 // Class Interface_method.
10021 // Bind a method to an object.
10023 Expression*
10024 Interface_method::do_bind_method(Expression* expr,
10025 Location location) const
10027 return Expression::make_interface_field_reference(expr, this->name_,
10028 location);
10031 // Class Methods.
10033 // Insert a new method. Return true if it was inserted, false
10034 // otherwise.
10036 bool
10037 Methods::insert(const std::string& name, Method* m)
10039 std::pair<Method_map::iterator, bool> ins =
10040 this->methods_.insert(std::make_pair(name, m));
10041 if (ins.second)
10042 return true;
10043 else
10045 Method* old_method = ins.first->second;
10046 if (m->depth() < old_method->depth())
10048 delete old_method;
10049 ins.first->second = m;
10050 return true;
10052 else
10054 if (m->depth() == old_method->depth())
10055 old_method->set_is_ambiguous();
10056 return false;
10061 // Return the number of unambiguous methods.
10063 size_t
10064 Methods::count() const
10066 size_t ret = 0;
10067 for (Method_map::const_iterator p = this->methods_.begin();
10068 p != this->methods_.end();
10069 ++p)
10070 if (!p->second->is_ambiguous())
10071 ++ret;
10072 return ret;
10075 // Class Named_type.
10077 // Return the name of the type.
10079 const std::string&
10080 Named_type::name() const
10082 return this->named_object_->name();
10085 // Return the name of the type to use in an error message.
10087 std::string
10088 Named_type::message_name() const
10090 return this->named_object_->message_name();
10093 // Return the base type for this type. We have to be careful about
10094 // circular type definitions, which are invalid but may be seen here.
10096 Type*
10097 Named_type::named_base()
10099 if (this->seen_)
10100 return this;
10101 this->seen_ = true;
10102 Type* ret = this->type_->base();
10103 this->seen_ = false;
10104 return ret;
10107 const Type*
10108 Named_type::named_base() const
10110 if (this->seen_)
10111 return this;
10112 this->seen_ = true;
10113 const Type* ret = this->type_->base();
10114 this->seen_ = false;
10115 return ret;
10118 // Return whether this is an error type. We have to be careful about
10119 // circular type definitions, which are invalid but may be seen here.
10121 bool
10122 Named_type::is_named_error_type() const
10124 if (this->seen_)
10125 return false;
10126 this->seen_ = true;
10127 bool ret = this->type_->is_error_type();
10128 this->seen_ = false;
10129 return ret;
10132 // Whether this type is comparable. We have to be careful about
10133 // circular type definitions.
10135 bool
10136 Named_type::named_type_is_comparable(std::string* reason) const
10138 if (this->seen_)
10139 return false;
10140 this->seen_ = true;
10141 bool ret = Type::are_compatible_for_comparison(true, this->type_,
10142 this->type_, reason);
10143 this->seen_ = false;
10144 return ret;
10147 // Add a method to this type.
10149 Named_object*
10150 Named_type::add_method(const std::string& name, Function* function)
10152 go_assert(!this->is_alias_);
10153 if (this->local_methods_ == NULL)
10154 this->local_methods_ = new Bindings(NULL);
10155 return this->local_methods_->add_function(name, NULL, function);
10158 // Add a method declaration to this type.
10160 Named_object*
10161 Named_type::add_method_declaration(const std::string& name, Package* package,
10162 Function_type* type,
10163 Location location)
10165 go_assert(!this->is_alias_);
10166 if (this->local_methods_ == NULL)
10167 this->local_methods_ = new Bindings(NULL);
10168 return this->local_methods_->add_function_declaration(name, package, type,
10169 location);
10172 // Add an existing method to this type.
10174 void
10175 Named_type::add_existing_method(Named_object* no)
10177 go_assert(!this->is_alias_);
10178 if (this->local_methods_ == NULL)
10179 this->local_methods_ = new Bindings(NULL);
10180 this->local_methods_->add_named_object(no);
10183 // Look for a local method NAME, and returns its named object, or NULL
10184 // if not there.
10186 Named_object*
10187 Named_type::find_local_method(const std::string& name) const
10189 if (this->is_error_)
10190 return NULL;
10191 if (this->is_alias_)
10193 Named_type* nt = this->type_->named_type();
10194 if (nt != NULL)
10196 if (this->seen_alias_)
10197 return NULL;
10198 this->seen_alias_ = true;
10199 Named_object* ret = nt->find_local_method(name);
10200 this->seen_alias_ = false;
10201 return ret;
10203 return NULL;
10205 if (this->local_methods_ == NULL)
10206 return NULL;
10207 return this->local_methods_->lookup(name);
10210 // Return the list of local methods.
10212 const Bindings*
10213 Named_type::local_methods() const
10215 if (this->is_error_)
10216 return NULL;
10217 if (this->is_alias_)
10219 Named_type* nt = this->type_->named_type();
10220 if (nt != NULL)
10222 if (this->seen_alias_)
10223 return NULL;
10224 this->seen_alias_ = true;
10225 const Bindings* ret = nt->local_methods();
10226 this->seen_alias_ = false;
10227 return ret;
10229 return NULL;
10231 return this->local_methods_;
10234 // Return whether NAME is an unexported field or method, for better
10235 // error reporting.
10237 bool
10238 Named_type::is_unexported_local_method(Gogo* gogo,
10239 const std::string& name) const
10241 if (this->is_error_)
10242 return false;
10243 if (this->is_alias_)
10245 Named_type* nt = this->type_->named_type();
10246 if (nt != NULL)
10248 if (this->seen_alias_)
10249 return false;
10250 this->seen_alias_ = true;
10251 bool ret = nt->is_unexported_local_method(gogo, name);
10252 this->seen_alias_ = false;
10253 return ret;
10255 return false;
10257 Bindings* methods = this->local_methods_;
10258 if (methods != NULL)
10260 for (Bindings::const_declarations_iterator p =
10261 methods->begin_declarations();
10262 p != methods->end_declarations();
10263 ++p)
10265 if (Gogo::is_hidden_name(p->first)
10266 && name == Gogo::unpack_hidden_name(p->first)
10267 && gogo->pack_hidden_name(name, false) != p->first)
10268 return true;
10271 return false;
10274 // Build the complete list of methods for this type, which means
10275 // recursively including all methods for anonymous fields. Create all
10276 // stub methods.
10278 void
10279 Named_type::finalize_methods(Gogo* gogo)
10281 if (this->is_alias_)
10282 return;
10283 if (this->all_methods_ != NULL)
10284 return;
10286 if (this->local_methods_ != NULL
10287 && (this->points_to() != NULL || this->interface_type() != NULL))
10289 const Bindings* lm = this->local_methods_;
10290 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10291 p != lm->end_declarations();
10292 ++p)
10293 go_error_at(p->second->location(),
10294 "invalid pointer or interface receiver type");
10295 delete this->local_methods_;
10296 this->local_methods_ = NULL;
10297 return;
10300 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10303 // Return whether this type has any methods.
10305 bool
10306 Named_type::has_any_methods() const
10308 if (this->is_error_)
10309 return false;
10310 if (this->is_alias_)
10312 if (this->type_->named_type() != NULL)
10314 if (this->seen_alias_)
10315 return false;
10316 this->seen_alias_ = true;
10317 bool ret = this->type_->named_type()->has_any_methods();
10318 this->seen_alias_ = false;
10319 return ret;
10321 if (this->type_->struct_type() != NULL)
10322 return this->type_->struct_type()->has_any_methods();
10323 return false;
10325 return this->all_methods_ != NULL;
10328 // Return the methods for this type.
10330 const Methods*
10331 Named_type::methods() const
10333 if (this->is_error_)
10334 return NULL;
10335 if (this->is_alias_)
10337 if (this->type_->named_type() != NULL)
10339 if (this->seen_alias_)
10340 return NULL;
10341 this->seen_alias_ = true;
10342 const Methods* ret = this->type_->named_type()->methods();
10343 this->seen_alias_ = false;
10344 return ret;
10346 if (this->type_->struct_type() != NULL)
10347 return this->type_->struct_type()->methods();
10348 return NULL;
10350 return this->all_methods_;
10353 // Return the method NAME, or NULL if there isn't one or if it is
10354 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10355 // ambiguous.
10357 Method*
10358 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10360 if (this->is_error_)
10361 return NULL;
10362 if (this->is_alias_)
10364 if (is_ambiguous != NULL)
10365 *is_ambiguous = false;
10366 if (this->type_->named_type() != NULL)
10368 if (this->seen_alias_)
10369 return NULL;
10370 this->seen_alias_ = true;
10371 Named_type* nt = this->type_->named_type();
10372 Method* ret = nt->method_function(name, is_ambiguous);
10373 this->seen_alias_ = false;
10374 return ret;
10376 if (this->type_->struct_type() != NULL)
10377 return this->type_->struct_type()->method_function(name, is_ambiguous);
10378 return NULL;
10380 return Type::method_function(this->all_methods_, name, is_ambiguous);
10383 // Return a pointer to the interface method table for this type for
10384 // the interface INTERFACE. IS_POINTER is true if this is for a
10385 // pointer to THIS.
10387 Expression*
10388 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10390 if (this->is_error_)
10391 return Expression::make_error(this->location_);
10392 if (this->is_alias_)
10394 if (this->type_->named_type() != NULL)
10396 if (this->seen_alias_)
10397 return Expression::make_error(this->location_);
10398 this->seen_alias_ = true;
10399 Named_type* nt = this->type_->named_type();
10400 Expression* ret = nt->interface_method_table(interface, is_pointer);
10401 this->seen_alias_ = false;
10402 return ret;
10404 if (this->type_->struct_type() != NULL)
10405 return this->type_->struct_type()->interface_method_table(interface,
10406 is_pointer);
10407 go_unreachable();
10409 return Type::interface_method_table(this, interface, is_pointer,
10410 &this->interface_method_tables_,
10411 &this->pointer_interface_method_tables_);
10414 // Look for a use of a complete type within another type. This is
10415 // used to check that we don't try to use a type within itself.
10417 class Find_type_use : public Traverse
10419 public:
10420 Find_type_use(Named_type* find_type)
10421 : Traverse(traverse_types),
10422 find_type_(find_type), found_(false)
10425 // Whether we found the type.
10426 bool
10427 found() const
10428 { return this->found_; }
10430 protected:
10432 type(Type*);
10434 private:
10435 // The type we are looking for.
10436 Named_type* find_type_;
10437 // Whether we found the type.
10438 bool found_;
10441 // Check for FIND_TYPE in TYPE.
10444 Find_type_use::type(Type* type)
10446 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10448 this->found_ = true;
10449 return TRAVERSE_EXIT;
10452 // It's OK if we see a reference to the type in any type which is
10453 // essentially a pointer: a pointer, a slice, a function, a map, or
10454 // a channel.
10455 if (type->points_to() != NULL
10456 || type->is_slice_type()
10457 || type->function_type() != NULL
10458 || type->map_type() != NULL
10459 || type->channel_type() != NULL)
10460 return TRAVERSE_SKIP_COMPONENTS;
10462 // For an interface, a reference to the type in a method type should
10463 // be ignored, but we have to consider direct inheritance. When
10464 // this is called, there may be cases of direct inheritance
10465 // represented as a method with no name.
10466 if (type->interface_type() != NULL)
10468 const Typed_identifier_list* methods = type->interface_type()->methods();
10469 if (methods != NULL)
10471 for (Typed_identifier_list::const_iterator p = methods->begin();
10472 p != methods->end();
10473 ++p)
10475 if (p->name().empty())
10477 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10478 return TRAVERSE_EXIT;
10482 return TRAVERSE_SKIP_COMPONENTS;
10485 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10486 // to convert TYPE to the backend representation before we convert
10487 // FIND_TYPE_.
10488 if (type->named_type() != NULL)
10490 switch (type->base()->classification())
10492 case Type::TYPE_ERROR:
10493 case Type::TYPE_BOOLEAN:
10494 case Type::TYPE_INTEGER:
10495 case Type::TYPE_FLOAT:
10496 case Type::TYPE_COMPLEX:
10497 case Type::TYPE_STRING:
10498 case Type::TYPE_NIL:
10499 break;
10501 case Type::TYPE_ARRAY:
10502 case Type::TYPE_STRUCT:
10503 this->find_type_->add_dependency(type->named_type());
10504 break;
10506 case Type::TYPE_NAMED:
10507 case Type::TYPE_FORWARD:
10508 go_assert(saw_errors());
10509 break;
10511 case Type::TYPE_VOID:
10512 case Type::TYPE_SINK:
10513 case Type::TYPE_FUNCTION:
10514 case Type::TYPE_POINTER:
10515 case Type::TYPE_CALL_MULTIPLE_RESULT:
10516 case Type::TYPE_MAP:
10517 case Type::TYPE_CHANNEL:
10518 case Type::TYPE_INTERFACE:
10519 default:
10520 go_unreachable();
10524 return TRAVERSE_CONTINUE;
10527 // Look for a circular reference of an alias.
10529 class Find_alias : public Traverse
10531 public:
10532 Find_alias(Named_type* find_type)
10533 : Traverse(traverse_types),
10534 find_type_(find_type), found_(false)
10537 // Whether we found the type.
10538 bool
10539 found() const
10540 { return this->found_; }
10542 protected:
10544 type(Type*);
10546 private:
10547 // The type we are looking for.
10548 Named_type* find_type_;
10549 // Whether we found the type.
10550 bool found_;
10554 Find_alias::type(Type* type)
10556 Named_type* nt = type->named_type();
10557 if (nt != NULL)
10559 if (nt == this->find_type_)
10561 this->found_ = true;
10562 return TRAVERSE_EXIT;
10565 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10566 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10567 // an alias itself, it's OK if whatever T2 is defined as refers
10568 // to T1.
10569 if (!nt->is_alias())
10570 return TRAVERSE_SKIP_COMPONENTS;
10573 return TRAVERSE_CONTINUE;
10576 // Verify that a named type does not refer to itself.
10578 bool
10579 Named_type::do_verify()
10581 if (this->is_verified_)
10582 return true;
10583 this->is_verified_ = true;
10585 if (this->is_error_)
10586 return false;
10588 if (this->is_alias_)
10590 Find_alias find(this);
10591 Type::traverse(this->type_, &find);
10592 if (find.found())
10594 go_error_at(this->location_, "invalid recursive alias %qs",
10595 this->message_name().c_str());
10596 this->is_error_ = true;
10597 return false;
10601 Find_type_use find(this);
10602 Type::traverse(this->type_, &find);
10603 if (find.found())
10605 go_error_at(this->location_, "invalid recursive type %qs",
10606 this->message_name().c_str());
10607 this->is_error_ = true;
10608 return false;
10611 // Check whether any of the local methods overloads an existing
10612 // struct field or interface method. We don't need to check the
10613 // list of methods against itself: that is handled by the Bindings
10614 // code.
10615 if (this->local_methods_ != NULL)
10617 Struct_type* st = this->type_->struct_type();
10618 if (st != NULL)
10620 for (Bindings::const_declarations_iterator p =
10621 this->local_methods_->begin_declarations();
10622 p != this->local_methods_->end_declarations();
10623 ++p)
10625 const std::string& name(p->first);
10626 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10628 go_error_at(p->second->location(),
10629 "method %qs redeclares struct field name",
10630 Gogo::message_name(name).c_str());
10636 return true;
10639 // Return whether this type is or contains a pointer.
10641 bool
10642 Named_type::do_has_pointer() const
10644 if (this->seen_)
10645 return false;
10646 this->seen_ = true;
10647 bool ret = this->type_->has_pointer();
10648 this->seen_ = false;
10649 return ret;
10652 // Return whether comparisons for this type can use the identity
10653 // function.
10655 bool
10656 Named_type::do_compare_is_identity(Gogo* gogo)
10658 // We don't use this->seen_ here because compare_is_identity may
10659 // call base() later, and that will mess up if seen_ is set here.
10660 if (this->seen_in_compare_is_identity_)
10661 return false;
10662 this->seen_in_compare_is_identity_ = true;
10663 bool ret = this->type_->compare_is_identity(gogo);
10664 this->seen_in_compare_is_identity_ = false;
10665 return ret;
10668 // Return whether this type is reflexive--whether it is always equal
10669 // to itself.
10671 bool
10672 Named_type::do_is_reflexive()
10674 if (this->seen_in_compare_is_identity_)
10675 return false;
10676 this->seen_in_compare_is_identity_ = true;
10677 bool ret = this->type_->is_reflexive();
10678 this->seen_in_compare_is_identity_ = false;
10679 return ret;
10682 // Return whether this type needs a key update when used as a map key.
10684 bool
10685 Named_type::do_needs_key_update()
10687 if (this->seen_in_compare_is_identity_)
10688 return true;
10689 this->seen_in_compare_is_identity_ = true;
10690 bool ret = this->type_->needs_key_update();
10691 this->seen_in_compare_is_identity_ = false;
10692 return ret;
10695 // Return a hash code. This is used for method lookup. We simply
10696 // hash on the name itself.
10698 unsigned int
10699 Named_type::do_hash_for_method(Gogo* gogo) const
10701 if (this->is_error_)
10702 return 0;
10704 // Aliases are handled in Type::hash_for_method.
10705 go_assert(!this->is_alias_);
10707 const std::string& name(this->named_object()->name());
10708 unsigned int ret = Type::hash_string(name, 0);
10710 // GOGO will be NULL here when called from Type_hash_identical.
10711 // That is OK because that is only used for internal hash tables
10712 // where we are going to be comparing named types for equality. In
10713 // other cases, which are cases where the runtime is going to
10714 // compare hash codes to see if the types are the same, we need to
10715 // include the pkgpath in the hash.
10716 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10718 const Package* package = this->named_object()->package();
10719 if (package == NULL)
10720 ret = Type::hash_string(gogo->pkgpath(), ret);
10721 else
10722 ret = Type::hash_string(package->pkgpath(), ret);
10725 return ret;
10728 // Convert a named type to the backend representation. In order to
10729 // get dependencies right, we fill in a dummy structure for this type,
10730 // then convert all the dependencies, then complete this type. When
10731 // this function is complete, the size of the type is known.
10733 void
10734 Named_type::convert(Gogo* gogo)
10736 if (this->is_error_ || this->is_converted_)
10737 return;
10739 this->create_placeholder(gogo);
10741 // If we are called to turn unsafe.Sizeof into a constant, we may
10742 // not have verified the type yet. We have to make sure it is
10743 // verified, since that sets the list of dependencies.
10744 this->verify();
10746 // Convert all the dependencies. If they refer indirectly back to
10747 // this type, they will pick up the intermediate representation we just
10748 // created.
10749 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10750 p != this->dependencies_.end();
10751 ++p)
10752 (*p)->convert(gogo);
10754 // Complete this type.
10755 Btype* bt = this->named_btype_;
10756 Type* base = this->type_->base();
10757 switch (base->classification())
10759 case TYPE_VOID:
10760 case TYPE_BOOLEAN:
10761 case TYPE_INTEGER:
10762 case TYPE_FLOAT:
10763 case TYPE_COMPLEX:
10764 case TYPE_STRING:
10765 case TYPE_NIL:
10766 break;
10768 case TYPE_MAP:
10769 case TYPE_CHANNEL:
10770 break;
10772 case TYPE_FUNCTION:
10773 case TYPE_POINTER:
10774 // The size of these types is already correct. We don't worry
10775 // about filling them in until later, when we also track
10776 // circular references.
10777 break;
10779 case TYPE_STRUCT:
10781 std::vector<Backend::Btyped_identifier> bfields;
10782 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10783 true, &bfields);
10784 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10785 bt = gogo->backend()->error_type();
10787 break;
10789 case TYPE_ARRAY:
10790 // Slice types were completed in create_placeholder.
10791 if (!base->is_slice_type())
10793 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10794 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10795 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10796 bt = gogo->backend()->error_type();
10798 break;
10800 case TYPE_INTERFACE:
10801 // Interface types were completed in create_placeholder.
10802 break;
10804 case TYPE_ERROR:
10805 return;
10807 default:
10808 case TYPE_SINK:
10809 case TYPE_CALL_MULTIPLE_RESULT:
10810 case TYPE_NAMED:
10811 case TYPE_FORWARD:
10812 go_unreachable();
10815 this->named_btype_ = bt;
10816 this->is_converted_ = true;
10817 this->is_placeholder_ = false;
10820 // Create the placeholder for a named type. This is the first step in
10821 // converting to the backend representation.
10823 void
10824 Named_type::create_placeholder(Gogo* gogo)
10826 if (this->is_error_)
10827 this->named_btype_ = gogo->backend()->error_type();
10829 if (this->named_btype_ != NULL)
10830 return;
10832 // Create the structure for this type. Note that because we call
10833 // base() here, we don't attempt to represent a named type defined
10834 // as another named type. Instead both named types will point to
10835 // different base representations.
10836 Type* base = this->type_->base();
10837 Btype* bt;
10838 bool set_name = true;
10839 switch (base->classification())
10841 case TYPE_ERROR:
10842 this->is_error_ = true;
10843 this->named_btype_ = gogo->backend()->error_type();
10844 return;
10846 case TYPE_VOID:
10847 case TYPE_BOOLEAN:
10848 case TYPE_INTEGER:
10849 case TYPE_FLOAT:
10850 case TYPE_COMPLEX:
10851 case TYPE_STRING:
10852 case TYPE_NIL:
10853 // These are simple basic types, we can just create them
10854 // directly.
10855 bt = Type::get_named_base_btype(gogo, base);
10856 break;
10858 case TYPE_MAP:
10859 case TYPE_CHANNEL:
10860 // All maps and channels have the same backend representation.
10861 bt = Type::get_named_base_btype(gogo, base);
10862 break;
10864 case TYPE_FUNCTION:
10865 case TYPE_POINTER:
10867 bool for_function = base->classification() == TYPE_FUNCTION;
10868 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10869 this->location_,
10870 for_function);
10871 set_name = false;
10873 break;
10875 case TYPE_STRUCT:
10876 bt = gogo->backend()->placeholder_struct_type(this->name(),
10877 this->location_);
10878 this->is_placeholder_ = true;
10879 set_name = false;
10880 break;
10882 case TYPE_ARRAY:
10883 if (base->is_slice_type())
10884 bt = gogo->backend()->placeholder_struct_type(this->name(),
10885 this->location_);
10886 else
10888 bt = gogo->backend()->placeholder_array_type(this->name(),
10889 this->location_);
10890 this->is_placeholder_ = true;
10892 set_name = false;
10893 break;
10895 case TYPE_INTERFACE:
10896 if (base->interface_type()->is_empty())
10897 bt = Interface_type::get_backend_empty_interface_type(gogo);
10898 else
10900 bt = gogo->backend()->placeholder_struct_type(this->name(),
10901 this->location_);
10902 set_name = false;
10904 break;
10906 default:
10907 case TYPE_SINK:
10908 case TYPE_CALL_MULTIPLE_RESULT:
10909 case TYPE_NAMED:
10910 case TYPE_FORWARD:
10911 go_unreachable();
10914 if (set_name)
10915 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10917 this->named_btype_ = bt;
10919 if (base->is_slice_type())
10921 // We do not record slices as dependencies of other types,
10922 // because we can fill them in completely here with the final
10923 // size.
10924 std::vector<Backend::Btyped_identifier> bfields;
10925 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10926 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10927 this->named_btype_ = gogo->backend()->error_type();
10929 else if (base->interface_type() != NULL
10930 && !base->interface_type()->is_empty())
10932 // We do not record interfaces as dependencies of other types,
10933 // because we can fill them in completely here with the final
10934 // size.
10935 std::vector<Backend::Btyped_identifier> bfields;
10936 get_backend_interface_fields(gogo, base->interface_type(), true,
10937 &bfields);
10938 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10939 this->named_btype_ = gogo->backend()->error_type();
10943 // Get the backend representation for a named type.
10945 Btype*
10946 Named_type::do_get_backend(Gogo* gogo)
10948 if (this->is_error_)
10949 return gogo->backend()->error_type();
10951 Btype* bt = this->named_btype_;
10953 if (!gogo->named_types_are_converted())
10955 // We have not completed converting named types. NAMED_BTYPE_
10956 // is a placeholder and we shouldn't do anything further.
10957 if (bt != NULL)
10958 return bt;
10960 // We don't build dependencies for types whose sizes do not
10961 // change or are not relevant, so we may see them here while
10962 // converting types.
10963 this->create_placeholder(gogo);
10964 bt = this->named_btype_;
10965 go_assert(bt != NULL);
10966 return bt;
10969 // We are not converting types. This should only be called if the
10970 // type has already been converted.
10971 if (!this->is_converted_)
10973 go_assert(saw_errors());
10974 return gogo->backend()->error_type();
10977 go_assert(bt != NULL);
10979 // Complete the backend representation.
10980 Type* base = this->type_->base();
10981 Btype* bt1;
10982 switch (base->classification())
10984 case TYPE_ERROR:
10985 return gogo->backend()->error_type();
10987 case TYPE_VOID:
10988 case TYPE_BOOLEAN:
10989 case TYPE_INTEGER:
10990 case TYPE_FLOAT:
10991 case TYPE_COMPLEX:
10992 case TYPE_STRING:
10993 case TYPE_NIL:
10994 case TYPE_MAP:
10995 case TYPE_CHANNEL:
10996 return bt;
10998 case TYPE_STRUCT:
10999 if (!this->seen_in_get_backend_)
11001 this->seen_in_get_backend_ = true;
11002 base->struct_type()->finish_backend_fields(gogo);
11003 this->seen_in_get_backend_ = false;
11005 return bt;
11007 case TYPE_ARRAY:
11008 if (!this->seen_in_get_backend_)
11010 this->seen_in_get_backend_ = true;
11011 base->array_type()->finish_backend_element(gogo);
11012 this->seen_in_get_backend_ = false;
11014 return bt;
11016 case TYPE_INTERFACE:
11017 if (!this->seen_in_get_backend_)
11019 this->seen_in_get_backend_ = true;
11020 base->interface_type()->finish_backend_methods(gogo);
11021 this->seen_in_get_backend_ = false;
11023 return bt;
11025 case TYPE_FUNCTION:
11026 // Don't build a circular data structure. GENERIC can't handle
11027 // it.
11028 if (this->seen_in_get_backend_)
11030 this->is_circular_ = true;
11031 return gogo->backend()->circular_pointer_type(bt, true);
11033 this->seen_in_get_backend_ = true;
11034 bt1 = Type::get_named_base_btype(gogo, base);
11035 this->seen_in_get_backend_ = false;
11036 if (this->is_circular_)
11037 bt1 = gogo->backend()->circular_pointer_type(bt, true);
11038 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11039 bt = gogo->backend()->error_type();
11040 return bt;
11042 case TYPE_POINTER:
11043 // Don't build a circular data structure. GENERIC can't handle
11044 // it.
11045 if (this->seen_in_get_backend_)
11047 this->is_circular_ = true;
11048 return gogo->backend()->circular_pointer_type(bt, false);
11050 this->seen_in_get_backend_ = true;
11051 bt1 = Type::get_named_base_btype(gogo, base);
11052 this->seen_in_get_backend_ = false;
11053 if (this->is_circular_)
11054 bt1 = gogo->backend()->circular_pointer_type(bt, false);
11055 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11056 bt = gogo->backend()->error_type();
11057 return bt;
11059 default:
11060 case TYPE_SINK:
11061 case TYPE_CALL_MULTIPLE_RESULT:
11062 case TYPE_NAMED:
11063 case TYPE_FORWARD:
11064 go_unreachable();
11067 go_unreachable();
11070 // Build a type descriptor for a named type.
11072 Expression*
11073 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11075 if (this->is_error_)
11076 return Expression::make_error(this->location_);
11077 if (name == NULL && this->is_alias_)
11079 if (this->seen_alias_)
11080 return Expression::make_error(this->location_);
11081 this->seen_alias_ = true;
11082 Expression* ret = this->type_->type_descriptor(gogo, NULL);
11083 this->seen_alias_ = false;
11084 return ret;
11087 // If NAME is not NULL, then we don't really want the type
11088 // descriptor for this type; we want the descriptor for the
11089 // underlying type, giving it the name NAME.
11090 return this->named_type_descriptor(gogo, this->type_,
11091 name == NULL ? this : name);
11094 // Add to the reflection string. This is used mostly for the name of
11095 // the type used in a type descriptor, not for actual reflection
11096 // strings.
11098 void
11099 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
11101 this->append_reflection_type_name(gogo, false, ret);
11104 // Add to the reflection string. For an alias we normally use the
11105 // real name, but if USE_ALIAS is true we use the alias name itself.
11107 void
11108 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
11109 std::string* ret) const
11111 if (this->is_error_)
11112 return;
11113 if (this->is_alias_ && !use_alias)
11115 if (this->seen_alias_)
11116 return;
11117 this->seen_alias_ = true;
11118 this->append_reflection(this->type_, gogo, ret);
11119 this->seen_alias_ = false;
11120 return;
11122 if (!this->is_builtin())
11124 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
11125 // make a unique reflection string, so that the type
11126 // canonicalization in the reflect package will work. In order
11127 // to be compatible with the gc compiler, we put tabs into the
11128 // package path, so that the reflect methods can discard it.
11129 const Package* package = this->named_object_->package();
11130 ret->push_back('\t');
11131 ret->append(package != NULL
11132 ? package->pkgpath_symbol()
11133 : gogo->pkgpath_symbol());
11134 ret->push_back('\t');
11135 ret->append(package != NULL
11136 ? package->package_name()
11137 : gogo->package_name());
11138 ret->push_back('.');
11140 if (this->in_function_ != NULL)
11142 ret->push_back('\t');
11143 const Typed_identifier* rcvr =
11144 this->in_function_->func_value()->type()->receiver();
11145 if (rcvr != NULL)
11147 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11148 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
11149 ret->push_back('.');
11151 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
11152 ret->push_back('$');
11153 if (this->in_function_index_ > 0)
11155 char buf[30];
11156 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11157 ret->append(buf);
11158 ret->push_back('$');
11160 ret->push_back('\t');
11162 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
11165 // Get the mangled name.
11167 void
11168 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
11170 this->append_mangled_type_name(gogo, false, ret);
11173 // Get the mangled name. For an alias we normally get the real name,
11174 // but if USE_ALIAS is true we use the alias name itself.
11176 void
11177 Named_type::append_mangled_type_name(Gogo* gogo, bool use_alias,
11178 std::string* ret) const
11180 if (this->is_error_)
11181 return;
11182 if (this->is_alias_ && !use_alias)
11184 if (this->seen_alias_)
11185 return;
11186 this->seen_alias_ = true;
11187 this->append_mangled_name(this->type_, gogo, ret);
11188 this->seen_alias_ = false;
11189 return;
11191 Named_object* no = this->named_object_;
11192 std::string name;
11193 if (this->is_builtin())
11194 go_assert(this->in_function_ == NULL);
11195 else
11197 const std::string& pkgpath(no->package() == NULL
11198 ? gogo->pkgpath_symbol()
11199 : no->package()->pkgpath_symbol());
11200 name = pkgpath;
11201 name.append(1, '.');
11202 if (this->in_function_ != NULL)
11204 const Typed_identifier* rcvr =
11205 this->in_function_->func_value()->type()->receiver();
11206 if (rcvr != NULL)
11208 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11209 name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
11210 name.append(1, '.');
11212 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
11213 name.append(1, '$');
11214 if (this->in_function_index_ > 0)
11216 char buf[30];
11217 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11218 name.append(buf);
11219 name.append(1, '$');
11223 name.append(Gogo::unpack_hidden_name(no->name()));
11224 char buf[20];
11225 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
11226 ret->append(buf);
11227 ret->append(name);
11230 // Export the type. This is called to export a global type.
11232 void
11233 Named_type::export_named_type(Export* exp, const std::string&) const
11235 // We don't need to write the name of the type here, because it will
11236 // be written by Export::write_type anyhow.
11237 exp->write_c_string("type ");
11238 exp->write_type(this);
11239 exp->write_c_string(";\n");
11242 // Import a named type.
11244 void
11245 Named_type::import_named_type(Import* imp, Named_type** ptype)
11247 imp->require_c_string("type ");
11248 Type *type = imp->read_type();
11249 *ptype = type->named_type();
11250 go_assert(*ptype != NULL);
11251 imp->require_c_string(";\n");
11254 // Export the type when it is referenced by another type. In this
11255 // case Export::export_type will already have issued the name.
11257 void
11258 Named_type::do_export(Export* exp) const
11260 exp->write_type(this->type_);
11262 // To save space, we only export the methods directly attached to
11263 // this type.
11264 Bindings* methods = this->local_methods_;
11265 if (methods == NULL)
11266 return;
11268 exp->write_c_string("\n");
11269 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
11270 p != methods->end_definitions();
11271 ++p)
11273 exp->write_c_string(" ");
11274 (*p)->export_named_object(exp);
11277 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
11278 p != methods->end_declarations();
11279 ++p)
11281 if (p->second->is_function_declaration())
11283 exp->write_c_string(" ");
11284 p->second->export_named_object(exp);
11289 // Make a named type.
11291 Named_type*
11292 Type::make_named_type(Named_object* named_object, Type* type,
11293 Location location)
11295 return new Named_type(named_object, type, location);
11298 // Finalize the methods for TYPE. It will be a named type or a struct
11299 // type. This sets *ALL_METHODS to the list of methods, and builds
11300 // all required stubs.
11302 void
11303 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
11304 Methods** all_methods)
11306 *all_methods = new Methods();
11307 std::vector<const Named_type*> seen;
11308 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
11309 if ((*all_methods)->empty())
11311 delete *all_methods;
11312 *all_methods = NULL;
11314 Type::build_stub_methods(gogo, type, *all_methods, location);
11317 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11318 // build up the struct field indexes as we go. DEPTH is the depth of
11319 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11320 // adding these methods for an anonymous field with pointer type.
11321 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11322 // calls the real method. TYPES_SEEN is used to avoid infinite
11323 // recursion.
11325 void
11326 Type::add_methods_for_type(const Type* type,
11327 const Method::Field_indexes* field_indexes,
11328 unsigned int depth,
11329 bool is_embedded_pointer,
11330 bool needs_stub_method,
11331 std::vector<const Named_type*>* seen,
11332 Methods* methods)
11334 // Pointer types may not have methods.
11335 if (type->points_to() != NULL)
11336 return;
11338 const Named_type* nt = type->named_type();
11339 if (nt != NULL)
11341 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11342 p != seen->end();
11343 ++p)
11345 if (*p == nt)
11346 return;
11349 seen->push_back(nt);
11351 Type::add_local_methods_for_type(nt, field_indexes, depth,
11352 is_embedded_pointer, needs_stub_method,
11353 methods);
11356 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11357 is_embedded_pointer, needs_stub_method,
11358 seen, methods);
11360 // If we are called with depth > 0, then we are looking at an
11361 // anonymous field of a struct. If such a field has interface type,
11362 // then we need to add the interface methods. We don't want to add
11363 // them when depth == 0, because we will already handle them
11364 // following the usual rules for an interface type.
11365 if (depth > 0)
11366 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11368 if (nt != NULL)
11369 seen->pop_back();
11372 // Add the local methods for the named type NT to *METHODS. The
11373 // parameters are as for add_methods_to_type.
11375 void
11376 Type::add_local_methods_for_type(const Named_type* nt,
11377 const Method::Field_indexes* field_indexes,
11378 unsigned int depth,
11379 bool is_embedded_pointer,
11380 bool needs_stub_method,
11381 Methods* methods)
11383 const Bindings* local_methods = nt->local_methods();
11384 if (local_methods == NULL)
11385 return;
11387 for (Bindings::const_declarations_iterator p =
11388 local_methods->begin_declarations();
11389 p != local_methods->end_declarations();
11390 ++p)
11392 Named_object* no = p->second;
11393 bool is_value_method = (is_embedded_pointer
11394 || !Type::method_expects_pointer(no));
11395 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11396 (needs_stub_method || depth > 0));
11397 if (!methods->insert(no->name(), m))
11398 delete m;
11402 // Add the embedded methods for TYPE to *METHODS. These are the
11403 // methods attached to anonymous fields. The parameters are as for
11404 // add_methods_to_type.
11406 void
11407 Type::add_embedded_methods_for_type(const Type* type,
11408 const Method::Field_indexes* field_indexes,
11409 unsigned int depth,
11410 bool is_embedded_pointer,
11411 bool needs_stub_method,
11412 std::vector<const Named_type*>* seen,
11413 Methods* methods)
11415 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11416 // struct.
11417 const Struct_type* st = type->struct_type();
11418 if (st == NULL)
11419 return;
11421 const Struct_field_list* fields = st->fields();
11422 if (fields == NULL)
11423 return;
11425 unsigned int i = 0;
11426 for (Struct_field_list::const_iterator pf = fields->begin();
11427 pf != fields->end();
11428 ++pf, ++i)
11430 if (!pf->is_anonymous())
11431 continue;
11433 Type* ftype = pf->type();
11434 bool is_pointer = false;
11435 if (ftype->points_to() != NULL)
11437 ftype = ftype->points_to();
11438 is_pointer = true;
11440 Named_type* fnt = ftype->named_type();
11441 if (fnt == NULL)
11443 // This is an error, but it will be diagnosed elsewhere.
11444 continue;
11447 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11448 sub_field_indexes->next = field_indexes;
11449 sub_field_indexes->field_index = i;
11451 Methods tmp_methods;
11452 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11453 (is_embedded_pointer || is_pointer),
11454 (needs_stub_method
11455 || is_pointer
11456 || i > 0),
11457 seen,
11458 &tmp_methods);
11459 // Check if there are promoted methods that conflict with field names and
11460 // don't add them to the method map.
11461 for (Methods::const_iterator p = tmp_methods.begin();
11462 p != tmp_methods.end();
11463 ++p)
11465 bool found = false;
11466 for (Struct_field_list::const_iterator fp = fields->begin();
11467 fp != fields->end();
11468 ++fp)
11470 if (fp->field_name() == p->first)
11472 found = true;
11473 break;
11476 if (!found &&
11477 !methods->insert(p->first, p->second))
11478 delete p->second;
11483 // If TYPE is an interface type, then add its method to *METHODS.
11484 // This is for interface methods attached to an anonymous field. The
11485 // parameters are as for add_methods_for_type.
11487 void
11488 Type::add_interface_methods_for_type(const Type* type,
11489 const Method::Field_indexes* field_indexes,
11490 unsigned int depth,
11491 Methods* methods)
11493 const Interface_type* it = type->interface_type();
11494 if (it == NULL)
11495 return;
11497 const Typed_identifier_list* imethods = it->methods();
11498 if (imethods == NULL)
11499 return;
11501 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11502 pm != imethods->end();
11503 ++pm)
11505 Function_type* fntype = pm->type()->function_type();
11506 if (fntype == NULL)
11508 // This is an error, but it should be reported elsewhere
11509 // when we look at the methods for IT.
11510 continue;
11512 go_assert(!fntype->is_method());
11513 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11514 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11515 field_indexes, depth);
11516 if (!methods->insert(pm->name(), m))
11517 delete m;
11521 // Build stub methods for TYPE as needed. METHODS is the set of
11522 // methods for the type. A stub method may be needed when a type
11523 // inherits a method from an anonymous field. When we need the
11524 // address of the method, as in a type descriptor, we need to build a
11525 // little stub which does the required field dereferences and jumps to
11526 // the real method. LOCATION is the location of the type definition.
11528 void
11529 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11530 Location location)
11532 if (methods == NULL)
11533 return;
11534 for (Methods::const_iterator p = methods->begin();
11535 p != methods->end();
11536 ++p)
11538 Method* m = p->second;
11539 if (m->is_ambiguous() || !m->needs_stub_method())
11540 continue;
11542 const std::string& name(p->first);
11544 // Build a stub method.
11546 const Function_type* fntype = m->type();
11548 static unsigned int counter;
11549 char buf[100];
11550 snprintf(buf, sizeof buf, "$this%u", counter);
11551 ++counter;
11553 Type* receiver_type = const_cast<Type*>(type);
11554 if (!m->is_value_method())
11555 receiver_type = Type::make_pointer_type(receiver_type);
11556 Location receiver_location = m->receiver_location();
11557 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11558 receiver_location);
11560 const Typed_identifier_list* fnparams = fntype->parameters();
11561 Typed_identifier_list* stub_params;
11562 if (fnparams == NULL || fnparams->empty())
11563 stub_params = NULL;
11564 else
11566 // We give each stub parameter a unique name.
11567 stub_params = new Typed_identifier_list();
11568 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11569 pp != fnparams->end();
11570 ++pp)
11572 char pbuf[100];
11573 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11574 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11575 pp->location()));
11576 ++counter;
11580 const Typed_identifier_list* fnresults = fntype->results();
11581 Typed_identifier_list* stub_results;
11582 if (fnresults == NULL || fnresults->empty())
11583 stub_results = NULL;
11584 else
11586 // We create the result parameters without any names, since
11587 // we won't refer to them.
11588 stub_results = new Typed_identifier_list();
11589 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11590 pr != fnresults->end();
11591 ++pr)
11592 stub_results->push_back(Typed_identifier("", pr->type(),
11593 pr->location()));
11596 Function_type* stub_type = Type::make_function_type(receiver,
11597 stub_params,
11598 stub_results,
11599 fntype->location());
11600 if (fntype->is_varargs())
11601 stub_type->set_is_varargs();
11603 // We only create the function in the package which creates the
11604 // type.
11605 const Package* package;
11606 if (type->named_type() == NULL)
11607 package = NULL;
11608 else
11609 package = type->named_type()->named_object()->package();
11610 std::string stub_name = name + "$stub";
11611 Named_object* stub;
11612 if (package != NULL)
11613 stub = Named_object::make_function_declaration(stub_name, package,
11614 stub_type, location);
11615 else
11617 stub = gogo->start_function(stub_name, stub_type, false,
11618 fntype->location());
11619 Type::build_one_stub_method(gogo, m, buf, stub_params,
11620 fntype->is_varargs(), location);
11621 gogo->finish_function(fntype->location());
11623 if (type->named_type() == NULL && stub->is_function())
11624 stub->func_value()->set_is_unnamed_type_stub_method();
11625 if (m->nointerface() && stub->is_function())
11626 stub->func_value()->set_nointerface();
11629 m->set_stub_object(stub);
11633 // Build a stub method which adjusts the receiver as required to call
11634 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11635 // PARAMS is the list of function parameters.
11637 void
11638 Type::build_one_stub_method(Gogo* gogo, Method* method,
11639 const char* receiver_name,
11640 const Typed_identifier_list* params,
11641 bool is_varargs,
11642 Location location)
11644 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11645 go_assert(receiver_object != NULL);
11647 Expression* expr = Expression::make_var_reference(receiver_object, location);
11648 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11649 if (expr->type()->points_to() == NULL)
11650 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11652 Expression_list* arguments;
11653 if (params == NULL || params->empty())
11654 arguments = NULL;
11655 else
11657 arguments = new Expression_list();
11658 for (Typed_identifier_list::const_iterator p = params->begin();
11659 p != params->end();
11660 ++p)
11662 Named_object* param = gogo->lookup(p->name(), NULL);
11663 go_assert(param != NULL);
11664 Expression* param_ref = Expression::make_var_reference(param,
11665 location);
11666 arguments->push_back(param_ref);
11670 Expression* func = method->bind_method(expr, location);
11671 go_assert(func != NULL);
11672 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11673 location);
11675 gogo->add_statement(Statement::make_return_from_call(call, location));
11678 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11679 // in reverse order.
11681 Expression*
11682 Type::apply_field_indexes(Expression* expr,
11683 const Method::Field_indexes* field_indexes,
11684 Location location)
11686 if (field_indexes == NULL)
11687 return expr;
11688 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11689 Struct_type* stype = expr->type()->deref()->struct_type();
11690 go_assert(stype != NULL
11691 && field_indexes->field_index < stype->field_count());
11692 if (expr->type()->struct_type() == NULL)
11694 go_assert(expr->type()->points_to() != NULL);
11695 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
11696 go_assert(expr->type()->struct_type() == stype);
11698 return Expression::make_field_reference(expr, field_indexes->field_index,
11699 location);
11702 // Return whether NO is a method for which the receiver is a pointer.
11704 bool
11705 Type::method_expects_pointer(const Named_object* no)
11707 const Function_type *fntype;
11708 if (no->is_function())
11709 fntype = no->func_value()->type();
11710 else if (no->is_function_declaration())
11711 fntype = no->func_declaration_value()->type();
11712 else
11713 go_unreachable();
11714 return fntype->receiver()->type()->points_to() != NULL;
11717 // Given a set of methods for a type, METHODS, return the method NAME,
11718 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11719 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11720 // but is ambiguous (and return NULL).
11722 Method*
11723 Type::method_function(const Methods* methods, const std::string& name,
11724 bool* is_ambiguous)
11726 if (is_ambiguous != NULL)
11727 *is_ambiguous = false;
11728 if (methods == NULL)
11729 return NULL;
11730 Methods::const_iterator p = methods->find(name);
11731 if (p == methods->end())
11732 return NULL;
11733 Method* m = p->second;
11734 if (m->is_ambiguous())
11736 if (is_ambiguous != NULL)
11737 *is_ambiguous = true;
11738 return NULL;
11740 return m;
11743 // Return a pointer to the interface method table for TYPE for the
11744 // interface INTERFACE.
11746 Expression*
11747 Type::interface_method_table(Type* type,
11748 Interface_type *interface,
11749 bool is_pointer,
11750 Interface_method_tables** method_tables,
11751 Interface_method_tables** pointer_tables)
11753 go_assert(!interface->is_empty());
11755 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11757 if (*pimt == NULL)
11758 *pimt = new Interface_method_tables(5);
11760 std::pair<Interface_type*, Expression*> val(interface, NULL);
11761 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11763 Location loc = Linemap::predeclared_location();
11764 if (ins.second)
11766 // This is a new entry in the hash table.
11767 go_assert(ins.first->second == NULL);
11768 ins.first->second =
11769 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11771 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11774 // Look for field or method NAME for TYPE. Return an Expression for
11775 // the field or method bound to EXPR. If there is no such field or
11776 // method, give an appropriate error and return an error expression.
11778 Expression*
11779 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11780 const std::string& name,
11781 Location location)
11783 if (type->deref()->is_error_type())
11784 return Expression::make_error(location);
11786 const Named_type* nt = type->deref()->named_type();
11787 const Struct_type* st = type->deref()->struct_type();
11788 const Interface_type* it = type->interface_type();
11790 // If this is a pointer to a pointer, then it is possible that the
11791 // pointed-to type has methods.
11792 bool dereferenced = false;
11793 if (nt == NULL
11794 && st == NULL
11795 && it == NULL
11796 && type->points_to() != NULL
11797 && type->points_to()->points_to() != NULL)
11799 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
11800 type = type->points_to();
11801 if (type->deref()->is_error_type())
11802 return Expression::make_error(location);
11803 nt = type->points_to()->named_type();
11804 st = type->points_to()->struct_type();
11805 dereferenced = true;
11808 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11809 || expr->is_addressable());
11810 std::vector<const Named_type*> seen;
11811 bool is_method = false;
11812 bool found_pointer_method = false;
11813 std::string ambig1;
11814 std::string ambig2;
11815 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11816 &seen, NULL, &is_method,
11817 &found_pointer_method, &ambig1, &ambig2))
11819 Expression* ret;
11820 if (!is_method)
11822 go_assert(st != NULL);
11823 if (type->struct_type() == NULL)
11825 go_assert(type->points_to() != NULL);
11826 expr = Expression::make_unary(OPERATOR_MULT, expr,
11827 location);
11828 go_assert(expr->type()->struct_type() == st);
11830 ret = st->field_reference(expr, name, location);
11832 else if (it != NULL && it->find_method(name) != NULL)
11833 ret = Expression::make_interface_field_reference(expr, name,
11834 location);
11835 else
11837 Method* m;
11838 if (nt != NULL)
11839 m = nt->method_function(name, NULL);
11840 else if (st != NULL)
11841 m = st->method_function(name, NULL);
11842 else
11843 go_unreachable();
11844 go_assert(m != NULL);
11845 if (dereferenced)
11847 go_error_at(location,
11848 "calling method %qs requires explicit dereference",
11849 Gogo::message_name(name).c_str());
11850 return Expression::make_error(location);
11852 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11853 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11854 ret = m->bind_method(expr, location);
11856 go_assert(ret != NULL);
11857 return ret;
11859 else
11861 if (Gogo::is_erroneous_name(name))
11863 // An error was already reported.
11865 else if (!ambig1.empty())
11866 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11867 Gogo::message_name(name).c_str(), ambig1.c_str(),
11868 ambig2.c_str());
11869 else if (found_pointer_method)
11870 go_error_at(location, "method requires a pointer receiver");
11871 else if (nt == NULL && st == NULL && it == NULL)
11872 go_error_at(location,
11873 ("reference to field %qs in object which "
11874 "has no fields or methods"),
11875 Gogo::message_name(name).c_str());
11876 else
11878 bool is_unexported;
11879 // The test for 'a' and 'z' is to handle builtin names,
11880 // which are not hidden.
11881 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11882 is_unexported = false;
11883 else
11885 std::string unpacked = Gogo::unpack_hidden_name(name);
11886 seen.clear();
11887 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11888 unpacked,
11889 &seen);
11891 if (is_unexported)
11892 go_error_at(location, "reference to unexported field or method %qs",
11893 Gogo::message_name(name).c_str());
11894 else
11895 go_error_at(location, "reference to undefined field or method %qs",
11896 Gogo::message_name(name).c_str());
11898 return Expression::make_error(location);
11902 // Look in TYPE for a field or method named NAME, return true if one
11903 // is found. This looks through embedded anonymous fields and handles
11904 // ambiguity. If a method is found, sets *IS_METHOD to true;
11905 // otherwise, if a field is found, set it to false. If
11906 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11907 // whose address can not be taken. SEEN is used to avoid infinite
11908 // recursion on invalid types.
11910 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11911 // method we couldn't use because it requires a pointer. LEVEL is
11912 // used for recursive calls, and can be NULL for a non-recursive call.
11913 // When this function returns false because it finds that the name is
11914 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11915 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11916 // will be unchanged.
11918 // This function just returns whether or not there is a field or
11919 // method, and whether it is a field or method. It doesn't build an
11920 // expression to refer to it. If it is a method, we then look in the
11921 // list of all methods for the type. If it is a field, the search has
11922 // to be done again, looking only for fields, and building up the
11923 // expression as we go.
11925 bool
11926 Type::find_field_or_method(const Type* type,
11927 const std::string& name,
11928 bool receiver_can_be_pointer,
11929 std::vector<const Named_type*>* seen,
11930 int* level,
11931 bool* is_method,
11932 bool* found_pointer_method,
11933 std::string* ambig1,
11934 std::string* ambig2)
11936 // Named types can have locally defined methods.
11937 const Named_type* nt = type->named_type();
11938 if (nt == NULL && type->points_to() != NULL)
11939 nt = type->points_to()->named_type();
11940 if (nt != NULL)
11942 Named_object* no = nt->find_local_method(name);
11943 if (no != NULL)
11945 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11947 *is_method = true;
11948 return true;
11951 // Record that we have found a pointer method in order to
11952 // give a better error message if we don't find anything
11953 // else.
11954 *found_pointer_method = true;
11957 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11958 p != seen->end();
11959 ++p)
11961 if (*p == nt)
11963 // We've already seen this type when searching for methods.
11964 return false;
11969 // Interface types can have methods.
11970 const Interface_type* it = type->interface_type();
11971 if (it != NULL && it->find_method(name) != NULL)
11973 *is_method = true;
11974 return true;
11977 // Struct types can have fields. They can also inherit fields and
11978 // methods from anonymous fields.
11979 const Struct_type* st = type->deref()->struct_type();
11980 if (st == NULL)
11981 return false;
11982 const Struct_field_list* fields = st->fields();
11983 if (fields == NULL)
11984 return false;
11986 if (nt != NULL)
11987 seen->push_back(nt);
11989 int found_level = 0;
11990 bool found_is_method = false;
11991 std::string found_ambig1;
11992 std::string found_ambig2;
11993 const Struct_field* found_parent = NULL;
11994 for (Struct_field_list::const_iterator pf = fields->begin();
11995 pf != fields->end();
11996 ++pf)
11998 if (pf->is_field_name(name))
12000 *is_method = false;
12001 if (nt != NULL)
12002 seen->pop_back();
12003 return true;
12006 if (!pf->is_anonymous())
12007 continue;
12009 if (pf->type()->deref()->is_error_type()
12010 || pf->type()->deref()->is_undefined())
12011 continue;
12013 Named_type* fnt = pf->type()->named_type();
12014 if (fnt == NULL)
12015 fnt = pf->type()->deref()->named_type();
12016 go_assert(fnt != NULL);
12018 // Methods with pointer receivers on embedded field are
12019 // inherited by the pointer to struct, and also by the struct
12020 // type if the field itself is a pointer.
12021 bool can_be_pointer = (receiver_can_be_pointer
12022 || pf->type()->points_to() != NULL);
12023 int sublevel = level == NULL ? 1 : *level + 1;
12024 bool sub_is_method;
12025 std::string subambig1;
12026 std::string subambig2;
12027 bool subfound = Type::find_field_or_method(fnt,
12028 name,
12029 can_be_pointer,
12030 seen,
12031 &sublevel,
12032 &sub_is_method,
12033 found_pointer_method,
12034 &subambig1,
12035 &subambig2);
12036 if (!subfound)
12038 if (!subambig1.empty())
12040 // The name was found via this field, but is ambiguous.
12041 // if the ambiguity is lower or at the same level as
12042 // anything else we have already found, then we want to
12043 // pass the ambiguity back to the caller.
12044 if (found_level == 0 || sublevel <= found_level)
12046 found_ambig1 = (Gogo::message_name(pf->field_name())
12047 + '.' + subambig1);
12048 found_ambig2 = (Gogo::message_name(pf->field_name())
12049 + '.' + subambig2);
12050 found_level = sublevel;
12054 else
12056 // The name was found via this field. Use the level to see
12057 // if we want to use this one, or whether it introduces an
12058 // ambiguity.
12059 if (found_level == 0 || sublevel < found_level)
12061 found_level = sublevel;
12062 found_is_method = sub_is_method;
12063 found_ambig1.clear();
12064 found_ambig2.clear();
12065 found_parent = &*pf;
12067 else if (sublevel > found_level)
12069 else if (found_ambig1.empty())
12071 // We found an ambiguity.
12072 go_assert(found_parent != NULL);
12073 found_ambig1 = Gogo::message_name(found_parent->field_name());
12074 found_ambig2 = Gogo::message_name(pf->field_name());
12076 else
12078 // We found an ambiguity, but we already know of one.
12079 // Just report the earlier one.
12084 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
12085 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
12086 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
12087 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
12089 if (nt != NULL)
12090 seen->pop_back();
12092 if (found_level == 0)
12093 return false;
12094 else if (found_is_method
12095 && type->named_type() != NULL
12096 && type->points_to() != NULL)
12098 // If this is a method inherited from a struct field in a named pointer
12099 // type, it is invalid to automatically dereference the pointer to the
12100 // struct to find this method.
12101 if (level != NULL)
12102 *level = found_level;
12103 *is_method = true;
12104 return false;
12106 else if (!found_ambig1.empty())
12108 go_assert(!found_ambig1.empty());
12109 ambig1->assign(found_ambig1);
12110 ambig2->assign(found_ambig2);
12111 if (level != NULL)
12112 *level = found_level;
12113 return false;
12115 else
12117 if (level != NULL)
12118 *level = found_level;
12119 *is_method = found_is_method;
12120 return true;
12124 // Return whether NAME is an unexported field or method for TYPE.
12126 bool
12127 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
12128 const std::string& name,
12129 std::vector<const Named_type*>* seen)
12131 const Named_type* nt = type->named_type();
12132 if (nt == NULL)
12133 nt = type->deref()->named_type();
12134 if (nt != NULL)
12136 if (nt->is_unexported_local_method(gogo, name))
12137 return true;
12139 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12140 p != seen->end();
12141 ++p)
12143 if (*p == nt)
12145 // We've already seen this type.
12146 return false;
12151 const Interface_type* it = type->interface_type();
12152 if (it != NULL && it->is_unexported_method(gogo, name))
12153 return true;
12155 type = type->deref();
12157 const Struct_type* st = type->struct_type();
12158 if (st != NULL && st->is_unexported_local_field(gogo, name))
12159 return true;
12161 if (st == NULL)
12162 return false;
12164 const Struct_field_list* fields = st->fields();
12165 if (fields == NULL)
12166 return false;
12168 if (nt != NULL)
12169 seen->push_back(nt);
12171 for (Struct_field_list::const_iterator pf = fields->begin();
12172 pf != fields->end();
12173 ++pf)
12175 if (pf->is_anonymous()
12176 && !pf->type()->deref()->is_error_type()
12177 && !pf->type()->deref()->is_undefined())
12179 Named_type* subtype = pf->type()->named_type();
12180 if (subtype == NULL)
12181 subtype = pf->type()->deref()->named_type();
12182 if (subtype == NULL)
12184 // This is an error, but it will be diagnosed elsewhere.
12185 continue;
12187 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
12189 if (nt != NULL)
12190 seen->pop_back();
12191 return true;
12196 if (nt != NULL)
12197 seen->pop_back();
12199 return false;
12202 // Class Forward_declaration.
12204 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
12205 : Type(TYPE_FORWARD),
12206 named_object_(named_object->resolve()), warned_(false)
12208 go_assert(this->named_object_->is_unknown()
12209 || this->named_object_->is_type_declaration());
12212 // Return the named object.
12214 Named_object*
12215 Forward_declaration_type::named_object()
12217 return this->named_object_->resolve();
12220 const Named_object*
12221 Forward_declaration_type::named_object() const
12223 return this->named_object_->resolve();
12226 // Return the name of the forward declared type.
12228 const std::string&
12229 Forward_declaration_type::name() const
12231 return this->named_object()->name();
12234 // Warn about a use of a type which has been declared but not defined.
12236 void
12237 Forward_declaration_type::warn() const
12239 Named_object* no = this->named_object_->resolve();
12240 if (no->is_unknown())
12242 // The name was not defined anywhere.
12243 if (!this->warned_)
12245 go_error_at(this->named_object_->location(),
12246 "use of undefined type %qs",
12247 no->message_name().c_str());
12248 this->warned_ = true;
12251 else if (no->is_type_declaration())
12253 // The name was seen as a type, but the type was never defined.
12254 if (no->type_declaration_value()->using_type())
12256 go_error_at(this->named_object_->location(),
12257 "use of undefined type %qs",
12258 no->message_name().c_str());
12259 this->warned_ = true;
12262 else
12264 // The name was defined, but not as a type.
12265 if (!this->warned_)
12267 go_error_at(this->named_object_->location(), "expected type");
12268 this->warned_ = true;
12273 // Get the base type of a declaration. This gives an error if the
12274 // type has not yet been defined.
12276 Type*
12277 Forward_declaration_type::real_type()
12279 if (this->is_defined())
12281 Named_type* nt = this->named_object()->type_value();
12282 if (!nt->is_valid())
12283 return Type::make_error_type();
12284 return this->named_object()->type_value();
12286 else
12288 this->warn();
12289 return Type::make_error_type();
12293 const Type*
12294 Forward_declaration_type::real_type() const
12296 if (this->is_defined())
12298 const Named_type* nt = this->named_object()->type_value();
12299 if (!nt->is_valid())
12300 return Type::make_error_type();
12301 return this->named_object()->type_value();
12303 else
12305 this->warn();
12306 return Type::make_error_type();
12310 // Return whether the base type is defined.
12312 bool
12313 Forward_declaration_type::is_defined() const
12315 return this->named_object()->is_type();
12318 // Add a method. This is used when methods are defined before the
12319 // type.
12321 Named_object*
12322 Forward_declaration_type::add_method(const std::string& name,
12323 Function* function)
12325 Named_object* no = this->named_object();
12326 if (no->is_unknown())
12327 no->declare_as_type();
12328 return no->type_declaration_value()->add_method(name, function);
12331 // Add a method declaration. This is used when methods are declared
12332 // before the type.
12334 Named_object*
12335 Forward_declaration_type::add_method_declaration(const std::string& name,
12336 Package* package,
12337 Function_type* type,
12338 Location location)
12340 Named_object* no = this->named_object();
12341 if (no->is_unknown())
12342 no->declare_as_type();
12343 Type_declaration* td = no->type_declaration_value();
12344 return td->add_method_declaration(name, package, type, location);
12347 // Add an already created object as a method.
12349 void
12350 Forward_declaration_type::add_existing_method(Named_object* nom)
12352 Named_object* no = this->named_object();
12353 if (no->is_unknown())
12354 no->declare_as_type();
12355 no->type_declaration_value()->add_existing_method(nom);
12358 // Traversal.
12361 Forward_declaration_type::do_traverse(Traverse* traverse)
12363 if (this->is_defined()
12364 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12365 return TRAVERSE_EXIT;
12366 return TRAVERSE_CONTINUE;
12369 // Verify the type.
12371 bool
12372 Forward_declaration_type::do_verify()
12374 if (!this->is_defined() && !this->is_nil_constant_as_type())
12376 this->warn();
12377 return false;
12379 return true;
12382 // Get the backend representation for the type.
12384 Btype*
12385 Forward_declaration_type::do_get_backend(Gogo* gogo)
12387 if (this->is_defined())
12388 return Type::get_named_base_btype(gogo, this->real_type());
12390 if (this->warned_)
12391 return gogo->backend()->error_type();
12393 // We represent an undefined type as a struct with no fields. That
12394 // should work fine for the backend, since the same case can arise
12395 // in C.
12396 std::vector<Backend::Btyped_identifier> fields;
12397 Btype* bt = gogo->backend()->struct_type(fields);
12398 return gogo->backend()->named_type(this->name(), bt,
12399 this->named_object()->location());
12402 // Build a type descriptor for a forwarded type.
12404 Expression*
12405 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12407 Location ploc = Linemap::predeclared_location();
12408 if (!this->is_defined())
12409 return Expression::make_error(ploc);
12410 else
12412 Type* t = this->real_type();
12413 if (name != NULL)
12414 return this->named_type_descriptor(gogo, t, name);
12415 else
12416 return Expression::make_error(this->named_object_->location());
12420 // The reflection string.
12422 void
12423 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12425 this->append_reflection(this->real_type(), gogo, ret);
12428 // The mangled name.
12430 void
12431 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
12433 if (this->is_defined())
12434 this->append_mangled_name(this->real_type(), gogo, ret);
12435 else
12437 const Named_object* no = this->named_object();
12438 std::string name;
12439 if (no->package() == NULL)
12440 name = gogo->pkgpath_symbol();
12441 else
12442 name = no->package()->pkgpath_symbol();
12443 name += '.';
12444 name += Gogo::unpack_hidden_name(no->name());
12445 char buf[20];
12446 snprintf(buf, sizeof buf, "N%u_",
12447 static_cast<unsigned int>(name.length()));
12448 ret->append(buf);
12449 ret->append(name);
12453 // Export a forward declaration. This can happen when a defined type
12454 // refers to a type which is only declared (and is presumably defined
12455 // in some other file in the same package).
12457 void
12458 Forward_declaration_type::do_export(Export*) const
12460 // If there is a base type, that should be exported instead of this.
12461 go_assert(!this->is_defined());
12463 // We don't output anything.
12466 // Make a forward declaration.
12468 Type*
12469 Type::make_forward_declaration(Named_object* named_object)
12471 return new Forward_declaration_type(named_object);
12474 // Class Typed_identifier_list.
12476 // Sort the entries by name.
12478 struct Typed_identifier_list_sort
12480 public:
12481 bool
12482 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12484 return (Gogo::unpack_hidden_name(t1.name())
12485 < Gogo::unpack_hidden_name(t2.name()));
12489 void
12490 Typed_identifier_list::sort_by_name()
12492 std::sort(this->entries_.begin(), this->entries_.end(),
12493 Typed_identifier_list_sort());
12496 // Traverse types.
12499 Typed_identifier_list::traverse(Traverse* traverse)
12501 for (Typed_identifier_list::const_iterator p = this->begin();
12502 p != this->end();
12503 ++p)
12505 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12506 return TRAVERSE_EXIT;
12508 return TRAVERSE_CONTINUE;
12511 // Copy the list.
12513 Typed_identifier_list*
12514 Typed_identifier_list::copy() const
12516 Typed_identifier_list* ret = new Typed_identifier_list();
12517 for (Typed_identifier_list::const_iterator p = this->begin();
12518 p != this->end();
12519 ++p)
12520 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12521 return ret;