net/internal/socktest: build sys_unix.go on AIX
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob4d923733667ff9d45338e87b892918ae3b194bac
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);
1060 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1061 Type::placeholder_pointers.push_back(pt);
1063 break;
1065 case TYPE_STRUCT:
1066 // We don't have to make the struct itself be a placeholder. We
1067 // are promised that we know the sizes of the struct fields.
1068 // But we may have to use a placeholder for any particular
1069 // struct field.
1071 std::vector<Backend::Btyped_identifier> bfields;
1072 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1073 true, &bfields);
1074 bt = gogo->backend()->struct_type(bfields);
1076 break;
1078 case TYPE_ARRAY:
1079 if (this->is_slice_type())
1081 std::vector<Backend::Btyped_identifier> bfields;
1082 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1083 bt = gogo->backend()->struct_type(bfields);
1085 else
1087 Btype* element = this->array_type()->get_backend_element(gogo, true);
1088 Bexpression* len = this->array_type()->get_backend_length(gogo);
1089 bt = gogo->backend()->array_type(element, len);
1091 break;
1093 case TYPE_INTERFACE:
1095 go_assert(!this->interface_type()->is_empty());
1096 std::vector<Backend::Btyped_identifier> bfields;
1097 get_backend_interface_fields(gogo, this->interface_type(), true,
1098 &bfields);
1099 bt = gogo->backend()->struct_type(bfields);
1101 break;
1103 case TYPE_SINK:
1104 case TYPE_CALL_MULTIPLE_RESULT:
1105 /* Note that various classifications were handled in the earlier
1106 switch. */
1107 default:
1108 go_unreachable();
1111 if (ins.first->second.btype == NULL)
1113 ins.first->second.btype = bt;
1114 ins.first->second.is_placeholder = true;
1116 else
1118 // A placeholder for this type got created along the way. Use
1119 // that one and ignore the one we just built.
1120 bt = ins.first->second.btype;
1123 return bt;
1126 // Complete the backend representation. This is called for a type
1127 // using a placeholder type.
1129 void
1130 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1132 switch (this->classification_)
1134 case TYPE_ERROR:
1135 case TYPE_VOID:
1136 case TYPE_BOOLEAN:
1137 case TYPE_INTEGER:
1138 case TYPE_FLOAT:
1139 case TYPE_COMPLEX:
1140 case TYPE_STRING:
1141 case TYPE_NIL:
1142 go_unreachable();
1144 case TYPE_FUNCTION:
1146 Btype* bt = this->do_get_backend(gogo);
1147 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1148 go_assert(saw_errors());
1150 break;
1152 case TYPE_POINTER:
1154 Btype* bt = this->do_get_backend(gogo);
1155 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1156 go_assert(saw_errors());
1158 break;
1160 case TYPE_STRUCT:
1161 // The struct type itself is done, but we have to make sure that
1162 // all the field types are converted.
1163 this->struct_type()->finish_backend_fields(gogo);
1164 break;
1166 case TYPE_ARRAY:
1167 // The array type itself is done, but make sure the element type
1168 // is converted.
1169 this->array_type()->finish_backend_element(gogo);
1170 break;
1172 case TYPE_MAP:
1173 case TYPE_CHANNEL:
1174 go_unreachable();
1176 case TYPE_INTERFACE:
1177 // The interface type itself is done, but make sure the method
1178 // types are converted.
1179 this->interface_type()->finish_backend_methods(gogo);
1180 break;
1182 case TYPE_NAMED:
1183 case TYPE_FORWARD:
1184 go_unreachable();
1186 case TYPE_SINK:
1187 case TYPE_CALL_MULTIPLE_RESULT:
1188 default:
1189 go_unreachable();
1192 this->btype_ = placeholder;
1195 // Return a pointer to the type descriptor for this type.
1197 Bexpression*
1198 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1200 Type* t = this->forwarded();
1201 while (t->named_type() != NULL && t->named_type()->is_alias())
1202 t = t->named_type()->real_type()->forwarded();
1203 if (t->type_descriptor_var_ == NULL)
1205 t->make_type_descriptor_var(gogo);
1206 go_assert(t->type_descriptor_var_ != NULL);
1208 Bexpression* var_expr =
1209 gogo->backend()->var_expression(t->type_descriptor_var_,
1210 VE_rvalue, location);
1211 Bexpression* var_addr =
1212 gogo->backend()->address_expression(var_expr, location);
1213 Type* td_type = Type::make_type_descriptor_type();
1214 Btype* td_btype = td_type->get_backend(gogo);
1215 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1216 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1219 // A mapping from unnamed types to type descriptor variables.
1221 Type::Type_descriptor_vars Type::type_descriptor_vars;
1223 // Build the type descriptor for this type.
1225 void
1226 Type::make_type_descriptor_var(Gogo* gogo)
1228 go_assert(this->type_descriptor_var_ == NULL);
1230 Named_type* nt = this->named_type();
1232 // We can have multiple instances of unnamed types, but we only want
1233 // to emit the type descriptor once. We use a hash table. This is
1234 // not necessary for named types, as they are unique, and we store
1235 // the type descriptor in the type itself.
1236 Bvariable** phash = NULL;
1237 if (nt == NULL)
1239 Bvariable* bvnull = NULL;
1240 std::pair<Type_descriptor_vars::iterator, bool> ins =
1241 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1242 if (!ins.second)
1244 // We've already built a type descriptor for this type.
1245 this->type_descriptor_var_ = ins.first->second;
1246 return;
1248 phash = &ins.first->second;
1251 // The type descriptor symbol for the unsafe.Pointer type is defined in
1252 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1253 // symbol if necessary.
1254 if (this->is_unsafe_pointer_type())
1256 Location bloc = Linemap::predeclared_location();
1258 Type* td_type = Type::make_type_descriptor_type();
1259 Btype* td_btype = td_type->get_backend(gogo);
1260 const char *name = "__go_tdn_unsafe.Pointer";
1261 std::string asm_name(go_selectively_encode_id(name));
1262 this->type_descriptor_var_ =
1263 gogo->backend()->immutable_struct_reference(name, asm_name,
1264 td_btype,
1265 bloc);
1267 if (phash != NULL)
1268 *phash = this->type_descriptor_var_;
1269 return;
1272 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1274 // Build the contents of the type descriptor.
1275 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1277 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1279 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1281 const Package* dummy;
1282 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1284 std::string asm_name(go_selectively_encode_id(var_name));
1285 this->type_descriptor_var_ =
1286 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1287 initializer_btype,
1288 loc);
1289 if (phash != NULL)
1290 *phash = this->type_descriptor_var_;
1291 return;
1294 // See if this type descriptor can appear in multiple packages.
1295 bool is_common = false;
1296 if (nt != NULL)
1298 // We create the descriptor for a builtin type whenever we need
1299 // it.
1300 is_common = nt->is_builtin();
1302 else
1304 // This is an unnamed type. The descriptor could be defined in
1305 // any package where it is needed, and the linker will pick one
1306 // descriptor to keep.
1307 is_common = true;
1310 // We are going to build the type descriptor in this package. We
1311 // must create the variable before we convert the initializer to the
1312 // backend representation, because the initializer may refer to the
1313 // type descriptor of this type. By setting type_descriptor_var_ we
1314 // ensure that type_descriptor_pointer will work if called while
1315 // converting INITIALIZER.
1317 std::string asm_name(go_selectively_encode_id(var_name));
1318 this->type_descriptor_var_ =
1319 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1320 initializer_btype, loc);
1321 if (phash != NULL)
1322 *phash = this->type_descriptor_var_;
1324 Translate_context context(gogo, NULL, NULL, NULL);
1325 context.set_is_const();
1326 Bexpression* binitializer = initializer->get_backend(&context);
1328 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1329 var_name, false, is_common,
1330 initializer_btype, loc,
1331 binitializer);
1334 // Return the name of the type descriptor variable. If NT is not
1335 // NULL, use it to get the name. Otherwise this is an unnamed type.
1337 std::string
1338 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1340 if (nt == NULL)
1341 return "__go_td_" + this->mangled_name(gogo);
1343 Named_object* no = nt->named_object();
1344 unsigned int index;
1345 const Named_object* in_function = nt->in_function(&index);
1346 std::string ret = "__go_tdn_";
1347 if (nt->is_builtin())
1348 go_assert(in_function == NULL);
1349 else
1351 const std::string& pkgpath(no->package() == NULL
1352 ? gogo->pkgpath_symbol()
1353 : no->package()->pkgpath_symbol());
1354 ret.append(pkgpath);
1355 ret.append(1, '.');
1356 if (in_function != NULL)
1358 const Typed_identifier* rcvr =
1359 in_function->func_value()->type()->receiver();
1360 if (rcvr != NULL)
1362 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1363 ret.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1364 ret.append(1, '.');
1366 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1367 ret.append(1, '.');
1368 if (index > 0)
1370 char buf[30];
1371 snprintf(buf, sizeof buf, "%u", index);
1372 ret.append(buf);
1373 ret.append(1, '.');
1378 std::string mname(Gogo::mangle_possibly_hidden_name(no->name()));
1379 ret.append(mname);
1381 return ret;
1384 // Return true if this type descriptor is defined in a different
1385 // package. If this returns true it sets *PACKAGE to the package.
1387 bool
1388 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1389 const Package** package)
1391 if (nt != NULL)
1393 if (nt->named_object()->package() != NULL)
1395 // This is a named type defined in a different package. The
1396 // type descriptor should be defined in that package.
1397 *package = nt->named_object()->package();
1398 return true;
1401 else
1403 if (this->points_to() != NULL
1404 && this->points_to()->named_type() != NULL
1405 && this->points_to()->named_type()->named_object()->package() != NULL)
1407 // This is an unnamed pointer to a named type defined in a
1408 // different package. The descriptor should be defined in
1409 // that package.
1410 *package = this->points_to()->named_type()->named_object()->package();
1411 return true;
1414 return false;
1417 // Return a composite literal for a type descriptor.
1419 Expression*
1420 Type::type_descriptor(Gogo* gogo, Type* type)
1422 return type->do_type_descriptor(gogo, NULL);
1425 // Return a composite literal for a type descriptor with a name.
1427 Expression*
1428 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1430 go_assert(name != NULL && type->named_type() != name);
1431 return type->do_type_descriptor(gogo, name);
1434 // Make a builtin struct type from a list of fields. The fields are
1435 // pairs of a name and a type.
1437 Struct_type*
1438 Type::make_builtin_struct_type(int nfields, ...)
1440 va_list ap;
1441 va_start(ap, nfields);
1443 Location bloc = Linemap::predeclared_location();
1444 Struct_field_list* sfl = new Struct_field_list();
1445 for (int i = 0; i < nfields; i++)
1447 const char* field_name = va_arg(ap, const char *);
1448 Type* type = va_arg(ap, Type*);
1449 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1452 va_end(ap);
1454 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1455 ret->set_is_struct_incomparable();
1456 return ret;
1459 // A list of builtin named types.
1461 std::vector<Named_type*> Type::named_builtin_types;
1463 // Make a builtin named type.
1465 Named_type*
1466 Type::make_builtin_named_type(const char* name, Type* type)
1468 Location bloc = Linemap::predeclared_location();
1469 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1470 Named_type* ret = no->type_value();
1471 Type::named_builtin_types.push_back(ret);
1472 return ret;
1475 // Convert the named builtin types.
1477 void
1478 Type::convert_builtin_named_types(Gogo* gogo)
1480 for (std::vector<Named_type*>::const_iterator p =
1481 Type::named_builtin_types.begin();
1482 p != Type::named_builtin_types.end();
1483 ++p)
1485 bool r = (*p)->verify();
1486 go_assert(r);
1487 (*p)->convert(gogo);
1491 // Return the type of a type descriptor. We should really tie this to
1492 // runtime.Type rather than copying it. This must match the struct "_type"
1493 // declared in libgo/go/runtime/type.go.
1495 Type*
1496 Type::make_type_descriptor_type()
1498 static Type* ret;
1499 if (ret == NULL)
1501 Location bloc = Linemap::predeclared_location();
1503 Type* uint8_type = Type::lookup_integer_type("uint8");
1504 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1505 Type* uint32_type = Type::lookup_integer_type("uint32");
1506 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1507 Type* string_type = Type::lookup_string_type();
1508 Type* pointer_string_type = Type::make_pointer_type(string_type);
1510 // This is an unnamed version of unsafe.Pointer. Perhaps we
1511 // should use the named version instead, although that would
1512 // require us to create the unsafe package if it has not been
1513 // imported. It probably doesn't matter.
1514 Type* void_type = Type::make_void_type();
1515 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1517 Typed_identifier_list *params = new Typed_identifier_list();
1518 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1519 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1521 Typed_identifier_list* results = new Typed_identifier_list();
1522 results->push_back(Typed_identifier("", uintptr_type, bloc));
1524 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1525 bloc);
1527 params = new Typed_identifier_list();
1528 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1529 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1531 results = new Typed_identifier_list();
1532 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1534 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1535 bloc);
1537 // Forward declaration for the type descriptor type.
1538 Named_object* named_type_descriptor_type =
1539 Named_object::make_type_declaration("_type", NULL, bloc);
1540 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1541 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1543 // The type of a method on a concrete type.
1544 Struct_type* method_type =
1545 Type::make_builtin_struct_type(5,
1546 "name", pointer_string_type,
1547 "pkgPath", pointer_string_type,
1548 "mtyp", pointer_type_descriptor_type,
1549 "typ", pointer_type_descriptor_type,
1550 "tfn", unsafe_pointer_type);
1551 Named_type* named_method_type =
1552 Type::make_builtin_named_type("method", method_type);
1554 // Information for types with a name or methods.
1555 Type* slice_named_method_type =
1556 Type::make_array_type(named_method_type, NULL);
1557 Struct_type* uncommon_type =
1558 Type::make_builtin_struct_type(3,
1559 "name", pointer_string_type,
1560 "pkgPath", pointer_string_type,
1561 "methods", slice_named_method_type);
1562 Named_type* named_uncommon_type =
1563 Type::make_builtin_named_type("uncommonType", uncommon_type);
1565 Type* pointer_uncommon_type =
1566 Type::make_pointer_type(named_uncommon_type);
1568 // The type descriptor type.
1570 Struct_type* type_descriptor_type =
1571 Type::make_builtin_struct_type(12,
1572 "size", uintptr_type,
1573 "ptrdata", uintptr_type,
1574 "hash", uint32_type,
1575 "kind", uint8_type,
1576 "align", uint8_type,
1577 "fieldAlign", uint8_type,
1578 "hashfn", hash_fntype,
1579 "equalfn", equal_fntype,
1580 "gcdata", pointer_uint8_type,
1581 "string", pointer_string_type,
1582 "", pointer_uncommon_type,
1583 "ptrToThis",
1584 pointer_type_descriptor_type);
1586 Named_type* named = Type::make_builtin_named_type("_type",
1587 type_descriptor_type);
1589 named_type_descriptor_type->set_type_value(named);
1591 ret = named;
1594 return ret;
1597 // Make the type of a pointer to a type descriptor as represented in
1598 // Go.
1600 Type*
1601 Type::make_type_descriptor_ptr_type()
1603 static Type* ret;
1604 if (ret == NULL)
1605 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1606 return ret;
1609 // Return the alignment required by the memequalN function. N is a
1610 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1611 // in libgo/go/runtime/alg.go.
1613 int64_t
1614 Type::memequal_align(Gogo* gogo, int size)
1616 const char* tn;
1617 switch (size)
1619 case 16:
1620 tn = "int16";
1621 break;
1622 case 32:
1623 tn = "int32";
1624 break;
1625 case 64:
1626 tn = "int64";
1627 break;
1628 case 128:
1629 // The code uses [2]int64, which must have the same alignment as
1630 // int64.
1631 tn = "int64";
1632 break;
1633 default:
1634 go_unreachable();
1637 Type* t = Type::lookup_integer_type(tn);
1639 int64_t ret;
1640 if (!t->backend_type_align(gogo, &ret))
1641 go_unreachable();
1642 return ret;
1645 // Return whether this type needs specially built type functions.
1646 // This returns true for types that are comparable and either can not
1647 // use an identity comparison, or are a non-standard size.
1649 bool
1650 Type::needs_specific_type_functions(Gogo* gogo)
1652 Named_type* nt = this->named_type();
1653 if (nt != NULL && nt->is_alias())
1654 return false;
1655 if (!this->is_comparable())
1656 return false;
1657 if (!this->compare_is_identity(gogo))
1658 return true;
1660 // We create a few predeclared types for type descriptors; they are
1661 // really just for the backend and don't need hash or equality
1662 // functions.
1663 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1664 return false;
1666 int64_t size, align;
1667 if (!this->backend_type_size(gogo, &size)
1668 || !this->backend_type_align(gogo, &align))
1670 go_assert(saw_errors());
1671 return false;
1673 // This switch matches the one in Type::type_functions.
1674 switch (size)
1676 case 0:
1677 case 1:
1678 case 2:
1679 return align < Type::memequal_align(gogo, 16);
1680 case 4:
1681 return align < Type::memequal_align(gogo, 32);
1682 case 8:
1683 return align < Type::memequal_align(gogo, 64);
1684 case 16:
1685 return align < Type::memequal_align(gogo, 128);
1686 default:
1687 return true;
1691 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1692 // hash code for this type and which compare whether two values of
1693 // this type are equal. If NAME is not NULL it is the name of this
1694 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1695 // functions, for convenience; they may be NULL.
1697 void
1698 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1699 Function_type* equal_fntype, Named_object** hash_fn,
1700 Named_object** equal_fn)
1702 // If this loop leaves NAME as NULL, then the type does not have a
1703 // name after all.
1704 while (name != NULL && name->is_alias())
1705 name = name->real_type()->named_type();
1707 if (!this->is_comparable())
1709 *hash_fn = NULL;
1710 *equal_fn = NULL;
1711 return;
1714 if (hash_fntype == NULL || equal_fntype == NULL)
1716 Location bloc = Linemap::predeclared_location();
1718 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1719 Type* void_type = Type::make_void_type();
1720 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1722 if (hash_fntype == NULL)
1724 Typed_identifier_list* params = new Typed_identifier_list();
1725 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1726 bloc));
1727 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1729 Typed_identifier_list* results = new Typed_identifier_list();
1730 results->push_back(Typed_identifier("", uintptr_type, bloc));
1732 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1734 if (equal_fntype == NULL)
1736 Typed_identifier_list* params = new Typed_identifier_list();
1737 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1738 bloc));
1739 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1740 bloc));
1742 Typed_identifier_list* results = new Typed_identifier_list();
1743 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1744 bloc));
1746 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1750 const char* hash_fnname;
1751 const char* equal_fnname;
1752 if (this->compare_is_identity(gogo))
1754 int64_t size, align;
1755 if (!this->backend_type_size(gogo, &size)
1756 || !this->backend_type_align(gogo, &align))
1758 go_assert(saw_errors());
1759 return;
1761 bool build_functions = false;
1762 // This switch matches the one in Type::needs_specific_type_functions.
1763 // The alignment tests are because of the memequal functions,
1764 // which assume that the values are aligned as required for an
1765 // integer of that size.
1766 switch (size)
1768 case 0:
1769 hash_fnname = "runtime.memhash0";
1770 equal_fnname = "runtime.memequal0";
1771 break;
1772 case 1:
1773 hash_fnname = "runtime.memhash8";
1774 equal_fnname = "runtime.memequal8";
1775 break;
1776 case 2:
1777 if (align < Type::memequal_align(gogo, 16))
1778 build_functions = true;
1779 else
1781 hash_fnname = "runtime.memhash16";
1782 equal_fnname = "runtime.memequal16";
1784 break;
1785 case 4:
1786 if (align < Type::memequal_align(gogo, 32))
1787 build_functions = true;
1788 else
1790 hash_fnname = "runtime.memhash32";
1791 equal_fnname = "runtime.memequal32";
1793 break;
1794 case 8:
1795 if (align < Type::memequal_align(gogo, 64))
1796 build_functions = true;
1797 else
1799 hash_fnname = "runtime.memhash64";
1800 equal_fnname = "runtime.memequal64";
1802 break;
1803 case 16:
1804 if (align < Type::memequal_align(gogo, 128))
1805 build_functions = true;
1806 else
1808 hash_fnname = "runtime.memhash128";
1809 equal_fnname = "runtime.memequal128";
1811 break;
1812 default:
1813 build_functions = true;
1814 break;
1816 if (build_functions)
1818 // We don't have a built-in function for a type of this size
1819 // and alignment. Build a function to use that calls the
1820 // generic hash/equality functions for identity, passing the size.
1821 this->specific_type_functions(gogo, name, size, hash_fntype,
1822 equal_fntype, hash_fn, equal_fn);
1823 return;
1826 else
1828 switch (this->base()->classification())
1830 case Type::TYPE_ERROR:
1831 case Type::TYPE_VOID:
1832 case Type::TYPE_NIL:
1833 case Type::TYPE_FUNCTION:
1834 case Type::TYPE_MAP:
1835 // For these types is_comparable should have returned false.
1836 go_unreachable();
1838 case Type::TYPE_BOOLEAN:
1839 case Type::TYPE_INTEGER:
1840 case Type::TYPE_POINTER:
1841 case Type::TYPE_CHANNEL:
1842 // For these types compare_is_identity should have returned true.
1843 go_unreachable();
1845 case Type::TYPE_FLOAT:
1846 switch (this->float_type()->bits())
1848 case 32:
1849 hash_fnname = "runtime.f32hash";
1850 equal_fnname = "runtime.f32equal";
1851 break;
1852 case 64:
1853 hash_fnname = "runtime.f64hash";
1854 equal_fnname = "runtime.f64equal";
1855 break;
1856 default:
1857 go_unreachable();
1859 break;
1861 case Type::TYPE_COMPLEX:
1862 switch (this->complex_type()->bits())
1864 case 64:
1865 hash_fnname = "runtime.c64hash";
1866 equal_fnname = "runtime.c64equal";
1867 break;
1868 case 128:
1869 hash_fnname = "runtime.c128hash";
1870 equal_fnname = "runtime.c128equal";
1871 break;
1872 default:
1873 go_unreachable();
1875 break;
1877 case Type::TYPE_STRING:
1878 hash_fnname = "runtime.strhash";
1879 equal_fnname = "runtime.strequal";
1880 break;
1882 case Type::TYPE_STRUCT:
1884 // This is a struct which can not be compared using a
1885 // simple identity function. We need to build a function
1886 // for comparison.
1887 this->specific_type_functions(gogo, name, -1, hash_fntype,
1888 equal_fntype, hash_fn, equal_fn);
1889 return;
1892 case Type::TYPE_ARRAY:
1893 if (this->is_slice_type())
1895 // Type::is_compatible_for_comparison should have
1896 // returned false.
1897 go_unreachable();
1899 else
1901 // This is an array which can not be compared using a
1902 // simple identity function. We need to build a
1903 // function for comparison.
1904 this->specific_type_functions(gogo, name, -1, hash_fntype,
1905 equal_fntype, hash_fn, equal_fn);
1906 return;
1908 break;
1910 case Type::TYPE_INTERFACE:
1911 if (this->interface_type()->is_empty())
1913 hash_fnname = "runtime.nilinterhash";
1914 equal_fnname = "runtime.nilinterequal";
1916 else
1918 hash_fnname = "runtime.interhash";
1919 equal_fnname = "runtime.interequal";
1921 break;
1923 case Type::TYPE_NAMED:
1924 case Type::TYPE_FORWARD:
1925 go_unreachable();
1927 default:
1928 go_unreachable();
1933 Location bloc = Linemap::predeclared_location();
1934 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1935 hash_fntype, bloc);
1936 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1937 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1938 equal_fntype, bloc);
1939 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1942 // A hash table mapping types to the specific hash functions.
1944 Type::Type_functions Type::type_functions_table;
1946 // Handle a type function which is specific to a type: if SIZE == -1,
1947 // this is a struct or array that can not use an identity comparison.
1948 // Otherwise, it is a type that uses an identity comparison but is not
1949 // one of the standard supported sizes.
1951 void
1952 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1953 Function_type* hash_fntype,
1954 Function_type* equal_fntype,
1955 Named_object** hash_fn,
1956 Named_object** equal_fn)
1958 Hash_equal_fn fnull(NULL, NULL);
1959 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1960 std::pair<Type_functions::iterator, bool> ins =
1961 Type::type_functions_table.insert(val);
1962 if (!ins.second)
1964 // We already have functions for this type
1965 *hash_fn = ins.first->second.first;
1966 *equal_fn = ins.first->second.second;
1967 return;
1970 std::string base_name;
1971 if (name == NULL)
1973 // Mangled names can have '.' if they happen to refer to named
1974 // types in some way. That's fine if this is simply a named
1975 // type, but otherwise it will confuse the code that builds
1976 // function identifiers. Remove '.' when necessary.
1977 base_name = this->mangled_name(gogo);
1978 size_t i;
1979 while ((i = base_name.find('.')) != std::string::npos)
1980 base_name[i] = '$';
1981 base_name = gogo->pack_hidden_name(base_name, false);
1983 else
1985 // This name is already hidden or not as appropriate.
1986 base_name = name->name();
1987 unsigned int index;
1988 const Named_object* in_function = name->in_function(&index);
1989 if (in_function != NULL)
1991 base_name.append(1, '$');
1992 const Typed_identifier* rcvr =
1993 in_function->func_value()->type()->receiver();
1994 if (rcvr != NULL)
1996 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1997 base_name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1998 base_name.append(1, '$');
2000 base_name.append(Gogo::unpack_hidden_name(in_function->name()));
2001 if (index > 0)
2003 char buf[30];
2004 snprintf(buf, sizeof buf, "%u", index);
2005 base_name += '$';
2006 base_name += buf;
2010 std::string hash_name = base_name + "$hash";
2011 std::string equal_name = base_name + "$equal";
2013 Location bloc = Linemap::predeclared_location();
2015 const Package* package = NULL;
2016 bool is_defined_elsewhere =
2017 this->type_descriptor_defined_elsewhere(name, &package);
2018 if (is_defined_elsewhere)
2020 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2021 hash_fntype, bloc);
2022 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2023 equal_fntype, bloc);
2025 else
2027 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2028 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2029 bloc);
2032 ins.first->second.first = *hash_fn;
2033 ins.first->second.second = *equal_fn;
2035 if (!is_defined_elsewhere)
2037 if (gogo->in_global_scope())
2038 this->write_specific_type_functions(gogo, name, size, hash_name,
2039 hash_fntype, equal_name,
2040 equal_fntype);
2041 else
2042 gogo->queue_specific_type_function(this, name, size, hash_name,
2043 hash_fntype, equal_name,
2044 equal_fntype);
2048 // Write the hash and equality functions for a type which needs to be
2049 // written specially.
2051 void
2052 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2053 const std::string& hash_name,
2054 Function_type* hash_fntype,
2055 const std::string& equal_name,
2056 Function_type* equal_fntype)
2058 Location bloc = Linemap::predeclared_location();
2060 if (gogo->specific_type_functions_are_written())
2062 go_assert(saw_errors());
2063 return;
2066 go_assert(this->is_comparable());
2068 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2069 bloc);
2070 hash_fn->func_value()->set_is_type_specific_function();
2071 gogo->start_block(bloc);
2073 if (size != -1)
2074 this->write_identity_hash(gogo, size);
2075 else if (name != NULL && name->real_type()->named_type() != NULL)
2076 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2077 else if (this->struct_type() != NULL)
2078 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2079 equal_fntype);
2080 else if (this->array_type() != NULL)
2081 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2082 equal_fntype);
2083 else
2084 go_unreachable();
2086 Block* b = gogo->finish_block(bloc);
2087 gogo->add_block(b, bloc);
2088 gogo->lower_block(hash_fn, b);
2089 gogo->finish_function(bloc);
2091 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2092 false, bloc);
2093 equal_fn->func_value()->set_is_type_specific_function();
2094 gogo->start_block(bloc);
2096 if (size != -1)
2097 this->write_identity_equal(gogo, size);
2098 else if (name != NULL && name->real_type()->named_type() != NULL)
2099 this->write_named_equal(gogo, name);
2100 else if (this->struct_type() != NULL)
2101 this->struct_type()->write_equal_function(gogo, name);
2102 else if (this->array_type() != NULL)
2103 this->array_type()->write_equal_function(gogo, name);
2104 else
2105 go_unreachable();
2107 b = gogo->finish_block(bloc);
2108 gogo->add_block(b, bloc);
2109 gogo->lower_block(equal_fn, b);
2110 gogo->finish_function(bloc);
2112 // Build the function descriptors for the type descriptor to refer to.
2113 hash_fn->func_value()->descriptor(gogo, hash_fn);
2114 equal_fn->func_value()->descriptor(gogo, equal_fn);
2117 // Write a hash function for a type that can use an identity hash but
2118 // is not one of the standard supported sizes. For example, this
2119 // would be used for the type [3]byte. This builds a return statement
2120 // that returns a call to the memhash function, passing the key and
2121 // seed from the function arguments (already constructed before this
2122 // is called), and the constant size.
2124 void
2125 Type::write_identity_hash(Gogo* gogo, int64_t size)
2127 Location bloc = Linemap::predeclared_location();
2129 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2130 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2132 Typed_identifier_list* params = new Typed_identifier_list();
2133 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2134 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2135 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2137 Typed_identifier_list* results = new Typed_identifier_list();
2138 results->push_back(Typed_identifier("", uintptr_type, bloc));
2140 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2141 results, bloc);
2143 Named_object* memhash =
2144 Named_object::make_function_declaration("runtime.memhash", NULL,
2145 memhash_fntype, bloc);
2146 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2148 Named_object* key_arg = gogo->lookup("key", NULL);
2149 go_assert(key_arg != NULL);
2150 Named_object* seed_arg = gogo->lookup("seed", NULL);
2151 go_assert(seed_arg != NULL);
2153 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2154 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2155 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2156 bloc);
2157 Expression_list* args = new Expression_list();
2158 args->push_back(key_ref);
2159 args->push_back(seed_ref);
2160 args->push_back(size_arg);
2161 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2162 Expression* call = Expression::make_call(func, args, false, bloc);
2164 Expression_list* vals = new Expression_list();
2165 vals->push_back(call);
2166 Statement* s = Statement::make_return_statement(vals, bloc);
2167 gogo->add_statement(s);
2170 // Write an equality function for a type that can use an identity
2171 // equality comparison but is not one of the standard supported sizes.
2172 // For example, this would be used for the type [3]byte. This builds
2173 // a return statement that returns a call to the memequal function,
2174 // passing the two keys from the function arguments (already
2175 // constructed before this is called), and the constant size.
2177 void
2178 Type::write_identity_equal(Gogo* gogo, int64_t size)
2180 Location bloc = Linemap::predeclared_location();
2182 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2183 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2185 Typed_identifier_list* params = new Typed_identifier_list();
2186 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2187 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2188 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2190 Typed_identifier_list* results = new Typed_identifier_list();
2191 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2193 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2194 results, bloc);
2196 Named_object* memequal =
2197 Named_object::make_function_declaration("runtime.memequal", NULL,
2198 memequal_fntype, bloc);
2199 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2201 Named_object* key1_arg = gogo->lookup("key1", NULL);
2202 go_assert(key1_arg != NULL);
2203 Named_object* key2_arg = gogo->lookup("key2", NULL);
2204 go_assert(key2_arg != NULL);
2206 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2207 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2208 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2209 bloc);
2210 Expression_list* args = new Expression_list();
2211 args->push_back(key1_ref);
2212 args->push_back(key2_ref);
2213 args->push_back(size_arg);
2214 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2215 Expression* call = Expression::make_call(func, args, false, bloc);
2217 Expression_list* vals = new Expression_list();
2218 vals->push_back(call);
2219 Statement* s = Statement::make_return_statement(vals, bloc);
2220 gogo->add_statement(s);
2223 // Write a hash function that simply calls the hash function for a
2224 // named type. This is used when one named type is defined as
2225 // another. This ensures that this case works when the other named
2226 // type is defined in another package and relies on calling hash
2227 // functions defined only in that package.
2229 void
2230 Type::write_named_hash(Gogo* gogo, Named_type* name,
2231 Function_type* hash_fntype, Function_type* equal_fntype)
2233 Location bloc = Linemap::predeclared_location();
2235 Named_type* base_type = name->real_type()->named_type();
2236 while (base_type->is_alias())
2238 base_type = base_type->real_type()->named_type();
2239 go_assert(base_type != NULL);
2241 go_assert(base_type != NULL);
2243 // The pointer to the type we are going to hash. This is an
2244 // unsafe.Pointer.
2245 Named_object* key_arg = gogo->lookup("key", NULL);
2246 go_assert(key_arg != NULL);
2248 // The seed argument to the hash function.
2249 Named_object* seed_arg = gogo->lookup("seed", NULL);
2250 go_assert(seed_arg != NULL);
2252 Named_object* hash_fn;
2253 Named_object* equal_fn;
2254 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2255 &hash_fn, &equal_fn);
2257 // Call the hash function for the base type.
2258 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2259 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2260 Expression_list* args = new Expression_list();
2261 args->push_back(key_ref);
2262 args->push_back(seed_ref);
2263 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2264 Expression* call = Expression::make_call(func, args, false, bloc);
2266 // Return the hash of the base type.
2267 Expression_list* vals = new Expression_list();
2268 vals->push_back(call);
2269 Statement* s = Statement::make_return_statement(vals, bloc);
2270 gogo->add_statement(s);
2273 // Write an equality function that simply calls the equality function
2274 // for a named type. This is used when one named type is defined as
2275 // another. This ensures that this case works when the other named
2276 // type is defined in another package and relies on calling equality
2277 // functions defined only in that package.
2279 void
2280 Type::write_named_equal(Gogo* gogo, Named_type* name)
2282 Location bloc = Linemap::predeclared_location();
2284 // The pointers to the types we are going to compare. These have
2285 // type unsafe.Pointer.
2286 Named_object* key1_arg = gogo->lookup("key1", NULL);
2287 Named_object* key2_arg = gogo->lookup("key2", NULL);
2288 go_assert(key1_arg != NULL && key2_arg != NULL);
2290 Named_type* base_type = name->real_type()->named_type();
2291 go_assert(base_type != NULL);
2293 // Build temporaries with the base type.
2294 Type* pt = Type::make_pointer_type(base_type);
2296 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2297 ref = Expression::make_cast(pt, ref, bloc);
2298 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2299 gogo->add_statement(p1);
2301 ref = Expression::make_var_reference(key2_arg, bloc);
2302 ref = Expression::make_cast(pt, ref, bloc);
2303 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2304 gogo->add_statement(p2);
2306 // Compare the values for equality.
2307 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2308 t1 = Expression::make_unary(OPERATOR_MULT, t1, bloc);
2310 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2311 t2 = Expression::make_unary(OPERATOR_MULT, t2, bloc);
2313 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2315 // Return the equality comparison.
2316 Expression_list* vals = new Expression_list();
2317 vals->push_back(cond);
2318 Statement* s = Statement::make_return_statement(vals, bloc);
2319 gogo->add_statement(s);
2322 // Return a composite literal for the type descriptor for a plain type
2323 // of kind RUNTIME_TYPE_KIND named NAME.
2325 Expression*
2326 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2327 Named_type* name, const Methods* methods,
2328 bool only_value_methods)
2330 Location bloc = Linemap::predeclared_location();
2332 Type* td_type = Type::make_type_descriptor_type();
2333 const Struct_field_list* fields = td_type->struct_type()->fields();
2335 Expression_list* vals = new Expression_list();
2336 vals->reserve(12);
2338 if (!this->has_pointer())
2339 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2340 if (this->points_to() != NULL)
2341 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2342 int64_t ptrsize;
2343 int64_t ptrdata;
2344 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2345 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2347 Struct_field_list::const_iterator p = fields->begin();
2348 go_assert(p->is_field_name("size"));
2349 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2350 vals->push_back(Expression::make_type_info(this, type_info));
2352 ++p;
2353 go_assert(p->is_field_name("ptrdata"));
2354 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2355 vals->push_back(Expression::make_type_info(this, type_info));
2357 ++p;
2358 go_assert(p->is_field_name("hash"));
2359 unsigned int h;
2360 if (name != NULL)
2361 h = name->hash_for_method(gogo);
2362 else
2363 h = this->hash_for_method(gogo);
2364 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2366 ++p;
2367 go_assert(p->is_field_name("kind"));
2368 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2369 bloc));
2371 ++p;
2372 go_assert(p->is_field_name("align"));
2373 type_info = Expression::TYPE_INFO_ALIGNMENT;
2374 vals->push_back(Expression::make_type_info(this, type_info));
2376 ++p;
2377 go_assert(p->is_field_name("fieldAlign"));
2378 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2379 vals->push_back(Expression::make_type_info(this, type_info));
2381 ++p;
2382 go_assert(p->is_field_name("hashfn"));
2383 Function_type* hash_fntype = p->type()->function_type();
2385 ++p;
2386 go_assert(p->is_field_name("equalfn"));
2387 Function_type* equal_fntype = p->type()->function_type();
2389 Named_object* hash_fn;
2390 Named_object* equal_fn;
2391 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2392 &equal_fn);
2393 if (hash_fn == NULL)
2394 vals->push_back(Expression::make_cast(hash_fntype,
2395 Expression::make_nil(bloc),
2396 bloc));
2397 else
2398 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2399 if (equal_fn == NULL)
2400 vals->push_back(Expression::make_cast(equal_fntype,
2401 Expression::make_nil(bloc),
2402 bloc));
2403 else
2404 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2406 ++p;
2407 go_assert(p->is_field_name("gcdata"));
2408 vals->push_back(Expression::make_gc_symbol(this));
2410 ++p;
2411 go_assert(p->is_field_name("string"));
2412 Expression* s = Expression::make_string((name != NULL
2413 ? name->reflection(gogo)
2414 : this->reflection(gogo)),
2415 bloc);
2416 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2418 ++p;
2419 go_assert(p->is_field_name("uncommonType"));
2420 if (name == NULL && methods == NULL)
2421 vals->push_back(Expression::make_nil(bloc));
2422 else
2424 if (methods == NULL)
2425 methods = name->methods();
2426 vals->push_back(this->uncommon_type_constructor(gogo,
2427 p->type()->deref(),
2428 name, methods,
2429 only_value_methods));
2432 ++p;
2433 go_assert(p->is_field_name("ptrToThis"));
2434 if (name == NULL && methods == NULL)
2435 vals->push_back(Expression::make_nil(bloc));
2436 else
2438 Type* pt;
2439 if (name != NULL)
2440 pt = Type::make_pointer_type(name);
2441 else
2442 pt = Type::make_pointer_type(this);
2443 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2446 ++p;
2447 go_assert(p == fields->end());
2449 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2452 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2453 // length used by the gc toolchain, and also appears in
2454 // libgo/go/reflect/type.go.
2456 static const int64_t max_ptrmask_bytes = 2048;
2458 // Return a pointer to the Garbage Collection information for this type.
2460 Bexpression*
2461 Type::gc_symbol_pointer(Gogo* gogo)
2463 Type* t = this->forwarded();
2464 while (t->named_type() != NULL && t->named_type()->is_alias())
2465 t = t->named_type()->real_type()->forwarded();
2467 if (!t->has_pointer())
2468 return gogo->backend()->nil_pointer_expression();
2470 if (t->gc_symbol_var_ == NULL)
2472 t->make_gc_symbol_var(gogo);
2473 go_assert(t->gc_symbol_var_ != NULL);
2475 Location bloc = Linemap::predeclared_location();
2476 Bexpression* var_expr =
2477 gogo->backend()->var_expression(t->gc_symbol_var_, VE_rvalue, bloc);
2478 Bexpression* addr_expr =
2479 gogo->backend()->address_expression(var_expr, bloc);
2481 Type* uint8_type = Type::lookup_integer_type("uint8");
2482 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2483 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2484 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2487 // A mapping from unnamed types to GC symbol variables.
2489 Type::GC_symbol_vars Type::gc_symbol_vars;
2491 // Build the GC symbol for this type.
2493 void
2494 Type::make_gc_symbol_var(Gogo* gogo)
2496 go_assert(this->gc_symbol_var_ == NULL);
2498 Named_type* nt = this->named_type();
2500 // We can have multiple instances of unnamed types and similar to type
2501 // descriptors, we only want to the emit the GC data once, so we use a
2502 // hash table.
2503 Bvariable** phash = NULL;
2504 if (nt == NULL)
2506 Bvariable* bvnull = NULL;
2507 std::pair<GC_symbol_vars::iterator, bool> ins =
2508 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2509 if (!ins.second)
2511 // We've already built a gc symbol for this type.
2512 this->gc_symbol_var_ = ins.first->second;
2513 return;
2515 phash = &ins.first->second;
2518 int64_t ptrsize;
2519 int64_t ptrdata;
2520 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2522 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2523 if (phash != NULL)
2524 *phash = this->gc_symbol_var_;
2525 return;
2528 std::string sym_name = this->type_descriptor_var_name(gogo, nt) + "$gc";
2530 // Build the contents of the gc symbol.
2531 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2532 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2534 // If the type descriptor for this type is defined somewhere else, so is the
2535 // GC symbol.
2536 const Package* dummy;
2537 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2539 std::string asm_name(go_selectively_encode_id(sym_name));
2540 this->gc_symbol_var_ =
2541 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2542 sym_btype);
2543 if (phash != NULL)
2544 *phash = this->gc_symbol_var_;
2545 return;
2548 // See if this gc symbol can appear in multiple packages.
2549 bool is_common = false;
2550 if (nt != NULL)
2552 // We create the symbol for a builtin type whenever we need
2553 // it.
2554 is_common = nt->is_builtin();
2556 else
2558 // This is an unnamed type. The descriptor could be defined in
2559 // any package where it is needed, and the linker will pick one
2560 // descriptor to keep.
2561 is_common = true;
2564 // Since we are building the GC symbol in this package, we must create the
2565 // variable before converting the initializer to its backend representation
2566 // because the initializer may refer to the GC symbol for this type.
2567 std::string asm_name(go_selectively_encode_id(sym_name));
2568 this->gc_symbol_var_ =
2569 gogo->backend()->implicit_variable(sym_name, asm_name,
2570 sym_btype, false, true, is_common, 0);
2571 if (phash != NULL)
2572 *phash = this->gc_symbol_var_;
2574 Translate_context context(gogo, NULL, NULL, NULL);
2575 context.set_is_const();
2576 Bexpression* sym_binit = sym_init->get_backend(&context);
2577 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2578 sym_btype, false, true, is_common,
2579 sym_binit);
2582 // Return whether this type needs a GC program, and set *PTRDATA to
2583 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2584 // pointer.
2586 bool
2587 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2589 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2590 if (!voidptr->backend_type_size(gogo, ptrsize))
2591 go_unreachable();
2593 if (!this->backend_type_ptrdata(gogo, ptrdata))
2595 go_assert(saw_errors());
2596 return false;
2599 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2602 // A simple class used to build a GC ptrmask for a type.
2604 class Ptrmask
2606 public:
2607 Ptrmask(size_t count)
2608 : bits_((count + 7) / 8, 0)
2611 void
2612 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2614 std::string
2615 symname() const;
2617 Expression*
2618 constructor(Gogo* gogo) const;
2620 private:
2621 void
2622 set(size_t index)
2623 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2625 // The actual bits.
2626 std::vector<unsigned char> bits_;
2629 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2630 // counts in bytes. PTRSIZE is the size of a pointer on the target
2631 // system.
2633 void
2634 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2636 switch (type->base()->classification())
2638 default:
2639 case Type::TYPE_NIL:
2640 case Type::TYPE_CALL_MULTIPLE_RESULT:
2641 case Type::TYPE_NAMED:
2642 case Type::TYPE_FORWARD:
2643 go_unreachable();
2645 case Type::TYPE_ERROR:
2646 case Type::TYPE_VOID:
2647 case Type::TYPE_BOOLEAN:
2648 case Type::TYPE_INTEGER:
2649 case Type::TYPE_FLOAT:
2650 case Type::TYPE_COMPLEX:
2651 case Type::TYPE_SINK:
2652 break;
2654 case Type::TYPE_FUNCTION:
2655 case Type::TYPE_POINTER:
2656 case Type::TYPE_MAP:
2657 case Type::TYPE_CHANNEL:
2658 // These types are all a single pointer.
2659 go_assert((offset % ptrsize) == 0);
2660 this->set(offset / ptrsize);
2661 break;
2663 case Type::TYPE_STRING:
2664 // A string starts with a single pointer.
2665 go_assert((offset % ptrsize) == 0);
2666 this->set(offset / ptrsize);
2667 break;
2669 case Type::TYPE_INTERFACE:
2670 // An interface is two pointers.
2671 go_assert((offset % ptrsize) == 0);
2672 this->set(offset / ptrsize);
2673 this->set((offset / ptrsize) + 1);
2674 break;
2676 case Type::TYPE_STRUCT:
2678 if (!type->has_pointer())
2679 return;
2681 const Struct_field_list* fields = type->struct_type()->fields();
2682 int64_t soffset = 0;
2683 for (Struct_field_list::const_iterator pf = fields->begin();
2684 pf != fields->end();
2685 ++pf)
2687 int64_t field_align;
2688 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2690 go_assert(saw_errors());
2691 return;
2693 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2695 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2697 int64_t field_size;
2698 if (!pf->type()->backend_type_size(gogo, &field_size))
2700 go_assert(saw_errors());
2701 return;
2703 soffset += field_size;
2706 break;
2708 case Type::TYPE_ARRAY:
2709 if (type->is_slice_type())
2711 // A slice starts with a single pointer.
2712 go_assert((offset % ptrsize) == 0);
2713 this->set(offset / ptrsize);
2714 break;
2716 else
2718 if (!type->has_pointer())
2719 return;
2721 int64_t len;
2722 if (!type->array_type()->int_length(&len))
2724 go_assert(saw_errors());
2725 return;
2728 Type* element_type = type->array_type()->element_type();
2729 int64_t ele_size;
2730 if (!element_type->backend_type_size(gogo, &ele_size))
2732 go_assert(saw_errors());
2733 return;
2736 int64_t eoffset = 0;
2737 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2738 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2739 break;
2744 // Return a symbol name for this ptrmask. This is used to coalesce
2745 // identical ptrmasks, which are common. The symbol name must use
2746 // only characters that are valid in symbols. It's nice if it's
2747 // short. We convert it to a base64 string.
2749 std::string
2750 Ptrmask::symname() const
2752 const char chars[65] =
2753 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
2754 go_assert(chars[64] == '\0');
2755 std::string ret;
2756 unsigned int b = 0;
2757 int remaining = 0;
2758 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2759 p != this->bits_.end();
2760 ++p)
2762 b |= *p << remaining;
2763 remaining += 8;
2764 while (remaining >= 6)
2766 ret += chars[b & 0x3f];
2767 b >>= 6;
2768 remaining -= 6;
2771 while (remaining > 0)
2773 ret += chars[b & 0x3f];
2774 b >>= 6;
2775 remaining -= 6;
2777 return ret;
2780 // Return a constructor for this ptrmask. This will be used to
2781 // initialize the runtime ptrmask value.
2783 Expression*
2784 Ptrmask::constructor(Gogo* gogo) const
2786 Location bloc = Linemap::predeclared_location();
2787 Type* byte_type = gogo->lookup_global("byte")->type_value();
2788 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2789 bloc);
2790 Array_type* at = Type::make_array_type(byte_type, len);
2791 Expression_list* vals = new Expression_list();
2792 vals->reserve(this->bits_.size());
2793 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2794 p != this->bits_.end();
2795 ++p)
2796 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2797 return Expression::make_array_composite_literal(at, vals, bloc);
2800 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2801 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2803 // Return a ptrmask variable for a type. For a type descriptor this
2804 // is only used for variables that are small enough to not need a
2805 // gcprog, but for a global variable this is used for a variable of
2806 // any size. PTRDATA is the number of bytes of the type that contain
2807 // pointer data. PTRSIZE is the size of a pointer on the target
2808 // system.
2810 Bvariable*
2811 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2813 Ptrmask ptrmask(ptrdata / ptrsize);
2814 if (ptrdata >= ptrsize)
2815 ptrmask.set_from(gogo, this, ptrsize, 0);
2816 else
2818 // This can happen in error cases. Just build an empty gcbits.
2819 go_assert(saw_errors());
2821 std::string sym_name = "runtime.gcbits." + ptrmask.symname();
2822 Bvariable* bvnull = NULL;
2823 std::pair<GC_gcbits_vars::iterator, bool> ins =
2824 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2825 if (!ins.second)
2827 // We've already built a GC symbol for this set of gcbits.
2828 return ins.first->second;
2831 Expression* val = ptrmask.constructor(gogo);
2832 Translate_context context(gogo, NULL, NULL, NULL);
2833 context.set_is_const();
2834 Bexpression* bval = val->get_backend(&context);
2836 std::string asm_name(go_selectively_encode_id(sym_name));
2837 Btype *btype = val->type()->get_backend(gogo);
2838 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2839 btype, false, true,
2840 true, 0);
2841 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2842 true, true, bval);
2843 ins.first->second = ret;
2844 return ret;
2847 // A GCProg is used to build a program for the garbage collector.
2848 // This is used for types with a lot of pointer data, to reduce the
2849 // size of the data in the compiled program. The program is expanded
2850 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2852 class GCProg
2854 public:
2855 GCProg()
2856 : bytes_(), index_(0), nb_(0)
2859 // The number of bits described so far.
2860 int64_t
2861 bit_index() const
2862 { return this->index_; }
2864 void
2865 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2867 void
2868 end();
2870 Expression*
2871 constructor(Gogo* gogo) const;
2873 private:
2874 void
2875 ptr(int64_t);
2877 bool
2878 should_repeat(int64_t, int64_t);
2880 void
2881 repeat(int64_t, int64_t);
2883 void
2884 zero_until(int64_t);
2886 void
2887 lit(unsigned char);
2889 void
2890 varint(int64_t);
2892 void
2893 flushlit();
2895 // Add a byte to the program.
2896 void
2897 byte(unsigned char x)
2898 { this->bytes_.push_back(x); }
2900 // The maximum number of bytes of literal bits.
2901 static const int max_literal = 127;
2903 // The program.
2904 std::vector<unsigned char> bytes_;
2905 // The index of the last bit described.
2906 int64_t index_;
2907 // The current set of literal bits.
2908 unsigned char b_[max_literal];
2909 // The current number of literal bits.
2910 int nb_;
2913 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2914 // counts in bytes. PTRSIZE is the size of a pointer on the target
2915 // system.
2917 void
2918 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2920 switch (type->base()->classification())
2922 default:
2923 case Type::TYPE_NIL:
2924 case Type::TYPE_CALL_MULTIPLE_RESULT:
2925 case Type::TYPE_NAMED:
2926 case Type::TYPE_FORWARD:
2927 go_unreachable();
2929 case Type::TYPE_ERROR:
2930 case Type::TYPE_VOID:
2931 case Type::TYPE_BOOLEAN:
2932 case Type::TYPE_INTEGER:
2933 case Type::TYPE_FLOAT:
2934 case Type::TYPE_COMPLEX:
2935 case Type::TYPE_SINK:
2936 break;
2938 case Type::TYPE_FUNCTION:
2939 case Type::TYPE_POINTER:
2940 case Type::TYPE_MAP:
2941 case Type::TYPE_CHANNEL:
2942 // These types are all a single pointer.
2943 go_assert((offset % ptrsize) == 0);
2944 this->ptr(offset / ptrsize);
2945 break;
2947 case Type::TYPE_STRING:
2948 // A string starts with a single pointer.
2949 go_assert((offset % ptrsize) == 0);
2950 this->ptr(offset / ptrsize);
2951 break;
2953 case Type::TYPE_INTERFACE:
2954 // An interface is two pointers.
2955 go_assert((offset % ptrsize) == 0);
2956 this->ptr(offset / ptrsize);
2957 this->ptr((offset / ptrsize) + 1);
2958 break;
2960 case Type::TYPE_STRUCT:
2962 if (!type->has_pointer())
2963 return;
2965 const Struct_field_list* fields = type->struct_type()->fields();
2966 int64_t soffset = 0;
2967 for (Struct_field_list::const_iterator pf = fields->begin();
2968 pf != fields->end();
2969 ++pf)
2971 int64_t field_align;
2972 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2974 go_assert(saw_errors());
2975 return;
2977 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2979 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2981 int64_t field_size;
2982 if (!pf->type()->backend_type_size(gogo, &field_size))
2984 go_assert(saw_errors());
2985 return;
2987 soffset += field_size;
2990 break;
2992 case Type::TYPE_ARRAY:
2993 if (type->is_slice_type())
2995 // A slice starts with a single pointer.
2996 go_assert((offset % ptrsize) == 0);
2997 this->ptr(offset / ptrsize);
2998 break;
3000 else
3002 if (!type->has_pointer())
3003 return;
3005 int64_t len;
3006 if (!type->array_type()->int_length(&len))
3008 go_assert(saw_errors());
3009 return;
3012 Type* element_type = type->array_type()->element_type();
3014 // Flatten array of array to a big array by multiplying counts.
3015 while (element_type->array_type() != NULL
3016 && !element_type->is_slice_type())
3018 int64_t ele_len;
3019 if (!element_type->array_type()->int_length(&ele_len))
3021 go_assert(saw_errors());
3022 return;
3025 len *= ele_len;
3026 element_type = element_type->array_type()->element_type();
3029 int64_t ele_size;
3030 if (!element_type->backend_type_size(gogo, &ele_size))
3032 go_assert(saw_errors());
3033 return;
3036 go_assert(len > 0 && ele_size > 0);
3038 if (!this->should_repeat(ele_size / ptrsize, len))
3040 // Cheaper to just emit the bits.
3041 int64_t eoffset = 0;
3042 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3043 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3045 else
3047 go_assert((offset % ptrsize) == 0);
3048 go_assert((ele_size % ptrsize) == 0);
3049 this->set_from(gogo, element_type, ptrsize, offset);
3050 this->zero_until((offset + ele_size) / ptrsize);
3051 this->repeat(ele_size / ptrsize, len - 1);
3054 break;
3059 // Emit a 1 into the bit stream of a GC program at the given bit index.
3061 void
3062 GCProg::ptr(int64_t index)
3064 go_assert(index >= this->index_);
3065 this->zero_until(index);
3066 this->lit(1);
3069 // Return whether it is worthwhile to use a repeat to describe c
3070 // elements of n bits each, compared to just emitting c copies of the
3071 // n-bit description.
3073 bool
3074 GCProg::should_repeat(int64_t n, int64_t c)
3076 // Repeat if there is more than 1 item and if the total data doesn't
3077 // fit into four bytes.
3078 return c > 1 && c * n > 4 * 8;
3081 // Emit an instruction to repeat the description of the last n words c
3082 // times (including the initial description, so c + 1 times in total).
3084 void
3085 GCProg::repeat(int64_t n, int64_t c)
3087 if (n == 0 || c == 0)
3088 return;
3089 this->flushlit();
3090 if (n < 128)
3091 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3092 else
3094 this->byte(0x80);
3095 this->varint(n);
3097 this->varint(c);
3098 this->index_ += n * c;
3101 // Add zeros to the bit stream up to the given index.
3103 void
3104 GCProg::zero_until(int64_t index)
3106 go_assert(index >= this->index_);
3107 int64_t skip = index - this->index_;
3108 if (skip == 0)
3109 return;
3110 if (skip < 4 * 8)
3112 for (int64_t i = 0; i < skip; ++i)
3113 this->lit(0);
3114 return;
3116 this->lit(0);
3117 this->flushlit();
3118 this->repeat(1, skip - 1);
3121 // Add a single literal bit to the program.
3123 void
3124 GCProg::lit(unsigned char x)
3126 if (this->nb_ == GCProg::max_literal)
3127 this->flushlit();
3128 this->b_[this->nb_] = x;
3129 ++this->nb_;
3130 ++this->index_;
3133 // Emit the varint encoding of x.
3135 void
3136 GCProg::varint(int64_t x)
3138 go_assert(x >= 0);
3139 while (x >= 0x80)
3141 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3142 x >>= 7;
3144 this->byte(static_cast<unsigned char>(x & 0x7f));
3147 // Flush any pending literal bits.
3149 void
3150 GCProg::flushlit()
3152 if (this->nb_ == 0)
3153 return;
3154 this->byte(static_cast<unsigned char>(this->nb_));
3155 unsigned char bits = 0;
3156 for (int i = 0; i < this->nb_; ++i)
3158 bits |= this->b_[i] << (i % 8);
3159 if ((i + 1) % 8 == 0)
3161 this->byte(bits);
3162 bits = 0;
3165 if (this->nb_ % 8 != 0)
3166 this->byte(bits);
3167 this->nb_ = 0;
3170 // Mark the end of a GC program.
3172 void
3173 GCProg::end()
3175 this->flushlit();
3176 this->byte(0);
3179 // Return an Expression for the bytes in a GC program.
3181 Expression*
3182 GCProg::constructor(Gogo* gogo) const
3184 Location bloc = Linemap::predeclared_location();
3186 // The first four bytes are the length of the program in target byte
3187 // order. Build a struct whose first type is uint32 to make this
3188 // work.
3190 Type* uint32_type = Type::lookup_integer_type("uint32");
3192 Type* byte_type = gogo->lookup_global("byte")->type_value();
3193 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3194 bloc);
3195 Array_type* at = Type::make_array_type(byte_type, len);
3197 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3198 "bytes", at);
3200 Expression_list* vals = new Expression_list();
3201 vals->reserve(this->bytes_.size());
3202 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3203 p != this->bytes_.end();
3204 ++p)
3205 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3206 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3208 vals = new Expression_list();
3209 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3210 bloc));
3211 vals->push_back(bytes);
3213 return Expression::make_struct_composite_literal(st, vals, bloc);
3216 // Return a composite literal for the garbage collection program for
3217 // this type. This is only used for types that are too large to use a
3218 // ptrmask.
3220 Expression*
3221 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3223 Location bloc = Linemap::predeclared_location();
3225 GCProg prog;
3226 prog.set_from(gogo, this, ptrsize, 0);
3227 int64_t offset = prog.bit_index() * ptrsize;
3228 prog.end();
3230 int64_t type_size;
3231 if (!this->backend_type_size(gogo, &type_size))
3233 go_assert(saw_errors());
3234 return Expression::make_error(bloc);
3237 go_assert(offset >= ptrdata && offset <= type_size);
3239 return prog.constructor(gogo);
3242 // Return a composite literal for the uncommon type information for
3243 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3244 // struct. If name is not NULL, it is the name of the type. If
3245 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3246 // is true if only value methods should be included. At least one of
3247 // NAME and METHODS must not be NULL.
3249 Expression*
3250 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3251 Named_type* name, const Methods* methods,
3252 bool only_value_methods) const
3254 Location bloc = Linemap::predeclared_location();
3256 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3258 Expression_list* vals = new Expression_list();
3259 vals->reserve(3);
3261 Struct_field_list::const_iterator p = fields->begin();
3262 go_assert(p->is_field_name("name"));
3264 ++p;
3265 go_assert(p->is_field_name("pkgPath"));
3267 if (name == NULL)
3269 vals->push_back(Expression::make_nil(bloc));
3270 vals->push_back(Expression::make_nil(bloc));
3272 else
3274 Named_object* no = name->named_object();
3275 std::string n = Gogo::unpack_hidden_name(no->name());
3276 Expression* s = Expression::make_string(n, bloc);
3277 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3279 if (name->is_builtin())
3280 vals->push_back(Expression::make_nil(bloc));
3281 else
3283 const Package* package = no->package();
3284 const std::string& pkgpath(package == NULL
3285 ? gogo->pkgpath()
3286 : package->pkgpath());
3287 s = Expression::make_string(pkgpath, bloc);
3288 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3292 ++p;
3293 go_assert(p->is_field_name("methods"));
3294 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3295 only_value_methods));
3297 ++p;
3298 go_assert(p == fields->end());
3300 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3301 vals, bloc);
3302 return Expression::make_unary(OPERATOR_AND, r, bloc);
3305 // Sort methods by name.
3307 class Sort_methods
3309 public:
3310 bool
3311 operator()(const std::pair<std::string, const Method*>& m1,
3312 const std::pair<std::string, const Method*>& m2) const
3314 return (Gogo::unpack_hidden_name(m1.first)
3315 < Gogo::unpack_hidden_name(m2.first));
3319 // Return a composite literal for the type method table for this type.
3320 // METHODS_TYPE is the type of the table, and is a slice type.
3321 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3322 // then only value methods are used.
3324 Expression*
3325 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3326 const Methods* methods,
3327 bool only_value_methods) const
3329 Location bloc = Linemap::predeclared_location();
3331 std::vector<std::pair<std::string, const Method*> > smethods;
3332 if (methods != NULL)
3334 smethods.reserve(methods->count());
3335 for (Methods::const_iterator p = methods->begin();
3336 p != methods->end();
3337 ++p)
3339 if (p->second->is_ambiguous())
3340 continue;
3341 if (only_value_methods && !p->second->is_value_method())
3342 continue;
3344 // This is where we implement the magic //go:nointerface
3345 // comment. If we saw that comment, we don't add this
3346 // method to the type descriptor.
3347 if (p->second->nointerface())
3348 continue;
3350 smethods.push_back(std::make_pair(p->first, p->second));
3354 if (smethods.empty())
3355 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3357 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3359 Type* method_type = methods_type->array_type()->element_type();
3361 Expression_list* vals = new Expression_list();
3362 vals->reserve(smethods.size());
3363 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3364 = smethods.begin();
3365 p != smethods.end();
3366 ++p)
3367 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3368 p->second, only_value_methods));
3370 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3373 // Return a composite literal for a single method. METHOD_TYPE is the
3374 // type of the entry. METHOD_NAME is the name of the method and M is
3375 // the method information.
3377 Expression*
3378 Type::method_constructor(Gogo*, Type* method_type,
3379 const std::string& method_name,
3380 const Method* m,
3381 bool only_value_methods) const
3383 Location bloc = Linemap::predeclared_location();
3385 const Struct_field_list* fields = method_type->struct_type()->fields();
3387 Expression_list* vals = new Expression_list();
3388 vals->reserve(5);
3390 Struct_field_list::const_iterator p = fields->begin();
3391 go_assert(p->is_field_name("name"));
3392 const std::string n = Gogo::unpack_hidden_name(method_name);
3393 Expression* s = Expression::make_string(n, bloc);
3394 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3396 ++p;
3397 go_assert(p->is_field_name("pkgPath"));
3398 if (!Gogo::is_hidden_name(method_name))
3399 vals->push_back(Expression::make_nil(bloc));
3400 else
3402 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3403 bloc);
3404 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3407 Named_object* no = (m->needs_stub_method()
3408 ? m->stub_object()
3409 : m->named_object());
3411 Function_type* mtype;
3412 if (no->is_function())
3413 mtype = no->func_value()->type();
3414 else
3415 mtype = no->func_declaration_value()->type();
3416 go_assert(mtype->is_method());
3417 Type* nonmethod_type = mtype->copy_without_receiver();
3419 ++p;
3420 go_assert(p->is_field_name("mtyp"));
3421 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3423 ++p;
3424 go_assert(p->is_field_name("typ"));
3425 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3426 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3427 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3429 ++p;
3430 go_assert(p->is_field_name("tfn"));
3431 vals->push_back(Expression::make_func_code_reference(no, bloc));
3433 ++p;
3434 go_assert(p == fields->end());
3436 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3439 // Return a composite literal for the type descriptor of a plain type.
3440 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3441 // NULL, it is the name to use as well as the list of methods.
3443 Expression*
3444 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3445 Named_type* name)
3447 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3448 name, NULL, true);
3451 // Return the type reflection string for this type.
3453 std::string
3454 Type::reflection(Gogo* gogo) const
3456 std::string ret;
3458 // The do_reflection virtual function should set RET to the
3459 // reflection string.
3460 this->do_reflection(gogo, &ret);
3462 return ret;
3465 // Return a mangled name for the type.
3467 std::string
3468 Type::mangled_name(Gogo* gogo) const
3470 std::string ret;
3472 // The do_mangled_name virtual function should set RET to the
3473 // mangled name. For a composite type it should append a code for
3474 // the composition and then call do_mangled_name on the components.
3475 this->do_mangled_name(gogo, &ret);
3477 return ret;
3480 // Return whether the backend size of the type is known.
3482 bool
3483 Type::is_backend_type_size_known(Gogo* gogo)
3485 switch (this->classification_)
3487 case TYPE_ERROR:
3488 case TYPE_VOID:
3489 case TYPE_BOOLEAN:
3490 case TYPE_INTEGER:
3491 case TYPE_FLOAT:
3492 case TYPE_COMPLEX:
3493 case TYPE_STRING:
3494 case TYPE_FUNCTION:
3495 case TYPE_POINTER:
3496 case TYPE_NIL:
3497 case TYPE_MAP:
3498 case TYPE_CHANNEL:
3499 case TYPE_INTERFACE:
3500 return true;
3502 case TYPE_STRUCT:
3504 const Struct_field_list* fields = this->struct_type()->fields();
3505 for (Struct_field_list::const_iterator pf = fields->begin();
3506 pf != fields->end();
3507 ++pf)
3508 if (!pf->type()->is_backend_type_size_known(gogo))
3509 return false;
3510 return true;
3513 case TYPE_ARRAY:
3515 const Array_type* at = this->array_type();
3516 if (at->length() == NULL)
3517 return true;
3518 else
3520 Numeric_constant nc;
3521 if (!at->length()->numeric_constant_value(&nc))
3522 return false;
3523 mpz_t ival;
3524 if (!nc.to_int(&ival))
3525 return false;
3526 mpz_clear(ival);
3527 return at->element_type()->is_backend_type_size_known(gogo);
3531 case TYPE_NAMED:
3532 this->named_type()->convert(gogo);
3533 return this->named_type()->is_named_backend_type_size_known();
3535 case TYPE_FORWARD:
3537 Forward_declaration_type* fdt = this->forward_declaration_type();
3538 return fdt->real_type()->is_backend_type_size_known(gogo);
3541 case TYPE_SINK:
3542 case TYPE_CALL_MULTIPLE_RESULT:
3543 go_unreachable();
3545 default:
3546 go_unreachable();
3550 // If the size of the type can be determined, set *PSIZE to the size
3551 // in bytes and return true. Otherwise, return false. This queries
3552 // the backend.
3554 bool
3555 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3557 if (!this->is_backend_type_size_known(gogo))
3558 return false;
3559 if (this->is_error_type())
3560 return false;
3561 Btype* bt = this->get_backend_placeholder(gogo);
3562 *psize = gogo->backend()->type_size(bt);
3563 if (*psize == -1)
3565 if (this->named_type() != NULL)
3566 go_error_at(this->named_type()->location(),
3567 "type %s larger than address space",
3568 Gogo::message_name(this->named_type()->name()).c_str());
3569 else
3570 go_error_at(Linemap::unknown_location(),
3571 "type %s larger than address space",
3572 this->reflection(gogo).c_str());
3574 // Make this an error type to avoid knock-on errors.
3575 this->classification_ = TYPE_ERROR;
3576 return false;
3578 return true;
3581 // If the alignment of the type can be determined, set *PALIGN to
3582 // the alignment in bytes and return true. Otherwise, return false.
3584 bool
3585 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3587 if (!this->is_backend_type_size_known(gogo))
3588 return false;
3589 Btype* bt = this->get_backend_placeholder(gogo);
3590 *palign = gogo->backend()->type_alignment(bt);
3591 return true;
3594 // Like backend_type_align, but return the alignment when used as a
3595 // field.
3597 bool
3598 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3600 if (!this->is_backend_type_size_known(gogo))
3601 return false;
3602 Btype* bt = this->get_backend_placeholder(gogo);
3603 *palign = gogo->backend()->type_field_alignment(bt);
3604 return true;
3607 // Get the ptrdata value for a type. This is the size of the prefix
3608 // of the type that contains all pointers. Store the ptrdata in
3609 // *PPTRDATA and return whether we found it.
3611 bool
3612 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3614 *pptrdata = 0;
3616 if (!this->has_pointer())
3617 return true;
3619 if (!this->is_backend_type_size_known(gogo))
3620 return false;
3622 switch (this->classification_)
3624 case TYPE_ERROR:
3625 return true;
3627 case TYPE_FUNCTION:
3628 case TYPE_POINTER:
3629 case TYPE_MAP:
3630 case TYPE_CHANNEL:
3631 // These types are nothing but a pointer.
3632 return this->backend_type_size(gogo, pptrdata);
3634 case TYPE_INTERFACE:
3635 // An interface is a struct of two pointers.
3636 return this->backend_type_size(gogo, pptrdata);
3638 case TYPE_STRING:
3640 // A string is a struct whose first field is a pointer, and
3641 // whose second field is not.
3642 Type* uint8_type = Type::lookup_integer_type("uint8");
3643 Type* ptr = Type::make_pointer_type(uint8_type);
3644 return ptr->backend_type_size(gogo, pptrdata);
3647 case TYPE_NAMED:
3648 case TYPE_FORWARD:
3649 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3651 case TYPE_STRUCT:
3653 const Struct_field_list* fields = this->struct_type()->fields();
3654 int64_t offset = 0;
3655 const Struct_field *ptr = NULL;
3656 int64_t ptr_offset = 0;
3657 for (Struct_field_list::const_iterator pf = fields->begin();
3658 pf != fields->end();
3659 ++pf)
3661 int64_t field_align;
3662 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3663 return false;
3664 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3666 if (pf->type()->has_pointer())
3668 ptr = &*pf;
3669 ptr_offset = offset;
3672 int64_t field_size;
3673 if (!pf->type()->backend_type_size(gogo, &field_size))
3674 return false;
3675 offset += field_size;
3678 if (ptr != NULL)
3680 int64_t ptr_ptrdata;
3681 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3682 return false;
3683 *pptrdata = ptr_offset + ptr_ptrdata;
3685 return true;
3688 case TYPE_ARRAY:
3689 if (this->is_slice_type())
3691 // A slice is a struct whose first field is a pointer, and
3692 // whose remaining fields are not.
3693 Type* element_type = this->array_type()->element_type();
3694 Type* ptr = Type::make_pointer_type(element_type);
3695 return ptr->backend_type_size(gogo, pptrdata);
3697 else
3699 Numeric_constant nc;
3700 if (!this->array_type()->length()->numeric_constant_value(&nc))
3701 return false;
3702 int64_t len;
3703 if (!nc.to_memory_size(&len))
3704 return false;
3706 Type* element_type = this->array_type()->element_type();
3707 int64_t ele_size;
3708 int64_t ele_ptrdata;
3709 if (!element_type->backend_type_size(gogo, &ele_size)
3710 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3711 return false;
3712 go_assert(ele_size > 0 && ele_ptrdata > 0);
3714 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3715 return true;
3718 default:
3719 case TYPE_VOID:
3720 case TYPE_BOOLEAN:
3721 case TYPE_INTEGER:
3722 case TYPE_FLOAT:
3723 case TYPE_COMPLEX:
3724 case TYPE_SINK:
3725 case TYPE_NIL:
3726 case TYPE_CALL_MULTIPLE_RESULT:
3727 go_unreachable();
3731 // Get the ptrdata value to store in a type descriptor. This is
3732 // normally the same as backend_type_ptrdata, but for a type that is
3733 // large enough to use a gcprog we may need to store a different value
3734 // if it ends with an array. If the gcprog uses a repeat descriptor
3735 // for the array, and if the array element ends with non-pointer data,
3736 // then the gcprog will produce a value that describes the complete
3737 // array where the backend ptrdata will omit the non-pointer elements
3738 // of the final array element. This is a subtle difference but the
3739 // run time code checks it to verify that it has expanded a gcprog as
3740 // expected.
3742 bool
3743 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3745 int64_t backend_ptrdata;
3746 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3747 return false;
3749 int64_t ptrsize;
3750 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3752 *pptrdata = backend_ptrdata;
3753 return true;
3756 GCProg prog;
3757 prog.set_from(gogo, this, ptrsize, 0);
3758 int64_t offset = prog.bit_index() * ptrsize;
3760 go_assert(offset >= backend_ptrdata);
3761 *pptrdata = offset;
3762 return true;
3765 // Default function to export a type.
3767 void
3768 Type::do_export(Export*) const
3770 go_unreachable();
3773 // Import a type.
3775 Type*
3776 Type::import_type(Import* imp)
3778 if (imp->match_c_string("("))
3779 return Function_type::do_import(imp);
3780 else if (imp->match_c_string("*"))
3781 return Pointer_type::do_import(imp);
3782 else if (imp->match_c_string("struct "))
3783 return Struct_type::do_import(imp);
3784 else if (imp->match_c_string("["))
3785 return Array_type::do_import(imp);
3786 else if (imp->match_c_string("map "))
3787 return Map_type::do_import(imp);
3788 else if (imp->match_c_string("chan "))
3789 return Channel_type::do_import(imp);
3790 else if (imp->match_c_string("interface"))
3791 return Interface_type::do_import(imp);
3792 else
3794 go_error_at(imp->location(), "import error: expected type");
3795 return Type::make_error_type();
3799 // A type used to indicate a parsing error. This exists to simplify
3800 // later error detection.
3802 class Error_type : public Type
3804 public:
3805 Error_type()
3806 : Type(TYPE_ERROR)
3809 protected:
3810 bool
3811 do_compare_is_identity(Gogo*)
3812 { return false; }
3814 Btype*
3815 do_get_backend(Gogo* gogo)
3816 { return gogo->backend()->error_type(); }
3818 Expression*
3819 do_type_descriptor(Gogo*, Named_type*)
3820 { return Expression::make_error(Linemap::predeclared_location()); }
3822 void
3823 do_reflection(Gogo*, std::string*) const
3824 { go_assert(saw_errors()); }
3826 void
3827 do_mangled_name(Gogo*, std::string* ret) const
3828 { ret->push_back('E'); }
3831 Type*
3832 Type::make_error_type()
3834 static Error_type singleton_error_type;
3835 return &singleton_error_type;
3838 // The void type.
3840 class Void_type : public Type
3842 public:
3843 Void_type()
3844 : Type(TYPE_VOID)
3847 protected:
3848 bool
3849 do_compare_is_identity(Gogo*)
3850 { return false; }
3852 Btype*
3853 do_get_backend(Gogo* gogo)
3854 { return gogo->backend()->void_type(); }
3856 Expression*
3857 do_type_descriptor(Gogo*, Named_type*)
3858 { go_unreachable(); }
3860 void
3861 do_reflection(Gogo*, std::string*) const
3864 void
3865 do_mangled_name(Gogo*, std::string* ret) const
3866 { ret->push_back('v'); }
3869 Type*
3870 Type::make_void_type()
3872 static Void_type singleton_void_type;
3873 return &singleton_void_type;
3876 // The boolean type.
3878 class Boolean_type : public Type
3880 public:
3881 Boolean_type()
3882 : Type(TYPE_BOOLEAN)
3885 protected:
3886 bool
3887 do_compare_is_identity(Gogo*)
3888 { return true; }
3890 Btype*
3891 do_get_backend(Gogo* gogo)
3892 { return gogo->backend()->bool_type(); }
3894 Expression*
3895 do_type_descriptor(Gogo*, Named_type* name);
3897 // We should not be asked for the reflection string of a basic type.
3898 void
3899 do_reflection(Gogo*, std::string* ret) const
3900 { ret->append("bool"); }
3902 void
3903 do_mangled_name(Gogo*, std::string* ret) const
3904 { ret->push_back('b'); }
3907 // Make the type descriptor.
3909 Expression*
3910 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3912 if (name != NULL)
3913 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3914 else
3916 Named_object* no = gogo->lookup_global("bool");
3917 go_assert(no != NULL);
3918 return Type::type_descriptor(gogo, no->type_value());
3922 Type*
3923 Type::make_boolean_type()
3925 static Boolean_type boolean_type;
3926 return &boolean_type;
3929 // The named type "bool".
3931 static Named_type* named_bool_type;
3933 // Get the named type "bool".
3935 Named_type*
3936 Type::lookup_bool_type()
3938 return named_bool_type;
3941 // Make the named type "bool".
3943 Named_type*
3944 Type::make_named_bool_type()
3946 Type* bool_type = Type::make_boolean_type();
3947 Named_object* named_object =
3948 Named_object::make_type("bool", NULL, bool_type,
3949 Linemap::predeclared_location());
3950 Named_type* named_type = named_object->type_value();
3951 named_bool_type = named_type;
3952 return named_type;
3955 // Class Integer_type.
3957 Integer_type::Named_integer_types Integer_type::named_integer_types;
3959 // Create a new integer type. Non-abstract integer types always have
3960 // names.
3962 Named_type*
3963 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3964 int bits, int runtime_type_kind)
3966 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3967 runtime_type_kind);
3968 std::string sname(name);
3969 Named_object* named_object =
3970 Named_object::make_type(sname, NULL, integer_type,
3971 Linemap::predeclared_location());
3972 Named_type* named_type = named_object->type_value();
3973 std::pair<Named_integer_types::iterator, bool> ins =
3974 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3975 go_assert(ins.second);
3976 return named_type;
3979 // Look up an existing integer type.
3981 Named_type*
3982 Integer_type::lookup_integer_type(const char* name)
3984 Named_integer_types::const_iterator p =
3985 Integer_type::named_integer_types.find(name);
3986 go_assert(p != Integer_type::named_integer_types.end());
3987 return p->second;
3990 // Create a new abstract integer type.
3992 Integer_type*
3993 Integer_type::create_abstract_integer_type()
3995 static Integer_type* abstract_type;
3996 if (abstract_type == NULL)
3998 Type* int_type = Type::lookup_integer_type("int");
3999 abstract_type = new Integer_type(true, false,
4000 int_type->integer_type()->bits(),
4001 RUNTIME_TYPE_KIND_INT);
4003 return abstract_type;
4006 // Create a new abstract character type.
4008 Integer_type*
4009 Integer_type::create_abstract_character_type()
4011 static Integer_type* abstract_type;
4012 if (abstract_type == NULL)
4014 abstract_type = new Integer_type(true, false, 32,
4015 RUNTIME_TYPE_KIND_INT32);
4016 abstract_type->set_is_rune();
4018 return abstract_type;
4021 // Integer type compatibility.
4023 bool
4024 Integer_type::is_identical(const Integer_type* t) const
4026 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
4027 return false;
4028 return this->is_abstract_ == t->is_abstract_;
4031 // Hash code.
4033 unsigned int
4034 Integer_type::do_hash_for_method(Gogo*) const
4036 return ((this->bits_ << 4)
4037 + ((this->is_unsigned_ ? 1 : 0) << 8)
4038 + ((this->is_abstract_ ? 1 : 0) << 9));
4041 // Convert an Integer_type to the backend representation.
4043 Btype*
4044 Integer_type::do_get_backend(Gogo* gogo)
4046 if (this->is_abstract_)
4048 go_assert(saw_errors());
4049 return gogo->backend()->error_type();
4051 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4054 // The type descriptor for an integer type. Integer types are always
4055 // named.
4057 Expression*
4058 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4060 go_assert(name != NULL || saw_errors());
4061 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4064 // We should not be asked for the reflection string of a basic type.
4066 void
4067 Integer_type::do_reflection(Gogo*, std::string*) const
4069 go_assert(saw_errors());
4072 // Mangled name.
4074 void
4075 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
4077 char buf[100];
4078 snprintf(buf, sizeof buf, "i%s%s%de",
4079 this->is_abstract_ ? "a" : "",
4080 this->is_unsigned_ ? "u" : "",
4081 this->bits_);
4082 ret->append(buf);
4085 // Make an integer type.
4087 Named_type*
4088 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4089 int runtime_type_kind)
4091 return Integer_type::create_integer_type(name, is_unsigned, bits,
4092 runtime_type_kind);
4095 // Make an abstract integer type.
4097 Integer_type*
4098 Type::make_abstract_integer_type()
4100 return Integer_type::create_abstract_integer_type();
4103 // Make an abstract character type.
4105 Integer_type*
4106 Type::make_abstract_character_type()
4108 return Integer_type::create_abstract_character_type();
4111 // Look up an integer type.
4113 Named_type*
4114 Type::lookup_integer_type(const char* name)
4116 return Integer_type::lookup_integer_type(name);
4119 // Class Float_type.
4121 Float_type::Named_float_types Float_type::named_float_types;
4123 // Create a new float type. Non-abstract float types always have
4124 // names.
4126 Named_type*
4127 Float_type::create_float_type(const char* name, int bits,
4128 int runtime_type_kind)
4130 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4131 std::string sname(name);
4132 Named_object* named_object =
4133 Named_object::make_type(sname, NULL, float_type,
4134 Linemap::predeclared_location());
4135 Named_type* named_type = named_object->type_value();
4136 std::pair<Named_float_types::iterator, bool> ins =
4137 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4138 go_assert(ins.second);
4139 return named_type;
4142 // Look up an existing float type.
4144 Named_type*
4145 Float_type::lookup_float_type(const char* name)
4147 Named_float_types::const_iterator p =
4148 Float_type::named_float_types.find(name);
4149 go_assert(p != Float_type::named_float_types.end());
4150 return p->second;
4153 // Create a new abstract float type.
4155 Float_type*
4156 Float_type::create_abstract_float_type()
4158 static Float_type* abstract_type;
4159 if (abstract_type == NULL)
4160 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4161 return abstract_type;
4164 // Whether this type is identical with T.
4166 bool
4167 Float_type::is_identical(const Float_type* t) const
4169 if (this->bits_ != t->bits_)
4170 return false;
4171 return this->is_abstract_ == t->is_abstract_;
4174 // Hash code.
4176 unsigned int
4177 Float_type::do_hash_for_method(Gogo*) const
4179 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4182 // Convert to the backend representation.
4184 Btype*
4185 Float_type::do_get_backend(Gogo* gogo)
4187 return gogo->backend()->float_type(this->bits_);
4190 // The type descriptor for a float type. Float types are always named.
4192 Expression*
4193 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4195 go_assert(name != NULL || saw_errors());
4196 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4199 // We should not be asked for the reflection string of a basic type.
4201 void
4202 Float_type::do_reflection(Gogo*, std::string*) const
4204 go_assert(saw_errors());
4207 // Mangled name.
4209 void
4210 Float_type::do_mangled_name(Gogo*, std::string* ret) const
4212 char buf[100];
4213 snprintf(buf, sizeof buf, "f%s%de",
4214 this->is_abstract_ ? "a" : "",
4215 this->bits_);
4216 ret->append(buf);
4219 // Make a floating point type.
4221 Named_type*
4222 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4224 return Float_type::create_float_type(name, bits, runtime_type_kind);
4227 // Make an abstract float type.
4229 Float_type*
4230 Type::make_abstract_float_type()
4232 return Float_type::create_abstract_float_type();
4235 // Look up a float type.
4237 Named_type*
4238 Type::lookup_float_type(const char* name)
4240 return Float_type::lookup_float_type(name);
4243 // Class Complex_type.
4245 Complex_type::Named_complex_types Complex_type::named_complex_types;
4247 // Create a new complex type. Non-abstract complex types always have
4248 // names.
4250 Named_type*
4251 Complex_type::create_complex_type(const char* name, int bits,
4252 int runtime_type_kind)
4254 Complex_type* complex_type = new Complex_type(false, bits,
4255 runtime_type_kind);
4256 std::string sname(name);
4257 Named_object* named_object =
4258 Named_object::make_type(sname, NULL, complex_type,
4259 Linemap::predeclared_location());
4260 Named_type* named_type = named_object->type_value();
4261 std::pair<Named_complex_types::iterator, bool> ins =
4262 Complex_type::named_complex_types.insert(std::make_pair(sname,
4263 named_type));
4264 go_assert(ins.second);
4265 return named_type;
4268 // Look up an existing complex type.
4270 Named_type*
4271 Complex_type::lookup_complex_type(const char* name)
4273 Named_complex_types::const_iterator p =
4274 Complex_type::named_complex_types.find(name);
4275 go_assert(p != Complex_type::named_complex_types.end());
4276 return p->second;
4279 // Create a new abstract complex type.
4281 Complex_type*
4282 Complex_type::create_abstract_complex_type()
4284 static Complex_type* abstract_type;
4285 if (abstract_type == NULL)
4286 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4287 return abstract_type;
4290 // Whether this type is identical with T.
4292 bool
4293 Complex_type::is_identical(const Complex_type *t) const
4295 if (this->bits_ != t->bits_)
4296 return false;
4297 return this->is_abstract_ == t->is_abstract_;
4300 // Hash code.
4302 unsigned int
4303 Complex_type::do_hash_for_method(Gogo*) const
4305 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4308 // Convert to the backend representation.
4310 Btype*
4311 Complex_type::do_get_backend(Gogo* gogo)
4313 return gogo->backend()->complex_type(this->bits_);
4316 // The type descriptor for a complex type. Complex types are always
4317 // named.
4319 Expression*
4320 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4322 go_assert(name != NULL || saw_errors());
4323 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4326 // We should not be asked for the reflection string of a basic type.
4328 void
4329 Complex_type::do_reflection(Gogo*, std::string*) const
4331 go_assert(saw_errors());
4334 // Mangled name.
4336 void
4337 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
4339 char buf[100];
4340 snprintf(buf, sizeof buf, "c%s%de",
4341 this->is_abstract_ ? "a" : "",
4342 this->bits_);
4343 ret->append(buf);
4346 // Make a complex type.
4348 Named_type*
4349 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4351 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4354 // Make an abstract complex type.
4356 Complex_type*
4357 Type::make_abstract_complex_type()
4359 return Complex_type::create_abstract_complex_type();
4362 // Look up a complex type.
4364 Named_type*
4365 Type::lookup_complex_type(const char* name)
4367 return Complex_type::lookup_complex_type(name);
4370 // Class String_type.
4372 // Convert String_type to the backend representation. A string is a
4373 // struct with two fields: a pointer to the characters and a length.
4375 Btype*
4376 String_type::do_get_backend(Gogo* gogo)
4378 static Btype* backend_string_type;
4379 if (backend_string_type == NULL)
4381 std::vector<Backend::Btyped_identifier> fields(2);
4383 Type* b = gogo->lookup_global("byte")->type_value();
4384 Type* pb = Type::make_pointer_type(b);
4386 // We aren't going to get back to this field to finish the
4387 // backend representation, so force it to be finished now.
4388 if (!gogo->named_types_are_converted())
4390 Btype* bt = pb->get_backend_placeholder(gogo);
4391 pb->finish_backend(gogo, bt);
4394 fields[0].name = "__data";
4395 fields[0].btype = pb->get_backend(gogo);
4396 fields[0].location = Linemap::predeclared_location();
4398 Type* int_type = Type::lookup_integer_type("int");
4399 fields[1].name = "__length";
4400 fields[1].btype = int_type->get_backend(gogo);
4401 fields[1].location = fields[0].location;
4403 backend_string_type = gogo->backend()->struct_type(fields);
4405 return backend_string_type;
4408 // The type descriptor for the string type.
4410 Expression*
4411 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4413 if (name != NULL)
4414 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4415 else
4417 Named_object* no = gogo->lookup_global("string");
4418 go_assert(no != NULL);
4419 return Type::type_descriptor(gogo, no->type_value());
4423 // We should not be asked for the reflection string of a basic type.
4425 void
4426 String_type::do_reflection(Gogo*, std::string* ret) const
4428 ret->append("string");
4431 // Mangled name of a string type.
4433 void
4434 String_type::do_mangled_name(Gogo*, std::string* ret) const
4436 ret->push_back('z');
4439 // Make a string type.
4441 Type*
4442 Type::make_string_type()
4444 static String_type string_type;
4445 return &string_type;
4448 // The named type "string".
4450 static Named_type* named_string_type;
4452 // Get the named type "string".
4454 Named_type*
4455 Type::lookup_string_type()
4457 return named_string_type;
4460 // Make the named type string.
4462 Named_type*
4463 Type::make_named_string_type()
4465 Type* string_type = Type::make_string_type();
4466 Named_object* named_object =
4467 Named_object::make_type("string", NULL, string_type,
4468 Linemap::predeclared_location());
4469 Named_type* named_type = named_object->type_value();
4470 named_string_type = named_type;
4471 return named_type;
4474 // The sink type. This is the type of the blank identifier _. Any
4475 // type may be assigned to it.
4477 class Sink_type : public Type
4479 public:
4480 Sink_type()
4481 : Type(TYPE_SINK)
4484 protected:
4485 bool
4486 do_compare_is_identity(Gogo*)
4487 { return false; }
4489 Btype*
4490 do_get_backend(Gogo*)
4491 { go_unreachable(); }
4493 Expression*
4494 do_type_descriptor(Gogo*, Named_type*)
4495 { go_unreachable(); }
4497 void
4498 do_reflection(Gogo*, std::string*) const
4499 { go_unreachable(); }
4501 void
4502 do_mangled_name(Gogo*, std::string*) const
4503 { go_unreachable(); }
4506 // Make the sink type.
4508 Type*
4509 Type::make_sink_type()
4511 static Sink_type sink_type;
4512 return &sink_type;
4515 // Class Function_type.
4517 // Traversal.
4520 Function_type::do_traverse(Traverse* traverse)
4522 if (this->receiver_ != NULL
4523 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4524 return TRAVERSE_EXIT;
4525 if (this->parameters_ != NULL
4526 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4527 return TRAVERSE_EXIT;
4528 if (this->results_ != NULL
4529 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4530 return TRAVERSE_EXIT;
4531 return TRAVERSE_CONTINUE;
4534 // Returns whether T is a valid redeclaration of this type. If this
4535 // returns false, and REASON is not NULL, *REASON may be set to a
4536 // brief explanation of why it returned false.
4538 bool
4539 Function_type::is_valid_redeclaration(const Function_type* t,
4540 std::string* reason) const
4542 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4543 return false;
4545 // A redeclaration of a function is required to use the same names
4546 // for the receiver and parameters.
4547 if (this->receiver() != NULL
4548 && this->receiver()->name() != t->receiver()->name())
4550 if (reason != NULL)
4551 *reason = "receiver name changed";
4552 return false;
4555 const Typed_identifier_list* parms1 = this->parameters();
4556 const Typed_identifier_list* parms2 = t->parameters();
4557 if (parms1 != NULL)
4559 Typed_identifier_list::const_iterator p1 = parms1->begin();
4560 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4561 p2 != parms2->end();
4562 ++p2, ++p1)
4564 if (p1->name() != p2->name())
4566 if (reason != NULL)
4567 *reason = "parameter name changed";
4568 return false;
4571 // This is called at parse time, so we may have unknown
4572 // types.
4573 Type* t1 = p1->type()->forwarded();
4574 Type* t2 = p2->type()->forwarded();
4575 if (t1 != t2
4576 && t1->forward_declaration_type() != NULL
4577 && (t2->forward_declaration_type() == NULL
4578 || (t1->forward_declaration_type()->named_object()
4579 != t2->forward_declaration_type()->named_object())))
4580 return false;
4584 const Typed_identifier_list* results1 = this->results();
4585 const Typed_identifier_list* results2 = t->results();
4586 if (results1 != NULL)
4588 Typed_identifier_list::const_iterator res1 = results1->begin();
4589 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4590 res2 != results2->end();
4591 ++res2, ++res1)
4593 if (res1->name() != res2->name())
4595 if (reason != NULL)
4596 *reason = "result name changed";
4597 return false;
4600 // This is called at parse time, so we may have unknown
4601 // types.
4602 Type* t1 = res1->type()->forwarded();
4603 Type* t2 = res2->type()->forwarded();
4604 if (t1 != t2
4605 && t1->forward_declaration_type() != NULL
4606 && (t2->forward_declaration_type() == NULL
4607 || (t1->forward_declaration_type()->named_object()
4608 != t2->forward_declaration_type()->named_object())))
4609 return false;
4613 return true;
4616 // Check whether T is the same as this type.
4618 bool
4619 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4620 Cmp_tags cmp_tags, bool errors_are_identical,
4621 std::string* reason) const
4623 if (!ignore_receiver)
4625 const Typed_identifier* r1 = this->receiver();
4626 const Typed_identifier* r2 = t->receiver();
4627 if ((r1 != NULL) != (r2 != NULL))
4629 if (reason != NULL)
4630 *reason = _("different receiver types");
4631 return false;
4633 if (r1 != NULL)
4635 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4636 errors_are_identical, reason))
4638 if (reason != NULL && !reason->empty())
4639 *reason = "receiver: " + *reason;
4640 return false;
4645 const Typed_identifier_list* parms1 = this->parameters();
4646 const Typed_identifier_list* parms2 = t->parameters();
4647 if ((parms1 != NULL) != (parms2 != NULL))
4649 if (reason != NULL)
4650 *reason = _("different number of parameters");
4651 return false;
4653 if (parms1 != NULL)
4655 Typed_identifier_list::const_iterator p1 = parms1->begin();
4656 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4657 p2 != parms2->end();
4658 ++p2, ++p1)
4660 if (p1 == parms1->end())
4662 if (reason != NULL)
4663 *reason = _("different number of parameters");
4664 return false;
4667 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4668 errors_are_identical, NULL))
4670 if (reason != NULL)
4671 *reason = _("different parameter types");
4672 return false;
4675 if (p1 != parms1->end())
4677 if (reason != NULL)
4678 *reason = _("different number of parameters");
4679 return false;
4683 if (this->is_varargs() != t->is_varargs())
4685 if (reason != NULL)
4686 *reason = _("different varargs");
4687 return false;
4690 const Typed_identifier_list* results1 = this->results();
4691 const Typed_identifier_list* results2 = t->results();
4692 if ((results1 != NULL) != (results2 != NULL))
4694 if (reason != NULL)
4695 *reason = _("different number of results");
4696 return false;
4698 if (results1 != NULL)
4700 Typed_identifier_list::const_iterator res1 = results1->begin();
4701 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4702 res2 != results2->end();
4703 ++res2, ++res1)
4705 if (res1 == results1->end())
4707 if (reason != NULL)
4708 *reason = _("different number of results");
4709 return false;
4712 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4713 cmp_tags, errors_are_identical,
4714 NULL))
4716 if (reason != NULL)
4717 *reason = _("different result types");
4718 return false;
4721 if (res1 != results1->end())
4723 if (reason != NULL)
4724 *reason = _("different number of results");
4725 return false;
4729 return true;
4732 // Hash code.
4734 unsigned int
4735 Function_type::do_hash_for_method(Gogo* gogo) const
4737 unsigned int ret = 0;
4738 // We ignore the receiver type for hash codes, because we need to
4739 // get the same hash code for a method in an interface and a method
4740 // declared for a type. The former will not have a receiver.
4741 if (this->parameters_ != NULL)
4743 int shift = 1;
4744 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4745 p != this->parameters_->end();
4746 ++p, ++shift)
4747 ret += p->type()->hash_for_method(gogo) << shift;
4749 if (this->results_ != NULL)
4751 int shift = 2;
4752 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4753 p != this->results_->end();
4754 ++p, ++shift)
4755 ret += p->type()->hash_for_method(gogo) << shift;
4757 if (this->is_varargs_)
4758 ret += 1;
4759 ret <<= 4;
4760 return ret;
4763 // Hash result parameters.
4765 unsigned int
4766 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4768 unsigned int hash = 0;
4769 for (Typed_identifier_list::const_iterator p = t->begin();
4770 p != t->end();
4771 ++p)
4773 hash <<= 2;
4774 hash = Type::hash_string(p->name(), hash);
4775 hash += p->type()->hash_for_method(NULL);
4777 return hash;
4780 // Compare result parameters so that can map identical result
4781 // parameters to a single struct type.
4783 bool
4784 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4785 const Typed_identifier_list* b) const
4787 if (a->size() != b->size())
4788 return false;
4789 Typed_identifier_list::const_iterator pa = a->begin();
4790 for (Typed_identifier_list::const_iterator pb = b->begin();
4791 pb != b->end();
4792 ++pa, ++pb)
4794 if (pa->name() != pb->name()
4795 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4796 return false;
4798 return true;
4801 // Hash from results to a backend struct type.
4803 Function_type::Results_structs Function_type::results_structs;
4805 // Get the backend representation for a function type.
4807 Btype*
4808 Function_type::get_backend_fntype(Gogo* gogo)
4810 if (this->fnbtype_ == NULL)
4812 Backend::Btyped_identifier breceiver;
4813 if (this->receiver_ != NULL)
4815 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4817 // We always pass the address of the receiver parameter, in
4818 // order to make interface calls work with unknown types.
4819 Type* rtype = this->receiver_->type();
4820 if (rtype->points_to() == NULL)
4821 rtype = Type::make_pointer_type(rtype);
4822 breceiver.btype = rtype->get_backend(gogo);
4823 breceiver.location = this->receiver_->location();
4826 std::vector<Backend::Btyped_identifier> bparameters;
4827 if (this->parameters_ != NULL)
4829 bparameters.resize(this->parameters_->size());
4830 size_t i = 0;
4831 for (Typed_identifier_list::const_iterator p =
4832 this->parameters_->begin(); p != this->parameters_->end();
4833 ++p, ++i)
4835 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4836 bparameters[i].btype = p->type()->get_backend(gogo);
4837 bparameters[i].location = p->location();
4839 go_assert(i == bparameters.size());
4842 std::vector<Backend::Btyped_identifier> bresults;
4843 Btype* bresult_struct = NULL;
4844 if (this->results_ != NULL)
4846 bresults.resize(this->results_->size());
4847 size_t i = 0;
4848 for (Typed_identifier_list::const_iterator p =
4849 this->results_->begin();
4850 p != this->results_->end();
4851 ++p, ++i)
4853 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4854 bresults[i].btype = p->type()->get_backend(gogo);
4855 bresults[i].location = p->location();
4857 go_assert(i == bresults.size());
4859 if (this->results_->size() > 1)
4861 // Use the same results struct for all functions that
4862 // return the same set of results. This is useful to
4863 // unify calls to interface methods with other calls.
4864 std::pair<Typed_identifier_list*, Btype*> val;
4865 val.first = this->results_;
4866 val.second = NULL;
4867 std::pair<Results_structs::iterator, bool> ins =
4868 Function_type::results_structs.insert(val);
4869 if (ins.second)
4871 // Build a new struct type.
4872 Struct_field_list* sfl = new Struct_field_list;
4873 for (Typed_identifier_list::const_iterator p =
4874 this->results_->begin();
4875 p != this->results_->end();
4876 ++p)
4878 Typed_identifier tid = *p;
4879 if (tid.name().empty())
4880 tid = Typed_identifier("UNNAMED", tid.type(),
4881 tid.location());
4882 sfl->push_back(Struct_field(tid));
4884 Struct_type* st = Type::make_struct_type(sfl,
4885 this->location());
4886 st->set_is_struct_incomparable();
4887 ins.first->second = st->get_backend(gogo);
4889 bresult_struct = ins.first->second;
4893 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4894 bresults, bresult_struct,
4895 this->location());
4899 return this->fnbtype_;
4902 // Get the backend representation for a Go function type.
4904 Btype*
4905 Function_type::do_get_backend(Gogo* gogo)
4907 // When we do anything with a function value other than call it, it
4908 // is represented as a pointer to a struct whose first field is the
4909 // actual function. So that is what we return as the type of a Go
4910 // function.
4912 Location loc = this->location();
4913 Btype* struct_type =
4914 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4915 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4917 std::vector<Backend::Btyped_identifier> fields(1);
4918 fields[0].name = "code";
4919 fields[0].btype = this->get_backend_fntype(gogo);
4920 fields[0].location = loc;
4921 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4922 return gogo->backend()->error_type();
4923 return ptr_struct_type;
4926 // The type of a function type descriptor.
4928 Type*
4929 Function_type::make_function_type_descriptor_type()
4931 static Type* ret;
4932 if (ret == NULL)
4934 Type* tdt = Type::make_type_descriptor_type();
4935 Type* ptdt = Type::make_type_descriptor_ptr_type();
4937 Type* bool_type = Type::lookup_bool_type();
4939 Type* slice_type = Type::make_array_type(ptdt, NULL);
4941 Struct_type* s = Type::make_builtin_struct_type(4,
4942 "", tdt,
4943 "dotdotdot", bool_type,
4944 "in", slice_type,
4945 "out", slice_type);
4947 ret = Type::make_builtin_named_type("FuncType", s);
4950 return ret;
4953 // The type descriptor for a function type.
4955 Expression*
4956 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4958 Location bloc = Linemap::predeclared_location();
4960 Type* ftdt = Function_type::make_function_type_descriptor_type();
4962 const Struct_field_list* fields = ftdt->struct_type()->fields();
4964 Expression_list* vals = new Expression_list();
4965 vals->reserve(4);
4967 Struct_field_list::const_iterator p = fields->begin();
4968 go_assert(p->is_field_name("_type"));
4969 vals->push_back(this->type_descriptor_constructor(gogo,
4970 RUNTIME_TYPE_KIND_FUNC,
4971 name, NULL, true));
4973 ++p;
4974 go_assert(p->is_field_name("dotdotdot"));
4975 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4977 ++p;
4978 go_assert(p->is_field_name("in"));
4979 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4980 this->parameters()));
4982 ++p;
4983 go_assert(p->is_field_name("out"));
4984 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4985 this->results()));
4987 ++p;
4988 go_assert(p == fields->end());
4990 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4993 // Return a composite literal for the parameters or results of a type
4994 // descriptor.
4996 Expression*
4997 Function_type::type_descriptor_params(Type* params_type,
4998 const Typed_identifier* receiver,
4999 const Typed_identifier_list* params)
5001 Location bloc = Linemap::predeclared_location();
5003 if (receiver == NULL && params == NULL)
5004 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
5006 Expression_list* vals = new Expression_list();
5007 vals->reserve((params == NULL ? 0 : params->size())
5008 + (receiver != NULL ? 1 : 0));
5010 if (receiver != NULL)
5011 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
5013 if (params != NULL)
5015 for (Typed_identifier_list::const_iterator p = params->begin();
5016 p != params->end();
5017 ++p)
5018 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
5021 return Expression::make_slice_composite_literal(params_type, vals, bloc);
5024 // The reflection string.
5026 void
5027 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
5029 // FIXME: Turn this off until we straighten out the type of the
5030 // struct field used in a go statement which calls a method.
5031 // go_assert(this->receiver_ == NULL);
5033 ret->append("func");
5035 if (this->receiver_ != NULL)
5037 ret->push_back('(');
5038 this->append_reflection(this->receiver_->type(), gogo, ret);
5039 ret->push_back(')');
5042 ret->push_back('(');
5043 const Typed_identifier_list* params = this->parameters();
5044 if (params != NULL)
5046 bool is_varargs = this->is_varargs_;
5047 for (Typed_identifier_list::const_iterator p = params->begin();
5048 p != params->end();
5049 ++p)
5051 if (p != params->begin())
5052 ret->append(", ");
5053 if (!is_varargs || p + 1 != params->end())
5054 this->append_reflection(p->type(), gogo, ret);
5055 else
5057 ret->append("...");
5058 this->append_reflection(p->type()->array_type()->element_type(),
5059 gogo, ret);
5063 ret->push_back(')');
5065 const Typed_identifier_list* results = this->results();
5066 if (results != NULL && !results->empty())
5068 if (results->size() == 1)
5069 ret->push_back(' ');
5070 else
5071 ret->append(" (");
5072 for (Typed_identifier_list::const_iterator p = results->begin();
5073 p != results->end();
5074 ++p)
5076 if (p != results->begin())
5077 ret->append(", ");
5078 this->append_reflection(p->type(), gogo, ret);
5080 if (results->size() > 1)
5081 ret->push_back(')');
5085 // Mangled name.
5087 void
5088 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5090 ret->push_back('F');
5092 if (this->receiver_ != NULL)
5094 ret->push_back('m');
5095 this->append_mangled_name(this->receiver_->type(), gogo, ret);
5098 const Typed_identifier_list* params = this->parameters();
5099 if (params != NULL)
5101 ret->push_back('p');
5102 for (Typed_identifier_list::const_iterator p = params->begin();
5103 p != params->end();
5104 ++p)
5105 this->append_mangled_name(p->type(), gogo, ret);
5106 if (this->is_varargs_)
5107 ret->push_back('V');
5108 ret->push_back('e');
5111 const Typed_identifier_list* results = this->results();
5112 if (results != NULL)
5114 ret->push_back('r');
5115 for (Typed_identifier_list::const_iterator p = results->begin();
5116 p != results->end();
5117 ++p)
5118 this->append_mangled_name(p->type(), gogo, ret);
5119 ret->push_back('e');
5122 ret->push_back('e');
5125 // Export a function type.
5127 void
5128 Function_type::do_export(Export* exp) const
5130 // We don't write out the receiver. The only function types which
5131 // should have a receiver are the ones associated with explicitly
5132 // defined methods. For those the receiver type is written out by
5133 // Function::export_func.
5135 exp->write_c_string("(");
5136 bool first = true;
5137 if (this->parameters_ != NULL)
5139 bool is_varargs = this->is_varargs_;
5140 for (Typed_identifier_list::const_iterator p =
5141 this->parameters_->begin();
5142 p != this->parameters_->end();
5143 ++p)
5145 if (first)
5146 first = false;
5147 else
5148 exp->write_c_string(", ");
5149 exp->write_name(p->name());
5150 exp->write_c_string(" ");
5151 if (!is_varargs || p + 1 != this->parameters_->end())
5152 exp->write_type(p->type());
5153 else
5155 exp->write_c_string("...");
5156 exp->write_type(p->type()->array_type()->element_type());
5160 exp->write_c_string(")");
5162 const Typed_identifier_list* results = this->results_;
5163 if (results != NULL)
5165 exp->write_c_string(" ");
5166 if (results->size() == 1 && results->begin()->name().empty())
5167 exp->write_type(results->begin()->type());
5168 else
5170 first = true;
5171 exp->write_c_string("(");
5172 for (Typed_identifier_list::const_iterator p = results->begin();
5173 p != results->end();
5174 ++p)
5176 if (first)
5177 first = false;
5178 else
5179 exp->write_c_string(", ");
5180 exp->write_name(p->name());
5181 exp->write_c_string(" ");
5182 exp->write_type(p->type());
5184 exp->write_c_string(")");
5189 // Import a function type.
5191 Function_type*
5192 Function_type::do_import(Import* imp)
5194 imp->require_c_string("(");
5195 Typed_identifier_list* parameters;
5196 bool is_varargs = false;
5197 if (imp->peek_char() == ')')
5198 parameters = NULL;
5199 else
5201 parameters = new Typed_identifier_list();
5202 while (true)
5204 std::string name = imp->read_name();
5205 imp->require_c_string(" ");
5207 if (imp->match_c_string("..."))
5209 imp->advance(3);
5210 is_varargs = true;
5213 Type* ptype = imp->read_type();
5214 if (is_varargs)
5215 ptype = Type::make_array_type(ptype, NULL);
5216 parameters->push_back(Typed_identifier(name, ptype,
5217 imp->location()));
5218 if (imp->peek_char() != ',')
5219 break;
5220 go_assert(!is_varargs);
5221 imp->require_c_string(", ");
5224 imp->require_c_string(")");
5226 Typed_identifier_list* results;
5227 if (imp->peek_char() != ' ')
5228 results = NULL;
5229 else
5231 imp->advance(1);
5232 results = new Typed_identifier_list;
5233 if (imp->peek_char() != '(')
5235 Type* rtype = imp->read_type();
5236 results->push_back(Typed_identifier("", rtype, imp->location()));
5238 else
5240 imp->advance(1);
5241 while (true)
5243 std::string name = imp->read_name();
5244 imp->require_c_string(" ");
5245 Type* rtype = imp->read_type();
5246 results->push_back(Typed_identifier(name, rtype,
5247 imp->location()));
5248 if (imp->peek_char() != ',')
5249 break;
5250 imp->require_c_string(", ");
5252 imp->require_c_string(")");
5256 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5257 imp->location());
5258 if (is_varargs)
5259 ret->set_is_varargs();
5260 return ret;
5263 // Make a copy of a function type without a receiver.
5265 Function_type*
5266 Function_type::copy_without_receiver() const
5268 go_assert(this->is_method());
5269 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5270 this->results_,
5271 this->location_);
5272 if (this->is_varargs())
5273 ret->set_is_varargs();
5274 if (this->is_builtin())
5275 ret->set_is_builtin();
5276 return ret;
5279 // Make a copy of a function type with a receiver.
5281 Function_type*
5282 Function_type::copy_with_receiver(Type* receiver_type) const
5284 go_assert(!this->is_method());
5285 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5286 this->location_);
5287 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5288 this->results_,
5289 this->location_);
5290 if (this->is_varargs_)
5291 ret->set_is_varargs();
5292 return ret;
5295 // Make a copy of a function type with the receiver as the first
5296 // parameter.
5298 Function_type*
5299 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5301 go_assert(this->is_method());
5302 Typed_identifier_list* new_params = new Typed_identifier_list();
5303 Type* rtype = this->receiver_->type();
5304 if (want_pointer_receiver)
5305 rtype = Type::make_pointer_type(rtype);
5306 Typed_identifier receiver(this->receiver_->name(), rtype,
5307 this->receiver_->location());
5308 new_params->push_back(receiver);
5309 const Typed_identifier_list* orig_params = this->parameters_;
5310 if (orig_params != NULL && !orig_params->empty())
5312 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5313 p != orig_params->end();
5314 ++p)
5315 new_params->push_back(*p);
5317 return Type::make_function_type(NULL, new_params, this->results_,
5318 this->location_);
5321 // Make a copy of a function type ignoring any receiver and adding a
5322 // closure parameter.
5324 Function_type*
5325 Function_type::copy_with_names() const
5327 Typed_identifier_list* new_params = new Typed_identifier_list();
5328 const Typed_identifier_list* orig_params = this->parameters_;
5329 if (orig_params != NULL && !orig_params->empty())
5331 static int count;
5332 char buf[50];
5333 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5334 p != orig_params->end();
5335 ++p)
5337 snprintf(buf, sizeof buf, "pt.%u", count);
5338 ++count;
5339 new_params->push_back(Typed_identifier(buf, p->type(),
5340 p->location()));
5344 const Typed_identifier_list* orig_results = this->results_;
5345 Typed_identifier_list* new_results;
5346 if (orig_results == NULL || orig_results->empty())
5347 new_results = NULL;
5348 else
5350 new_results = new Typed_identifier_list();
5351 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5352 p != orig_results->end();
5353 ++p)
5354 new_results->push_back(Typed_identifier("", p->type(),
5355 p->location()));
5358 return Type::make_function_type(NULL, new_params, new_results,
5359 this->location());
5362 // Make a function type.
5364 Function_type*
5365 Type::make_function_type(Typed_identifier* receiver,
5366 Typed_identifier_list* parameters,
5367 Typed_identifier_list* results,
5368 Location location)
5370 return new Function_type(receiver, parameters, results, location);
5373 // Make a backend function type.
5375 Backend_function_type*
5376 Type::make_backend_function_type(Typed_identifier* receiver,
5377 Typed_identifier_list* parameters,
5378 Typed_identifier_list* results,
5379 Location location)
5381 return new Backend_function_type(receiver, parameters, results, location);
5384 // Class Pointer_type.
5386 // Traversal.
5389 Pointer_type::do_traverse(Traverse* traverse)
5391 return Type::traverse(this->to_type_, traverse);
5394 // Hash code.
5396 unsigned int
5397 Pointer_type::do_hash_for_method(Gogo* gogo) const
5399 return this->to_type_->hash_for_method(gogo) << 4;
5402 // Get the backend representation for a pointer type.
5404 Btype*
5405 Pointer_type::do_get_backend(Gogo* gogo)
5407 Btype* to_btype = this->to_type_->get_backend(gogo);
5408 return gogo->backend()->pointer_type(to_btype);
5411 // The type of a pointer type descriptor.
5413 Type*
5414 Pointer_type::make_pointer_type_descriptor_type()
5416 static Type* ret;
5417 if (ret == NULL)
5419 Type* tdt = Type::make_type_descriptor_type();
5420 Type* ptdt = Type::make_type_descriptor_ptr_type();
5422 Struct_type* s = Type::make_builtin_struct_type(2,
5423 "", tdt,
5424 "elem", ptdt);
5426 ret = Type::make_builtin_named_type("PtrType", s);
5429 return ret;
5432 // The type descriptor for a pointer type.
5434 Expression*
5435 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5437 if (this->is_unsafe_pointer_type())
5439 go_assert(name != NULL);
5440 return this->plain_type_descriptor(gogo,
5441 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5442 name);
5444 else
5446 Location bloc = Linemap::predeclared_location();
5448 const Methods* methods;
5449 Type* deref = this->points_to();
5450 if (deref->named_type() != NULL)
5451 methods = deref->named_type()->methods();
5452 else if (deref->struct_type() != NULL)
5453 methods = deref->struct_type()->methods();
5454 else
5455 methods = NULL;
5457 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5459 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5461 Expression_list* vals = new Expression_list();
5462 vals->reserve(2);
5464 Struct_field_list::const_iterator p = fields->begin();
5465 go_assert(p->is_field_name("_type"));
5466 vals->push_back(this->type_descriptor_constructor(gogo,
5467 RUNTIME_TYPE_KIND_PTR,
5468 name, methods, false));
5470 ++p;
5471 go_assert(p->is_field_name("elem"));
5472 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5474 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5478 // Reflection string.
5480 void
5481 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5483 ret->push_back('*');
5484 this->append_reflection(this->to_type_, gogo, ret);
5487 void
5488 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5490 ret->push_back('p');
5491 this->append_mangled_name(this->to_type_, gogo, ret);
5494 // Export.
5496 void
5497 Pointer_type::do_export(Export* exp) const
5499 exp->write_c_string("*");
5500 if (this->is_unsafe_pointer_type())
5501 exp->write_c_string("any");
5502 else
5503 exp->write_type(this->to_type_);
5506 // Import.
5508 Pointer_type*
5509 Pointer_type::do_import(Import* imp)
5511 imp->require_c_string("*");
5512 if (imp->match_c_string("any"))
5514 imp->advance(3);
5515 return Type::make_pointer_type(Type::make_void_type());
5517 Type* to = imp->read_type();
5518 return Type::make_pointer_type(to);
5521 // Cache of pointer types. Key is "to" type, value is pointer type
5522 // that points to key.
5524 Type::Pointer_type_table Type::pointer_types;
5526 // A list of placeholder pointer types. We keep this so we can ensure
5527 // they are finalized.
5529 std::vector<Pointer_type*> Type::placeholder_pointers;
5531 // Make a pointer type.
5533 Pointer_type*
5534 Type::make_pointer_type(Type* to_type)
5536 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5537 if (p != pointer_types.end())
5538 return p->second;
5539 Pointer_type* ret = new Pointer_type(to_type);
5540 pointer_types[to_type] = ret;
5541 return ret;
5544 // This helper is invoked immediately after named types have been
5545 // converted, to clean up any unresolved pointer types remaining in
5546 // the pointer type cache.
5548 // The motivation for this routine: occasionally the compiler creates
5549 // some specific pointer type as part of a lowering operation (ex:
5550 // pointer-to-void), then Type::backend_type_size() is invoked on the
5551 // type (which creates a Btype placeholder for it), that placeholder
5552 // passed somewhere along the line to the back end, but since there is
5553 // no reference to the type in user code, there is never a call to
5554 // Type::finish_backend for the type (hence the Btype remains as an
5555 // unresolved placeholder). Calling this routine will clean up such
5556 // instances.
5558 void
5559 Type::finish_pointer_types(Gogo* gogo)
5561 // We don't use begin() and end() because it is possible to add new
5562 // placeholder pointer types as we finalized existing ones.
5563 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5565 Pointer_type* pt = Type::placeholder_pointers[i];
5566 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5567 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5569 pt->finish_backend(gogo, tbti->second.btype);
5570 tbti->second.is_placeholder = false;
5575 // The nil type. We use a special type for nil because it is not the
5576 // same as any other type. In C term nil has type void*, but there is
5577 // no such type in Go.
5579 class Nil_type : public Type
5581 public:
5582 Nil_type()
5583 : Type(TYPE_NIL)
5586 protected:
5587 bool
5588 do_compare_is_identity(Gogo*)
5589 { return false; }
5591 Btype*
5592 do_get_backend(Gogo* gogo)
5593 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
5595 Expression*
5596 do_type_descriptor(Gogo*, Named_type*)
5597 { go_unreachable(); }
5599 void
5600 do_reflection(Gogo*, std::string*) const
5601 { go_unreachable(); }
5603 void
5604 do_mangled_name(Gogo*, std::string* ret) const
5605 { ret->push_back('n'); }
5608 // Make the nil type.
5610 Type*
5611 Type::make_nil_type()
5613 static Nil_type singleton_nil_type;
5614 return &singleton_nil_type;
5617 // The type of a function call which returns multiple values. This is
5618 // really a struct, but we don't want to confuse a function call which
5619 // returns a struct with a function call which returns multiple
5620 // values.
5622 class Call_multiple_result_type : public Type
5624 public:
5625 Call_multiple_result_type(Call_expression* call)
5626 : Type(TYPE_CALL_MULTIPLE_RESULT),
5627 call_(call)
5630 protected:
5631 bool
5632 do_has_pointer() const
5633 { return false; }
5635 bool
5636 do_compare_is_identity(Gogo*)
5637 { return false; }
5639 Btype*
5640 do_get_backend(Gogo* gogo)
5642 go_assert(saw_errors());
5643 return gogo->backend()->error_type();
5646 Expression*
5647 do_type_descriptor(Gogo*, Named_type*)
5649 go_assert(saw_errors());
5650 return Expression::make_error(Linemap::unknown_location());
5653 void
5654 do_reflection(Gogo*, std::string*) const
5655 { go_assert(saw_errors()); }
5657 void
5658 do_mangled_name(Gogo*, std::string*) const
5659 { go_assert(saw_errors()); }
5661 private:
5662 // The expression being called.
5663 Call_expression* call_;
5666 // Make a call result type.
5668 Type*
5669 Type::make_call_multiple_result_type(Call_expression* call)
5671 return new Call_multiple_result_type(call);
5674 // Class Struct_field.
5676 // Get the name of a field.
5678 const std::string&
5679 Struct_field::field_name() const
5681 const std::string& name(this->typed_identifier_.name());
5682 if (!name.empty())
5683 return name;
5684 else
5686 // This is called during parsing, before anything is lowered, so
5687 // we have to be pretty careful to avoid dereferencing an
5688 // unknown type name.
5689 Type* t = this->typed_identifier_.type();
5690 Type* dt = t;
5691 if (t->classification() == Type::TYPE_POINTER)
5693 // Very ugly.
5694 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5695 dt = ptype->points_to();
5697 if (dt->forward_declaration_type() != NULL)
5698 return dt->forward_declaration_type()->name();
5699 else if (dt->named_type() != NULL)
5701 // Note that this can be an alias name.
5702 return dt->named_type()->name();
5704 else if (t->is_error_type() || dt->is_error_type())
5706 static const std::string error_string = "*error*";
5707 return error_string;
5709 else
5711 // Avoid crashing in the erroneous case where T is named but
5712 // DT is not.
5713 go_assert(t != dt);
5714 if (t->forward_declaration_type() != NULL)
5715 return t->forward_declaration_type()->name();
5716 else if (t->named_type() != NULL)
5717 return t->named_type()->name();
5718 else
5719 go_unreachable();
5724 // Return whether this field is named NAME.
5726 bool
5727 Struct_field::is_field_name(const std::string& name) const
5729 const std::string& me(this->typed_identifier_.name());
5730 if (!me.empty())
5731 return me == name;
5732 else
5734 Type* t = this->typed_identifier_.type();
5735 if (t->points_to() != NULL)
5736 t = t->points_to();
5737 Named_type* nt = t->named_type();
5738 if (nt != NULL && nt->name() == name)
5739 return true;
5741 // This is a horrible hack caused by the fact that we don't pack
5742 // the names of builtin types. FIXME.
5743 if (!this->is_imported_
5744 && nt != NULL
5745 && nt->is_builtin()
5746 && nt->name() == Gogo::unpack_hidden_name(name))
5747 return true;
5749 return false;
5753 // Return whether this field is an unexported field named NAME.
5755 bool
5756 Struct_field::is_unexported_field_name(Gogo* gogo,
5757 const std::string& name) const
5759 const std::string& field_name(this->field_name());
5760 if (Gogo::is_hidden_name(field_name)
5761 && name == Gogo::unpack_hidden_name(field_name)
5762 && gogo->pack_hidden_name(name, false) != field_name)
5763 return true;
5765 // Check for the name of a builtin type. This is like the test in
5766 // is_field_name, only there we return false if this->is_imported_,
5767 // and here we return true.
5768 if (this->is_imported_ && this->is_anonymous())
5770 Type* t = this->typed_identifier_.type();
5771 if (t->points_to() != NULL)
5772 t = t->points_to();
5773 Named_type* nt = t->named_type();
5774 if (nt != NULL
5775 && nt->is_builtin()
5776 && nt->name() == Gogo::unpack_hidden_name(name))
5777 return true;
5780 return false;
5783 // Return whether this field is an embedded built-in type.
5785 bool
5786 Struct_field::is_embedded_builtin(Gogo* gogo) const
5788 const std::string& name(this->field_name());
5789 // We know that a field is an embedded type if it is anonymous.
5790 // We can decide if it is a built-in type by checking to see if it is
5791 // registered globally under the field's name.
5792 // This allows us to distinguish between embedded built-in types and
5793 // embedded types that are aliases to built-in types.
5794 return (this->is_anonymous()
5795 && !Gogo::is_hidden_name(name)
5796 && gogo->lookup_global(name.c_str()) != NULL);
5799 // Class Struct_type.
5801 // A hash table used to find identical unnamed structs so that they
5802 // share method tables.
5804 Struct_type::Identical_structs Struct_type::identical_structs;
5806 // A hash table used to merge method sets for identical unnamed
5807 // structs.
5809 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5811 // Traversal.
5814 Struct_type::do_traverse(Traverse* traverse)
5816 Struct_field_list* fields = this->fields_;
5817 if (fields != NULL)
5819 for (Struct_field_list::iterator p = fields->begin();
5820 p != fields->end();
5821 ++p)
5823 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5824 return TRAVERSE_EXIT;
5827 return TRAVERSE_CONTINUE;
5830 // Verify that the struct type is complete and valid.
5832 bool
5833 Struct_type::do_verify()
5835 Struct_field_list* fields = this->fields_;
5836 if (fields == NULL)
5837 return true;
5838 for (Struct_field_list::iterator p = fields->begin();
5839 p != fields->end();
5840 ++p)
5842 Type* t = p->type();
5843 if (p->is_anonymous())
5845 if (t->named_type() != NULL && t->points_to() != NULL)
5847 go_error_at(p->location(), "embedded type may not be a pointer");
5848 p->set_type(Type::make_error_type());
5850 else if (t->points_to() != NULL
5851 && t->points_to()->interface_type() != NULL)
5853 go_error_at(p->location(),
5854 "embedded type may not be pointer to interface");
5855 p->set_type(Type::make_error_type());
5859 return true;
5862 // Whether this contains a pointer.
5864 bool
5865 Struct_type::do_has_pointer() const
5867 const Struct_field_list* fields = this->fields();
5868 if (fields == NULL)
5869 return false;
5870 for (Struct_field_list::const_iterator p = fields->begin();
5871 p != fields->end();
5872 ++p)
5874 if (p->type()->has_pointer())
5875 return true;
5877 return false;
5880 // Whether this type is identical to T.
5882 bool
5883 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5884 bool errors_are_identical) const
5886 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5887 return false;
5888 const Struct_field_list* fields1 = this->fields();
5889 const Struct_field_list* fields2 = t->fields();
5890 if (fields1 == NULL || fields2 == NULL)
5891 return fields1 == fields2;
5892 Struct_field_list::const_iterator pf2 = fields2->begin();
5893 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5894 pf1 != fields1->end();
5895 ++pf1, ++pf2)
5897 if (pf2 == fields2->end())
5898 return false;
5899 if (pf1->field_name() != pf2->field_name())
5900 return false;
5901 if (pf1->is_anonymous() != pf2->is_anonymous()
5902 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5903 errors_are_identical, NULL))
5904 return false;
5905 if (cmp_tags == COMPARE_TAGS)
5907 if (!pf1->has_tag())
5909 if (pf2->has_tag())
5910 return false;
5912 else
5914 if (!pf2->has_tag())
5915 return false;
5916 if (pf1->tag() != pf2->tag())
5917 return false;
5921 if (pf2 != fields2->end())
5922 return false;
5923 return true;
5926 // Whether comparisons of this struct type are simple identity
5927 // comparisons.
5929 bool
5930 Struct_type::do_compare_is_identity(Gogo* gogo)
5932 const Struct_field_list* fields = this->fields_;
5933 if (fields == NULL)
5934 return true;
5935 int64_t offset = 0;
5936 for (Struct_field_list::const_iterator pf = fields->begin();
5937 pf != fields->end();
5938 ++pf)
5940 if (Gogo::is_sink_name(pf->field_name()))
5941 return false;
5943 if (!pf->type()->compare_is_identity(gogo))
5944 return false;
5946 int64_t field_align;
5947 if (!pf->type()->backend_type_align(gogo, &field_align))
5948 return false;
5949 if ((offset & (field_align - 1)) != 0)
5951 // This struct has padding. We don't guarantee that that
5952 // padding is zero-initialized for a stack variable, so we
5953 // can't use memcmp to compare struct values.
5954 return false;
5957 int64_t field_size;
5958 if (!pf->type()->backend_type_size(gogo, &field_size))
5959 return false;
5960 offset += field_size;
5963 int64_t struct_size;
5964 if (!this->backend_type_size(gogo, &struct_size))
5965 return false;
5966 if (offset != struct_size)
5968 // Trailing padding may not be zero when on the stack.
5969 return false;
5972 return true;
5975 // Return whether this struct type is reflexive--whether a value of
5976 // this type is always equal to itself.
5978 bool
5979 Struct_type::do_is_reflexive()
5981 const Struct_field_list* fields = this->fields_;
5982 if (fields == NULL)
5983 return true;
5984 for (Struct_field_list::const_iterator pf = fields->begin();
5985 pf != fields->end();
5986 ++pf)
5988 if (!pf->type()->is_reflexive())
5989 return false;
5991 return true;
5994 // Return whether this struct type needs a key update when used as a
5995 // map key.
5997 bool
5998 Struct_type::do_needs_key_update()
6000 const Struct_field_list* fields = this->fields_;
6001 if (fields == NULL)
6002 return false;
6003 for (Struct_field_list::const_iterator pf = fields->begin();
6004 pf != fields->end();
6005 ++pf)
6007 if (pf->type()->needs_key_update())
6008 return true;
6010 return false;
6013 // Return whether this struct type is permitted to be in the heap.
6015 bool
6016 Struct_type::do_in_heap()
6018 const Struct_field_list* fields = this->fields_;
6019 if (fields == NULL)
6020 return true;
6021 for (Struct_field_list::const_iterator pf = fields->begin();
6022 pf != fields->end();
6023 ++pf)
6025 if (!pf->type()->in_heap())
6026 return false;
6028 return true;
6031 // Build identity and hash functions for this struct.
6033 // Hash code.
6035 unsigned int
6036 Struct_type::do_hash_for_method(Gogo* gogo) const
6038 unsigned int ret = 0;
6039 if (this->fields() != NULL)
6041 for (Struct_field_list::const_iterator pf = this->fields()->begin();
6042 pf != this->fields()->end();
6043 ++pf)
6044 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
6046 ret <<= 2;
6047 if (this->is_struct_incomparable_)
6048 ret <<= 1;
6049 return ret;
6052 // Find the local field NAME.
6054 const Struct_field*
6055 Struct_type::find_local_field(const std::string& name,
6056 unsigned int *pindex) const
6058 const Struct_field_list* fields = this->fields_;
6059 if (fields == NULL)
6060 return NULL;
6061 unsigned int i = 0;
6062 for (Struct_field_list::const_iterator pf = fields->begin();
6063 pf != fields->end();
6064 ++pf, ++i)
6066 if (pf->is_field_name(name))
6068 if (pindex != NULL)
6069 *pindex = i;
6070 return &*pf;
6073 return NULL;
6076 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
6078 Field_reference_expression*
6079 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
6080 Location location) const
6082 unsigned int depth;
6083 return this->field_reference_depth(struct_expr, name, location, NULL,
6084 &depth);
6087 // Return an expression for a field, along with the depth at which it
6088 // was found.
6090 Field_reference_expression*
6091 Struct_type::field_reference_depth(Expression* struct_expr,
6092 const std::string& name,
6093 Location location,
6094 Saw_named_type* saw,
6095 unsigned int* depth) const
6097 const Struct_field_list* fields = this->fields_;
6098 if (fields == NULL)
6099 return NULL;
6101 // Look for a field with this name.
6102 unsigned int i = 0;
6103 for (Struct_field_list::const_iterator pf = fields->begin();
6104 pf != fields->end();
6105 ++pf, ++i)
6107 if (pf->is_field_name(name))
6109 *depth = 0;
6110 return Expression::make_field_reference(struct_expr, i, location);
6114 // Look for an anonymous field which contains a field with this
6115 // name.
6116 unsigned int found_depth = 0;
6117 Field_reference_expression* ret = NULL;
6118 i = 0;
6119 for (Struct_field_list::const_iterator pf = fields->begin();
6120 pf != fields->end();
6121 ++pf, ++i)
6123 if (!pf->is_anonymous())
6124 continue;
6126 Struct_type* st = pf->type()->deref()->struct_type();
6127 if (st == NULL)
6128 continue;
6130 Saw_named_type* hold_saw = saw;
6131 Saw_named_type saw_here;
6132 Named_type* nt = pf->type()->named_type();
6133 if (nt == NULL)
6134 nt = pf->type()->deref()->named_type();
6135 if (nt != NULL)
6137 Saw_named_type* q;
6138 for (q = saw; q != NULL; q = q->next)
6140 if (q->nt == nt)
6142 // If this is an error, it will be reported
6143 // elsewhere.
6144 break;
6147 if (q != NULL)
6148 continue;
6149 saw_here.next = saw;
6150 saw_here.nt = nt;
6151 saw = &saw_here;
6154 // Look for a reference using a NULL struct expression. If we
6155 // find one, fill in the struct expression with a reference to
6156 // this field.
6157 unsigned int subdepth;
6158 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6159 location,
6160 saw,
6161 &subdepth);
6163 saw = hold_saw;
6165 if (sub == NULL)
6166 continue;
6168 if (ret == NULL || subdepth < found_depth)
6170 if (ret != NULL)
6171 delete ret;
6172 ret = sub;
6173 found_depth = subdepth;
6174 Expression* here = Expression::make_field_reference(struct_expr, i,
6175 location);
6176 if (pf->type()->points_to() != NULL)
6177 here = Expression::make_unary(OPERATOR_MULT, here, location);
6178 while (sub->expr() != NULL)
6180 sub = sub->expr()->deref()->field_reference_expression();
6181 go_assert(sub != NULL);
6183 sub->set_struct_expression(here);
6184 sub->set_implicit(true);
6186 else if (subdepth > found_depth)
6187 delete sub;
6188 else
6190 // We do not handle ambiguity here--it should be handled by
6191 // Type::bind_field_or_method.
6192 delete sub;
6193 found_depth = 0;
6194 ret = NULL;
6198 if (ret != NULL)
6199 *depth = found_depth + 1;
6201 return ret;
6204 // Return the total number of fields, including embedded fields.
6206 unsigned int
6207 Struct_type::total_field_count() const
6209 if (this->fields_ == NULL)
6210 return 0;
6211 unsigned int ret = 0;
6212 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6213 pf != this->fields_->end();
6214 ++pf)
6216 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6217 ++ret;
6218 else
6219 ret += pf->type()->struct_type()->total_field_count();
6221 return ret;
6224 // Return whether NAME is an unexported field, for better error reporting.
6226 bool
6227 Struct_type::is_unexported_local_field(Gogo* gogo,
6228 const std::string& name) const
6230 const Struct_field_list* fields = this->fields_;
6231 if (fields != NULL)
6233 for (Struct_field_list::const_iterator pf = fields->begin();
6234 pf != fields->end();
6235 ++pf)
6236 if (pf->is_unexported_field_name(gogo, name))
6237 return true;
6239 return false;
6242 // Finalize the methods of an unnamed struct.
6244 void
6245 Struct_type::finalize_methods(Gogo* gogo)
6247 if (this->all_methods_ != NULL)
6248 return;
6250 // It is possible to have multiple identical structs that have
6251 // methods. We want them to share method tables. Otherwise we will
6252 // emit identical methods more than once, which is bad since they
6253 // will even have the same names.
6254 std::pair<Identical_structs::iterator, bool> ins =
6255 Struct_type::identical_structs.insert(std::make_pair(this, this));
6256 if (!ins.second)
6258 // An identical struct was already entered into the hash table.
6259 // Note that finalize_methods is, fortunately, not recursive.
6260 this->all_methods_ = ins.first->second->all_methods_;
6261 return;
6264 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6267 // Return the method NAME, or NULL if there isn't one or if it is
6268 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6269 // ambiguous.
6271 Method*
6272 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6274 return Type::method_function(this->all_methods_, name, is_ambiguous);
6277 // Return a pointer to the interface method table for this type for
6278 // the interface INTERFACE. IS_POINTER is true if this is for a
6279 // pointer to THIS.
6281 Expression*
6282 Struct_type::interface_method_table(Interface_type* interface,
6283 bool is_pointer)
6285 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6286 val(this, NULL);
6287 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6288 Struct_type::struct_method_tables.insert(val);
6290 Struct_method_table_pair* smtp;
6291 if (!ins.second)
6292 smtp = ins.first->second;
6293 else
6295 smtp = new Struct_method_table_pair();
6296 smtp->first = NULL;
6297 smtp->second = NULL;
6298 ins.first->second = smtp;
6301 return Type::interface_method_table(this, interface, is_pointer,
6302 &smtp->first, &smtp->second);
6305 // Convert struct fields to the backend representation. This is not
6306 // declared in types.h so that types.h doesn't have to #include
6307 // backend.h.
6309 static void
6310 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6311 bool use_placeholder,
6312 std::vector<Backend::Btyped_identifier>* bfields)
6314 bfields->resize(fields->size());
6315 size_t i = 0;
6316 for (Struct_field_list::const_iterator p = fields->begin();
6317 p != fields->end();
6318 ++p, ++i)
6320 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6321 (*bfields)[i].btype = (use_placeholder
6322 ? p->type()->get_backend_placeholder(gogo)
6323 : p->type()->get_backend(gogo));
6324 (*bfields)[i].location = p->location();
6326 go_assert(i == fields->size());
6329 // Get the backend representation for a struct type.
6331 Btype*
6332 Struct_type::do_get_backend(Gogo* gogo)
6334 std::vector<Backend::Btyped_identifier> bfields;
6335 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6336 return gogo->backend()->struct_type(bfields);
6339 // Finish the backend representation of the fields of a struct.
6341 void
6342 Struct_type::finish_backend_fields(Gogo* gogo)
6344 const Struct_field_list* fields = this->fields_;
6345 if (fields != NULL)
6347 for (Struct_field_list::const_iterator p = fields->begin();
6348 p != fields->end();
6349 ++p)
6350 p->type()->get_backend(gogo);
6354 // The type of a struct type descriptor.
6356 Type*
6357 Struct_type::make_struct_type_descriptor_type()
6359 static Type* ret;
6360 if (ret == NULL)
6362 Type* tdt = Type::make_type_descriptor_type();
6363 Type* ptdt = Type::make_type_descriptor_ptr_type();
6365 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6366 Type* string_type = Type::lookup_string_type();
6367 Type* pointer_string_type = Type::make_pointer_type(string_type);
6369 Struct_type* sf =
6370 Type::make_builtin_struct_type(5,
6371 "name", pointer_string_type,
6372 "pkgPath", pointer_string_type,
6373 "typ", ptdt,
6374 "tag", pointer_string_type,
6375 "offset", uintptr_type);
6376 Type* nsf = Type::make_builtin_named_type("structField", sf);
6378 Type* slice_type = Type::make_array_type(nsf, NULL);
6380 Struct_type* s = Type::make_builtin_struct_type(2,
6381 "", tdt,
6382 "fields", slice_type);
6384 ret = Type::make_builtin_named_type("StructType", s);
6387 return ret;
6390 // Build a type descriptor for a struct type.
6392 Expression*
6393 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6395 Location bloc = Linemap::predeclared_location();
6397 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6399 const Struct_field_list* fields = stdt->struct_type()->fields();
6401 Expression_list* vals = new Expression_list();
6402 vals->reserve(2);
6404 const Methods* methods = this->methods();
6405 // A named struct should not have methods--the methods should attach
6406 // to the named type.
6407 go_assert(methods == NULL || name == NULL);
6409 Struct_field_list::const_iterator ps = fields->begin();
6410 go_assert(ps->is_field_name("_type"));
6411 vals->push_back(this->type_descriptor_constructor(gogo,
6412 RUNTIME_TYPE_KIND_STRUCT,
6413 name, methods, true));
6415 ++ps;
6416 go_assert(ps->is_field_name("fields"));
6418 Expression_list* elements = new Expression_list();
6419 elements->reserve(this->fields_->size());
6420 Type* element_type = ps->type()->array_type()->element_type();
6421 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6422 pf != this->fields_->end();
6423 ++pf)
6425 const Struct_field_list* f = element_type->struct_type()->fields();
6427 Expression_list* fvals = new Expression_list();
6428 fvals->reserve(5);
6430 Struct_field_list::const_iterator q = f->begin();
6431 go_assert(q->is_field_name("name"));
6432 if (pf->is_anonymous())
6433 fvals->push_back(Expression::make_nil(bloc));
6434 else
6436 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6437 Expression* s = Expression::make_string(n, bloc);
6438 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6441 ++q;
6442 go_assert(q->is_field_name("pkgPath"));
6443 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6444 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6445 fvals->push_back(Expression::make_nil(bloc));
6446 else
6448 std::string n;
6449 if (is_embedded_builtin)
6450 n = gogo->package_name();
6451 else
6452 n = Gogo::hidden_name_pkgpath(pf->field_name());
6453 Expression* s = Expression::make_string(n, bloc);
6454 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6457 ++q;
6458 go_assert(q->is_field_name("typ"));
6459 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6461 ++q;
6462 go_assert(q->is_field_name("tag"));
6463 if (!pf->has_tag())
6464 fvals->push_back(Expression::make_nil(bloc));
6465 else
6467 Expression* s = Expression::make_string(pf->tag(), bloc);
6468 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6471 ++q;
6472 go_assert(q->is_field_name("offset"));
6473 fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
6475 Expression* v = Expression::make_struct_composite_literal(element_type,
6476 fvals, bloc);
6477 elements->push_back(v);
6480 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6481 elements, bloc));
6483 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6486 // Write the hash function for a struct which can not use the identity
6487 // function.
6489 void
6490 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6491 Function_type* hash_fntype,
6492 Function_type* equal_fntype)
6494 Location bloc = Linemap::predeclared_location();
6496 // The pointer to the struct that we are going to hash. This is an
6497 // argument to the hash function we are implementing here.
6498 Named_object* key_arg = gogo->lookup("key", NULL);
6499 go_assert(key_arg != NULL);
6500 Type* key_arg_type = key_arg->var_value()->type();
6502 // The seed argument to the hash function.
6503 Named_object* seed_arg = gogo->lookup("seed", NULL);
6504 go_assert(seed_arg != NULL);
6506 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6508 // Make a temporary to hold the return value, initialized to the seed.
6509 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6510 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6511 bloc);
6512 gogo->add_statement(retval);
6514 // Make a temporary to hold the key as a uintptr.
6515 ref = Expression::make_var_reference(key_arg, bloc);
6516 ref = Expression::make_cast(uintptr_type, ref, bloc);
6517 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6518 bloc);
6519 gogo->add_statement(key);
6521 // Loop over the struct fields.
6522 const Struct_field_list* fields = this->fields_;
6523 for (Struct_field_list::const_iterator pf = fields->begin();
6524 pf != fields->end();
6525 ++pf)
6527 if (Gogo::is_sink_name(pf->field_name()))
6528 continue;
6530 // Get a pointer to the value of this field.
6531 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6532 ref = Expression::make_temporary_reference(key, bloc);
6533 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6534 bloc);
6535 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6537 // Get the hash function to use for the type of this field.
6538 Named_object* hash_fn;
6539 Named_object* equal_fn;
6540 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6541 equal_fntype, &hash_fn, &equal_fn);
6543 // Call the hash function for the field, passing retval as the seed.
6544 ref = Expression::make_temporary_reference(retval, bloc);
6545 Expression_list* args = new Expression_list();
6546 args->push_back(subkey);
6547 args->push_back(ref);
6548 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6549 Expression* call = Expression::make_call(func, args, false, bloc);
6551 // Set retval to the result.
6552 Temporary_reference_expression* tref =
6553 Expression::make_temporary_reference(retval, bloc);
6554 tref->set_is_lvalue();
6555 Statement* s = Statement::make_assignment(tref, call, bloc);
6556 gogo->add_statement(s);
6559 // Return retval to the caller of the hash function.
6560 Expression_list* vals = new Expression_list();
6561 ref = Expression::make_temporary_reference(retval, bloc);
6562 vals->push_back(ref);
6563 Statement* s = Statement::make_return_statement(vals, bloc);
6564 gogo->add_statement(s);
6567 // Write the equality function for a struct which can not use the
6568 // identity function.
6570 void
6571 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6573 Location bloc = Linemap::predeclared_location();
6575 // The pointers to the structs we are going to compare.
6576 Named_object* key1_arg = gogo->lookup("key1", NULL);
6577 Named_object* key2_arg = gogo->lookup("key2", NULL);
6578 go_assert(key1_arg != NULL && key2_arg != NULL);
6580 // Build temporaries with the right types.
6581 Type* pt = Type::make_pointer_type(name != NULL
6582 ? static_cast<Type*>(name)
6583 : static_cast<Type*>(this));
6585 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6586 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6587 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6588 gogo->add_statement(p1);
6590 ref = Expression::make_var_reference(key2_arg, bloc);
6591 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6592 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6593 gogo->add_statement(p2);
6595 const Struct_field_list* fields = this->fields_;
6596 unsigned int field_index = 0;
6597 for (Struct_field_list::const_iterator pf = fields->begin();
6598 pf != fields->end();
6599 ++pf, ++field_index)
6601 if (Gogo::is_sink_name(pf->field_name()))
6602 continue;
6604 // Compare one field in both P1 and P2.
6605 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6606 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
6607 f1 = Expression::make_field_reference(f1, field_index, bloc);
6609 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6610 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
6611 f2 = Expression::make_field_reference(f2, field_index, bloc);
6613 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6615 // If the values are not equal, return false.
6616 gogo->start_block(bloc);
6617 Expression_list* vals = new Expression_list();
6618 vals->push_back(Expression::make_boolean(false, bloc));
6619 Statement* s = Statement::make_return_statement(vals, bloc);
6620 gogo->add_statement(s);
6621 Block* then_block = gogo->finish_block(bloc);
6623 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6624 gogo->add_statement(s);
6627 // All the fields are equal, so return true.
6628 Expression_list* vals = new Expression_list();
6629 vals->push_back(Expression::make_boolean(true, bloc));
6630 Statement* s = Statement::make_return_statement(vals, bloc);
6631 gogo->add_statement(s);
6634 // Reflection string.
6636 void
6637 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6639 ret->append("struct {");
6641 for (Struct_field_list::const_iterator p = this->fields_->begin();
6642 p != this->fields_->end();
6643 ++p)
6645 if (p != this->fields_->begin())
6646 ret->push_back(';');
6647 ret->push_back(' ');
6648 if (p->is_anonymous())
6649 ret->push_back('?');
6650 else
6651 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6652 ret->push_back(' ');
6653 if (p->is_anonymous()
6654 && p->type()->named_type() != NULL
6655 && p->type()->named_type()->is_alias())
6656 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6657 else
6658 this->append_reflection(p->type(), gogo, ret);
6660 if (p->has_tag())
6662 const std::string& tag(p->tag());
6663 ret->append(" \"");
6664 for (std::string::const_iterator p = tag.begin();
6665 p != tag.end();
6666 ++p)
6668 if (*p == '\0')
6669 ret->append("\\x00");
6670 else if (*p == '\n')
6671 ret->append("\\n");
6672 else if (*p == '\t')
6673 ret->append("\\t");
6674 else if (*p == '"')
6675 ret->append("\\\"");
6676 else if (*p == '\\')
6677 ret->append("\\\\");
6678 else
6679 ret->push_back(*p);
6681 ret->push_back('"');
6685 if (!this->fields_->empty())
6686 ret->push_back(' ');
6688 ret->push_back('}');
6691 // Mangled name.
6693 void
6694 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6696 ret->push_back('S');
6698 const Struct_field_list* fields = this->fields_;
6699 if (fields != NULL)
6701 for (Struct_field_list::const_iterator p = fields->begin();
6702 p != fields->end();
6703 ++p)
6705 if (p->is_anonymous())
6706 ret->append("0_");
6707 else
6710 std::string n(Gogo::mangle_possibly_hidden_name(p->field_name()));
6711 char buf[20];
6712 snprintf(buf, sizeof buf, "%u_",
6713 static_cast<unsigned int>(n.length()));
6714 ret->append(buf);
6715 ret->append(n);
6718 // For an anonymous field with an alias type, the field name
6719 // is the alias name.
6720 if (p->is_anonymous()
6721 && p->type()->named_type() != NULL
6722 && p->type()->named_type()->is_alias())
6723 p->type()->named_type()->append_mangled_type_name(gogo, true, ret);
6724 else
6725 this->append_mangled_name(p->type(), gogo, ret);
6726 if (p->has_tag())
6728 const std::string& tag(p->tag());
6729 std::string out;
6730 for (std::string::const_iterator p = tag.begin();
6731 p != tag.end();
6732 ++p)
6734 if (ISALNUM(*p) || *p == '_')
6735 out.push_back(*p);
6736 else
6738 char buf[20];
6739 snprintf(buf, sizeof buf, ".%x.",
6740 static_cast<unsigned int>(*p));
6741 out.append(buf);
6744 char buf[20];
6745 snprintf(buf, sizeof buf, "T%u_",
6746 static_cast<unsigned int>(out.length()));
6747 ret->append(buf);
6748 ret->append(out);
6753 if (this->is_struct_incomparable_)
6754 ret->push_back('x');
6756 ret->push_back('e');
6759 // If the offset of field INDEX in the backend implementation can be
6760 // determined, set *POFFSET to the offset in bytes and return true.
6761 // Otherwise, return false.
6763 bool
6764 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6765 int64_t* poffset)
6767 if (!this->is_backend_type_size_known(gogo))
6768 return false;
6769 Btype* bt = this->get_backend_placeholder(gogo);
6770 *poffset = gogo->backend()->type_field_offset(bt, index);
6771 return true;
6774 // Export.
6776 void
6777 Struct_type::do_export(Export* exp) const
6779 exp->write_c_string("struct { ");
6780 const Struct_field_list* fields = this->fields_;
6781 go_assert(fields != NULL);
6782 for (Struct_field_list::const_iterator p = fields->begin();
6783 p != fields->end();
6784 ++p)
6786 if (p->is_anonymous())
6787 exp->write_string("? ");
6788 else
6790 exp->write_string(p->field_name());
6791 exp->write_c_string(" ");
6793 exp->write_type(p->type());
6795 if (p->has_tag())
6797 exp->write_c_string(" ");
6798 Expression* expr =
6799 Expression::make_string(p->tag(), Linemap::predeclared_location());
6800 expr->export_expression(exp);
6801 delete expr;
6804 exp->write_c_string("; ");
6806 exp->write_c_string("}");
6809 // Import.
6811 Struct_type*
6812 Struct_type::do_import(Import* imp)
6814 imp->require_c_string("struct { ");
6815 Struct_field_list* fields = new Struct_field_list;
6816 if (imp->peek_char() != '}')
6818 while (true)
6820 std::string name;
6821 if (imp->match_c_string("? "))
6822 imp->advance(2);
6823 else
6825 name = imp->read_identifier();
6826 imp->require_c_string(" ");
6828 Type* ftype = imp->read_type();
6830 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6831 sf.set_is_imported();
6833 if (imp->peek_char() == ' ')
6835 imp->advance(1);
6836 Expression* expr = Expression::import_expression(imp);
6837 String_expression* sexpr = expr->string_expression();
6838 go_assert(sexpr != NULL);
6839 sf.set_tag(sexpr->val());
6840 delete sexpr;
6843 imp->require_c_string("; ");
6844 fields->push_back(sf);
6845 if (imp->peek_char() == '}')
6846 break;
6849 imp->require_c_string("}");
6851 return Type::make_struct_type(fields, imp->location());
6854 // Whether we can write this struct type to a C header file.
6855 // We can't if any of the fields are structs defined in a different package.
6857 bool
6858 Struct_type::can_write_to_c_header(
6859 std::vector<const Named_object*>* requires,
6860 std::vector<const Named_object*>* declare) const
6862 const Struct_field_list* fields = this->fields_;
6863 if (fields == NULL || fields->empty())
6864 return false;
6865 int sinks = 0;
6866 for (Struct_field_list::const_iterator p = fields->begin();
6867 p != fields->end();
6868 ++p)
6870 if (p->is_anonymous())
6871 return false;
6872 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6873 return false;
6874 if (Gogo::message_name(p->field_name()) == "_")
6875 sinks++;
6877 if (sinks > 1)
6878 return false;
6879 return true;
6882 // Whether we can write the type T to a C header file.
6884 bool
6885 Struct_type::can_write_type_to_c_header(
6886 const Type* t,
6887 std::vector<const Named_object*>* requires,
6888 std::vector<const Named_object*>* declare) const
6890 t = t->forwarded();
6891 switch (t->classification())
6893 case TYPE_ERROR:
6894 case TYPE_FORWARD:
6895 return false;
6897 case TYPE_VOID:
6898 case TYPE_BOOLEAN:
6899 case TYPE_INTEGER:
6900 case TYPE_FLOAT:
6901 case TYPE_COMPLEX:
6902 case TYPE_STRING:
6903 case TYPE_FUNCTION:
6904 case TYPE_MAP:
6905 case TYPE_CHANNEL:
6906 case TYPE_INTERFACE:
6907 return true;
6909 case TYPE_POINTER:
6910 // Don't try to handle a pointer to an array.
6911 if (t->points_to()->array_type() != NULL
6912 && !t->points_to()->is_slice_type())
6913 return false;
6915 if (t->points_to()->named_type() != NULL
6916 && t->points_to()->struct_type() != NULL)
6917 declare->push_back(t->points_to()->named_type()->named_object());
6918 return true;
6920 case TYPE_STRUCT:
6921 return t->struct_type()->can_write_to_c_header(requires, declare);
6923 case TYPE_ARRAY:
6924 if (t->is_slice_type())
6925 return true;
6926 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6927 requires, declare);
6929 case TYPE_NAMED:
6931 const Named_object* no = t->named_type()->named_object();
6932 if (no->package() != NULL)
6934 if (t->is_unsafe_pointer_type())
6935 return true;
6936 return false;
6938 if (t->struct_type() != NULL)
6940 requires->push_back(no);
6941 return t->struct_type()->can_write_to_c_header(requires, declare);
6943 return this->can_write_type_to_c_header(t->base(), requires, declare);
6946 case TYPE_CALL_MULTIPLE_RESULT:
6947 case TYPE_NIL:
6948 case TYPE_SINK:
6949 default:
6950 go_unreachable();
6954 // Write this struct to a C header file.
6956 void
6957 Struct_type::write_to_c_header(std::ostream& os) const
6959 const Struct_field_list* fields = this->fields_;
6960 for (Struct_field_list::const_iterator p = fields->begin();
6961 p != fields->end();
6962 ++p)
6964 os << '\t';
6965 this->write_field_to_c_header(os, p->field_name(), p->type());
6966 os << ';' << std::endl;
6970 // Write the type of a struct field to a C header file.
6972 void
6973 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6974 const Type *t) const
6976 bool print_name = true;
6977 t = t->forwarded();
6978 switch (t->classification())
6980 case TYPE_VOID:
6981 os << "void";
6982 break;
6984 case TYPE_BOOLEAN:
6985 os << "_Bool";
6986 break;
6988 case TYPE_INTEGER:
6990 const Integer_type* it = t->integer_type();
6991 if (it->is_unsigned())
6992 os << 'u';
6993 os << "int" << it->bits() << "_t";
6995 break;
6997 case TYPE_FLOAT:
6998 switch (t->float_type()->bits())
7000 case 32:
7001 os << "float";
7002 break;
7003 case 64:
7004 os << "double";
7005 break;
7006 default:
7007 go_unreachable();
7009 break;
7011 case TYPE_COMPLEX:
7012 switch (t->complex_type()->bits())
7014 case 64:
7015 os << "float _Complex";
7016 break;
7017 case 128:
7018 os << "double _Complex";
7019 break;
7020 default:
7021 go_unreachable();
7023 break;
7025 case TYPE_STRING:
7026 os << "String";
7027 break;
7029 case TYPE_FUNCTION:
7030 os << "FuncVal*";
7031 break;
7033 case TYPE_POINTER:
7035 std::vector<const Named_object*> requires;
7036 std::vector<const Named_object*> declare;
7037 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
7038 &declare))
7039 os << "void*";
7040 else
7042 this->write_field_to_c_header(os, "", t->points_to());
7043 os << '*';
7046 break;
7048 case TYPE_MAP:
7049 os << "Map*";
7050 break;
7052 case TYPE_CHANNEL:
7053 os << "Chan*";
7054 break;
7056 case TYPE_INTERFACE:
7057 if (t->interface_type()->is_empty())
7058 os << "Eface";
7059 else
7060 os << "Iface";
7061 break;
7063 case TYPE_STRUCT:
7064 os << "struct {" << std::endl;
7065 t->struct_type()->write_to_c_header(os);
7066 os << "\t}";
7067 break;
7069 case TYPE_ARRAY:
7070 if (t->is_slice_type())
7071 os << "Slice";
7072 else
7074 const Type *ele = t;
7075 std::vector<const Type*> array_types;
7076 while (ele->array_type() != NULL && !ele->is_slice_type())
7078 array_types.push_back(ele);
7079 ele = ele->array_type()->element_type();
7081 this->write_field_to_c_header(os, "", ele);
7082 os << ' ' << Gogo::message_name(name);
7083 print_name = false;
7084 while (!array_types.empty())
7086 ele = array_types.back();
7087 array_types.pop_back();
7088 os << '[';
7089 Numeric_constant nc;
7090 if (!ele->array_type()->length()->numeric_constant_value(&nc))
7091 go_unreachable();
7092 mpz_t val;
7093 if (!nc.to_int(&val))
7094 go_unreachable();
7095 char* s = mpz_get_str(NULL, 10, val);
7096 os << s;
7097 free(s);
7098 mpz_clear(val);
7099 os << ']';
7102 break;
7104 case TYPE_NAMED:
7106 const Named_object* no = t->named_type()->named_object();
7107 if (t->struct_type() != NULL)
7108 os << "struct " << no->message_name();
7109 else if (t->is_unsafe_pointer_type())
7110 os << "void*";
7111 else if (t == Type::lookup_integer_type("uintptr"))
7112 os << "uintptr_t";
7113 else
7115 this->write_field_to_c_header(os, name, t->base());
7116 print_name = false;
7119 break;
7121 case TYPE_ERROR:
7122 case TYPE_FORWARD:
7123 case TYPE_CALL_MULTIPLE_RESULT:
7124 case TYPE_NIL:
7125 case TYPE_SINK:
7126 default:
7127 go_unreachable();
7130 if (print_name && !name.empty())
7131 os << ' ' << Gogo::message_name(name);
7134 // Make a struct type.
7136 Struct_type*
7137 Type::make_struct_type(Struct_field_list* fields,
7138 Location location)
7140 return new Struct_type(fields, location);
7143 // Class Array_type.
7145 // Store the length of an array as an int64_t into *PLEN. Return
7146 // false if the length can not be determined. This will assert if
7147 // called for a slice.
7149 bool
7150 Array_type::int_length(int64_t* plen)
7152 go_assert(this->length_ != NULL);
7153 Numeric_constant nc;
7154 if (!this->length_->numeric_constant_value(&nc))
7155 return false;
7156 return nc.to_memory_size(plen);
7159 // Whether two array types are identical.
7161 bool
7162 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
7163 bool errors_are_identical) const
7165 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
7166 cmp_tags, errors_are_identical, NULL))
7167 return false;
7169 if (this->is_array_incomparable_ != t->is_array_incomparable_)
7170 return false;
7172 Expression* l1 = this->length();
7173 Expression* l2 = t->length();
7175 // Slices of the same element type are identical.
7176 if (l1 == NULL && l2 == NULL)
7177 return true;
7179 // Arrays of the same element type are identical if they have the
7180 // same length.
7181 if (l1 != NULL && l2 != NULL)
7183 if (l1 == l2)
7184 return true;
7186 // Try to determine the lengths. If we can't, assume the arrays
7187 // are not identical.
7188 bool ret = false;
7189 Numeric_constant nc1, nc2;
7190 if (l1->numeric_constant_value(&nc1)
7191 && l2->numeric_constant_value(&nc2))
7193 mpz_t v1;
7194 if (nc1.to_int(&v1))
7196 mpz_t v2;
7197 if (nc2.to_int(&v2))
7199 ret = mpz_cmp(v1, v2) == 0;
7200 mpz_clear(v2);
7202 mpz_clear(v1);
7205 return ret;
7208 // Otherwise the arrays are not identical.
7209 return false;
7212 // Traversal.
7215 Array_type::do_traverse(Traverse* traverse)
7217 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7218 return TRAVERSE_EXIT;
7219 if (this->length_ != NULL
7220 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7221 return TRAVERSE_EXIT;
7222 return TRAVERSE_CONTINUE;
7225 // Check that the length is valid.
7227 bool
7228 Array_type::verify_length()
7230 if (this->length_ == NULL)
7231 return true;
7233 Type_context context(Type::lookup_integer_type("int"), false);
7234 this->length_->determine_type(&context);
7236 if (!this->length_->is_constant())
7238 go_error_at(this->length_->location(), "array bound is not constant");
7239 return false;
7242 Numeric_constant nc;
7243 if (!this->length_->numeric_constant_value(&nc))
7245 if (this->length_->type()->integer_type() != NULL
7246 || this->length_->type()->float_type() != NULL)
7247 go_error_at(this->length_->location(), "array bound is not constant");
7248 else
7249 go_error_at(this->length_->location(), "array bound is not numeric");
7250 return false;
7253 Type* int_type = Type::lookup_integer_type("int");
7254 unsigned int tbits = int_type->integer_type()->bits();
7255 unsigned long val;
7256 switch (nc.to_unsigned_long(&val))
7258 case Numeric_constant::NC_UL_VALID:
7259 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7261 go_error_at(this->length_->location(), "array bound overflows");
7262 return false;
7264 break;
7265 case Numeric_constant::NC_UL_NOTINT:
7266 go_error_at(this->length_->location(), "array bound truncated to integer");
7267 return false;
7268 case Numeric_constant::NC_UL_NEGATIVE:
7269 go_error_at(this->length_->location(), "negative array bound");
7270 return false;
7271 case Numeric_constant::NC_UL_BIG:
7273 mpz_t val;
7274 if (!nc.to_int(&val))
7275 go_unreachable();
7276 unsigned int bits = mpz_sizeinbase(val, 2);
7277 mpz_clear(val);
7278 if (bits >= tbits)
7280 go_error_at(this->length_->location(), "array bound overflows");
7281 return false;
7284 break;
7285 default:
7286 go_unreachable();
7289 return true;
7292 // Verify the type.
7294 bool
7295 Array_type::do_verify()
7297 if (this->element_type()->is_error_type())
7298 return false;
7299 if (!this->verify_length())
7300 this->length_ = Expression::make_error(this->length_->location());
7301 return true;
7304 // Whether the type contains pointers. This is always true for a
7305 // slice. For an array it is true if the element type has pointers
7306 // and the length is greater than zero.
7308 bool
7309 Array_type::do_has_pointer() const
7311 if (this->length_ == NULL)
7312 return true;
7313 if (!this->element_type_->has_pointer())
7314 return false;
7316 Numeric_constant nc;
7317 if (!this->length_->numeric_constant_value(&nc))
7319 // Error reported elsewhere.
7320 return false;
7323 unsigned long val;
7324 switch (nc.to_unsigned_long(&val))
7326 case Numeric_constant::NC_UL_VALID:
7327 return val > 0;
7328 case Numeric_constant::NC_UL_BIG:
7329 return true;
7330 default:
7331 // Error reported elsewhere.
7332 return false;
7336 // Whether we can use memcmp to compare this array.
7338 bool
7339 Array_type::do_compare_is_identity(Gogo* gogo)
7341 if (this->length_ == NULL)
7342 return false;
7344 // Check for [...], which indicates that this is not a real type.
7345 if (this->length_->is_nil_expression())
7346 return false;
7348 if (!this->element_type_->compare_is_identity(gogo))
7349 return false;
7351 // If there is any padding, then we can't use memcmp.
7352 int64_t size;
7353 int64_t align;
7354 if (!this->element_type_->backend_type_size(gogo, &size)
7355 || !this->element_type_->backend_type_align(gogo, &align))
7356 return false;
7357 if ((size & (align - 1)) != 0)
7358 return false;
7360 return true;
7363 // Array type hash code.
7365 unsigned int
7366 Array_type::do_hash_for_method(Gogo* gogo) const
7368 unsigned int ret;
7370 // There is no very convenient way to get a hash code for the
7371 // length.
7372 ret = this->element_type_->hash_for_method(gogo) + 1;
7373 if (this->is_array_incomparable_)
7374 ret <<= 1;
7375 return ret;
7378 // Write the hash function for an array which can not use the identify
7379 // function.
7381 void
7382 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7383 Function_type* hash_fntype,
7384 Function_type* equal_fntype)
7386 Location bloc = Linemap::predeclared_location();
7388 // The pointer to the array that we are going to hash. This is an
7389 // argument to the hash function we are implementing here.
7390 Named_object* key_arg = gogo->lookup("key", NULL);
7391 go_assert(key_arg != NULL);
7392 Type* key_arg_type = key_arg->var_value()->type();
7394 // The seed argument to the hash function.
7395 Named_object* seed_arg = gogo->lookup("seed", NULL);
7396 go_assert(seed_arg != NULL);
7398 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7400 // Make a temporary to hold the return value, initialized to the seed.
7401 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7402 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7403 bloc);
7404 gogo->add_statement(retval);
7406 // Make a temporary to hold the key as a uintptr.
7407 ref = Expression::make_var_reference(key_arg, bloc);
7408 ref = Expression::make_cast(uintptr_type, ref, bloc);
7409 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7410 bloc);
7411 gogo->add_statement(key);
7413 // Loop over the array elements.
7414 // for i = range a
7415 Type* int_type = Type::lookup_integer_type("int");
7416 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7417 gogo->add_statement(index);
7419 Expression* iref = Expression::make_temporary_reference(index, bloc);
7420 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7421 Type* pt = Type::make_pointer_type(name != NULL
7422 ? static_cast<Type*>(name)
7423 : static_cast<Type*>(this));
7424 aref = Expression::make_cast(pt, aref, bloc);
7425 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7426 NULL,
7427 aref,
7428 bloc);
7430 gogo->start_block(bloc);
7432 // Get the hash function for the element type.
7433 Named_object* hash_fn;
7434 Named_object* equal_fn;
7435 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7436 hash_fntype, equal_fntype, &hash_fn,
7437 &equal_fn);
7439 // Get a pointer to this element in the loop.
7440 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7441 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7443 // Get the size of each element.
7444 Expression* ele_size = Expression::make_type_info(this->element_type_,
7445 Expression::TYPE_INFO_SIZE);
7447 // Get the hash of this element, passing retval as the seed.
7448 ref = Expression::make_temporary_reference(retval, bloc);
7449 Expression_list* args = new Expression_list();
7450 args->push_back(subkey);
7451 args->push_back(ref);
7452 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7453 Expression* call = Expression::make_call(func, args, false, bloc);
7455 // Set retval to the result.
7456 Temporary_reference_expression* tref =
7457 Expression::make_temporary_reference(retval, bloc);
7458 tref->set_is_lvalue();
7459 Statement* s = Statement::make_assignment(tref, call, bloc);
7460 gogo->add_statement(s);
7462 // Increase the element pointer.
7463 tref = Expression::make_temporary_reference(key, bloc);
7464 tref->set_is_lvalue();
7465 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7466 bloc);
7467 Block* statements = gogo->finish_block(bloc);
7469 for_range->add_statements(statements);
7470 gogo->add_statement(for_range);
7472 // Return retval to the caller of the hash function.
7473 Expression_list* vals = new Expression_list();
7474 ref = Expression::make_temporary_reference(retval, bloc);
7475 vals->push_back(ref);
7476 s = Statement::make_return_statement(vals, bloc);
7477 gogo->add_statement(s);
7480 // Write the equality function for an array which can not use the
7481 // identity function.
7483 void
7484 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7486 Location bloc = Linemap::predeclared_location();
7488 // The pointers to the arrays we are going to compare.
7489 Named_object* key1_arg = gogo->lookup("key1", NULL);
7490 Named_object* key2_arg = gogo->lookup("key2", NULL);
7491 go_assert(key1_arg != NULL && key2_arg != NULL);
7493 // Build temporaries for the keys with the right types.
7494 Type* pt = Type::make_pointer_type(name != NULL
7495 ? static_cast<Type*>(name)
7496 : static_cast<Type*>(this));
7498 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7499 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7500 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7501 gogo->add_statement(p1);
7503 ref = Expression::make_var_reference(key2_arg, bloc);
7504 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7505 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7506 gogo->add_statement(p2);
7508 // Loop over the array elements.
7509 // for i = range a
7510 Type* int_type = Type::lookup_integer_type("int");
7511 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7512 gogo->add_statement(index);
7514 Expression* iref = Expression::make_temporary_reference(index, bloc);
7515 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7516 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7517 NULL,
7518 aref,
7519 bloc);
7521 gogo->start_block(bloc);
7523 // Compare element in P1 and P2.
7524 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7525 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
7526 ref = Expression::make_temporary_reference(index, bloc);
7527 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7529 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7530 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
7531 ref = Expression::make_temporary_reference(index, bloc);
7532 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7534 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7536 // If the elements are not equal, return false.
7537 gogo->start_block(bloc);
7538 Expression_list* vals = new Expression_list();
7539 vals->push_back(Expression::make_boolean(false, bloc));
7540 Statement* s = Statement::make_return_statement(vals, bloc);
7541 gogo->add_statement(s);
7542 Block* then_block = gogo->finish_block(bloc);
7544 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7545 gogo->add_statement(s);
7547 Block* statements = gogo->finish_block(bloc);
7549 for_range->add_statements(statements);
7550 gogo->add_statement(for_range);
7552 // All the elements are equal, so return true.
7553 vals = new Expression_list();
7554 vals->push_back(Expression::make_boolean(true, bloc));
7555 s = Statement::make_return_statement(vals, bloc);
7556 gogo->add_statement(s);
7559 // Get the backend representation of the fields of a slice. This is
7560 // not declared in types.h so that types.h doesn't have to #include
7561 // backend.h.
7563 // We use int for the count and capacity fields. This matches 6g.
7564 // The language more or less assumes that we can't allocate space of a
7565 // size which does not fit in int.
7567 static void
7568 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7569 std::vector<Backend::Btyped_identifier>* bfields)
7571 bfields->resize(3);
7573 Type* pet = Type::make_pointer_type(type->element_type());
7574 Btype* pbet = (use_placeholder
7575 ? pet->get_backend_placeholder(gogo)
7576 : pet->get_backend(gogo));
7577 Location ploc = Linemap::predeclared_location();
7579 Backend::Btyped_identifier* p = &(*bfields)[0];
7580 p->name = "__values";
7581 p->btype = pbet;
7582 p->location = ploc;
7584 Type* int_type = Type::lookup_integer_type("int");
7586 p = &(*bfields)[1];
7587 p->name = "__count";
7588 p->btype = int_type->get_backend(gogo);
7589 p->location = ploc;
7591 p = &(*bfields)[2];
7592 p->name = "__capacity";
7593 p->btype = int_type->get_backend(gogo);
7594 p->location = ploc;
7597 // Get the backend representation for the type of this array. A fixed array is
7598 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7599 // just like an array in C. An open array is a struct with three
7600 // fields: a data pointer, the length, and the capacity.
7602 Btype*
7603 Array_type::do_get_backend(Gogo* gogo)
7605 if (this->length_ == NULL)
7607 std::vector<Backend::Btyped_identifier> bfields;
7608 get_backend_slice_fields(gogo, this, false, &bfields);
7609 return gogo->backend()->struct_type(bfields);
7611 else
7613 Btype* element = this->get_backend_element(gogo, false);
7614 Bexpression* len = this->get_backend_length(gogo);
7615 return gogo->backend()->array_type(element, len);
7619 // Return the backend representation of the element type.
7621 Btype*
7622 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7624 if (use_placeholder)
7625 return this->element_type_->get_backend_placeholder(gogo);
7626 else
7627 return this->element_type_->get_backend(gogo);
7630 // Return the backend representation of the length. The length may be
7631 // computed using a function call, so we must only evaluate it once.
7633 Bexpression*
7634 Array_type::get_backend_length(Gogo* gogo)
7636 go_assert(this->length_ != NULL);
7637 if (this->blength_ == NULL)
7639 Numeric_constant nc;
7640 mpz_t val;
7641 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7643 if (mpz_sgn(val) < 0)
7645 this->blength_ = gogo->backend()->error_expression();
7646 return this->blength_;
7648 Type* t = nc.type();
7649 if (t == NULL)
7650 t = Type::lookup_integer_type("int");
7651 else if (t->is_abstract())
7652 t = t->make_non_abstract_type();
7653 Btype* btype = t->get_backend(gogo);
7654 this->blength_ =
7655 gogo->backend()->integer_constant_expression(btype, val);
7656 mpz_clear(val);
7658 else
7660 // Make up a translation context for the array length
7661 // expression. FIXME: This won't work in general.
7662 Translate_context context(gogo, NULL, NULL, NULL);
7663 this->blength_ = this->length_->get_backend(&context);
7665 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7666 this->blength_ =
7667 gogo->backend()->convert_expression(ibtype, this->blength_,
7668 this->length_->location());
7671 return this->blength_;
7674 // Finish backend representation of the array.
7676 void
7677 Array_type::finish_backend_element(Gogo* gogo)
7679 Type* et = this->array_type()->element_type();
7680 et->get_backend(gogo);
7681 if (this->is_slice_type())
7683 // This relies on the fact that we always use the same
7684 // structure for a pointer to any given type.
7685 Type* pet = Type::make_pointer_type(et);
7686 pet->get_backend(gogo);
7690 // Return an expression for a pointer to the values in ARRAY.
7692 Expression*
7693 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7695 if (this->length() != NULL)
7697 // Fixed array.
7698 go_assert(array->type()->array_type() != NULL);
7699 Type* etype = array->type()->array_type()->element_type();
7700 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7701 return Expression::make_cast(Type::make_pointer_type(etype), array,
7702 array->location());
7705 // Slice.
7707 if (is_lvalue)
7709 Temporary_reference_expression* tref =
7710 array->temporary_reference_expression();
7711 Var_expression* ve = array->var_expression();
7712 if (tref != NULL)
7714 tref = tref->copy()->temporary_reference_expression();
7715 tref->set_is_lvalue();
7716 array = tref;
7718 else if (ve != NULL)
7720 ve = new Var_expression(ve->named_object(), ve->location());
7721 ve->set_in_lvalue_pos();
7722 array = ve;
7726 return Expression::make_slice_info(array,
7727 Expression::SLICE_INFO_VALUE_POINTER,
7728 array->location());
7731 // Return an expression for the length of the array ARRAY which has this
7732 // type.
7734 Expression*
7735 Array_type::get_length(Gogo*, Expression* array) const
7737 if (this->length_ != NULL)
7738 return this->length_;
7740 // This is a slice. We need to read the length field.
7741 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7742 array->location());
7745 // Return an expression for the capacity of the array ARRAY which has this
7746 // type.
7748 Expression*
7749 Array_type::get_capacity(Gogo*, Expression* array) const
7751 if (this->length_ != NULL)
7752 return this->length_;
7754 // This is a slice. We need to read the capacity field.
7755 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7756 array->location());
7759 // Export.
7761 void
7762 Array_type::do_export(Export* exp) const
7764 exp->write_c_string("[");
7765 if (this->length_ != NULL)
7766 this->length_->export_expression(exp);
7767 exp->write_c_string("] ");
7768 exp->write_type(this->element_type_);
7771 // Import.
7773 Array_type*
7774 Array_type::do_import(Import* imp)
7776 imp->require_c_string("[");
7777 Expression* length;
7778 if (imp->peek_char() == ']')
7779 length = NULL;
7780 else
7781 length = Expression::import_expression(imp);
7782 imp->require_c_string("] ");
7783 Type* element_type = imp->read_type();
7784 return Type::make_array_type(element_type, length);
7787 // The type of an array type descriptor.
7789 Type*
7790 Array_type::make_array_type_descriptor_type()
7792 static Type* ret;
7793 if (ret == NULL)
7795 Type* tdt = Type::make_type_descriptor_type();
7796 Type* ptdt = Type::make_type_descriptor_ptr_type();
7798 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7800 Struct_type* sf =
7801 Type::make_builtin_struct_type(4,
7802 "", tdt,
7803 "elem", ptdt,
7804 "slice", ptdt,
7805 "len", uintptr_type);
7807 ret = Type::make_builtin_named_type("ArrayType", sf);
7810 return ret;
7813 // The type of an slice type descriptor.
7815 Type*
7816 Array_type::make_slice_type_descriptor_type()
7818 static Type* ret;
7819 if (ret == NULL)
7821 Type* tdt = Type::make_type_descriptor_type();
7822 Type* ptdt = Type::make_type_descriptor_ptr_type();
7824 Struct_type* sf =
7825 Type::make_builtin_struct_type(2,
7826 "", tdt,
7827 "elem", ptdt);
7829 ret = Type::make_builtin_named_type("SliceType", sf);
7832 return ret;
7835 // Build a type descriptor for an array/slice type.
7837 Expression*
7838 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7840 if (this->length_ != NULL)
7841 return this->array_type_descriptor(gogo, name);
7842 else
7843 return this->slice_type_descriptor(gogo, name);
7846 // Build a type descriptor for an array type.
7848 Expression*
7849 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7851 Location bloc = Linemap::predeclared_location();
7853 Type* atdt = Array_type::make_array_type_descriptor_type();
7855 const Struct_field_list* fields = atdt->struct_type()->fields();
7857 Expression_list* vals = new Expression_list();
7858 vals->reserve(3);
7860 Struct_field_list::const_iterator p = fields->begin();
7861 go_assert(p->is_field_name("_type"));
7862 vals->push_back(this->type_descriptor_constructor(gogo,
7863 RUNTIME_TYPE_KIND_ARRAY,
7864 name, NULL, true));
7866 ++p;
7867 go_assert(p->is_field_name("elem"));
7868 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7870 ++p;
7871 go_assert(p->is_field_name("slice"));
7872 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7873 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7875 ++p;
7876 go_assert(p->is_field_name("len"));
7877 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7879 ++p;
7880 go_assert(p == fields->end());
7882 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7885 // Build a type descriptor for a slice type.
7887 Expression*
7888 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7890 Location bloc = Linemap::predeclared_location();
7892 Type* stdt = Array_type::make_slice_type_descriptor_type();
7894 const Struct_field_list* fields = stdt->struct_type()->fields();
7896 Expression_list* vals = new Expression_list();
7897 vals->reserve(2);
7899 Struct_field_list::const_iterator p = fields->begin();
7900 go_assert(p->is_field_name("_type"));
7901 vals->push_back(this->type_descriptor_constructor(gogo,
7902 RUNTIME_TYPE_KIND_SLICE,
7903 name, NULL, true));
7905 ++p;
7906 go_assert(p->is_field_name("elem"));
7907 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7909 ++p;
7910 go_assert(p == fields->end());
7912 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7915 // Reflection string.
7917 void
7918 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7920 ret->push_back('[');
7921 if (this->length_ != NULL)
7923 Numeric_constant nc;
7924 if (!this->length_->numeric_constant_value(&nc))
7926 go_assert(saw_errors());
7927 return;
7929 mpz_t val;
7930 if (!nc.to_int(&val))
7932 go_assert(saw_errors());
7933 return;
7935 char* s = mpz_get_str(NULL, 10, val);
7936 ret->append(s);
7937 free(s);
7938 mpz_clear(val);
7940 ret->push_back(']');
7942 this->append_reflection(this->element_type_, gogo, ret);
7945 // Mangled name.
7947 void
7948 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7950 ret->push_back('A');
7951 this->append_mangled_name(this->element_type_, gogo, ret);
7952 if (this->length_ != NULL)
7954 Numeric_constant nc;
7955 if (!this->length_->numeric_constant_value(&nc))
7957 go_assert(saw_errors());
7958 return;
7960 mpz_t val;
7961 if (!nc.to_int(&val))
7963 go_assert(saw_errors());
7964 return;
7966 char *s = mpz_get_str(NULL, 10, val);
7967 ret->append(s);
7968 free(s);
7969 mpz_clear(val);
7970 if (this->is_array_incomparable_)
7971 ret->push_back('x');
7973 ret->push_back('e');
7976 // Make an array type.
7978 Array_type*
7979 Type::make_array_type(Type* element_type, Expression* length)
7981 return new Array_type(element_type, length);
7984 // Class Map_type.
7986 Named_object* Map_type::zero_value;
7987 int64_t Map_type::zero_value_size;
7988 int64_t Map_type::zero_value_align;
7990 // If this map requires the "fat" functions, return the pointer to
7991 // pass as the zero value to those functions. Otherwise, in the
7992 // normal case, return NULL. The map requires the "fat" functions if
7993 // the value size is larger than max_zero_size bytes. max_zero_size
7994 // must match maxZero in libgo/go/runtime/hashmap.go.
7996 Expression*
7997 Map_type::fat_zero_value(Gogo* gogo)
7999 int64_t valsize;
8000 if (!this->val_type_->backend_type_size(gogo, &valsize))
8002 go_assert(saw_errors());
8003 return NULL;
8005 if (valsize <= Map_type::max_zero_size)
8006 return NULL;
8008 if (Map_type::zero_value_size < valsize)
8009 Map_type::zero_value_size = valsize;
8011 int64_t valalign;
8012 if (!this->val_type_->backend_type_align(gogo, &valalign))
8014 go_assert(saw_errors());
8015 return NULL;
8018 if (Map_type::zero_value_align < valalign)
8019 Map_type::zero_value_align = valalign;
8021 Location bloc = Linemap::predeclared_location();
8023 if (Map_type::zero_value == NULL)
8025 // The final type will be set in backend_zero_value.
8026 Type* uint8_type = Type::lookup_integer_type("uint8");
8027 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
8028 Array_type* array_type = Type::make_array_type(uint8_type, size);
8029 array_type->set_is_array_incomparable();
8030 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
8031 Map_type::zero_value = Named_object::make_variable("go$zerovalue", NULL,
8032 var);
8035 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
8036 z = Expression::make_unary(OPERATOR_AND, z, bloc);
8037 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8038 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
8039 return z;
8042 // Return whether VAR is the map zero value.
8044 bool
8045 Map_type::is_zero_value(Variable* var)
8047 return (Map_type::zero_value != NULL
8048 && Map_type::zero_value->var_value() == var);
8051 // Return the backend representation for the zero value.
8053 Bvariable*
8054 Map_type::backend_zero_value(Gogo* gogo)
8056 Location bloc = Linemap::predeclared_location();
8058 go_assert(Map_type::zero_value != NULL);
8060 Type* uint8_type = Type::lookup_integer_type("uint8");
8061 Btype* buint8_type = uint8_type->get_backend(gogo);
8063 Type* int_type = Type::lookup_integer_type("int");
8065 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
8066 int_type, bloc);
8067 Translate_context context(gogo, NULL, NULL, NULL);
8068 Bexpression* blength = e->get_backend(&context);
8070 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
8072 std::string zname = Map_type::zero_value->name();
8073 std::string asm_name(go_selectively_encode_id(zname));
8074 Bvariable* zvar =
8075 gogo->backend()->implicit_variable(zname, asm_name,
8076 barray_type, false, true, true,
8077 Map_type::zero_value_align);
8078 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
8079 false, true, true, NULL);
8080 return zvar;
8083 // Traversal.
8086 Map_type::do_traverse(Traverse* traverse)
8088 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
8089 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
8090 return TRAVERSE_EXIT;
8091 return TRAVERSE_CONTINUE;
8094 // Check that the map type is OK.
8096 bool
8097 Map_type::do_verify()
8099 // The runtime support uses "map[void]void".
8100 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
8101 go_error_at(this->location_, "invalid map key type");
8102 if (!this->key_type_->in_heap())
8103 go_error_at(this->location_, "go:notinheap map key not allowed");
8104 if (!this->val_type_->in_heap())
8105 go_error_at(this->location_, "go:notinheap map value not allowed");
8106 return true;
8109 // Whether two map types are identical.
8111 bool
8112 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
8113 bool errors_are_identical) const
8115 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
8116 cmp_tags, errors_are_identical, NULL)
8117 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
8118 cmp_tags, errors_are_identical,
8119 NULL));
8122 // Hash code.
8124 unsigned int
8125 Map_type::do_hash_for_method(Gogo* gogo) const
8127 return (this->key_type_->hash_for_method(gogo)
8128 + this->val_type_->hash_for_method(gogo)
8129 + 2);
8132 // Get the backend representation for a map type. A map type is
8133 // represented as a pointer to a struct. The struct is hmap in
8134 // runtime/hashmap.go.
8136 Btype*
8137 Map_type::do_get_backend(Gogo* gogo)
8139 static Btype* backend_map_type;
8140 if (backend_map_type == NULL)
8142 std::vector<Backend::Btyped_identifier> bfields(9);
8144 Location bloc = Linemap::predeclared_location();
8146 Type* int_type = Type::lookup_integer_type("int");
8147 bfields[0].name = "count";
8148 bfields[0].btype = int_type->get_backend(gogo);
8149 bfields[0].location = bloc;
8151 Type* uint8_type = Type::lookup_integer_type("uint8");
8152 bfields[1].name = "flags";
8153 bfields[1].btype = uint8_type->get_backend(gogo);
8154 bfields[1].location = bloc;
8156 bfields[2].name = "B";
8157 bfields[2].btype = bfields[1].btype;
8158 bfields[2].location = bloc;
8160 Type* uint16_type = Type::lookup_integer_type("uint16");
8161 bfields[3].name = "noverflow";
8162 bfields[3].btype = uint16_type->get_backend(gogo);
8163 bfields[3].location = bloc;
8165 Type* uint32_type = Type::lookup_integer_type("uint32");
8166 bfields[4].name = "hash0";
8167 bfields[4].btype = uint32_type->get_backend(gogo);
8168 bfields[4].location = bloc;
8170 Btype* bvt = gogo->backend()->void_type();
8171 Btype* bpvt = gogo->backend()->pointer_type(bvt);
8172 bfields[5].name = "buckets";
8173 bfields[5].btype = bpvt;
8174 bfields[5].location = bloc;
8176 bfields[6].name = "oldbuckets";
8177 bfields[6].btype = bpvt;
8178 bfields[6].location = bloc;
8180 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8181 bfields[7].name = "nevacuate";
8182 bfields[7].btype = uintptr_type->get_backend(gogo);
8183 bfields[7].location = bloc;
8185 bfields[8].name = "overflow";
8186 bfields[8].btype = bpvt;
8187 bfields[8].location = bloc;
8189 Btype *bt = gogo->backend()->struct_type(bfields);
8190 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
8191 backend_map_type = gogo->backend()->pointer_type(bt);
8193 return backend_map_type;
8196 // The type of a map type descriptor.
8198 Type*
8199 Map_type::make_map_type_descriptor_type()
8201 static Type* ret;
8202 if (ret == NULL)
8204 Type* tdt = Type::make_type_descriptor_type();
8205 Type* ptdt = Type::make_type_descriptor_ptr_type();
8206 Type* uint8_type = Type::lookup_integer_type("uint8");
8207 Type* uint16_type = Type::lookup_integer_type("uint16");
8208 Type* bool_type = Type::lookup_bool_type();
8210 Struct_type* sf =
8211 Type::make_builtin_struct_type(12,
8212 "", tdt,
8213 "key", ptdt,
8214 "elem", ptdt,
8215 "bucket", ptdt,
8216 "hmap", ptdt,
8217 "keysize", uint8_type,
8218 "indirectkey", bool_type,
8219 "valuesize", uint8_type,
8220 "indirectvalue", bool_type,
8221 "bucketsize", uint16_type,
8222 "reflexivekey", bool_type,
8223 "needkeyupdate", bool_type);
8225 ret = Type::make_builtin_named_type("MapType", sf);
8228 return ret;
8231 // Build a type descriptor for a map type.
8233 Expression*
8234 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8236 Location bloc = Linemap::predeclared_location();
8238 Type* mtdt = Map_type::make_map_type_descriptor_type();
8239 Type* uint8_type = Type::lookup_integer_type("uint8");
8240 Type* uint16_type = Type::lookup_integer_type("uint16");
8242 int64_t keysize;
8243 if (!this->key_type_->backend_type_size(gogo, &keysize))
8245 go_error_at(this->location_, "error determining map key type size");
8246 return Expression::make_error(this->location_);
8249 int64_t valsize;
8250 if (!this->val_type_->backend_type_size(gogo, &valsize))
8252 go_error_at(this->location_, "error determining map value type size");
8253 return Expression::make_error(this->location_);
8256 int64_t ptrsize;
8257 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8259 go_assert(saw_errors());
8260 return Expression::make_error(this->location_);
8263 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8264 if (bucket_type == NULL)
8266 go_assert(saw_errors());
8267 return Expression::make_error(this->location_);
8270 int64_t bucketsize;
8271 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8273 go_assert(saw_errors());
8274 return Expression::make_error(this->location_);
8277 const Struct_field_list* fields = mtdt->struct_type()->fields();
8279 Expression_list* vals = new Expression_list();
8280 vals->reserve(12);
8282 Struct_field_list::const_iterator p = fields->begin();
8283 go_assert(p->is_field_name("_type"));
8284 vals->push_back(this->type_descriptor_constructor(gogo,
8285 RUNTIME_TYPE_KIND_MAP,
8286 name, NULL, true));
8288 ++p;
8289 go_assert(p->is_field_name("key"));
8290 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8292 ++p;
8293 go_assert(p->is_field_name("elem"));
8294 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8296 ++p;
8297 go_assert(p->is_field_name("bucket"));
8298 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8300 ++p;
8301 go_assert(p->is_field_name("hmap"));
8302 Type* hmap_type = this->hmap_type(bucket_type);
8303 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8305 ++p;
8306 go_assert(p->is_field_name("keysize"));
8307 if (keysize > Map_type::max_key_size)
8308 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8309 else
8310 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8312 ++p;
8313 go_assert(p->is_field_name("indirectkey"));
8314 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8315 bloc));
8317 ++p;
8318 go_assert(p->is_field_name("valuesize"));
8319 if (valsize > Map_type::max_val_size)
8320 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8321 else
8322 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8324 ++p;
8325 go_assert(p->is_field_name("indirectvalue"));
8326 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8327 bloc));
8329 ++p;
8330 go_assert(p->is_field_name("bucketsize"));
8331 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8332 bloc));
8334 ++p;
8335 go_assert(p->is_field_name("reflexivekey"));
8336 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8337 bloc));
8339 ++p;
8340 go_assert(p->is_field_name("needkeyupdate"));
8341 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8342 bloc));
8344 ++p;
8345 go_assert(p == fields->end());
8347 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8350 // Return the bucket type to use for a map type. This must correspond
8351 // to libgo/go/runtime/hashmap.go.
8353 Type*
8354 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8356 if (this->bucket_type_ != NULL)
8357 return this->bucket_type_;
8359 Type* key_type = this->key_type_;
8360 if (keysize > Map_type::max_key_size)
8361 key_type = Type::make_pointer_type(key_type);
8363 Type* val_type = this->val_type_;
8364 if (valsize > Map_type::max_val_size)
8365 val_type = Type::make_pointer_type(val_type);
8367 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8368 NULL, this->location_);
8370 Type* uint8_type = Type::lookup_integer_type("uint8");
8371 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8372 topbits_type->set_is_array_incomparable();
8373 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8374 keys_type->set_is_array_incomparable();
8375 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8376 values_type->set_is_array_incomparable();
8378 // If keys and values have no pointers, the map implementation can
8379 // keep a list of overflow pointers on the side so that buckets can
8380 // be marked as having no pointers. Arrange for the bucket to have
8381 // no pointers by changing the type of the overflow field to uintptr
8382 // in this case. See comment on the hmap.overflow field in
8383 // libgo/go/runtime/hashmap.go.
8384 Type* overflow_type;
8385 if (!key_type->has_pointer() && !val_type->has_pointer())
8386 overflow_type = Type::lookup_integer_type("uintptr");
8387 else
8389 // This should really be a pointer to the bucket type itself,
8390 // but that would require us to construct a Named_type for it to
8391 // give it a way to refer to itself. Since nothing really cares
8392 // (except perhaps for someone using a debugger) just use an
8393 // unsafe pointer.
8394 overflow_type = Type::make_pointer_type(Type::make_void_type());
8397 // Make sure the overflow pointer is the last memory in the struct,
8398 // because the runtime assumes it can use size-ptrSize as the offset
8399 // of the overflow pointer. We double-check that property below
8400 // once the offsets and size are computed.
8402 int64_t topbits_field_size, topbits_field_align;
8403 int64_t keys_field_size, keys_field_align;
8404 int64_t values_field_size, values_field_align;
8405 int64_t overflow_field_size, overflow_field_align;
8406 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8407 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8408 || !keys_type->backend_type_size(gogo, &keys_field_size)
8409 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8410 || !values_type->backend_type_size(gogo, &values_field_size)
8411 || !values_type->backend_type_field_align(gogo, &values_field_align)
8412 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8413 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8415 go_assert(saw_errors());
8416 return NULL;
8419 Struct_type* ret;
8420 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8421 values_field_align);
8422 if (max_align <= overflow_field_align)
8423 ret = make_builtin_struct_type(4,
8424 "topbits", topbits_type,
8425 "keys", keys_type,
8426 "values", values_type,
8427 "overflow", overflow_type);
8428 else
8430 size_t off = topbits_field_size;
8431 off = ((off + keys_field_align - 1)
8432 &~ static_cast<size_t>(keys_field_align - 1));
8433 off += keys_field_size;
8434 off = ((off + values_field_align - 1)
8435 &~ static_cast<size_t>(values_field_align - 1));
8436 off += values_field_size;
8438 int64_t padded_overflow_field_size =
8439 ((overflow_field_size + max_align - 1)
8440 &~ static_cast<size_t>(max_align - 1));
8442 size_t ovoff = off;
8443 ovoff = ((ovoff + max_align - 1)
8444 &~ static_cast<size_t>(max_align - 1));
8445 size_t pad = (ovoff - off
8446 + padded_overflow_field_size - overflow_field_size);
8448 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8449 this->location_);
8450 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8451 pad_type->set_is_array_incomparable();
8453 ret = make_builtin_struct_type(5,
8454 "topbits", topbits_type,
8455 "keys", keys_type,
8456 "values", values_type,
8457 "pad", pad_type,
8458 "overflow", overflow_type);
8461 // Verify that the overflow field is just before the end of the
8462 // bucket type.
8464 Btype* btype = ret->get_backend(gogo);
8465 int64_t offset = gogo->backend()->type_field_offset(btype,
8466 ret->field_count() - 1);
8467 int64_t size;
8468 if (!ret->backend_type_size(gogo, &size))
8470 go_assert(saw_errors());
8471 return NULL;
8474 int64_t ptr_size;
8475 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8477 go_assert(saw_errors());
8478 return NULL;
8481 go_assert(offset + ptr_size == size);
8483 ret->set_is_struct_incomparable();
8485 this->bucket_type_ = ret;
8486 return ret;
8489 // Return the hashmap type for a map type.
8491 Type*
8492 Map_type::hmap_type(Type* bucket_type)
8494 if (this->hmap_type_ != NULL)
8495 return this->hmap_type_;
8497 Type* int_type = Type::lookup_integer_type("int");
8498 Type* uint8_type = Type::lookup_integer_type("uint8");
8499 Type* uint32_type = Type::lookup_integer_type("uint32");
8500 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8501 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8503 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8505 Struct_type* ret = make_builtin_struct_type(8,
8506 "count", int_type,
8507 "flags", uint8_type,
8508 "B", uint8_type,
8509 "hash0", uint32_type,
8510 "buckets", ptr_bucket_type,
8511 "oldbuckets", ptr_bucket_type,
8512 "nevacuate", uintptr_type,
8513 "overflow", void_ptr_type);
8514 ret->set_is_struct_incomparable();
8515 this->hmap_type_ = ret;
8516 return ret;
8519 // Return the iterator type for a map type. This is the type of the
8520 // value used when doing a range over a map.
8522 Type*
8523 Map_type::hiter_type(Gogo* gogo)
8525 if (this->hiter_type_ != NULL)
8526 return this->hiter_type_;
8528 int64_t keysize, valsize;
8529 if (!this->key_type_->backend_type_size(gogo, &keysize)
8530 || !this->val_type_->backend_type_size(gogo, &valsize))
8532 go_assert(saw_errors());
8533 return NULL;
8536 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8537 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8538 Type* uint8_type = Type::lookup_integer_type("uint8");
8539 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8540 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8541 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8542 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8543 Type* hmap_type = this->hmap_type(bucket_type);
8544 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8545 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8547 Struct_type* ret = make_builtin_struct_type(12,
8548 "key", key_ptr_type,
8549 "val", val_ptr_type,
8550 "t", uint8_ptr_type,
8551 "h", hmap_ptr_type,
8552 "buckets", bucket_ptr_type,
8553 "bptr", bucket_ptr_type,
8554 "overflow0", void_ptr_type,
8555 "overflow1", void_ptr_type,
8556 "startBucket", uintptr_type,
8557 "stuff", uintptr_type,
8558 "bucket", uintptr_type,
8559 "checkBucket", uintptr_type);
8560 ret->set_is_struct_incomparable();
8561 this->hiter_type_ = ret;
8562 return ret;
8565 // Reflection string for a map.
8567 void
8568 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8570 ret->append("map[");
8571 this->append_reflection(this->key_type_, gogo, ret);
8572 ret->append("]");
8573 this->append_reflection(this->val_type_, gogo, ret);
8576 // Mangled name for a map.
8578 void
8579 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8581 ret->push_back('M');
8582 this->append_mangled_name(this->key_type_, gogo, ret);
8583 ret->append("__");
8584 this->append_mangled_name(this->val_type_, gogo, ret);
8587 // Export a map type.
8589 void
8590 Map_type::do_export(Export* exp) const
8592 exp->write_c_string("map [");
8593 exp->write_type(this->key_type_);
8594 exp->write_c_string("] ");
8595 exp->write_type(this->val_type_);
8598 // Import a map type.
8600 Map_type*
8601 Map_type::do_import(Import* imp)
8603 imp->require_c_string("map [");
8604 Type* key_type = imp->read_type();
8605 imp->require_c_string("] ");
8606 Type* val_type = imp->read_type();
8607 return Type::make_map_type(key_type, val_type, imp->location());
8610 // Make a map type.
8612 Map_type*
8613 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8615 return new Map_type(key_type, val_type, location);
8618 // Class Channel_type.
8620 // Verify.
8622 bool
8623 Channel_type::do_verify()
8625 // We have no location for this error, but this is not something the
8626 // ordinary user will see.
8627 if (!this->element_type_->in_heap())
8628 go_error_at(Linemap::unknown_location(),
8629 "chan of go:notinheap type not allowed");
8630 return true;
8633 // Hash code.
8635 unsigned int
8636 Channel_type::do_hash_for_method(Gogo* gogo) const
8638 unsigned int ret = 0;
8639 if (this->may_send_)
8640 ret += 1;
8641 if (this->may_receive_)
8642 ret += 2;
8643 if (this->element_type_ != NULL)
8644 ret += this->element_type_->hash_for_method(gogo) << 2;
8645 return ret << 3;
8648 // Whether this type is the same as T.
8650 bool
8651 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8652 bool errors_are_identical) const
8654 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8655 cmp_tags, errors_are_identical, NULL))
8656 return false;
8657 return (this->may_send_ == t->may_send_
8658 && this->may_receive_ == t->may_receive_);
8661 // Return the backend representation for a channel type. A channel is a pointer
8662 // to a __go_channel struct. The __go_channel struct is defined in
8663 // libgo/runtime/channel.h.
8665 Btype*
8666 Channel_type::do_get_backend(Gogo* gogo)
8668 static Btype* backend_channel_type;
8669 if (backend_channel_type == NULL)
8671 std::vector<Backend::Btyped_identifier> bfields;
8672 Btype* bt = gogo->backend()->struct_type(bfields);
8673 bt = gogo->backend()->named_type("__go_channel", bt,
8674 Linemap::predeclared_location());
8675 backend_channel_type = gogo->backend()->pointer_type(bt);
8677 return backend_channel_type;
8680 // Build a type descriptor for a channel type.
8682 Type*
8683 Channel_type::make_chan_type_descriptor_type()
8685 static Type* ret;
8686 if (ret == NULL)
8688 Type* tdt = Type::make_type_descriptor_type();
8689 Type* ptdt = Type::make_type_descriptor_ptr_type();
8691 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8693 Struct_type* sf =
8694 Type::make_builtin_struct_type(3,
8695 "", tdt,
8696 "elem", ptdt,
8697 "dir", uintptr_type);
8699 ret = Type::make_builtin_named_type("ChanType", sf);
8702 return ret;
8705 // Build a type descriptor for a map type.
8707 Expression*
8708 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8710 Location bloc = Linemap::predeclared_location();
8712 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8714 const Struct_field_list* fields = ctdt->struct_type()->fields();
8716 Expression_list* vals = new Expression_list();
8717 vals->reserve(3);
8719 Struct_field_list::const_iterator p = fields->begin();
8720 go_assert(p->is_field_name("_type"));
8721 vals->push_back(this->type_descriptor_constructor(gogo,
8722 RUNTIME_TYPE_KIND_CHAN,
8723 name, NULL, true));
8725 ++p;
8726 go_assert(p->is_field_name("elem"));
8727 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8729 ++p;
8730 go_assert(p->is_field_name("dir"));
8731 // These bits must match the ones in libgo/runtime/go-type.h.
8732 int val = 0;
8733 if (this->may_receive_)
8734 val |= 1;
8735 if (this->may_send_)
8736 val |= 2;
8737 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8739 ++p;
8740 go_assert(p == fields->end());
8742 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8745 // Reflection string.
8747 void
8748 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8750 if (!this->may_send_)
8751 ret->append("<-");
8752 ret->append("chan");
8753 if (!this->may_receive_)
8754 ret->append("<-");
8755 ret->push_back(' ');
8756 this->append_reflection(this->element_type_, gogo, ret);
8759 // Mangled name.
8761 void
8762 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8764 ret->push_back('C');
8765 this->append_mangled_name(this->element_type_, gogo, ret);
8766 if (this->may_send_)
8767 ret->push_back('s');
8768 if (this->may_receive_)
8769 ret->push_back('r');
8770 ret->push_back('e');
8773 // Export.
8775 void
8776 Channel_type::do_export(Export* exp) const
8778 exp->write_c_string("chan ");
8779 if (this->may_send_ && !this->may_receive_)
8780 exp->write_c_string("-< ");
8781 else if (this->may_receive_ && !this->may_send_)
8782 exp->write_c_string("<- ");
8783 exp->write_type(this->element_type_);
8786 // Import.
8788 Channel_type*
8789 Channel_type::do_import(Import* imp)
8791 imp->require_c_string("chan ");
8793 bool may_send;
8794 bool may_receive;
8795 if (imp->match_c_string("-< "))
8797 imp->advance(3);
8798 may_send = true;
8799 may_receive = false;
8801 else if (imp->match_c_string("<- "))
8803 imp->advance(3);
8804 may_receive = true;
8805 may_send = false;
8807 else
8809 may_send = true;
8810 may_receive = true;
8813 Type* element_type = imp->read_type();
8815 return Type::make_channel_type(may_send, may_receive, element_type);
8818 // Return the type to manage a select statement with ncases case
8819 // statements. A value of this type is allocated on the stack. This
8820 // must match the type hselect in libgo/go/runtime/select.go.
8822 Type*
8823 Channel_type::select_type(int ncases)
8825 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8826 Type* uint16_type = Type::lookup_integer_type("uint16");
8828 static Struct_type* scase_type;
8829 if (scase_type == NULL)
8831 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8832 Type* uint64_type = Type::lookup_integer_type("uint64");
8833 scase_type =
8834 Type::make_builtin_struct_type(7,
8835 "elem", unsafe_pointer_type,
8836 "chan", unsafe_pointer_type,
8837 "pc", uintptr_type,
8838 "kind", uint16_type,
8839 "index", uint16_type,
8840 "receivedp", unsafe_pointer_type,
8841 "releasetime", uint64_type);
8842 scase_type->set_is_struct_incomparable();
8845 Expression* ncases_expr =
8846 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8847 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8848 scases->set_is_array_incomparable();
8849 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8850 order->set_is_array_incomparable();
8852 Struct_type* ret =
8853 Type::make_builtin_struct_type(7,
8854 "tcase", uint16_type,
8855 "ncase", uint16_type,
8856 "pollorder", unsafe_pointer_type,
8857 "lockorder", unsafe_pointer_type,
8858 "scase", scases,
8859 "lockorderarr", order,
8860 "pollorderarr", order);
8861 ret->set_is_struct_incomparable();
8862 return ret;
8865 // Make a new channel type.
8867 Channel_type*
8868 Type::make_channel_type(bool send, bool receive, Type* element_type)
8870 return new Channel_type(send, receive, element_type);
8873 // Class Interface_type.
8875 // Return the list of methods.
8877 const Typed_identifier_list*
8878 Interface_type::methods() const
8880 go_assert(this->methods_are_finalized_ || saw_errors());
8881 return this->all_methods_;
8884 // Return the number of methods.
8886 size_t
8887 Interface_type::method_count() const
8889 go_assert(this->methods_are_finalized_ || saw_errors());
8890 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8893 // Traversal.
8896 Interface_type::do_traverse(Traverse* traverse)
8898 Typed_identifier_list* methods = (this->methods_are_finalized_
8899 ? this->all_methods_
8900 : this->parse_methods_);
8901 if (methods == NULL)
8902 return TRAVERSE_CONTINUE;
8903 return methods->traverse(traverse);
8906 // Finalize the methods. This handles interface inheritance.
8908 void
8909 Interface_type::finalize_methods()
8911 if (this->methods_are_finalized_)
8912 return;
8913 this->methods_are_finalized_ = true;
8914 if (this->parse_methods_ == NULL)
8915 return;
8917 this->all_methods_ = new Typed_identifier_list();
8918 this->all_methods_->reserve(this->parse_methods_->size());
8919 Typed_identifier_list inherit;
8920 for (Typed_identifier_list::const_iterator pm =
8921 this->parse_methods_->begin();
8922 pm != this->parse_methods_->end();
8923 ++pm)
8925 const Typed_identifier* p = &*pm;
8926 if (p->name().empty())
8927 inherit.push_back(*p);
8928 else if (this->find_method(p->name()) == NULL)
8929 this->all_methods_->push_back(*p);
8930 else
8931 go_error_at(p->location(), "duplicate method %qs",
8932 Gogo::message_name(p->name()).c_str());
8935 std::vector<Named_type*> seen;
8936 seen.reserve(inherit.size());
8937 bool issued_recursive_error = false;
8938 while (!inherit.empty())
8940 Type* t = inherit.back().type();
8941 Location tl = inherit.back().location();
8942 inherit.pop_back();
8944 Interface_type* it = t->interface_type();
8945 if (it == NULL)
8947 if (!t->is_error())
8948 go_error_at(tl, "interface contains embedded non-interface");
8949 continue;
8951 if (it == this)
8953 if (!issued_recursive_error)
8955 go_error_at(tl, "invalid recursive interface");
8956 issued_recursive_error = true;
8958 continue;
8961 Named_type* nt = t->named_type();
8962 if (nt != NULL && it->parse_methods_ != NULL)
8964 std::vector<Named_type*>::const_iterator q;
8965 for (q = seen.begin(); q != seen.end(); ++q)
8967 if (*q == nt)
8969 go_error_at(tl, "inherited interface loop");
8970 break;
8973 if (q != seen.end())
8974 continue;
8975 seen.push_back(nt);
8978 const Typed_identifier_list* imethods = it->parse_methods_;
8979 if (imethods == NULL)
8980 continue;
8981 for (Typed_identifier_list::const_iterator q = imethods->begin();
8982 q != imethods->end();
8983 ++q)
8985 if (q->name().empty())
8986 inherit.push_back(*q);
8987 else if (this->find_method(q->name()) == NULL)
8988 this->all_methods_->push_back(Typed_identifier(q->name(),
8989 q->type(), tl));
8990 else
8991 go_error_at(tl, "inherited method %qs is ambiguous",
8992 Gogo::message_name(q->name()).c_str());
8996 if (!this->all_methods_->empty())
8997 this->all_methods_->sort_by_name();
8998 else
9000 delete this->all_methods_;
9001 this->all_methods_ = NULL;
9005 // Return the method NAME, or NULL.
9007 const Typed_identifier*
9008 Interface_type::find_method(const std::string& name) const
9010 go_assert(this->methods_are_finalized_);
9011 if (this->all_methods_ == NULL)
9012 return NULL;
9013 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9014 p != this->all_methods_->end();
9015 ++p)
9016 if (p->name() == name)
9017 return &*p;
9018 return NULL;
9021 // Return the method index.
9023 size_t
9024 Interface_type::method_index(const std::string& name) const
9026 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
9027 size_t ret = 0;
9028 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9029 p != this->all_methods_->end();
9030 ++p, ++ret)
9031 if (p->name() == name)
9032 return ret;
9033 go_unreachable();
9036 // Return whether NAME is an unexported method, for better error
9037 // reporting.
9039 bool
9040 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
9042 go_assert(this->methods_are_finalized_);
9043 if (this->all_methods_ == NULL)
9044 return false;
9045 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9046 p != this->all_methods_->end();
9047 ++p)
9049 const std::string& method_name(p->name());
9050 if (Gogo::is_hidden_name(method_name)
9051 && name == Gogo::unpack_hidden_name(method_name)
9052 && gogo->pack_hidden_name(name, false) != method_name)
9053 return true;
9055 return false;
9058 // Whether this type is identical with T.
9060 bool
9061 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
9062 bool errors_are_identical) const
9064 // If methods have not been finalized, then we are asking whether
9065 // func redeclarations are the same. This is an error, so for
9066 // simplicity we say they are never the same.
9067 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
9068 return false;
9070 // We require the same methods with the same types. The methods
9071 // have already been sorted.
9072 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
9073 return this->all_methods_ == t->all_methods_;
9075 if (this->assume_identical(this, t) || t->assume_identical(t, this))
9076 return true;
9078 Assume_identical* hold_ai = this->assume_identical_;
9079 Assume_identical ai;
9080 ai.t1 = this;
9081 ai.t2 = t;
9082 ai.next = hold_ai;
9083 this->assume_identical_ = &ai;
9085 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
9086 Typed_identifier_list::const_iterator p2;
9087 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
9089 if (p1 == this->all_methods_->end())
9090 break;
9091 if (p1->name() != p2->name()
9092 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
9093 errors_are_identical, NULL))
9094 break;
9097 this->assume_identical_ = hold_ai;
9099 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
9102 // Return true if T1 and T2 are assumed to be identical during a type
9103 // comparison.
9105 bool
9106 Interface_type::assume_identical(const Interface_type* t1,
9107 const Interface_type* t2) const
9109 for (Assume_identical* p = this->assume_identical_;
9110 p != NULL;
9111 p = p->next)
9112 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
9113 return true;
9114 return false;
9117 // Whether we can assign the interface type T to this type. The types
9118 // are known to not be identical. An interface assignment is only
9119 // permitted if T is known to implement all methods in THIS.
9120 // Otherwise a type guard is required.
9122 bool
9123 Interface_type::is_compatible_for_assign(const Interface_type* t,
9124 std::string* reason) const
9126 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
9127 if (this->all_methods_ == NULL)
9128 return true;
9129 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9130 p != this->all_methods_->end();
9131 ++p)
9133 const Typed_identifier* m = t->find_method(p->name());
9134 if (m == NULL)
9136 if (reason != NULL)
9138 char buf[200];
9139 snprintf(buf, sizeof buf,
9140 _("need explicit conversion; missing method %s%s%s"),
9141 go_open_quote(), Gogo::message_name(p->name()).c_str(),
9142 go_close_quote());
9143 reason->assign(buf);
9145 return false;
9148 std::string subreason;
9149 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
9151 if (reason != NULL)
9153 std::string n = Gogo::message_name(p->name());
9154 size_t len = 100 + n.length() + subreason.length();
9155 char* buf = new char[len];
9156 if (subreason.empty())
9157 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9158 go_open_quote(), n.c_str(), go_close_quote());
9159 else
9160 snprintf(buf, len,
9161 _("incompatible type for method %s%s%s (%s)"),
9162 go_open_quote(), n.c_str(), go_close_quote(),
9163 subreason.c_str());
9164 reason->assign(buf);
9165 delete[] buf;
9167 return false;
9171 return true;
9174 // Hash code.
9176 unsigned int
9177 Interface_type::do_hash_for_method(Gogo*) const
9179 go_assert(this->methods_are_finalized_);
9180 unsigned int ret = 0;
9181 if (this->all_methods_ != NULL)
9183 for (Typed_identifier_list::const_iterator p =
9184 this->all_methods_->begin();
9185 p != this->all_methods_->end();
9186 ++p)
9188 ret = Type::hash_string(p->name(), ret);
9189 // We don't use the method type in the hash, to avoid
9190 // infinite recursion if an interface method uses a type
9191 // which is an interface which inherits from the interface
9192 // itself.
9193 // type T interface { F() interface {T}}
9194 ret <<= 1;
9197 return ret;
9200 // Return true if T implements the interface. If it does not, and
9201 // REASON is not NULL, set *REASON to a useful error message.
9203 bool
9204 Interface_type::implements_interface(const Type* t, std::string* reason) const
9206 go_assert(this->methods_are_finalized_);
9207 if (this->all_methods_ == NULL)
9208 return true;
9210 bool is_pointer = false;
9211 const Named_type* nt = t->named_type();
9212 const Struct_type* st = t->struct_type();
9213 // If we start with a named type, we don't dereference it to find
9214 // methods.
9215 if (nt == NULL)
9217 const Type* pt = t->points_to();
9218 if (pt != NULL)
9220 // If T is a pointer to a named type, then we need to look at
9221 // the type to which it points.
9222 is_pointer = true;
9223 nt = pt->named_type();
9224 st = pt->struct_type();
9228 // If we have a named type, get the methods from it rather than from
9229 // any struct type.
9230 if (nt != NULL)
9231 st = NULL;
9233 // Only named and struct types have methods.
9234 if (nt == NULL && st == NULL)
9236 if (reason != NULL)
9238 if (t->points_to() != NULL
9239 && t->points_to()->interface_type() != NULL)
9240 reason->assign(_("pointer to interface type has no methods"));
9241 else
9242 reason->assign(_("type has no methods"));
9244 return false;
9247 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
9249 if (reason != NULL)
9251 if (t->points_to() != NULL
9252 && t->points_to()->interface_type() != NULL)
9253 reason->assign(_("pointer to interface type has no methods"));
9254 else
9255 reason->assign(_("type has no methods"));
9257 return false;
9260 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9261 p != this->all_methods_->end();
9262 ++p)
9264 bool is_ambiguous = false;
9265 Method* m = (nt != NULL
9266 ? nt->method_function(p->name(), &is_ambiguous)
9267 : st->method_function(p->name(), &is_ambiguous));
9268 if (m == NULL)
9270 if (reason != NULL)
9272 std::string n = Gogo::message_name(p->name());
9273 size_t len = n.length() + 100;
9274 char* buf = new char[len];
9275 if (is_ambiguous)
9276 snprintf(buf, len, _("ambiguous method %s%s%s"),
9277 go_open_quote(), n.c_str(), go_close_quote());
9278 else
9279 snprintf(buf, len, _("missing method %s%s%s"),
9280 go_open_quote(), n.c_str(), go_close_quote());
9281 reason->assign(buf);
9282 delete[] buf;
9284 return false;
9287 Function_type *p_fn_type = p->type()->function_type();
9288 Function_type* m_fn_type = m->type()->function_type();
9289 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9290 std::string subreason;
9291 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9292 &subreason))
9294 if (reason != NULL)
9296 std::string n = Gogo::message_name(p->name());
9297 size_t len = 100 + n.length() + subreason.length();
9298 char* buf = new char[len];
9299 if (subreason.empty())
9300 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9301 go_open_quote(), n.c_str(), go_close_quote());
9302 else
9303 snprintf(buf, len,
9304 _("incompatible type for method %s%s%s (%s)"),
9305 go_open_quote(), n.c_str(), go_close_quote(),
9306 subreason.c_str());
9307 reason->assign(buf);
9308 delete[] buf;
9310 return false;
9313 if (!is_pointer && !m->is_value_method())
9315 if (reason != NULL)
9317 std::string n = Gogo::message_name(p->name());
9318 size_t len = 100 + n.length();
9319 char* buf = new char[len];
9320 snprintf(buf, len,
9321 _("method %s%s%s requires a pointer receiver"),
9322 go_open_quote(), n.c_str(), go_close_quote());
9323 reason->assign(buf);
9324 delete[] buf;
9326 return false;
9329 // If the magic //go:nointerface comment was used, the method
9330 // may not be used to implement interfaces.
9331 if (m->nointerface())
9333 if (reason != NULL)
9335 std::string n = Gogo::message_name(p->name());
9336 size_t len = 100 + n.length();
9337 char* buf = new char[len];
9338 snprintf(buf, len,
9339 _("method %s%s%s is marked go:nointerface"),
9340 go_open_quote(), n.c_str(), go_close_quote());
9341 reason->assign(buf);
9342 delete[] buf;
9344 return false;
9348 return true;
9351 // Return the backend representation of the empty interface type. We
9352 // use the same struct for all empty interfaces.
9354 Btype*
9355 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9357 static Btype* empty_interface_type;
9358 if (empty_interface_type == NULL)
9360 std::vector<Backend::Btyped_identifier> bfields(2);
9362 Location bloc = Linemap::predeclared_location();
9364 Type* pdt = Type::make_type_descriptor_ptr_type();
9365 bfields[0].name = "__type_descriptor";
9366 bfields[0].btype = pdt->get_backend(gogo);
9367 bfields[0].location = bloc;
9369 Type* vt = Type::make_pointer_type(Type::make_void_type());
9370 bfields[1].name = "__object";
9371 bfields[1].btype = vt->get_backend(gogo);
9372 bfields[1].location = bloc;
9374 empty_interface_type = gogo->backend()->struct_type(bfields);
9376 return empty_interface_type;
9379 // Return a pointer to the backend representation of the method table.
9381 Btype*
9382 Interface_type::get_backend_methods(Gogo* gogo)
9384 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9385 return this->bmethods_;
9387 Location loc = this->location();
9389 std::vector<Backend::Btyped_identifier>
9390 mfields(this->all_methods_->size() + 1);
9392 Type* pdt = Type::make_type_descriptor_ptr_type();
9393 mfields[0].name = "__type_descriptor";
9394 mfields[0].btype = pdt->get_backend(gogo);
9395 mfields[0].location = loc;
9397 std::string last_name = "";
9398 size_t i = 1;
9399 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9400 p != this->all_methods_->end();
9401 ++p, ++i)
9403 // The type of the method in Go only includes the parameters.
9404 // The actual method also has a receiver, which is always a
9405 // pointer. We need to add that pointer type here in order to
9406 // generate the correct type for the backend.
9407 Function_type* ft = p->type()->function_type();
9408 go_assert(ft->receiver() == NULL);
9410 const Typed_identifier_list* params = ft->parameters();
9411 Typed_identifier_list* mparams = new Typed_identifier_list();
9412 if (params != NULL)
9413 mparams->reserve(params->size() + 1);
9414 Type* vt = Type::make_pointer_type(Type::make_void_type());
9415 mparams->push_back(Typed_identifier("", vt, ft->location()));
9416 if (params != NULL)
9418 for (Typed_identifier_list::const_iterator pp = params->begin();
9419 pp != params->end();
9420 ++pp)
9421 mparams->push_back(*pp);
9424 Typed_identifier_list* mresults = (ft->results() == NULL
9425 ? NULL
9426 : ft->results()->copy());
9427 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9428 ft->location());
9430 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9431 mfields[i].btype = mft->get_backend_fntype(gogo);
9432 mfields[i].location = loc;
9434 // Sanity check: the names should be sorted.
9435 go_assert(Gogo::unpack_hidden_name(p->name())
9436 > Gogo::unpack_hidden_name(last_name));
9437 last_name = p->name();
9440 Btype* st = gogo->backend()->struct_type(mfields);
9441 Btype* ret = gogo->backend()->pointer_type(st);
9443 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
9444 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
9445 this->bmethods_ = ret;
9446 this->bmethods_is_placeholder_ = false;
9447 return ret;
9450 // Return a placeholder for the pointer to the backend methods table.
9452 Btype*
9453 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9455 if (this->bmethods_ == NULL)
9457 Location loc = this->location();
9458 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
9459 false);
9460 this->bmethods_is_placeholder_ = true;
9462 return this->bmethods_;
9465 // Return the fields of a non-empty interface type. This is not
9466 // declared in types.h so that types.h doesn't have to #include
9467 // backend.h.
9469 static void
9470 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9471 bool use_placeholder,
9472 std::vector<Backend::Btyped_identifier>* bfields)
9474 Location loc = type->location();
9476 bfields->resize(2);
9478 (*bfields)[0].name = "__methods";
9479 (*bfields)[0].btype = (use_placeholder
9480 ? type->get_backend_methods_placeholder(gogo)
9481 : type->get_backend_methods(gogo));
9482 (*bfields)[0].location = loc;
9484 Type* vt = Type::make_pointer_type(Type::make_void_type());
9485 (*bfields)[1].name = "__object";
9486 (*bfields)[1].btype = vt->get_backend(gogo);
9487 (*bfields)[1].location = Linemap::predeclared_location();
9490 // Return the backend representation for an interface type. An interface is a
9491 // pointer to a struct. The struct has three fields. The first field is a
9492 // pointer to the type descriptor for the dynamic type of the object.
9493 // The second field is a pointer to a table of methods for the
9494 // interface to be used with the object. The third field is the value
9495 // of the object itself.
9497 Btype*
9498 Interface_type::do_get_backend(Gogo* gogo)
9500 if (this->is_empty())
9501 return Interface_type::get_backend_empty_interface_type(gogo);
9502 else
9504 if (this->interface_btype_ != NULL)
9505 return this->interface_btype_;
9506 this->interface_btype_ =
9507 gogo->backend()->placeholder_struct_type("", this->location_);
9508 std::vector<Backend::Btyped_identifier> bfields;
9509 get_backend_interface_fields(gogo, this, false, &bfields);
9510 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9511 bfields))
9512 this->interface_btype_ = gogo->backend()->error_type();
9513 return this->interface_btype_;
9517 // Finish the backend representation of the methods.
9519 void
9520 Interface_type::finish_backend_methods(Gogo* gogo)
9522 if (!this->is_empty())
9524 const Typed_identifier_list* methods = this->methods();
9525 if (methods != NULL)
9527 for (Typed_identifier_list::const_iterator p = methods->begin();
9528 p != methods->end();
9529 ++p)
9530 p->type()->get_backend(gogo);
9533 // Getting the backend methods now will set the placeholder
9534 // pointer.
9535 this->get_backend_methods(gogo);
9539 // The type of an interface type descriptor.
9541 Type*
9542 Interface_type::make_interface_type_descriptor_type()
9544 static Type* ret;
9545 if (ret == NULL)
9547 Type* tdt = Type::make_type_descriptor_type();
9548 Type* ptdt = Type::make_type_descriptor_ptr_type();
9550 Type* string_type = Type::lookup_string_type();
9551 Type* pointer_string_type = Type::make_pointer_type(string_type);
9553 Struct_type* sm =
9554 Type::make_builtin_struct_type(3,
9555 "name", pointer_string_type,
9556 "pkgPath", pointer_string_type,
9557 "typ", ptdt);
9559 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9561 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9563 Struct_type* s = Type::make_builtin_struct_type(2,
9564 "", tdt,
9565 "methods", slice_nsm);
9567 ret = Type::make_builtin_named_type("InterfaceType", s);
9570 return ret;
9573 // Build a type descriptor for an interface type.
9575 Expression*
9576 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9578 Location bloc = Linemap::predeclared_location();
9580 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9582 const Struct_field_list* ifields = itdt->struct_type()->fields();
9584 Expression_list* ivals = new Expression_list();
9585 ivals->reserve(2);
9587 Struct_field_list::const_iterator pif = ifields->begin();
9588 go_assert(pif->is_field_name("_type"));
9589 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9590 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9591 true));
9593 ++pif;
9594 go_assert(pif->is_field_name("methods"));
9596 Expression_list* methods = new Expression_list();
9597 if (this->all_methods_ != NULL)
9599 Type* elemtype = pif->type()->array_type()->element_type();
9601 methods->reserve(this->all_methods_->size());
9602 for (Typed_identifier_list::const_iterator pm =
9603 this->all_methods_->begin();
9604 pm != this->all_methods_->end();
9605 ++pm)
9607 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9609 Expression_list* mvals = new Expression_list();
9610 mvals->reserve(3);
9612 Struct_field_list::const_iterator pmf = mfields->begin();
9613 go_assert(pmf->is_field_name("name"));
9614 std::string s = Gogo::unpack_hidden_name(pm->name());
9615 Expression* e = Expression::make_string(s, bloc);
9616 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9618 ++pmf;
9619 go_assert(pmf->is_field_name("pkgPath"));
9620 if (!Gogo::is_hidden_name(pm->name()))
9621 mvals->push_back(Expression::make_nil(bloc));
9622 else
9624 s = Gogo::hidden_name_pkgpath(pm->name());
9625 e = Expression::make_string(s, bloc);
9626 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9629 ++pmf;
9630 go_assert(pmf->is_field_name("typ"));
9631 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9633 ++pmf;
9634 go_assert(pmf == mfields->end());
9636 e = Expression::make_struct_composite_literal(elemtype, mvals,
9637 bloc);
9638 methods->push_back(e);
9642 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9643 methods, bloc));
9645 ++pif;
9646 go_assert(pif == ifields->end());
9648 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9651 // Reflection string.
9653 void
9654 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9656 ret->append("interface {");
9657 const Typed_identifier_list* methods = this->parse_methods_;
9658 if (methods != NULL)
9660 ret->push_back(' ');
9661 for (Typed_identifier_list::const_iterator p = methods->begin();
9662 p != methods->end();
9663 ++p)
9665 if (p != methods->begin())
9666 ret->append("; ");
9667 if (p->name().empty())
9668 this->append_reflection(p->type(), gogo, ret);
9669 else
9671 if (!Gogo::is_hidden_name(p->name()))
9672 ret->append(p->name());
9673 else if (gogo->pkgpath_from_option())
9674 ret->append(p->name().substr(1));
9675 else
9677 // If no -fgo-pkgpath option, backward compatibility
9678 // for how this used to work before -fgo-pkgpath was
9679 // introduced.
9680 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9681 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9682 ret->push_back('.');
9683 ret->append(Gogo::unpack_hidden_name(p->name()));
9685 std::string sub = p->type()->reflection(gogo);
9686 go_assert(sub.compare(0, 4, "func") == 0);
9687 sub = sub.substr(4);
9688 ret->append(sub);
9691 ret->push_back(' ');
9693 ret->append("}");
9696 // Mangled name.
9698 void
9699 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9701 go_assert(this->methods_are_finalized_);
9703 ret->push_back('I');
9705 const Typed_identifier_list* methods = this->all_methods_;
9706 if (methods != NULL && !this->seen_)
9708 this->seen_ = true;
9709 for (Typed_identifier_list::const_iterator p = methods->begin();
9710 p != methods->end();
9711 ++p)
9713 if (!p->name().empty())
9715 std::string n(Gogo::mangle_possibly_hidden_name(p->name()));
9716 char buf[20];
9717 snprintf(buf, sizeof buf, "%u_",
9718 static_cast<unsigned int>(n.length()));
9719 ret->append(buf);
9720 ret->append(n);
9722 this->append_mangled_name(p->type(), gogo, ret);
9724 this->seen_ = false;
9727 ret->push_back('e');
9730 // Export.
9732 void
9733 Interface_type::do_export(Export* exp) const
9735 exp->write_c_string("interface { ");
9737 const Typed_identifier_list* methods = this->parse_methods_;
9738 if (methods != NULL)
9740 for (Typed_identifier_list::const_iterator pm = methods->begin();
9741 pm != methods->end();
9742 ++pm)
9744 if (pm->name().empty())
9746 exp->write_c_string("? ");
9747 exp->write_type(pm->type());
9749 else
9751 exp->write_string(pm->name());
9752 exp->write_c_string(" (");
9754 const Function_type* fntype = pm->type()->function_type();
9756 bool first = true;
9757 const Typed_identifier_list* parameters = fntype->parameters();
9758 if (parameters != NULL)
9760 bool is_varargs = fntype->is_varargs();
9761 for (Typed_identifier_list::const_iterator pp =
9762 parameters->begin();
9763 pp != parameters->end();
9764 ++pp)
9766 if (first)
9767 first = false;
9768 else
9769 exp->write_c_string(", ");
9770 exp->write_name(pp->name());
9771 exp->write_c_string(" ");
9772 if (!is_varargs || pp + 1 != parameters->end())
9773 exp->write_type(pp->type());
9774 else
9776 exp->write_c_string("...");
9777 Type *pptype = pp->type();
9778 exp->write_type(pptype->array_type()->element_type());
9783 exp->write_c_string(")");
9785 const Typed_identifier_list* results = fntype->results();
9786 if (results != NULL)
9788 exp->write_c_string(" ");
9789 if (results->size() == 1 && results->begin()->name().empty())
9790 exp->write_type(results->begin()->type());
9791 else
9793 first = true;
9794 exp->write_c_string("(");
9795 for (Typed_identifier_list::const_iterator p =
9796 results->begin();
9797 p != results->end();
9798 ++p)
9800 if (first)
9801 first = false;
9802 else
9803 exp->write_c_string(", ");
9804 exp->write_name(p->name());
9805 exp->write_c_string(" ");
9806 exp->write_type(p->type());
9808 exp->write_c_string(")");
9813 exp->write_c_string("; ");
9817 exp->write_c_string("}");
9820 // Import an interface type.
9822 Interface_type*
9823 Interface_type::do_import(Import* imp)
9825 imp->require_c_string("interface { ");
9827 Typed_identifier_list* methods = new Typed_identifier_list;
9828 while (imp->peek_char() != '}')
9830 std::string name = imp->read_identifier();
9832 if (name == "?")
9834 imp->require_c_string(" ");
9835 Type* t = imp->read_type();
9836 methods->push_back(Typed_identifier("", t, imp->location()));
9837 imp->require_c_string("; ");
9838 continue;
9841 imp->require_c_string(" (");
9843 Typed_identifier_list* parameters;
9844 bool is_varargs = false;
9845 if (imp->peek_char() == ')')
9846 parameters = NULL;
9847 else
9849 parameters = new Typed_identifier_list;
9850 while (true)
9852 std::string name = imp->read_name();
9853 imp->require_c_string(" ");
9855 if (imp->match_c_string("..."))
9857 imp->advance(3);
9858 is_varargs = true;
9861 Type* ptype = imp->read_type();
9862 if (is_varargs)
9863 ptype = Type::make_array_type(ptype, NULL);
9864 parameters->push_back(Typed_identifier(name, ptype,
9865 imp->location()));
9866 if (imp->peek_char() != ',')
9867 break;
9868 go_assert(!is_varargs);
9869 imp->require_c_string(", ");
9872 imp->require_c_string(")");
9874 Typed_identifier_list* results;
9875 if (imp->peek_char() != ' ')
9876 results = NULL;
9877 else
9879 results = new Typed_identifier_list;
9880 imp->advance(1);
9881 if (imp->peek_char() != '(')
9883 Type* rtype = imp->read_type();
9884 results->push_back(Typed_identifier("", rtype, imp->location()));
9886 else
9888 imp->advance(1);
9889 while (true)
9891 std::string name = imp->read_name();
9892 imp->require_c_string(" ");
9893 Type* rtype = imp->read_type();
9894 results->push_back(Typed_identifier(name, rtype,
9895 imp->location()));
9896 if (imp->peek_char() != ',')
9897 break;
9898 imp->require_c_string(", ");
9900 imp->require_c_string(")");
9904 Function_type* fntype = Type::make_function_type(NULL, parameters,
9905 results,
9906 imp->location());
9907 if (is_varargs)
9908 fntype->set_is_varargs();
9909 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9911 imp->require_c_string("; ");
9914 imp->require_c_string("}");
9916 if (methods->empty())
9918 delete methods;
9919 methods = NULL;
9922 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9923 ret->package_ = imp->package();
9924 return ret;
9927 // Make an interface type.
9929 Interface_type*
9930 Type::make_interface_type(Typed_identifier_list* methods,
9931 Location location)
9933 return new Interface_type(methods, location);
9936 // Make an empty interface type.
9938 Interface_type*
9939 Type::make_empty_interface_type(Location location)
9941 Interface_type* ret = new Interface_type(NULL, location);
9942 ret->finalize_methods();
9943 return ret;
9946 // Class Method.
9948 // Bind a method to an object.
9950 Expression*
9951 Method::bind_method(Expression* expr, Location location) const
9953 if (this->stub_ == NULL)
9955 // When there is no stub object, the binding is determined by
9956 // the child class.
9957 return this->do_bind_method(expr, location);
9959 return Expression::make_bound_method(expr, this, this->stub_, location);
9962 // Return the named object associated with a method. This may only be
9963 // called after methods are finalized.
9965 Named_object*
9966 Method::named_object() const
9968 if (this->stub_ != NULL)
9969 return this->stub_;
9970 return this->do_named_object();
9973 // Class Named_method.
9975 // The type of the method.
9977 Function_type*
9978 Named_method::do_type() const
9980 if (this->named_object_->is_function())
9981 return this->named_object_->func_value()->type();
9982 else if (this->named_object_->is_function_declaration())
9983 return this->named_object_->func_declaration_value()->type();
9984 else
9985 go_unreachable();
9988 // Return the location of the method receiver.
9990 Location
9991 Named_method::do_receiver_location() const
9993 return this->do_type()->receiver()->location();
9996 // Bind a method to an object.
9998 Expression*
9999 Named_method::do_bind_method(Expression* expr, Location location) const
10001 Named_object* no = this->named_object_;
10002 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
10003 no, location);
10004 // If this is not a local method, and it does not use a stub, then
10005 // the real method expects a different type. We need to cast the
10006 // first argument.
10007 if (this->depth() > 0 && !this->needs_stub_method())
10009 Function_type* ftype = this->do_type();
10010 go_assert(ftype->is_method());
10011 Type* frtype = ftype->receiver()->type();
10012 bme->set_first_argument_type(frtype);
10014 return bme;
10017 // Return whether this method should not participate in interfaces.
10019 bool
10020 Named_method::do_nointerface() const
10022 Named_object* no = this->named_object_;
10023 return no->is_function() && no->func_value()->nointerface();
10026 // Class Interface_method.
10028 // Bind a method to an object.
10030 Expression*
10031 Interface_method::do_bind_method(Expression* expr,
10032 Location location) const
10034 return Expression::make_interface_field_reference(expr, this->name_,
10035 location);
10038 // Class Methods.
10040 // Insert a new method. Return true if it was inserted, false
10041 // otherwise.
10043 bool
10044 Methods::insert(const std::string& name, Method* m)
10046 std::pair<Method_map::iterator, bool> ins =
10047 this->methods_.insert(std::make_pair(name, m));
10048 if (ins.second)
10049 return true;
10050 else
10052 Method* old_method = ins.first->second;
10053 if (m->depth() < old_method->depth())
10055 delete old_method;
10056 ins.first->second = m;
10057 return true;
10059 else
10061 if (m->depth() == old_method->depth())
10062 old_method->set_is_ambiguous();
10063 return false;
10068 // Return the number of unambiguous methods.
10070 size_t
10071 Methods::count() const
10073 size_t ret = 0;
10074 for (Method_map::const_iterator p = this->methods_.begin();
10075 p != this->methods_.end();
10076 ++p)
10077 if (!p->second->is_ambiguous())
10078 ++ret;
10079 return ret;
10082 // Class Named_type.
10084 // Return the name of the type.
10086 const std::string&
10087 Named_type::name() const
10089 return this->named_object_->name();
10092 // Return the name of the type to use in an error message.
10094 std::string
10095 Named_type::message_name() const
10097 return this->named_object_->message_name();
10100 // Return the base type for this type. We have to be careful about
10101 // circular type definitions, which are invalid but may be seen here.
10103 Type*
10104 Named_type::named_base()
10106 if (this->seen_)
10107 return this;
10108 this->seen_ = true;
10109 Type* ret = this->type_->base();
10110 this->seen_ = false;
10111 return ret;
10114 const Type*
10115 Named_type::named_base() const
10117 if (this->seen_)
10118 return this;
10119 this->seen_ = true;
10120 const Type* ret = this->type_->base();
10121 this->seen_ = false;
10122 return ret;
10125 // Return whether this is an error type. We have to be careful about
10126 // circular type definitions, which are invalid but may be seen here.
10128 bool
10129 Named_type::is_named_error_type() const
10131 if (this->seen_)
10132 return false;
10133 this->seen_ = true;
10134 bool ret = this->type_->is_error_type();
10135 this->seen_ = false;
10136 return ret;
10139 // Whether this type is comparable. We have to be careful about
10140 // circular type definitions.
10142 bool
10143 Named_type::named_type_is_comparable(std::string* reason) const
10145 if (this->seen_)
10146 return false;
10147 this->seen_ = true;
10148 bool ret = Type::are_compatible_for_comparison(true, this->type_,
10149 this->type_, reason);
10150 this->seen_ = false;
10151 return ret;
10154 // Add a method to this type.
10156 Named_object*
10157 Named_type::add_method(const std::string& name, Function* function)
10159 go_assert(!this->is_alias_);
10160 if (this->local_methods_ == NULL)
10161 this->local_methods_ = new Bindings(NULL);
10162 return this->local_methods_->add_function(name, NULL, function);
10165 // Add a method declaration to this type.
10167 Named_object*
10168 Named_type::add_method_declaration(const std::string& name, Package* package,
10169 Function_type* type,
10170 Location location)
10172 go_assert(!this->is_alias_);
10173 if (this->local_methods_ == NULL)
10174 this->local_methods_ = new Bindings(NULL);
10175 return this->local_methods_->add_function_declaration(name, package, type,
10176 location);
10179 // Add an existing method to this type.
10181 void
10182 Named_type::add_existing_method(Named_object* no)
10184 go_assert(!this->is_alias_);
10185 if (this->local_methods_ == NULL)
10186 this->local_methods_ = new Bindings(NULL);
10187 this->local_methods_->add_named_object(no);
10190 // Look for a local method NAME, and returns its named object, or NULL
10191 // if not there.
10193 Named_object*
10194 Named_type::find_local_method(const std::string& name) const
10196 if (this->is_error_)
10197 return NULL;
10198 if (this->is_alias_)
10200 Named_type* nt = this->type_->named_type();
10201 if (nt != NULL)
10203 if (this->seen_alias_)
10204 return NULL;
10205 this->seen_alias_ = true;
10206 Named_object* ret = nt->find_local_method(name);
10207 this->seen_alias_ = false;
10208 return ret;
10210 return NULL;
10212 if (this->local_methods_ == NULL)
10213 return NULL;
10214 return this->local_methods_->lookup(name);
10217 // Return the list of local methods.
10219 const Bindings*
10220 Named_type::local_methods() const
10222 if (this->is_error_)
10223 return NULL;
10224 if (this->is_alias_)
10226 Named_type* nt = this->type_->named_type();
10227 if (nt != NULL)
10229 if (this->seen_alias_)
10230 return NULL;
10231 this->seen_alias_ = true;
10232 const Bindings* ret = nt->local_methods();
10233 this->seen_alias_ = false;
10234 return ret;
10236 return NULL;
10238 return this->local_methods_;
10241 // Return whether NAME is an unexported field or method, for better
10242 // error reporting.
10244 bool
10245 Named_type::is_unexported_local_method(Gogo* gogo,
10246 const std::string& name) const
10248 if (this->is_error_)
10249 return false;
10250 if (this->is_alias_)
10252 Named_type* nt = this->type_->named_type();
10253 if (nt != NULL)
10255 if (this->seen_alias_)
10256 return false;
10257 this->seen_alias_ = true;
10258 bool ret = nt->is_unexported_local_method(gogo, name);
10259 this->seen_alias_ = false;
10260 return ret;
10262 return false;
10264 Bindings* methods = this->local_methods_;
10265 if (methods != NULL)
10267 for (Bindings::const_declarations_iterator p =
10268 methods->begin_declarations();
10269 p != methods->end_declarations();
10270 ++p)
10272 if (Gogo::is_hidden_name(p->first)
10273 && name == Gogo::unpack_hidden_name(p->first)
10274 && gogo->pack_hidden_name(name, false) != p->first)
10275 return true;
10278 return false;
10281 // Build the complete list of methods for this type, which means
10282 // recursively including all methods for anonymous fields. Create all
10283 // stub methods.
10285 void
10286 Named_type::finalize_methods(Gogo* gogo)
10288 if (this->is_alias_)
10289 return;
10290 if (this->all_methods_ != NULL)
10291 return;
10293 if (this->local_methods_ != NULL
10294 && (this->points_to() != NULL || this->interface_type() != NULL))
10296 const Bindings* lm = this->local_methods_;
10297 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10298 p != lm->end_declarations();
10299 ++p)
10300 go_error_at(p->second->location(),
10301 "invalid pointer or interface receiver type");
10302 delete this->local_methods_;
10303 this->local_methods_ = NULL;
10304 return;
10307 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10310 // Return whether this type has any methods.
10312 bool
10313 Named_type::has_any_methods() const
10315 if (this->is_error_)
10316 return false;
10317 if (this->is_alias_)
10319 if (this->type_->named_type() != NULL)
10321 if (this->seen_alias_)
10322 return false;
10323 this->seen_alias_ = true;
10324 bool ret = this->type_->named_type()->has_any_methods();
10325 this->seen_alias_ = false;
10326 return ret;
10328 if (this->type_->struct_type() != NULL)
10329 return this->type_->struct_type()->has_any_methods();
10330 return false;
10332 return this->all_methods_ != NULL;
10335 // Return the methods for this type.
10337 const Methods*
10338 Named_type::methods() const
10340 if (this->is_error_)
10341 return NULL;
10342 if (this->is_alias_)
10344 if (this->type_->named_type() != NULL)
10346 if (this->seen_alias_)
10347 return NULL;
10348 this->seen_alias_ = true;
10349 const Methods* ret = this->type_->named_type()->methods();
10350 this->seen_alias_ = false;
10351 return ret;
10353 if (this->type_->struct_type() != NULL)
10354 return this->type_->struct_type()->methods();
10355 return NULL;
10357 return this->all_methods_;
10360 // Return the method NAME, or NULL if there isn't one or if it is
10361 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10362 // ambiguous.
10364 Method*
10365 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10367 if (this->is_error_)
10368 return NULL;
10369 if (this->is_alias_)
10371 if (is_ambiguous != NULL)
10372 *is_ambiguous = false;
10373 if (this->type_->named_type() != NULL)
10375 if (this->seen_alias_)
10376 return NULL;
10377 this->seen_alias_ = true;
10378 Named_type* nt = this->type_->named_type();
10379 Method* ret = nt->method_function(name, is_ambiguous);
10380 this->seen_alias_ = false;
10381 return ret;
10383 if (this->type_->struct_type() != NULL)
10384 return this->type_->struct_type()->method_function(name, is_ambiguous);
10385 return NULL;
10387 return Type::method_function(this->all_methods_, name, is_ambiguous);
10390 // Return a pointer to the interface method table for this type for
10391 // the interface INTERFACE. IS_POINTER is true if this is for a
10392 // pointer to THIS.
10394 Expression*
10395 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10397 if (this->is_error_)
10398 return Expression::make_error(this->location_);
10399 if (this->is_alias_)
10401 if (this->type_->named_type() != NULL)
10403 if (this->seen_alias_)
10404 return Expression::make_error(this->location_);
10405 this->seen_alias_ = true;
10406 Named_type* nt = this->type_->named_type();
10407 Expression* ret = nt->interface_method_table(interface, is_pointer);
10408 this->seen_alias_ = false;
10409 return ret;
10411 if (this->type_->struct_type() != NULL)
10412 return this->type_->struct_type()->interface_method_table(interface,
10413 is_pointer);
10414 go_unreachable();
10416 return Type::interface_method_table(this, interface, is_pointer,
10417 &this->interface_method_tables_,
10418 &this->pointer_interface_method_tables_);
10421 // Look for a use of a complete type within another type. This is
10422 // used to check that we don't try to use a type within itself.
10424 class Find_type_use : public Traverse
10426 public:
10427 Find_type_use(Named_type* find_type)
10428 : Traverse(traverse_types),
10429 find_type_(find_type), found_(false)
10432 // Whether we found the type.
10433 bool
10434 found() const
10435 { return this->found_; }
10437 protected:
10439 type(Type*);
10441 private:
10442 // The type we are looking for.
10443 Named_type* find_type_;
10444 // Whether we found the type.
10445 bool found_;
10448 // Check for FIND_TYPE in TYPE.
10451 Find_type_use::type(Type* type)
10453 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10455 this->found_ = true;
10456 return TRAVERSE_EXIT;
10459 // It's OK if we see a reference to the type in any type which is
10460 // essentially a pointer: a pointer, a slice, a function, a map, or
10461 // a channel.
10462 if (type->points_to() != NULL
10463 || type->is_slice_type()
10464 || type->function_type() != NULL
10465 || type->map_type() != NULL
10466 || type->channel_type() != NULL)
10467 return TRAVERSE_SKIP_COMPONENTS;
10469 // For an interface, a reference to the type in a method type should
10470 // be ignored, but we have to consider direct inheritance. When
10471 // this is called, there may be cases of direct inheritance
10472 // represented as a method with no name.
10473 if (type->interface_type() != NULL)
10475 const Typed_identifier_list* methods = type->interface_type()->methods();
10476 if (methods != NULL)
10478 for (Typed_identifier_list::const_iterator p = methods->begin();
10479 p != methods->end();
10480 ++p)
10482 if (p->name().empty())
10484 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10485 return TRAVERSE_EXIT;
10489 return TRAVERSE_SKIP_COMPONENTS;
10492 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10493 // to convert TYPE to the backend representation before we convert
10494 // FIND_TYPE_.
10495 if (type->named_type() != NULL)
10497 switch (type->base()->classification())
10499 case Type::TYPE_ERROR:
10500 case Type::TYPE_BOOLEAN:
10501 case Type::TYPE_INTEGER:
10502 case Type::TYPE_FLOAT:
10503 case Type::TYPE_COMPLEX:
10504 case Type::TYPE_STRING:
10505 case Type::TYPE_NIL:
10506 break;
10508 case Type::TYPE_ARRAY:
10509 case Type::TYPE_STRUCT:
10510 this->find_type_->add_dependency(type->named_type());
10511 break;
10513 case Type::TYPE_NAMED:
10514 case Type::TYPE_FORWARD:
10515 go_assert(saw_errors());
10516 break;
10518 case Type::TYPE_VOID:
10519 case Type::TYPE_SINK:
10520 case Type::TYPE_FUNCTION:
10521 case Type::TYPE_POINTER:
10522 case Type::TYPE_CALL_MULTIPLE_RESULT:
10523 case Type::TYPE_MAP:
10524 case Type::TYPE_CHANNEL:
10525 case Type::TYPE_INTERFACE:
10526 default:
10527 go_unreachable();
10531 return TRAVERSE_CONTINUE;
10534 // Look for a circular reference of an alias.
10536 class Find_alias : public Traverse
10538 public:
10539 Find_alias(Named_type* find_type)
10540 : Traverse(traverse_types),
10541 find_type_(find_type), found_(false)
10544 // Whether we found the type.
10545 bool
10546 found() const
10547 { return this->found_; }
10549 protected:
10551 type(Type*);
10553 private:
10554 // The type we are looking for.
10555 Named_type* find_type_;
10556 // Whether we found the type.
10557 bool found_;
10561 Find_alias::type(Type* type)
10563 Named_type* nt = type->named_type();
10564 if (nt != NULL)
10566 if (nt == this->find_type_)
10568 this->found_ = true;
10569 return TRAVERSE_EXIT;
10572 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10573 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10574 // an alias itself, it's OK if whatever T2 is defined as refers
10575 // to T1.
10576 if (!nt->is_alias())
10577 return TRAVERSE_SKIP_COMPONENTS;
10580 return TRAVERSE_CONTINUE;
10583 // Verify that a named type does not refer to itself.
10585 bool
10586 Named_type::do_verify()
10588 if (this->is_verified_)
10589 return true;
10590 this->is_verified_ = true;
10592 if (this->is_error_)
10593 return false;
10595 if (this->is_alias_)
10597 Find_alias find(this);
10598 Type::traverse(this->type_, &find);
10599 if (find.found())
10601 go_error_at(this->location_, "invalid recursive alias %qs",
10602 this->message_name().c_str());
10603 this->is_error_ = true;
10604 return false;
10608 Find_type_use find(this);
10609 Type::traverse(this->type_, &find);
10610 if (find.found())
10612 go_error_at(this->location_, "invalid recursive type %qs",
10613 this->message_name().c_str());
10614 this->is_error_ = true;
10615 return false;
10618 // Check whether any of the local methods overloads an existing
10619 // struct field or interface method. We don't need to check the
10620 // list of methods against itself: that is handled by the Bindings
10621 // code.
10622 if (this->local_methods_ != NULL)
10624 Struct_type* st = this->type_->struct_type();
10625 if (st != NULL)
10627 for (Bindings::const_declarations_iterator p =
10628 this->local_methods_->begin_declarations();
10629 p != this->local_methods_->end_declarations();
10630 ++p)
10632 const std::string& name(p->first);
10633 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10635 go_error_at(p->second->location(),
10636 "method %qs redeclares struct field name",
10637 Gogo::message_name(name).c_str());
10643 return true;
10646 // Return whether this type is or contains a pointer.
10648 bool
10649 Named_type::do_has_pointer() const
10651 if (this->seen_)
10652 return false;
10653 this->seen_ = true;
10654 bool ret = this->type_->has_pointer();
10655 this->seen_ = false;
10656 return ret;
10659 // Return whether comparisons for this type can use the identity
10660 // function.
10662 bool
10663 Named_type::do_compare_is_identity(Gogo* gogo)
10665 // We don't use this->seen_ here because compare_is_identity may
10666 // call base() later, and that will mess up if seen_ is set here.
10667 if (this->seen_in_compare_is_identity_)
10668 return false;
10669 this->seen_in_compare_is_identity_ = true;
10670 bool ret = this->type_->compare_is_identity(gogo);
10671 this->seen_in_compare_is_identity_ = false;
10672 return ret;
10675 // Return whether this type is reflexive--whether it is always equal
10676 // to itself.
10678 bool
10679 Named_type::do_is_reflexive()
10681 if (this->seen_in_compare_is_identity_)
10682 return false;
10683 this->seen_in_compare_is_identity_ = true;
10684 bool ret = this->type_->is_reflexive();
10685 this->seen_in_compare_is_identity_ = false;
10686 return ret;
10689 // Return whether this type needs a key update when used as a map key.
10691 bool
10692 Named_type::do_needs_key_update()
10694 if (this->seen_in_compare_is_identity_)
10695 return true;
10696 this->seen_in_compare_is_identity_ = true;
10697 bool ret = this->type_->needs_key_update();
10698 this->seen_in_compare_is_identity_ = false;
10699 return ret;
10702 // Return a hash code. This is used for method lookup. We simply
10703 // hash on the name itself.
10705 unsigned int
10706 Named_type::do_hash_for_method(Gogo* gogo) const
10708 if (this->is_error_)
10709 return 0;
10711 // Aliases are handled in Type::hash_for_method.
10712 go_assert(!this->is_alias_);
10714 const std::string& name(this->named_object()->name());
10715 unsigned int ret = Type::hash_string(name, 0);
10717 // GOGO will be NULL here when called from Type_hash_identical.
10718 // That is OK because that is only used for internal hash tables
10719 // where we are going to be comparing named types for equality. In
10720 // other cases, which are cases where the runtime is going to
10721 // compare hash codes to see if the types are the same, we need to
10722 // include the pkgpath in the hash.
10723 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10725 const Package* package = this->named_object()->package();
10726 if (package == NULL)
10727 ret = Type::hash_string(gogo->pkgpath(), ret);
10728 else
10729 ret = Type::hash_string(package->pkgpath(), ret);
10732 return ret;
10735 // Convert a named type to the backend representation. In order to
10736 // get dependencies right, we fill in a dummy structure for this type,
10737 // then convert all the dependencies, then complete this type. When
10738 // this function is complete, the size of the type is known.
10740 void
10741 Named_type::convert(Gogo* gogo)
10743 if (this->is_error_ || this->is_converted_)
10744 return;
10746 this->create_placeholder(gogo);
10748 // If we are called to turn unsafe.Sizeof into a constant, we may
10749 // not have verified the type yet. We have to make sure it is
10750 // verified, since that sets the list of dependencies.
10751 this->verify();
10753 // Convert all the dependencies. If they refer indirectly back to
10754 // this type, they will pick up the intermediate representation we just
10755 // created.
10756 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10757 p != this->dependencies_.end();
10758 ++p)
10759 (*p)->convert(gogo);
10761 // Complete this type.
10762 Btype* bt = this->named_btype_;
10763 Type* base = this->type_->base();
10764 switch (base->classification())
10766 case TYPE_VOID:
10767 case TYPE_BOOLEAN:
10768 case TYPE_INTEGER:
10769 case TYPE_FLOAT:
10770 case TYPE_COMPLEX:
10771 case TYPE_STRING:
10772 case TYPE_NIL:
10773 break;
10775 case TYPE_MAP:
10776 case TYPE_CHANNEL:
10777 break;
10779 case TYPE_FUNCTION:
10780 case TYPE_POINTER:
10781 // The size of these types is already correct. We don't worry
10782 // about filling them in until later, when we also track
10783 // circular references.
10784 break;
10786 case TYPE_STRUCT:
10788 std::vector<Backend::Btyped_identifier> bfields;
10789 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10790 true, &bfields);
10791 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10792 bt = gogo->backend()->error_type();
10794 break;
10796 case TYPE_ARRAY:
10797 // Slice types were completed in create_placeholder.
10798 if (!base->is_slice_type())
10800 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10801 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10802 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10803 bt = gogo->backend()->error_type();
10805 break;
10807 case TYPE_INTERFACE:
10808 // Interface types were completed in create_placeholder.
10809 break;
10811 case TYPE_ERROR:
10812 return;
10814 default:
10815 case TYPE_SINK:
10816 case TYPE_CALL_MULTIPLE_RESULT:
10817 case TYPE_NAMED:
10818 case TYPE_FORWARD:
10819 go_unreachable();
10822 this->named_btype_ = bt;
10823 this->is_converted_ = true;
10824 this->is_placeholder_ = false;
10827 // Create the placeholder for a named type. This is the first step in
10828 // converting to the backend representation.
10830 void
10831 Named_type::create_placeholder(Gogo* gogo)
10833 if (this->is_error_)
10834 this->named_btype_ = gogo->backend()->error_type();
10836 if (this->named_btype_ != NULL)
10837 return;
10839 // Create the structure for this type. Note that because we call
10840 // base() here, we don't attempt to represent a named type defined
10841 // as another named type. Instead both named types will point to
10842 // different base representations.
10843 Type* base = this->type_->base();
10844 Btype* bt;
10845 bool set_name = true;
10846 switch (base->classification())
10848 case TYPE_ERROR:
10849 this->is_error_ = true;
10850 this->named_btype_ = gogo->backend()->error_type();
10851 return;
10853 case TYPE_VOID:
10854 case TYPE_BOOLEAN:
10855 case TYPE_INTEGER:
10856 case TYPE_FLOAT:
10857 case TYPE_COMPLEX:
10858 case TYPE_STRING:
10859 case TYPE_NIL:
10860 // These are simple basic types, we can just create them
10861 // directly.
10862 bt = Type::get_named_base_btype(gogo, base);
10863 break;
10865 case TYPE_MAP:
10866 case TYPE_CHANNEL:
10867 // All maps and channels have the same backend representation.
10868 bt = Type::get_named_base_btype(gogo, base);
10869 break;
10871 case TYPE_FUNCTION:
10872 case TYPE_POINTER:
10874 bool for_function = base->classification() == TYPE_FUNCTION;
10875 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10876 this->location_,
10877 for_function);
10878 set_name = false;
10880 break;
10882 case TYPE_STRUCT:
10883 bt = gogo->backend()->placeholder_struct_type(this->name(),
10884 this->location_);
10885 this->is_placeholder_ = true;
10886 set_name = false;
10887 break;
10889 case TYPE_ARRAY:
10890 if (base->is_slice_type())
10891 bt = gogo->backend()->placeholder_struct_type(this->name(),
10892 this->location_);
10893 else
10895 bt = gogo->backend()->placeholder_array_type(this->name(),
10896 this->location_);
10897 this->is_placeholder_ = true;
10899 set_name = false;
10900 break;
10902 case TYPE_INTERFACE:
10903 if (base->interface_type()->is_empty())
10904 bt = Interface_type::get_backend_empty_interface_type(gogo);
10905 else
10907 bt = gogo->backend()->placeholder_struct_type(this->name(),
10908 this->location_);
10909 set_name = false;
10911 break;
10913 default:
10914 case TYPE_SINK:
10915 case TYPE_CALL_MULTIPLE_RESULT:
10916 case TYPE_NAMED:
10917 case TYPE_FORWARD:
10918 go_unreachable();
10921 if (set_name)
10922 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10924 this->named_btype_ = bt;
10926 if (base->is_slice_type())
10928 // We do not record slices as dependencies of other types,
10929 // because we can fill them in completely here with the final
10930 // size.
10931 std::vector<Backend::Btyped_identifier> bfields;
10932 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10933 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10934 this->named_btype_ = gogo->backend()->error_type();
10936 else if (base->interface_type() != NULL
10937 && !base->interface_type()->is_empty())
10939 // We do not record interfaces as dependencies of other types,
10940 // because we can fill them in completely here with the final
10941 // size.
10942 std::vector<Backend::Btyped_identifier> bfields;
10943 get_backend_interface_fields(gogo, base->interface_type(), true,
10944 &bfields);
10945 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10946 this->named_btype_ = gogo->backend()->error_type();
10950 // Get the backend representation for a named type.
10952 Btype*
10953 Named_type::do_get_backend(Gogo* gogo)
10955 if (this->is_error_)
10956 return gogo->backend()->error_type();
10958 Btype* bt = this->named_btype_;
10960 if (!gogo->named_types_are_converted())
10962 // We have not completed converting named types. NAMED_BTYPE_
10963 // is a placeholder and we shouldn't do anything further.
10964 if (bt != NULL)
10965 return bt;
10967 // We don't build dependencies for types whose sizes do not
10968 // change or are not relevant, so we may see them here while
10969 // converting types.
10970 this->create_placeholder(gogo);
10971 bt = this->named_btype_;
10972 go_assert(bt != NULL);
10973 return bt;
10976 // We are not converting types. This should only be called if the
10977 // type has already been converted.
10978 if (!this->is_converted_)
10980 go_assert(saw_errors());
10981 return gogo->backend()->error_type();
10984 go_assert(bt != NULL);
10986 // Complete the backend representation.
10987 Type* base = this->type_->base();
10988 Btype* bt1;
10989 switch (base->classification())
10991 case TYPE_ERROR:
10992 return gogo->backend()->error_type();
10994 case TYPE_VOID:
10995 case TYPE_BOOLEAN:
10996 case TYPE_INTEGER:
10997 case TYPE_FLOAT:
10998 case TYPE_COMPLEX:
10999 case TYPE_STRING:
11000 case TYPE_NIL:
11001 case TYPE_MAP:
11002 case TYPE_CHANNEL:
11003 return bt;
11005 case TYPE_STRUCT:
11006 if (!this->seen_in_get_backend_)
11008 this->seen_in_get_backend_ = true;
11009 base->struct_type()->finish_backend_fields(gogo);
11010 this->seen_in_get_backend_ = false;
11012 return bt;
11014 case TYPE_ARRAY:
11015 if (!this->seen_in_get_backend_)
11017 this->seen_in_get_backend_ = true;
11018 base->array_type()->finish_backend_element(gogo);
11019 this->seen_in_get_backend_ = false;
11021 return bt;
11023 case TYPE_INTERFACE:
11024 if (!this->seen_in_get_backend_)
11026 this->seen_in_get_backend_ = true;
11027 base->interface_type()->finish_backend_methods(gogo);
11028 this->seen_in_get_backend_ = false;
11030 return bt;
11032 case TYPE_FUNCTION:
11033 // Don't build a circular data structure. GENERIC can't handle
11034 // it.
11035 if (this->seen_in_get_backend_)
11037 this->is_circular_ = true;
11038 return gogo->backend()->circular_pointer_type(bt, true);
11040 this->seen_in_get_backend_ = true;
11041 bt1 = Type::get_named_base_btype(gogo, base);
11042 this->seen_in_get_backend_ = false;
11043 if (this->is_circular_)
11044 bt1 = gogo->backend()->circular_pointer_type(bt, true);
11045 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11046 bt = gogo->backend()->error_type();
11047 return bt;
11049 case TYPE_POINTER:
11050 // Don't build a circular data structure. GENERIC can't handle
11051 // it.
11052 if (this->seen_in_get_backend_)
11054 this->is_circular_ = true;
11055 return gogo->backend()->circular_pointer_type(bt, false);
11057 this->seen_in_get_backend_ = true;
11058 bt1 = Type::get_named_base_btype(gogo, base);
11059 this->seen_in_get_backend_ = false;
11060 if (this->is_circular_)
11061 bt1 = gogo->backend()->circular_pointer_type(bt, false);
11062 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11063 bt = gogo->backend()->error_type();
11064 return bt;
11066 default:
11067 case TYPE_SINK:
11068 case TYPE_CALL_MULTIPLE_RESULT:
11069 case TYPE_NAMED:
11070 case TYPE_FORWARD:
11071 go_unreachable();
11074 go_unreachable();
11077 // Build a type descriptor for a named type.
11079 Expression*
11080 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11082 if (this->is_error_)
11083 return Expression::make_error(this->location_);
11084 if (name == NULL && this->is_alias_)
11086 if (this->seen_alias_)
11087 return Expression::make_error(this->location_);
11088 this->seen_alias_ = true;
11089 Expression* ret = this->type_->type_descriptor(gogo, NULL);
11090 this->seen_alias_ = false;
11091 return ret;
11094 // If NAME is not NULL, then we don't really want the type
11095 // descriptor for this type; we want the descriptor for the
11096 // underlying type, giving it the name NAME.
11097 return this->named_type_descriptor(gogo, this->type_,
11098 name == NULL ? this : name);
11101 // Add to the reflection string. This is used mostly for the name of
11102 // the type used in a type descriptor, not for actual reflection
11103 // strings.
11105 void
11106 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
11108 this->append_reflection_type_name(gogo, false, ret);
11111 // Add to the reflection string. For an alias we normally use the
11112 // real name, but if USE_ALIAS is true we use the alias name itself.
11114 void
11115 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
11116 std::string* ret) const
11118 if (this->is_error_)
11119 return;
11120 if (this->is_alias_ && !use_alias)
11122 if (this->seen_alias_)
11123 return;
11124 this->seen_alias_ = true;
11125 this->append_reflection(this->type_, gogo, ret);
11126 this->seen_alias_ = false;
11127 return;
11129 if (!this->is_builtin())
11131 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
11132 // make a unique reflection string, so that the type
11133 // canonicalization in the reflect package will work. In order
11134 // to be compatible with the gc compiler, we put tabs into the
11135 // package path, so that the reflect methods can discard it.
11136 const Package* package = this->named_object_->package();
11137 ret->push_back('\t');
11138 ret->append(package != NULL
11139 ? package->pkgpath_symbol()
11140 : gogo->pkgpath_symbol());
11141 ret->push_back('\t');
11142 ret->append(package != NULL
11143 ? package->package_name()
11144 : gogo->package_name());
11145 ret->push_back('.');
11147 if (this->in_function_ != NULL)
11149 ret->push_back('\t');
11150 const Typed_identifier* rcvr =
11151 this->in_function_->func_value()->type()->receiver();
11152 if (rcvr != NULL)
11154 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11155 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
11156 ret->push_back('.');
11158 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
11159 ret->push_back('$');
11160 if (this->in_function_index_ > 0)
11162 char buf[30];
11163 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11164 ret->append(buf);
11165 ret->push_back('$');
11167 ret->push_back('\t');
11169 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
11172 // Get the mangled name.
11174 void
11175 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
11177 this->append_mangled_type_name(gogo, false, ret);
11180 // Get the mangled name. For an alias we normally get the real name,
11181 // but if USE_ALIAS is true we use the alias name itself.
11183 void
11184 Named_type::append_mangled_type_name(Gogo* gogo, bool use_alias,
11185 std::string* ret) const
11187 if (this->is_error_)
11188 return;
11189 if (this->is_alias_ && !use_alias)
11191 if (this->seen_alias_)
11192 return;
11193 this->seen_alias_ = true;
11194 this->append_mangled_name(this->type_, gogo, ret);
11195 this->seen_alias_ = false;
11196 return;
11198 Named_object* no = this->named_object_;
11199 std::string name;
11200 if (this->is_builtin())
11201 go_assert(this->in_function_ == NULL);
11202 else
11204 const std::string& pkgpath(no->package() == NULL
11205 ? gogo->pkgpath_symbol()
11206 : no->package()->pkgpath_symbol());
11207 name = pkgpath;
11208 name.append(1, '.');
11209 if (this->in_function_ != NULL)
11211 const Typed_identifier* rcvr =
11212 this->in_function_->func_value()->type()->receiver();
11213 if (rcvr != NULL)
11215 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11216 name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
11217 name.append(1, '.');
11219 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
11220 name.append(1, '$');
11221 if (this->in_function_index_ > 0)
11223 char buf[30];
11224 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11225 name.append(buf);
11226 name.append(1, '$');
11230 name.append(Gogo::unpack_hidden_name(no->name()));
11231 char buf[20];
11232 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
11233 ret->append(buf);
11234 ret->append(name);
11237 // Export the type. This is called to export a global type.
11239 void
11240 Named_type::export_named_type(Export* exp, const std::string&) const
11242 // We don't need to write the name of the type here, because it will
11243 // be written by Export::write_type anyhow.
11244 exp->write_c_string("type ");
11245 exp->write_type(this);
11246 exp->write_c_string(";\n");
11249 // Import a named type.
11251 void
11252 Named_type::import_named_type(Import* imp, Named_type** ptype)
11254 imp->require_c_string("type ");
11255 Type *type = imp->read_type();
11256 *ptype = type->named_type();
11257 go_assert(*ptype != NULL);
11258 imp->require_c_string(";\n");
11261 // Export the type when it is referenced by another type. In this
11262 // case Export::export_type will already have issued the name.
11264 void
11265 Named_type::do_export(Export* exp) const
11267 exp->write_type(this->type_);
11269 // To save space, we only export the methods directly attached to
11270 // this type.
11271 Bindings* methods = this->local_methods_;
11272 if (methods == NULL)
11273 return;
11275 exp->write_c_string("\n");
11276 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
11277 p != methods->end_definitions();
11278 ++p)
11280 exp->write_c_string(" ");
11281 (*p)->export_named_object(exp);
11284 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
11285 p != methods->end_declarations();
11286 ++p)
11288 if (p->second->is_function_declaration())
11290 exp->write_c_string(" ");
11291 p->second->export_named_object(exp);
11296 // Make a named type.
11298 Named_type*
11299 Type::make_named_type(Named_object* named_object, Type* type,
11300 Location location)
11302 return new Named_type(named_object, type, location);
11305 // Finalize the methods for TYPE. It will be a named type or a struct
11306 // type. This sets *ALL_METHODS to the list of methods, and builds
11307 // all required stubs.
11309 void
11310 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
11311 Methods** all_methods)
11313 *all_methods = new Methods();
11314 std::vector<const Named_type*> seen;
11315 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
11316 if ((*all_methods)->empty())
11318 delete *all_methods;
11319 *all_methods = NULL;
11321 Type::build_stub_methods(gogo, type, *all_methods, location);
11324 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11325 // build up the struct field indexes as we go. DEPTH is the depth of
11326 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11327 // adding these methods for an anonymous field with pointer type.
11328 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11329 // calls the real method. TYPES_SEEN is used to avoid infinite
11330 // recursion.
11332 void
11333 Type::add_methods_for_type(const Type* type,
11334 const Method::Field_indexes* field_indexes,
11335 unsigned int depth,
11336 bool is_embedded_pointer,
11337 bool needs_stub_method,
11338 std::vector<const Named_type*>* seen,
11339 Methods* methods)
11341 // Pointer types may not have methods.
11342 if (type->points_to() != NULL)
11343 return;
11345 const Named_type* nt = type->named_type();
11346 if (nt != NULL)
11348 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11349 p != seen->end();
11350 ++p)
11352 if (*p == nt)
11353 return;
11356 seen->push_back(nt);
11358 Type::add_local_methods_for_type(nt, field_indexes, depth,
11359 is_embedded_pointer, needs_stub_method,
11360 methods);
11363 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11364 is_embedded_pointer, needs_stub_method,
11365 seen, methods);
11367 // If we are called with depth > 0, then we are looking at an
11368 // anonymous field of a struct. If such a field has interface type,
11369 // then we need to add the interface methods. We don't want to add
11370 // them when depth == 0, because we will already handle them
11371 // following the usual rules for an interface type.
11372 if (depth > 0)
11373 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11375 if (nt != NULL)
11376 seen->pop_back();
11379 // Add the local methods for the named type NT to *METHODS. The
11380 // parameters are as for add_methods_to_type.
11382 void
11383 Type::add_local_methods_for_type(const Named_type* nt,
11384 const Method::Field_indexes* field_indexes,
11385 unsigned int depth,
11386 bool is_embedded_pointer,
11387 bool needs_stub_method,
11388 Methods* methods)
11390 const Bindings* local_methods = nt->local_methods();
11391 if (local_methods == NULL)
11392 return;
11394 for (Bindings::const_declarations_iterator p =
11395 local_methods->begin_declarations();
11396 p != local_methods->end_declarations();
11397 ++p)
11399 Named_object* no = p->second;
11400 bool is_value_method = (is_embedded_pointer
11401 || !Type::method_expects_pointer(no));
11402 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11403 (needs_stub_method || depth > 0));
11404 if (!methods->insert(no->name(), m))
11405 delete m;
11409 // Add the embedded methods for TYPE to *METHODS. These are the
11410 // methods attached to anonymous fields. The parameters are as for
11411 // add_methods_to_type.
11413 void
11414 Type::add_embedded_methods_for_type(const Type* type,
11415 const Method::Field_indexes* field_indexes,
11416 unsigned int depth,
11417 bool is_embedded_pointer,
11418 bool needs_stub_method,
11419 std::vector<const Named_type*>* seen,
11420 Methods* methods)
11422 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11423 // struct.
11424 const Struct_type* st = type->struct_type();
11425 if (st == NULL)
11426 return;
11428 const Struct_field_list* fields = st->fields();
11429 if (fields == NULL)
11430 return;
11432 unsigned int i = 0;
11433 for (Struct_field_list::const_iterator pf = fields->begin();
11434 pf != fields->end();
11435 ++pf, ++i)
11437 if (!pf->is_anonymous())
11438 continue;
11440 Type* ftype = pf->type();
11441 bool is_pointer = false;
11442 if (ftype->points_to() != NULL)
11444 ftype = ftype->points_to();
11445 is_pointer = true;
11447 Named_type* fnt = ftype->named_type();
11448 if (fnt == NULL)
11450 // This is an error, but it will be diagnosed elsewhere.
11451 continue;
11454 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11455 sub_field_indexes->next = field_indexes;
11456 sub_field_indexes->field_index = i;
11458 Methods tmp_methods;
11459 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11460 (is_embedded_pointer || is_pointer),
11461 (needs_stub_method
11462 || is_pointer
11463 || i > 0),
11464 seen,
11465 &tmp_methods);
11466 // Check if there are promoted methods that conflict with field names and
11467 // don't add them to the method map.
11468 for (Methods::const_iterator p = tmp_methods.begin();
11469 p != tmp_methods.end();
11470 ++p)
11472 bool found = false;
11473 for (Struct_field_list::const_iterator fp = fields->begin();
11474 fp != fields->end();
11475 ++fp)
11477 if (fp->field_name() == p->first)
11479 found = true;
11480 break;
11483 if (!found &&
11484 !methods->insert(p->first, p->second))
11485 delete p->second;
11490 // If TYPE is an interface type, then add its method to *METHODS.
11491 // This is for interface methods attached to an anonymous field. The
11492 // parameters are as for add_methods_for_type.
11494 void
11495 Type::add_interface_methods_for_type(const Type* type,
11496 const Method::Field_indexes* field_indexes,
11497 unsigned int depth,
11498 Methods* methods)
11500 const Interface_type* it = type->interface_type();
11501 if (it == NULL)
11502 return;
11504 const Typed_identifier_list* imethods = it->methods();
11505 if (imethods == NULL)
11506 return;
11508 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11509 pm != imethods->end();
11510 ++pm)
11512 Function_type* fntype = pm->type()->function_type();
11513 if (fntype == NULL)
11515 // This is an error, but it should be reported elsewhere
11516 // when we look at the methods for IT.
11517 continue;
11519 go_assert(!fntype->is_method());
11520 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11521 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11522 field_indexes, depth);
11523 if (!methods->insert(pm->name(), m))
11524 delete m;
11528 // Build stub methods for TYPE as needed. METHODS is the set of
11529 // methods for the type. A stub method may be needed when a type
11530 // inherits a method from an anonymous field. When we need the
11531 // address of the method, as in a type descriptor, we need to build a
11532 // little stub which does the required field dereferences and jumps to
11533 // the real method. LOCATION is the location of the type definition.
11535 void
11536 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11537 Location location)
11539 if (methods == NULL)
11540 return;
11541 for (Methods::const_iterator p = methods->begin();
11542 p != methods->end();
11543 ++p)
11545 Method* m = p->second;
11546 if (m->is_ambiguous() || !m->needs_stub_method())
11547 continue;
11549 const std::string& name(p->first);
11551 // Build a stub method.
11553 const Function_type* fntype = m->type();
11555 static unsigned int counter;
11556 char buf[100];
11557 snprintf(buf, sizeof buf, "$this%u", counter);
11558 ++counter;
11560 Type* receiver_type = const_cast<Type*>(type);
11561 if (!m->is_value_method())
11562 receiver_type = Type::make_pointer_type(receiver_type);
11563 Location receiver_location = m->receiver_location();
11564 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11565 receiver_location);
11567 const Typed_identifier_list* fnparams = fntype->parameters();
11568 Typed_identifier_list* stub_params;
11569 if (fnparams == NULL || fnparams->empty())
11570 stub_params = NULL;
11571 else
11573 // We give each stub parameter a unique name.
11574 stub_params = new Typed_identifier_list();
11575 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11576 pp != fnparams->end();
11577 ++pp)
11579 char pbuf[100];
11580 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11581 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11582 pp->location()));
11583 ++counter;
11587 const Typed_identifier_list* fnresults = fntype->results();
11588 Typed_identifier_list* stub_results;
11589 if (fnresults == NULL || fnresults->empty())
11590 stub_results = NULL;
11591 else
11593 // We create the result parameters without any names, since
11594 // we won't refer to them.
11595 stub_results = new Typed_identifier_list();
11596 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11597 pr != fnresults->end();
11598 ++pr)
11599 stub_results->push_back(Typed_identifier("", pr->type(),
11600 pr->location()));
11603 Function_type* stub_type = Type::make_function_type(receiver,
11604 stub_params,
11605 stub_results,
11606 fntype->location());
11607 if (fntype->is_varargs())
11608 stub_type->set_is_varargs();
11610 // We only create the function in the package which creates the
11611 // type.
11612 const Package* package;
11613 if (type->named_type() == NULL)
11614 package = NULL;
11615 else
11616 package = type->named_type()->named_object()->package();
11617 std::string stub_name = name + "$stub";
11618 Named_object* stub;
11619 if (package != NULL)
11620 stub = Named_object::make_function_declaration(stub_name, package,
11621 stub_type, location);
11622 else
11624 stub = gogo->start_function(stub_name, stub_type, false,
11625 fntype->location());
11626 Type::build_one_stub_method(gogo, m, buf, stub_params,
11627 fntype->is_varargs(), location);
11628 gogo->finish_function(fntype->location());
11630 if (type->named_type() == NULL && stub->is_function())
11631 stub->func_value()->set_is_unnamed_type_stub_method();
11632 if (m->nointerface() && stub->is_function())
11633 stub->func_value()->set_nointerface();
11636 m->set_stub_object(stub);
11640 // Build a stub method which adjusts the receiver as required to call
11641 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11642 // PARAMS is the list of function parameters.
11644 void
11645 Type::build_one_stub_method(Gogo* gogo, Method* method,
11646 const char* receiver_name,
11647 const Typed_identifier_list* params,
11648 bool is_varargs,
11649 Location location)
11651 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11652 go_assert(receiver_object != NULL);
11654 Expression* expr = Expression::make_var_reference(receiver_object, location);
11655 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11656 if (expr->type()->points_to() == NULL)
11657 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11659 Expression_list* arguments;
11660 if (params == NULL || params->empty())
11661 arguments = NULL;
11662 else
11664 arguments = new Expression_list();
11665 for (Typed_identifier_list::const_iterator p = params->begin();
11666 p != params->end();
11667 ++p)
11669 Named_object* param = gogo->lookup(p->name(), NULL);
11670 go_assert(param != NULL);
11671 Expression* param_ref = Expression::make_var_reference(param,
11672 location);
11673 arguments->push_back(param_ref);
11677 Expression* func = method->bind_method(expr, location);
11678 go_assert(func != NULL);
11679 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11680 location);
11682 gogo->add_statement(Statement::make_return_from_call(call, location));
11685 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11686 // in reverse order.
11688 Expression*
11689 Type::apply_field_indexes(Expression* expr,
11690 const Method::Field_indexes* field_indexes,
11691 Location location)
11693 if (field_indexes == NULL)
11694 return expr;
11695 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11696 Struct_type* stype = expr->type()->deref()->struct_type();
11697 go_assert(stype != NULL
11698 && field_indexes->field_index < stype->field_count());
11699 if (expr->type()->struct_type() == NULL)
11701 go_assert(expr->type()->points_to() != NULL);
11702 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
11703 go_assert(expr->type()->struct_type() == stype);
11705 return Expression::make_field_reference(expr, field_indexes->field_index,
11706 location);
11709 // Return whether NO is a method for which the receiver is a pointer.
11711 bool
11712 Type::method_expects_pointer(const Named_object* no)
11714 const Function_type *fntype;
11715 if (no->is_function())
11716 fntype = no->func_value()->type();
11717 else if (no->is_function_declaration())
11718 fntype = no->func_declaration_value()->type();
11719 else
11720 go_unreachable();
11721 return fntype->receiver()->type()->points_to() != NULL;
11724 // Given a set of methods for a type, METHODS, return the method NAME,
11725 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11726 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11727 // but is ambiguous (and return NULL).
11729 Method*
11730 Type::method_function(const Methods* methods, const std::string& name,
11731 bool* is_ambiguous)
11733 if (is_ambiguous != NULL)
11734 *is_ambiguous = false;
11735 if (methods == NULL)
11736 return NULL;
11737 Methods::const_iterator p = methods->find(name);
11738 if (p == methods->end())
11739 return NULL;
11740 Method* m = p->second;
11741 if (m->is_ambiguous())
11743 if (is_ambiguous != NULL)
11744 *is_ambiguous = true;
11745 return NULL;
11747 return m;
11750 // Return a pointer to the interface method table for TYPE for the
11751 // interface INTERFACE.
11753 Expression*
11754 Type::interface_method_table(Type* type,
11755 Interface_type *interface,
11756 bool is_pointer,
11757 Interface_method_tables** method_tables,
11758 Interface_method_tables** pointer_tables)
11760 go_assert(!interface->is_empty());
11762 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11764 if (*pimt == NULL)
11765 *pimt = new Interface_method_tables(5);
11767 std::pair<Interface_type*, Expression*> val(interface, NULL);
11768 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11770 Location loc = Linemap::predeclared_location();
11771 if (ins.second)
11773 // This is a new entry in the hash table.
11774 go_assert(ins.first->second == NULL);
11775 ins.first->second =
11776 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11778 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11781 // Look for field or method NAME for TYPE. Return an Expression for
11782 // the field or method bound to EXPR. If there is no such field or
11783 // method, give an appropriate error and return an error expression.
11785 Expression*
11786 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11787 const std::string& name,
11788 Location location)
11790 if (type->deref()->is_error_type())
11791 return Expression::make_error(location);
11793 const Named_type* nt = type->deref()->named_type();
11794 const Struct_type* st = type->deref()->struct_type();
11795 const Interface_type* it = type->interface_type();
11797 // If this is a pointer to a pointer, then it is possible that the
11798 // pointed-to type has methods.
11799 bool dereferenced = false;
11800 if (nt == NULL
11801 && st == NULL
11802 && it == NULL
11803 && type->points_to() != NULL
11804 && type->points_to()->points_to() != NULL)
11806 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
11807 type = type->points_to();
11808 if (type->deref()->is_error_type())
11809 return Expression::make_error(location);
11810 nt = type->points_to()->named_type();
11811 st = type->points_to()->struct_type();
11812 dereferenced = true;
11815 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11816 || expr->is_addressable());
11817 std::vector<const Named_type*> seen;
11818 bool is_method = false;
11819 bool found_pointer_method = false;
11820 std::string ambig1;
11821 std::string ambig2;
11822 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11823 &seen, NULL, &is_method,
11824 &found_pointer_method, &ambig1, &ambig2))
11826 Expression* ret;
11827 if (!is_method)
11829 go_assert(st != NULL);
11830 if (type->struct_type() == NULL)
11832 go_assert(type->points_to() != NULL);
11833 expr = Expression::make_unary(OPERATOR_MULT, expr,
11834 location);
11835 go_assert(expr->type()->struct_type() == st);
11837 ret = st->field_reference(expr, name, location);
11839 else if (it != NULL && it->find_method(name) != NULL)
11840 ret = Expression::make_interface_field_reference(expr, name,
11841 location);
11842 else
11844 Method* m;
11845 if (nt != NULL)
11846 m = nt->method_function(name, NULL);
11847 else if (st != NULL)
11848 m = st->method_function(name, NULL);
11849 else
11850 go_unreachable();
11851 go_assert(m != NULL);
11852 if (dereferenced)
11854 go_error_at(location,
11855 "calling method %qs requires explicit dereference",
11856 Gogo::message_name(name).c_str());
11857 return Expression::make_error(location);
11859 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11860 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11861 ret = m->bind_method(expr, location);
11863 go_assert(ret != NULL);
11864 return ret;
11866 else
11868 if (Gogo::is_erroneous_name(name))
11870 // An error was already reported.
11872 else if (!ambig1.empty())
11873 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11874 Gogo::message_name(name).c_str(), ambig1.c_str(),
11875 ambig2.c_str());
11876 else if (found_pointer_method)
11877 go_error_at(location, "method requires a pointer receiver");
11878 else if (nt == NULL && st == NULL && it == NULL)
11879 go_error_at(location,
11880 ("reference to field %qs in object which "
11881 "has no fields or methods"),
11882 Gogo::message_name(name).c_str());
11883 else
11885 bool is_unexported;
11886 // The test for 'a' and 'z' is to handle builtin names,
11887 // which are not hidden.
11888 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11889 is_unexported = false;
11890 else
11892 std::string unpacked = Gogo::unpack_hidden_name(name);
11893 seen.clear();
11894 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11895 unpacked,
11896 &seen);
11898 if (is_unexported)
11899 go_error_at(location, "reference to unexported field or method %qs",
11900 Gogo::message_name(name).c_str());
11901 else
11902 go_error_at(location, "reference to undefined field or method %qs",
11903 Gogo::message_name(name).c_str());
11905 return Expression::make_error(location);
11909 // Look in TYPE for a field or method named NAME, return true if one
11910 // is found. This looks through embedded anonymous fields and handles
11911 // ambiguity. If a method is found, sets *IS_METHOD to true;
11912 // otherwise, if a field is found, set it to false. If
11913 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11914 // whose address can not be taken. SEEN is used to avoid infinite
11915 // recursion on invalid types.
11917 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11918 // method we couldn't use because it requires a pointer. LEVEL is
11919 // used for recursive calls, and can be NULL for a non-recursive call.
11920 // When this function returns false because it finds that the name is
11921 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11922 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11923 // will be unchanged.
11925 // This function just returns whether or not there is a field or
11926 // method, and whether it is a field or method. It doesn't build an
11927 // expression to refer to it. If it is a method, we then look in the
11928 // list of all methods for the type. If it is a field, the search has
11929 // to be done again, looking only for fields, and building up the
11930 // expression as we go.
11932 bool
11933 Type::find_field_or_method(const Type* type,
11934 const std::string& name,
11935 bool receiver_can_be_pointer,
11936 std::vector<const Named_type*>* seen,
11937 int* level,
11938 bool* is_method,
11939 bool* found_pointer_method,
11940 std::string* ambig1,
11941 std::string* ambig2)
11943 // Named types can have locally defined methods.
11944 const Named_type* nt = type->named_type();
11945 if (nt == NULL && type->points_to() != NULL)
11946 nt = type->points_to()->named_type();
11947 if (nt != NULL)
11949 Named_object* no = nt->find_local_method(name);
11950 if (no != NULL)
11952 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11954 *is_method = true;
11955 return true;
11958 // Record that we have found a pointer method in order to
11959 // give a better error message if we don't find anything
11960 // else.
11961 *found_pointer_method = true;
11964 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11965 p != seen->end();
11966 ++p)
11968 if (*p == nt)
11970 // We've already seen this type when searching for methods.
11971 return false;
11976 // Interface types can have methods.
11977 const Interface_type* it = type->interface_type();
11978 if (it != NULL && it->find_method(name) != NULL)
11980 *is_method = true;
11981 return true;
11984 // Struct types can have fields. They can also inherit fields and
11985 // methods from anonymous fields.
11986 const Struct_type* st = type->deref()->struct_type();
11987 if (st == NULL)
11988 return false;
11989 const Struct_field_list* fields = st->fields();
11990 if (fields == NULL)
11991 return false;
11993 if (nt != NULL)
11994 seen->push_back(nt);
11996 int found_level = 0;
11997 bool found_is_method = false;
11998 std::string found_ambig1;
11999 std::string found_ambig2;
12000 const Struct_field* found_parent = NULL;
12001 for (Struct_field_list::const_iterator pf = fields->begin();
12002 pf != fields->end();
12003 ++pf)
12005 if (pf->is_field_name(name))
12007 *is_method = false;
12008 if (nt != NULL)
12009 seen->pop_back();
12010 return true;
12013 if (!pf->is_anonymous())
12014 continue;
12016 if (pf->type()->deref()->is_error_type()
12017 || pf->type()->deref()->is_undefined())
12018 continue;
12020 Named_type* fnt = pf->type()->named_type();
12021 if (fnt == NULL)
12022 fnt = pf->type()->deref()->named_type();
12023 go_assert(fnt != NULL);
12025 // Methods with pointer receivers on embedded field are
12026 // inherited by the pointer to struct, and also by the struct
12027 // type if the field itself is a pointer.
12028 bool can_be_pointer = (receiver_can_be_pointer
12029 || pf->type()->points_to() != NULL);
12030 int sublevel = level == NULL ? 1 : *level + 1;
12031 bool sub_is_method;
12032 std::string subambig1;
12033 std::string subambig2;
12034 bool subfound = Type::find_field_or_method(fnt,
12035 name,
12036 can_be_pointer,
12037 seen,
12038 &sublevel,
12039 &sub_is_method,
12040 found_pointer_method,
12041 &subambig1,
12042 &subambig2);
12043 if (!subfound)
12045 if (!subambig1.empty())
12047 // The name was found via this field, but is ambiguous.
12048 // if the ambiguity is lower or at the same level as
12049 // anything else we have already found, then we want to
12050 // pass the ambiguity back to the caller.
12051 if (found_level == 0 || sublevel <= found_level)
12053 found_ambig1 = (Gogo::message_name(pf->field_name())
12054 + '.' + subambig1);
12055 found_ambig2 = (Gogo::message_name(pf->field_name())
12056 + '.' + subambig2);
12057 found_level = sublevel;
12061 else
12063 // The name was found via this field. Use the level to see
12064 // if we want to use this one, or whether it introduces an
12065 // ambiguity.
12066 if (found_level == 0 || sublevel < found_level)
12068 found_level = sublevel;
12069 found_is_method = sub_is_method;
12070 found_ambig1.clear();
12071 found_ambig2.clear();
12072 found_parent = &*pf;
12074 else if (sublevel > found_level)
12076 else if (found_ambig1.empty())
12078 // We found an ambiguity.
12079 go_assert(found_parent != NULL);
12080 found_ambig1 = Gogo::message_name(found_parent->field_name());
12081 found_ambig2 = Gogo::message_name(pf->field_name());
12083 else
12085 // We found an ambiguity, but we already know of one.
12086 // Just report the earlier one.
12091 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
12092 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
12093 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
12094 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
12096 if (nt != NULL)
12097 seen->pop_back();
12099 if (found_level == 0)
12100 return false;
12101 else if (found_is_method
12102 && type->named_type() != NULL
12103 && type->points_to() != NULL)
12105 // If this is a method inherited from a struct field in a named pointer
12106 // type, it is invalid to automatically dereference the pointer to the
12107 // struct to find this method.
12108 if (level != NULL)
12109 *level = found_level;
12110 *is_method = true;
12111 return false;
12113 else if (!found_ambig1.empty())
12115 go_assert(!found_ambig1.empty());
12116 ambig1->assign(found_ambig1);
12117 ambig2->assign(found_ambig2);
12118 if (level != NULL)
12119 *level = found_level;
12120 return false;
12122 else
12124 if (level != NULL)
12125 *level = found_level;
12126 *is_method = found_is_method;
12127 return true;
12131 // Return whether NAME is an unexported field or method for TYPE.
12133 bool
12134 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
12135 const std::string& name,
12136 std::vector<const Named_type*>* seen)
12138 const Named_type* nt = type->named_type();
12139 if (nt == NULL)
12140 nt = type->deref()->named_type();
12141 if (nt != NULL)
12143 if (nt->is_unexported_local_method(gogo, name))
12144 return true;
12146 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12147 p != seen->end();
12148 ++p)
12150 if (*p == nt)
12152 // We've already seen this type.
12153 return false;
12158 const Interface_type* it = type->interface_type();
12159 if (it != NULL && it->is_unexported_method(gogo, name))
12160 return true;
12162 type = type->deref();
12164 const Struct_type* st = type->struct_type();
12165 if (st != NULL && st->is_unexported_local_field(gogo, name))
12166 return true;
12168 if (st == NULL)
12169 return false;
12171 const Struct_field_list* fields = st->fields();
12172 if (fields == NULL)
12173 return false;
12175 if (nt != NULL)
12176 seen->push_back(nt);
12178 for (Struct_field_list::const_iterator pf = fields->begin();
12179 pf != fields->end();
12180 ++pf)
12182 if (pf->is_anonymous()
12183 && !pf->type()->deref()->is_error_type()
12184 && !pf->type()->deref()->is_undefined())
12186 Named_type* subtype = pf->type()->named_type();
12187 if (subtype == NULL)
12188 subtype = pf->type()->deref()->named_type();
12189 if (subtype == NULL)
12191 // This is an error, but it will be diagnosed elsewhere.
12192 continue;
12194 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
12196 if (nt != NULL)
12197 seen->pop_back();
12198 return true;
12203 if (nt != NULL)
12204 seen->pop_back();
12206 return false;
12209 // Class Forward_declaration.
12211 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
12212 : Type(TYPE_FORWARD),
12213 named_object_(named_object->resolve()), warned_(false)
12215 go_assert(this->named_object_->is_unknown()
12216 || this->named_object_->is_type_declaration());
12219 // Return the named object.
12221 Named_object*
12222 Forward_declaration_type::named_object()
12224 return this->named_object_->resolve();
12227 const Named_object*
12228 Forward_declaration_type::named_object() const
12230 return this->named_object_->resolve();
12233 // Return the name of the forward declared type.
12235 const std::string&
12236 Forward_declaration_type::name() const
12238 return this->named_object()->name();
12241 // Warn about a use of a type which has been declared but not defined.
12243 void
12244 Forward_declaration_type::warn() const
12246 Named_object* no = this->named_object_->resolve();
12247 if (no->is_unknown())
12249 // The name was not defined anywhere.
12250 if (!this->warned_)
12252 go_error_at(this->named_object_->location(),
12253 "use of undefined type %qs",
12254 no->message_name().c_str());
12255 this->warned_ = true;
12258 else if (no->is_type_declaration())
12260 // The name was seen as a type, but the type was never defined.
12261 if (no->type_declaration_value()->using_type())
12263 go_error_at(this->named_object_->location(),
12264 "use of undefined type %qs",
12265 no->message_name().c_str());
12266 this->warned_ = true;
12269 else
12271 // The name was defined, but not as a type.
12272 if (!this->warned_)
12274 go_error_at(this->named_object_->location(), "expected type");
12275 this->warned_ = true;
12280 // Get the base type of a declaration. This gives an error if the
12281 // type has not yet been defined.
12283 Type*
12284 Forward_declaration_type::real_type()
12286 if (this->is_defined())
12288 Named_type* nt = this->named_object()->type_value();
12289 if (!nt->is_valid())
12290 return Type::make_error_type();
12291 return this->named_object()->type_value();
12293 else
12295 this->warn();
12296 return Type::make_error_type();
12300 const Type*
12301 Forward_declaration_type::real_type() const
12303 if (this->is_defined())
12305 const Named_type* nt = this->named_object()->type_value();
12306 if (!nt->is_valid())
12307 return Type::make_error_type();
12308 return this->named_object()->type_value();
12310 else
12312 this->warn();
12313 return Type::make_error_type();
12317 // Return whether the base type is defined.
12319 bool
12320 Forward_declaration_type::is_defined() const
12322 return this->named_object()->is_type();
12325 // Add a method. This is used when methods are defined before the
12326 // type.
12328 Named_object*
12329 Forward_declaration_type::add_method(const std::string& name,
12330 Function* function)
12332 Named_object* no = this->named_object();
12333 if (no->is_unknown())
12334 no->declare_as_type();
12335 return no->type_declaration_value()->add_method(name, function);
12338 // Add a method declaration. This is used when methods are declared
12339 // before the type.
12341 Named_object*
12342 Forward_declaration_type::add_method_declaration(const std::string& name,
12343 Package* package,
12344 Function_type* type,
12345 Location location)
12347 Named_object* no = this->named_object();
12348 if (no->is_unknown())
12349 no->declare_as_type();
12350 Type_declaration* td = no->type_declaration_value();
12351 return td->add_method_declaration(name, package, type, location);
12354 // Add an already created object as a method.
12356 void
12357 Forward_declaration_type::add_existing_method(Named_object* nom)
12359 Named_object* no = this->named_object();
12360 if (no->is_unknown())
12361 no->declare_as_type();
12362 no->type_declaration_value()->add_existing_method(nom);
12365 // Traversal.
12368 Forward_declaration_type::do_traverse(Traverse* traverse)
12370 if (this->is_defined()
12371 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12372 return TRAVERSE_EXIT;
12373 return TRAVERSE_CONTINUE;
12376 // Verify the type.
12378 bool
12379 Forward_declaration_type::do_verify()
12381 if (!this->is_defined() && !this->is_nil_constant_as_type())
12383 this->warn();
12384 return false;
12386 return true;
12389 // Get the backend representation for the type.
12391 Btype*
12392 Forward_declaration_type::do_get_backend(Gogo* gogo)
12394 if (this->is_defined())
12395 return Type::get_named_base_btype(gogo, this->real_type());
12397 if (this->warned_)
12398 return gogo->backend()->error_type();
12400 // We represent an undefined type as a struct with no fields. That
12401 // should work fine for the backend, since the same case can arise
12402 // in C.
12403 std::vector<Backend::Btyped_identifier> fields;
12404 Btype* bt = gogo->backend()->struct_type(fields);
12405 return gogo->backend()->named_type(this->name(), bt,
12406 this->named_object()->location());
12409 // Build a type descriptor for a forwarded type.
12411 Expression*
12412 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12414 Location ploc = Linemap::predeclared_location();
12415 if (!this->is_defined())
12416 return Expression::make_error(ploc);
12417 else
12419 Type* t = this->real_type();
12420 if (name != NULL)
12421 return this->named_type_descriptor(gogo, t, name);
12422 else
12423 return Expression::make_error(this->named_object_->location());
12427 // The reflection string.
12429 void
12430 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12432 this->append_reflection(this->real_type(), gogo, ret);
12435 // The mangled name.
12437 void
12438 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
12440 if (this->is_defined())
12441 this->append_mangled_name(this->real_type(), gogo, ret);
12442 else
12444 const Named_object* no = this->named_object();
12445 std::string name;
12446 if (no->package() == NULL)
12447 name = gogo->pkgpath_symbol();
12448 else
12449 name = no->package()->pkgpath_symbol();
12450 name += '.';
12451 name += Gogo::unpack_hidden_name(no->name());
12452 char buf[20];
12453 snprintf(buf, sizeof buf, "N%u_",
12454 static_cast<unsigned int>(name.length()));
12455 ret->append(buf);
12456 ret->append(name);
12460 // Export a forward declaration. This can happen when a defined type
12461 // refers to a type which is only declared (and is presumably defined
12462 // in some other file in the same package).
12464 void
12465 Forward_declaration_type::do_export(Export*) const
12467 // If there is a base type, that should be exported instead of this.
12468 go_assert(!this->is_defined());
12470 // We don't output anything.
12473 // Make a forward declaration.
12475 Type*
12476 Type::make_forward_declaration(Named_object* named_object)
12478 return new Forward_declaration_type(named_object);
12481 // Class Typed_identifier_list.
12483 // Sort the entries by name.
12485 struct Typed_identifier_list_sort
12487 public:
12488 bool
12489 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12491 return (Gogo::unpack_hidden_name(t1.name())
12492 < Gogo::unpack_hidden_name(t2.name()));
12496 void
12497 Typed_identifier_list::sort_by_name()
12499 std::sort(this->entries_.begin(), this->entries_.end(),
12500 Typed_identifier_list_sort());
12503 // Traverse types.
12506 Typed_identifier_list::traverse(Traverse* traverse)
12508 for (Typed_identifier_list::const_iterator p = this->begin();
12509 p != this->end();
12510 ++p)
12512 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12513 return TRAVERSE_EXIT;
12515 return TRAVERSE_CONTINUE;
12518 // Copy the list.
12520 Typed_identifier_list*
12521 Typed_identifier_list::copy() const
12523 Typed_identifier_list* ret = new Typed_identifier_list();
12524 for (Typed_identifier_list::const_iterator p = this->begin();
12525 p != this->end();
12526 ++p)
12527 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12528 return ret;