]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/go/gofrontend/types.cc
7f65b4a5db2e07b411b144d2310fb473a278e16e
[thirdparty/gcc.git] / gcc / go / gofrontend / types.cc
1 // types.cc -- Go frontend types.
2
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.
6
7 #include "go-system.h"
8
9 #include <ostream>
10
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "go-sha1.h"
16 #include "operator.h"
17 #include "expressions.h"
18 #include "statements.h"
19 #include "export.h"
20 #include "import.h"
21 #include "backend.h"
22 #include "types.h"
23
24 // Forward declarations so that we don't have to make types.h #include
25 // backend.h.
26
27 static void
28 get_backend_struct_fields(Gogo* gogo, Struct_type* type, bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
30
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 std::vector<Backend::Btyped_identifier>* bfields);
34
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 bool use_placeholder,
38 std::vector<Backend::Btyped_identifier>* bfields);
39
40 // Class Type.
41
42 Type::Type(Type_classification classification)
43 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44 gc_symbol_var_(NULL)
45 {
46 }
47
48 Type::~Type()
49 {
50 }
51
52 // Get the base type for a type--skip names and forward declarations.
53
54 Type*
55 Type::base()
56 {
57 switch (this->classification_)
58 {
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;
65 }
66 }
67
68 const Type*
69 Type::base() const
70 {
71 switch (this->classification_)
72 {
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;
79 }
80 }
81
82 // Skip defined forward declarations.
83
84 Type*
85 Type::forwarded()
86 {
87 Type* t = this;
88 Forward_declaration_type* ftype = t->forward_declaration_type();
89 while (ftype != NULL && ftype->is_defined())
90 {
91 t = ftype->real_type();
92 ftype = t->forward_declaration_type();
93 }
94 return t;
95 }
96
97 const Type*
98 Type::forwarded() const
99 {
100 const Type* t = this;
101 const Forward_declaration_type* ftype = t->forward_declaration_type();
102 while (ftype != NULL && ftype->is_defined())
103 {
104 t = ftype->real_type();
105 ftype = t->forward_declaration_type();
106 }
107 return t;
108 }
109
110 // Skip alias definitions.
111
112 Type*
113 Type::unalias()
114 {
115 Type* t = this->forwarded();
116 Named_type* nt = t->named_type();
117 while (nt != NULL && nt->is_alias())
118 {
119 t = nt->real_type()->forwarded();
120 nt = t->named_type();
121 }
122 return t;
123 }
124
125 const Type*
126 Type::unalias() const
127 {
128 const Type* t = this->forwarded();
129 const Named_type* nt = t->named_type();
130 while (nt != NULL && nt->is_alias())
131 {
132 t = nt->real_type()->forwarded();
133 nt = t->named_type();
134 }
135 return t;
136 }
137
138 // If this is a named type, return it. Otherwise, return NULL.
139
140 Named_type*
141 Type::named_type()
142 {
143 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
144 }
145
146 const Named_type*
147 Type::named_type() const
148 {
149 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
150 }
151
152 // Return true if this type is not defined.
153
154 bool
155 Type::is_undefined() const
156 {
157 return this->forwarded()->forward_declaration_type() != NULL;
158 }
159
160 // Return true if this is a basic type: a type which is not composed
161 // of other types, and is not void.
162
163 bool
164 Type::is_basic_type() const
165 {
166 switch (this->classification_)
167 {
168 case TYPE_INTEGER:
169 case TYPE_FLOAT:
170 case TYPE_COMPLEX:
171 case TYPE_BOOLEAN:
172 case TYPE_STRING:
173 case TYPE_NIL:
174 return true;
175
176 case TYPE_ERROR:
177 case TYPE_VOID:
178 case TYPE_FUNCTION:
179 case TYPE_POINTER:
180 case TYPE_STRUCT:
181 case TYPE_ARRAY:
182 case TYPE_MAP:
183 case TYPE_CHANNEL:
184 case TYPE_INTERFACE:
185 return false;
186
187 case TYPE_NAMED:
188 case TYPE_FORWARD:
189 return this->base()->is_basic_type();
190
191 default:
192 go_unreachable();
193 }
194 }
195
196 // Return true if this is an abstract type.
197
198 bool
199 Type::is_abstract() const
200 {
201 switch (this->classification())
202 {
203 case TYPE_INTEGER:
204 return this->integer_type()->is_abstract();
205 case TYPE_FLOAT:
206 return this->float_type()->is_abstract();
207 case TYPE_COMPLEX:
208 return this->complex_type()->is_abstract();
209 case TYPE_STRING:
210 return this->is_abstract_string_type();
211 case TYPE_BOOLEAN:
212 return this->is_abstract_boolean_type();
213 default:
214 return false;
215 }
216 }
217
218 // Return a non-abstract version of an abstract type.
219
220 Type*
221 Type::make_non_abstract_type()
222 {
223 go_assert(this->is_abstract());
224 switch (this->classification())
225 {
226 case TYPE_INTEGER:
227 if (this->integer_type()->is_rune())
228 return Type::lookup_integer_type("int32");
229 else
230 return Type::lookup_integer_type("int");
231 case TYPE_FLOAT:
232 return Type::lookup_float_type("float64");
233 case TYPE_COMPLEX:
234 return Type::lookup_complex_type("complex128");
235 case TYPE_STRING:
236 return Type::lookup_string_type();
237 case TYPE_BOOLEAN:
238 return Type::lookup_bool_type();
239 default:
240 go_unreachable();
241 }
242 }
243
244 // Return true if this is an error type. Don't give an error if we
245 // try to dereference an undefined forwarding type, as this is called
246 // in the parser when the type may legitimately be undefined.
247
248 bool
249 Type::is_error_type() const
250 {
251 const Type* t = this->forwarded();
252 // Note that we return false for an undefined forward type.
253 switch (t->classification_)
254 {
255 case TYPE_ERROR:
256 return true;
257 case TYPE_NAMED:
258 return t->named_type()->is_named_error_type();
259 default:
260 return false;
261 }
262 }
263
264 // If this is a pointer type, return the type to which it points.
265 // Otherwise, return NULL.
266
267 Type*
268 Type::points_to() const
269 {
270 const Pointer_type* ptype = this->convert<const Pointer_type,
271 TYPE_POINTER>();
272 return ptype == NULL ? NULL : ptype->points_to();
273 }
274
275 // Return whether this is a slice type.
276
277 bool
278 Type::is_slice_type() const
279 {
280 return this->array_type() != NULL && this->array_type()->length() == NULL;
281 }
282
283 // Return whether this is the predeclared constant nil being used as a
284 // type.
285
286 bool
287 Type::is_nil_constant_as_type() const
288 {
289 const Type* t = this->forwarded();
290 if (t->forward_declaration_type() != NULL)
291 {
292 const Named_object* no = t->forward_declaration_type()->named_object();
293 if (no->is_unknown())
294 no = no->unknown_value()->real_named_object();
295 if (no != NULL
296 && no->is_const()
297 && no->const_value()->expr()->is_nil_expression())
298 return true;
299 }
300 return false;
301 }
302
303 // Traverse a type.
304
305 int
306 Type::traverse(Type* type, Traverse* traverse)
307 {
308 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
309 || (traverse->traverse_mask()
310 & Traverse::traverse_expressions) != 0);
311 if (traverse->remember_type(type))
312 {
313 // We have already traversed this type.
314 return TRAVERSE_CONTINUE;
315 }
316 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
317 {
318 int t = traverse->type(type);
319 if (t == TRAVERSE_EXIT)
320 return TRAVERSE_EXIT;
321 else if (t == TRAVERSE_SKIP_COMPONENTS)
322 return TRAVERSE_CONTINUE;
323 }
324 // An array type has an expression which we need to traverse if
325 // traverse_expressions is set.
326 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
327 return TRAVERSE_EXIT;
328 return TRAVERSE_CONTINUE;
329 }
330
331 // Default implementation for do_traverse for child class.
332
333 int
334 Type::do_traverse(Traverse*)
335 {
336 return TRAVERSE_CONTINUE;
337 }
338
339 // Return whether two types are identical. If REASON is not NULL,
340 // optionally set *REASON to the reason the types are not identical.
341
342 bool
343 Type::are_identical(const Type* t1, const Type* t2, int flags,
344 std::string* reason)
345 {
346 if (t1 == NULL || t2 == NULL)
347 {
348 // Something is wrong.
349 return (flags & COMPARE_ERRORS) == 0 ? true : t1 == t2;
350 }
351
352 // Skip defined forward declarations.
353 t1 = t1->forwarded();
354 t2 = t2->forwarded();
355
356 if ((flags & COMPARE_ALIASES) == 0)
357 {
358 // Ignore aliases.
359 t1 = t1->unalias();
360 t2 = t2->unalias();
361 }
362
363 if (t1 == t2)
364 return true;
365
366 // An undefined forward declaration is an error.
367 if (t1->forward_declaration_type() != NULL
368 || t2->forward_declaration_type() != NULL)
369 return (flags & COMPARE_ERRORS) == 0;
370
371 // Avoid cascading errors with error types.
372 if (t1->is_error_type() || t2->is_error_type())
373 {
374 if ((flags & COMPARE_ERRORS) == 0)
375 return true;
376 return t1->is_error_type() && t2->is_error_type();
377 }
378
379 // Get a good reason for the sink type. Note that the sink type on
380 // the left hand side of an assignment is handled in are_assignable.
381 if (t1->is_sink_type() || t2->is_sink_type())
382 {
383 if (reason != NULL)
384 *reason = "invalid use of _";
385 return false;
386 }
387
388 // A named type is only identical to itself.
389 if (t1->named_type() != NULL || t2->named_type() != NULL)
390 return false;
391
392 // Check type shapes.
393 if (t1->classification() != t2->classification())
394 return false;
395
396 switch (t1->classification())
397 {
398 case TYPE_VOID:
399 case TYPE_BOOLEAN:
400 case TYPE_STRING:
401 case TYPE_NIL:
402 // These types are always identical.
403 return true;
404
405 case TYPE_INTEGER:
406 return t1->integer_type()->is_identical(t2->integer_type());
407
408 case TYPE_FLOAT:
409 return t1->float_type()->is_identical(t2->float_type());
410
411 case TYPE_COMPLEX:
412 return t1->complex_type()->is_identical(t2->complex_type());
413
414 case TYPE_FUNCTION:
415 return t1->function_type()->is_identical(t2->function_type(),
416 false, flags, reason);
417
418 case TYPE_POINTER:
419 return Type::are_identical(t1->points_to(), t2->points_to(), flags,
420 reason);
421
422 case TYPE_STRUCT:
423 return t1->struct_type()->is_identical(t2->struct_type(), flags);
424
425 case TYPE_ARRAY:
426 return t1->array_type()->is_identical(t2->array_type(), flags);
427
428 case TYPE_MAP:
429 return t1->map_type()->is_identical(t2->map_type(), flags);
430
431 case TYPE_CHANNEL:
432 return t1->channel_type()->is_identical(t2->channel_type(), flags);
433
434 case TYPE_INTERFACE:
435 return t1->interface_type()->is_identical(t2->interface_type(), flags);
436
437 case TYPE_CALL_MULTIPLE_RESULT:
438 if (reason != NULL)
439 *reason = "invalid use of multiple-value function call";
440 return false;
441
442 default:
443 go_unreachable();
444 }
445 }
446
447 // Return true if it's OK to have a binary operation with types LHS
448 // and RHS. This is not used for shifts or comparisons.
449
450 bool
451 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
452 {
453 if (Type::are_identical(lhs, rhs, Type::COMPARE_TAGS, NULL))
454 return true;
455
456 // A constant of abstract bool type may be mixed with any bool type.
457 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
458 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
459 return true;
460
461 // A constant of abstract string type may be mixed with any string
462 // type.
463 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
464 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
465 return true;
466
467 lhs = lhs->base();
468 rhs = rhs->base();
469
470 // A constant of abstract integer, float, or complex type may be
471 // mixed with an integer, float, or complex type.
472 if ((rhs->is_abstract()
473 && (rhs->integer_type() != NULL
474 || rhs->float_type() != NULL
475 || rhs->complex_type() != NULL)
476 && (lhs->integer_type() != NULL
477 || lhs->float_type() != NULL
478 || lhs->complex_type() != NULL))
479 || (lhs->is_abstract()
480 && (lhs->integer_type() != NULL
481 || lhs->float_type() != NULL
482 || lhs->complex_type() != NULL)
483 && (rhs->integer_type() != NULL
484 || rhs->float_type() != NULL
485 || rhs->complex_type() != NULL)))
486 return true;
487
488 // The nil type may be compared to a pointer, an interface type, a
489 // slice type, a channel type, a map type, or a function type.
490 if (lhs->is_nil_type()
491 && (rhs->points_to() != NULL
492 || rhs->interface_type() != NULL
493 || rhs->is_slice_type()
494 || rhs->map_type() != NULL
495 || rhs->channel_type() != NULL
496 || rhs->function_type() != NULL))
497 return true;
498 if (rhs->is_nil_type()
499 && (lhs->points_to() != NULL
500 || lhs->interface_type() != NULL
501 || lhs->is_slice_type()
502 || lhs->map_type() != NULL
503 || lhs->channel_type() != NULL
504 || lhs->function_type() != NULL))
505 return true;
506
507 return false;
508 }
509
510 // Return true if a value with type T1 may be compared with a value of
511 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
512
513 bool
514 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
515 const Type *t2, std::string *reason)
516 {
517 if (t1 != t2
518 && !Type::are_assignable(t1, t2, NULL)
519 && !Type::are_assignable(t2, t1, NULL))
520 {
521 if (reason != NULL)
522 *reason = "incompatible types in binary expression";
523 return false;
524 }
525
526 if (!is_equality_op)
527 {
528 if (t1->integer_type() == NULL
529 && t1->float_type() == NULL
530 && !t1->is_string_type())
531 {
532 if (reason != NULL)
533 *reason = _("invalid comparison of non-ordered type");
534 return false;
535 }
536 }
537 else if (t1->is_slice_type()
538 || t1->map_type() != NULL
539 || t1->function_type() != NULL
540 || t2->is_slice_type()
541 || t2->map_type() != NULL
542 || t2->function_type() != NULL)
543 {
544 if (!t1->is_nil_type() && !t2->is_nil_type())
545 {
546 if (reason != NULL)
547 {
548 if (t1->is_slice_type() || t2->is_slice_type())
549 *reason = _("slice can only be compared to nil");
550 else if (t1->map_type() != NULL || t2->map_type() != NULL)
551 *reason = _("map can only be compared to nil");
552 else
553 *reason = _("func can only be compared to nil");
554
555 // Match 6g error messages.
556 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
557 {
558 char buf[200];
559 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
560 reason->c_str());
561 *reason = buf;
562 }
563 }
564 return false;
565 }
566 }
567 else
568 {
569 if (!t1->is_boolean_type()
570 && t1->integer_type() == NULL
571 && t1->float_type() == NULL
572 && t1->complex_type() == NULL
573 && !t1->is_string_type()
574 && t1->points_to() == NULL
575 && t1->channel_type() == NULL
576 && t1->interface_type() == NULL
577 && t1->struct_type() == NULL
578 && t1->array_type() == NULL
579 && !t1->is_nil_type())
580 {
581 if (reason != NULL)
582 *reason = _("invalid comparison of non-comparable type");
583 return false;
584 }
585
586 if (t1->unalias()->named_type() != NULL)
587 return t1->unalias()->named_type()->named_type_is_comparable(reason);
588 else if (t2->unalias()->named_type() != NULL)
589 return t2->unalias()->named_type()->named_type_is_comparable(reason);
590 else if (t1->struct_type() != NULL)
591 {
592 if (t1->struct_type()->is_struct_incomparable())
593 {
594 if (reason != NULL)
595 *reason = _("invalid comparison of generated struct");
596 return false;
597 }
598 const Struct_field_list* fields = t1->struct_type()->fields();
599 for (Struct_field_list::const_iterator p = fields->begin();
600 p != fields->end();
601 ++p)
602 {
603 if (!p->type()->is_comparable())
604 {
605 if (reason != NULL)
606 *reason = _("invalid comparison of non-comparable struct");
607 return false;
608 }
609 }
610 }
611 else if (t1->array_type() != NULL)
612 {
613 if (t1->array_type()->is_array_incomparable())
614 {
615 if (reason != NULL)
616 *reason = _("invalid comparison of generated array");
617 return false;
618 }
619 if (t1->array_type()->length()->is_nil_expression()
620 || !t1->array_type()->element_type()->is_comparable())
621 {
622 if (reason != NULL)
623 *reason = _("invalid comparison of non-comparable array");
624 return false;
625 }
626 }
627 }
628
629 return true;
630 }
631
632 // Return true if a value with type RHS may be assigned to a variable
633 // with type LHS. If REASON is not NULL, set *REASON to the reason
634 // the types are not assignable.
635
636 bool
637 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
638 {
639 // Do some checks first. Make sure the types are defined.
640 if (rhs != NULL && !rhs->is_undefined())
641 {
642 if (rhs->is_void_type())
643 {
644 if (reason != NULL)
645 *reason = "non-value used as value";
646 return false;
647 }
648 if (rhs->is_call_multiple_result_type())
649 {
650 if (reason != NULL)
651 reason->assign(_("multiple-value function call in "
652 "single-value context"));
653 return false;
654 }
655 }
656
657 // Any value may be assigned to the blank identifier.
658 if (lhs != NULL
659 && !lhs->is_undefined()
660 && lhs->is_sink_type())
661 return true;
662
663 // Identical types are assignable.
664 if (Type::are_identical(lhs, rhs, Type::COMPARE_TAGS, reason))
665 return true;
666
667 // Ignore aliases, except for error messages.
668 const Type* lhs_orig = lhs;
669 const Type* rhs_orig = rhs;
670 lhs = lhs->unalias();
671 rhs = rhs->unalias();
672
673 // The types are assignable if they have identical underlying types
674 // and either LHS or RHS is not a named type.
675 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
676 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
677 && Type::are_identical(lhs->base(), rhs->base(), Type::COMPARE_TAGS,
678 reason))
679 return true;
680
681 // The types are assignable if LHS is an interface type and RHS
682 // implements the required methods.
683 const Interface_type* lhs_interface_type = lhs->interface_type();
684 if (lhs_interface_type != NULL)
685 {
686 if (lhs_interface_type->implements_interface(rhs, reason))
687 return true;
688 const Interface_type* rhs_interface_type = rhs->interface_type();
689 if (rhs_interface_type != NULL
690 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
691 reason))
692 return true;
693 }
694
695 // The type are assignable if RHS is a bidirectional channel type,
696 // LHS is a channel type, they have identical element types, and
697 // either LHS or RHS is not a named type.
698 if (lhs->channel_type() != NULL
699 && rhs->channel_type() != NULL
700 && rhs->channel_type()->may_send()
701 && rhs->channel_type()->may_receive()
702 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
703 && Type::are_identical(lhs->channel_type()->element_type(),
704 rhs->channel_type()->element_type(),
705 Type::COMPARE_TAGS,
706 reason))
707 return true;
708
709 // The nil type may be assigned to a pointer, function, slice, map,
710 // channel, or interface type.
711 if (rhs->is_nil_type()
712 && (lhs->points_to() != NULL
713 || lhs->function_type() != NULL
714 || lhs->is_slice_type()
715 || lhs->map_type() != NULL
716 || lhs->channel_type() != NULL
717 || lhs->interface_type() != NULL))
718 return true;
719
720 // An untyped numeric constant may be assigned to a numeric type if
721 // it is representable in that type.
722 if ((rhs->is_abstract()
723 && (rhs->integer_type() != NULL
724 || rhs->float_type() != NULL
725 || rhs->complex_type() != NULL))
726 && (lhs->integer_type() != NULL
727 || lhs->float_type() != NULL
728 || lhs->complex_type() != NULL))
729 return true;
730
731 // Give some better error messages.
732 if (reason != NULL && reason->empty())
733 {
734 if (rhs->interface_type() != NULL)
735 reason->assign(_("need explicit conversion"));
736 else if (lhs_orig->named_type() != NULL
737 && rhs_orig->named_type() != NULL)
738 {
739 size_t len = (lhs_orig->named_type()->name().length()
740 + rhs_orig->named_type()->name().length()
741 + 100);
742 char* buf = new char[len];
743 snprintf(buf, len, _("cannot use type %s as type %s"),
744 rhs_orig->named_type()->message_name().c_str(),
745 lhs_orig->named_type()->message_name().c_str());
746 reason->assign(buf);
747 delete[] buf;
748 }
749 }
750
751 return false;
752 }
753
754 // Return true if a value with type RHS may be converted to type LHS.
755 // If REASON is not NULL, set *REASON to the reason the types are not
756 // convertible.
757
758 bool
759 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
760 {
761 // The types are convertible if they are assignable.
762 if (Type::are_assignable(lhs, rhs, reason))
763 return true;
764
765 // Ignore aliases.
766 lhs = lhs->unalias();
767 rhs = rhs->unalias();
768
769 // A pointer to a regular type may not be converted to a pointer to
770 // a type that may not live in the heap, except when converting from
771 // unsafe.Pointer.
772 if (lhs->points_to() != NULL
773 && rhs->points_to() != NULL
774 && !lhs->points_to()->in_heap()
775 && rhs->points_to()->in_heap()
776 && !rhs->is_unsafe_pointer_type())
777 {
778 if (reason != NULL)
779 reason->assign(_("conversion from normal type to notinheap type"));
780 return false;
781 }
782
783 // The types are convertible if they have identical underlying
784 // types, ignoring struct field tags.
785 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
786 && Type::are_identical(lhs->base(), rhs->base(), 0, reason))
787 return true;
788
789 // The types are convertible if they are both unnamed pointer types
790 // and their pointer base types have identical underlying types,
791 // ignoring struct field tags.
792 if (lhs->named_type() == NULL
793 && rhs->named_type() == NULL
794 && lhs->points_to() != NULL
795 && rhs->points_to() != NULL
796 && (lhs->points_to()->named_type() != NULL
797 || rhs->points_to()->named_type() != NULL)
798 && Type::are_identical(lhs->points_to()->base(),
799 rhs->points_to()->base(),
800 0, reason))
801 return true;
802
803 // Integer and floating point types are convertible to each other.
804 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
805 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
806 return true;
807
808 // Complex types are convertible to each other.
809 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
810 return true;
811
812 // An integer, or []byte, or []rune, may be converted to a string.
813 if (lhs->is_string_type())
814 {
815 if (rhs->integer_type() != NULL)
816 return true;
817 if (rhs->is_slice_type())
818 {
819 const Type* e = rhs->array_type()->element_type()->forwarded();
820 if (e->integer_type() != NULL
821 && (e->integer_type()->is_byte()
822 || e->integer_type()->is_rune()))
823 return true;
824 }
825 }
826
827 // A string may be converted to []byte or []rune.
828 if (rhs->is_string_type() && lhs->is_slice_type())
829 {
830 const Type* e = lhs->array_type()->element_type()->forwarded();
831 if (e->integer_type() != NULL
832 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
833 return true;
834 }
835
836 // An unsafe.Pointer type may be converted to any pointer type or to
837 // a type whose underlying type is uintptr, and vice-versa.
838 if (lhs->is_unsafe_pointer_type()
839 && (rhs->points_to() != NULL
840 || (rhs->integer_type() != NULL
841 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
842 return true;
843 if (rhs->is_unsafe_pointer_type()
844 && (lhs->points_to() != NULL
845 || (lhs->integer_type() != NULL
846 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
847 return true;
848
849 // Give a better error message.
850 if (reason != NULL)
851 {
852 if (reason->empty())
853 *reason = "invalid type conversion";
854 else
855 {
856 std::string s = "invalid type conversion (";
857 s += *reason;
858 s += ')';
859 *reason = s;
860 }
861 }
862
863 return false;
864 }
865
866 // Copy expressions if it may change the size.
867 //
868 // The only type that has an expression is an array type. The only
869 // types whose size can be changed by the size of an array type are an
870 // array type itself, or a struct type with an array field.
871 Type*
872 Type::copy_expressions()
873 {
874 // This is run during parsing, so types may not be valid yet.
875 // We only have to worry about array type literals.
876 switch (this->classification_)
877 {
878 default:
879 return this;
880
881 case TYPE_ARRAY:
882 {
883 Array_type* at = this->array_type();
884 if (at->length() == NULL)
885 return this;
886 Expression* len = at->length()->copy();
887 if (at->length() == len)
888 return this;
889 return Type::make_array_type(at->element_type(), len);
890 }
891
892 case TYPE_STRUCT:
893 {
894 Struct_type* st = this->struct_type();
895 const Struct_field_list* sfl = st->fields();
896 if (sfl == NULL)
897 return this;
898 bool changed = false;
899 Struct_field_list *nsfl = new Struct_field_list();
900 for (Struct_field_list::const_iterator pf = sfl->begin();
901 pf != sfl->end();
902 ++pf)
903 {
904 Type* ft = pf->type()->copy_expressions();
905 Struct_field nf(Typed_identifier((pf->is_anonymous()
906 ? ""
907 : pf->field_name()),
908 ft,
909 pf->location()));
910 if (pf->has_tag())
911 nf.set_tag(pf->tag());
912 nsfl->push_back(nf);
913 if (ft != pf->type())
914 changed = true;
915 }
916 if (!changed)
917 {
918 delete(nsfl);
919 return this;
920 }
921 return Type::make_struct_type(nsfl, st->location());
922 }
923 }
924
925 go_unreachable();
926 }
927
928 // Return a hash code for the type to be used for method lookup.
929
930 unsigned int
931 Type::hash_for_method(Gogo* gogo, int flags) const
932 {
933 const Type* t = this->forwarded();
934 if (t->named_type() != NULL && t->named_type()->is_alias())
935 {
936 unsigned int r =
937 t->named_type()->real_type()->hash_for_method(gogo, flags);
938 if ((flags & Type::COMPARE_ALIASES) != 0)
939 r += TYPE_FORWARD;
940 return r;
941 }
942 unsigned int ret = t->classification_;
943 return ret + t->do_hash_for_method(gogo, flags);
944 }
945
946 // Default implementation of do_hash_for_method. This is appropriate
947 // for types with no subfields.
948
949 unsigned int
950 Type::do_hash_for_method(Gogo*, int) const
951 {
952 return 0;
953 }
954
955 // A hash table mapping unnamed types to the backend representation of
956 // those types.
957
958 Type::Type_btypes Type::type_btypes;
959
960 // Return the backend representation for this type.
961
962 Btype*
963 Type::get_backend(Gogo* gogo)
964 {
965 if (this->btype_ != NULL)
966 return this->btype_;
967
968 if (this->named_type() != NULL && this->named_type()->is_alias())
969 {
970 Btype* bt = this->unalias()->get_backend(gogo);
971 if (gogo != NULL && gogo->named_types_are_converted())
972 this->btype_ = bt;
973 return bt;
974 }
975
976 if (this->forward_declaration_type() != NULL
977 || this->named_type() != NULL)
978 return this->get_btype_without_hash(gogo);
979
980 if (this->is_error_type())
981 return gogo->backend()->error_type();
982
983 // To avoid confusing the backend, translate all identical Go types
984 // to the same backend representation. We use a hash table to do
985 // that. There is no need to use the hash table for named types, as
986 // named types are only identical to themselves.
987
988 std::pair<Type*, Type_btype_entry> val;
989 val.first = this;
990 val.second.btype = NULL;
991 val.second.is_placeholder = false;
992 std::pair<Type_btypes::iterator, bool> ins =
993 Type::type_btypes.insert(val);
994 if (!ins.second && ins.first->second.btype != NULL)
995 {
996 // Note that GOGO can be NULL here, but only when the GCC
997 // middle-end is asking for a frontend type. That will only
998 // happen for simple types, which should never require
999 // placeholders.
1000 if (!ins.first->second.is_placeholder)
1001 this->btype_ = ins.first->second.btype;
1002 else if (gogo->named_types_are_converted())
1003 {
1004 this->finish_backend(gogo, ins.first->second.btype);
1005 ins.first->second.is_placeholder = false;
1006 }
1007
1008 // We set the has_padding field of a Struct_type when we convert
1009 // to the backend type, so if we have multiple Struct_type's
1010 // mapping to the same backend type we need to copy the
1011 // has_padding field. FIXME: This is awkward. We shouldn't
1012 // really change the type when setting the backend type, but
1013 // there isn't any other good time to add the padding field.
1014 if (ins.first->first->struct_type() != NULL
1015 && ins.first->first->struct_type()->has_padding())
1016 this->struct_type()->set_has_padding();
1017
1018 return ins.first->second.btype;
1019 }
1020
1021 Btype* bt = this->get_btype_without_hash(gogo);
1022
1023 if (ins.first->second.btype == NULL)
1024 {
1025 ins.first->second.btype = bt;
1026 ins.first->second.is_placeholder = false;
1027 }
1028 else
1029 {
1030 // We have already created a backend representation for this
1031 // type. This can happen when an unnamed type is defined using
1032 // a named type which in turns uses an identical unnamed type.
1033 // Use the representation we created earlier and ignore the one we just
1034 // built.
1035 if (this->btype_ == bt)
1036 this->btype_ = ins.first->second.btype;
1037 bt = ins.first->second.btype;
1038 }
1039
1040 return bt;
1041 }
1042
1043 // Return the backend representation for a type without looking in the
1044 // hash table for identical types. This is used for named types,
1045 // since a named type is never identical to any other type.
1046
1047 Btype*
1048 Type::get_btype_without_hash(Gogo* gogo)
1049 {
1050 if (this->btype_ == NULL)
1051 {
1052 Btype* bt = this->do_get_backend(gogo);
1053
1054 // For a recursive function or pointer type, we will temporarily
1055 // return a circular pointer type during the recursion. We
1056 // don't want to record that for a forwarding type, as it may
1057 // confuse us later.
1058 if (this->forward_declaration_type() != NULL
1059 && gogo->backend()->is_circular_pointer_type(bt))
1060 return bt;
1061
1062 if (gogo == NULL || !gogo->named_types_are_converted())
1063 return bt;
1064
1065 this->btype_ = bt;
1066 }
1067 return this->btype_;
1068 }
1069
1070 // Get the backend representation of a type without forcing the
1071 // creation of the backend representation of all supporting types.
1072 // This will return a backend type that has the correct size but may
1073 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1074 // and will not contain the final representation of the type to which
1075 // it points. This is used while converting all named types to the
1076 // backend representation, to avoid problems with indirect references
1077 // to types which are not yet complete. When this is called, the
1078 // sizes of all direct references (e.g., a struct field) should be
1079 // known, but the sizes of indirect references (e.g., the type to
1080 // which a pointer points) may not.
1081
1082 Btype*
1083 Type::get_backend_placeholder(Gogo* gogo)
1084 {
1085 if (gogo->named_types_are_converted())
1086 return this->get_backend(gogo);
1087 if (this->btype_ != NULL)
1088 return this->btype_;
1089
1090 Btype* bt;
1091 switch (this->classification_)
1092 {
1093 case TYPE_ERROR:
1094 case TYPE_VOID:
1095 case TYPE_BOOLEAN:
1096 case TYPE_INTEGER:
1097 case TYPE_FLOAT:
1098 case TYPE_COMPLEX:
1099 case TYPE_STRING:
1100 case TYPE_NIL:
1101 // These are simple types that can just be created directly.
1102 return this->get_backend(gogo);
1103
1104 case TYPE_MAP:
1105 case TYPE_CHANNEL:
1106 // All maps and channels have the same backend representation.
1107 return this->get_backend(gogo);
1108
1109 case TYPE_NAMED:
1110 case TYPE_FORWARD:
1111 // Named types keep track of their own dependencies and manage
1112 // their own placeholders.
1113 if (this->named_type() != NULL && this->named_type()->is_alias())
1114 return this->unalias()->get_backend_placeholder(gogo);
1115 return this->get_backend(gogo);
1116
1117 case TYPE_INTERFACE:
1118 if (this->interface_type()->is_empty())
1119 return Interface_type::get_backend_empty_interface_type(gogo);
1120 break;
1121
1122 default:
1123 break;
1124 }
1125
1126 std::pair<Type*, Type_btype_entry> val;
1127 val.first = this;
1128 val.second.btype = NULL;
1129 val.second.is_placeholder = false;
1130 std::pair<Type_btypes::iterator, bool> ins =
1131 Type::type_btypes.insert(val);
1132 if (!ins.second && ins.first->second.btype != NULL)
1133 return ins.first->second.btype;
1134
1135 switch (this->classification_)
1136 {
1137 case TYPE_FUNCTION:
1138 {
1139 // A Go function type is a pointer to a struct type.
1140 Location loc = this->function_type()->location();
1141 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1142 Type::placeholder_pointers.push_back(this);
1143 }
1144 break;
1145
1146 case TYPE_POINTER:
1147 {
1148 Location loc = Linemap::unknown_location();
1149 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1150 Type::placeholder_pointers.push_back(this);
1151 }
1152 break;
1153
1154 case TYPE_STRUCT:
1155 // We don't have to make the struct itself be a placeholder. We
1156 // are promised that we know the sizes of the struct fields.
1157 // But we may have to use a placeholder for any particular
1158 // struct field.
1159 {
1160 std::vector<Backend::Btyped_identifier> bfields;
1161 get_backend_struct_fields(gogo, this->struct_type(), true, &bfields);
1162 bt = gogo->backend()->struct_type(bfields);
1163 }
1164 break;
1165
1166 case TYPE_ARRAY:
1167 if (this->is_slice_type())
1168 {
1169 std::vector<Backend::Btyped_identifier> bfields;
1170 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1171 bt = gogo->backend()->struct_type(bfields);
1172 }
1173 else
1174 {
1175 Btype* element = this->array_type()->get_backend_element(gogo, true);
1176 Bexpression* len = this->array_type()->get_backend_length(gogo);
1177 bt = gogo->backend()->array_type(element, len);
1178 }
1179 break;
1180
1181 case TYPE_INTERFACE:
1182 {
1183 go_assert(!this->interface_type()->is_empty());
1184 std::vector<Backend::Btyped_identifier> bfields;
1185 get_backend_interface_fields(gogo, this->interface_type(), true,
1186 &bfields);
1187 bt = gogo->backend()->struct_type(bfields);
1188 }
1189 break;
1190
1191 case TYPE_SINK:
1192 case TYPE_CALL_MULTIPLE_RESULT:
1193 /* Note that various classifications were handled in the earlier
1194 switch. */
1195 default:
1196 go_unreachable();
1197 }
1198
1199 if (ins.first->second.btype == NULL)
1200 {
1201 ins.first->second.btype = bt;
1202 ins.first->second.is_placeholder = true;
1203 }
1204 else
1205 {
1206 // A placeholder for this type got created along the way. Use
1207 // that one and ignore the one we just built.
1208 bt = ins.first->second.btype;
1209 }
1210
1211 return bt;
1212 }
1213
1214 // Complete the backend representation. This is called for a type
1215 // using a placeholder type.
1216
1217 void
1218 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1219 {
1220 switch (this->classification_)
1221 {
1222 case TYPE_ERROR:
1223 case TYPE_VOID:
1224 case TYPE_BOOLEAN:
1225 case TYPE_INTEGER:
1226 case TYPE_FLOAT:
1227 case TYPE_COMPLEX:
1228 case TYPE_STRING:
1229 case TYPE_NIL:
1230 go_unreachable();
1231
1232 case TYPE_FUNCTION:
1233 {
1234 Btype* bt = this->do_get_backend(gogo);
1235 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1236 go_assert(saw_errors());
1237 }
1238 break;
1239
1240 case TYPE_POINTER:
1241 {
1242 Btype* bt = this->do_get_backend(gogo);
1243 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1244 go_assert(saw_errors());
1245 }
1246 break;
1247
1248 case TYPE_STRUCT:
1249 // The struct type itself is done, but we have to make sure that
1250 // all the field types are converted.
1251 this->struct_type()->finish_backend_fields(gogo);
1252 break;
1253
1254 case TYPE_ARRAY:
1255 // The array type itself is done, but make sure the element type
1256 // is converted.
1257 this->array_type()->finish_backend_element(gogo);
1258 break;
1259
1260 case TYPE_MAP:
1261 case TYPE_CHANNEL:
1262 go_unreachable();
1263
1264 case TYPE_INTERFACE:
1265 // The interface type itself is done, but make sure the method
1266 // types are converted.
1267 this->interface_type()->finish_backend_methods(gogo);
1268 break;
1269
1270 case TYPE_NAMED:
1271 case TYPE_FORWARD:
1272 go_unreachable();
1273
1274 case TYPE_SINK:
1275 case TYPE_CALL_MULTIPLE_RESULT:
1276 default:
1277 go_unreachable();
1278 }
1279
1280 this->btype_ = placeholder;
1281 }
1282
1283 // Return a pointer to the type descriptor for this type.
1284
1285 Bexpression*
1286 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1287 {
1288 Type* t = this->unalias();
1289 if (t->type_descriptor_var_ == NULL)
1290 {
1291 t->make_type_descriptor_var(gogo);
1292 go_assert(t->type_descriptor_var_ != NULL);
1293 }
1294 Bexpression* var_expr =
1295 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1296 Bexpression* var_addr =
1297 gogo->backend()->address_expression(var_expr, location);
1298 Type* td_type = Type::make_type_descriptor_type();
1299 Btype* td_btype = td_type->get_backend(gogo);
1300 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1301 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1302 }
1303
1304 // A mapping from unnamed types to type descriptor variables.
1305
1306 Type::Type_descriptor_vars Type::type_descriptor_vars;
1307
1308 // Build the type descriptor for this type.
1309
1310 void
1311 Type::make_type_descriptor_var(Gogo* gogo)
1312 {
1313 go_assert(this->type_descriptor_var_ == NULL);
1314
1315 Named_type* nt = this->named_type();
1316
1317 // We can have multiple instances of unnamed types, but we only want
1318 // to emit the type descriptor once. We use a hash table. This is
1319 // not necessary for named types, as they are unique, and we store
1320 // the type descriptor in the type itself.
1321 Bvariable** phash = NULL;
1322 if (nt == NULL)
1323 {
1324 Bvariable* bvnull = NULL;
1325 std::pair<Type_descriptor_vars::iterator, bool> ins =
1326 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1327 if (!ins.second)
1328 {
1329 // We've already built a type descriptor for this type.
1330 this->type_descriptor_var_ = ins.first->second;
1331 return;
1332 }
1333 phash = &ins.first->second;
1334 }
1335
1336 // The type descriptor symbol for the unsafe.Pointer type is defined in
1337 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1338 // symbol if necessary.
1339 if (this->is_unsafe_pointer_type())
1340 {
1341 Location bloc = Linemap::predeclared_location();
1342
1343 Type* td_type = Type::make_type_descriptor_type();
1344 Btype* td_btype = td_type->get_backend(gogo);
1345 std::string name = gogo->type_descriptor_name(this, nt);
1346 std::string asm_name(go_selectively_encode_id(name));
1347 this->type_descriptor_var_ =
1348 gogo->backend()->immutable_struct_reference(name, asm_name,
1349 td_btype,
1350 bloc);
1351
1352 if (phash != NULL)
1353 *phash = this->type_descriptor_var_;
1354 return;
1355 }
1356
1357 std::string var_name = gogo->type_descriptor_name(this, nt);
1358
1359 // Build the contents of the type descriptor.
1360 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1361
1362 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1363
1364 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1365
1366 const Package* dummy;
1367 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1368 {
1369 std::string asm_name(go_selectively_encode_id(var_name));
1370 this->type_descriptor_var_ =
1371 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1372 initializer_btype,
1373 loc);
1374 if (phash != NULL)
1375 *phash = this->type_descriptor_var_;
1376 return;
1377 }
1378
1379 // See if this type descriptor can appear in multiple packages.
1380 bool is_common = false;
1381 if (nt != NULL)
1382 {
1383 // We create the descriptor for a builtin type whenever we need
1384 // it.
1385 is_common = nt->is_builtin();
1386 }
1387 else
1388 {
1389 // This is an unnamed type. The descriptor could be defined in
1390 // any package where it is needed, and the linker will pick one
1391 // descriptor to keep.
1392 is_common = true;
1393 }
1394
1395 // We are going to build the type descriptor in this package. We
1396 // must create the variable before we convert the initializer to the
1397 // backend representation, because the initializer may refer to the
1398 // type descriptor of this type. By setting type_descriptor_var_ we
1399 // ensure that type_descriptor_pointer will work if called while
1400 // converting INITIALIZER.
1401
1402 std::string asm_name(go_selectively_encode_id(var_name));
1403 this->type_descriptor_var_ =
1404 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1405 initializer_btype, loc);
1406 if (phash != NULL)
1407 *phash = this->type_descriptor_var_;
1408
1409 Translate_context context(gogo, NULL, NULL, NULL);
1410 context.set_is_const();
1411 Bexpression* binitializer = initializer->get_backend(&context);
1412
1413 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1414 var_name, false, is_common,
1415 initializer_btype, loc,
1416 binitializer);
1417
1418 // For types that may be created by reflection, add it to the
1419 // list of which we will register the type descriptor to the
1420 // runtime.
1421 // Do not add generated incomparable array/struct types, see
1422 // issue #22605.
1423 if (is_common
1424 && (this->points_to() != NULL
1425 || this->channel_type() != NULL
1426 || this->map_type() != NULL
1427 || this->function_type() != NULL
1428 || this->is_slice_type()
1429 || (this->struct_type() != NULL
1430 && !this->struct_type()->is_struct_incomparable())
1431 || (this->array_type() != NULL
1432 && !this->array_type()->is_array_incomparable())))
1433 gogo->add_type_descriptor(this);
1434 }
1435
1436 // Return true if this type descriptor is defined in a different
1437 // package. If this returns true it sets *PACKAGE to the package.
1438
1439 bool
1440 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1441 const Package** package)
1442 {
1443 if (nt != NULL)
1444 {
1445 if (nt->named_object()->package() != NULL)
1446 {
1447 // This is a named type defined in a different package. The
1448 // type descriptor should be defined in that package.
1449 *package = nt->named_object()->package();
1450 return true;
1451 }
1452 }
1453 else
1454 {
1455 if (this->points_to() != NULL
1456 && this->points_to()->unalias()->named_type() != NULL
1457 && this->points_to()->unalias()->named_type()->named_object()->package() != NULL)
1458 {
1459 // This is an unnamed pointer to a named type defined in a
1460 // different package. The descriptor should be defined in
1461 // that package.
1462 *package = this->points_to()->unalias()->named_type()->named_object()->package();
1463 return true;
1464 }
1465 }
1466 return false;
1467 }
1468
1469 // Return a composite literal for a type descriptor.
1470
1471 Expression*
1472 Type::type_descriptor(Gogo* gogo, Type* type)
1473 {
1474 return type->do_type_descriptor(gogo, NULL);
1475 }
1476
1477 // Return a composite literal for a type descriptor with a name.
1478
1479 Expression*
1480 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1481 {
1482 go_assert(name != NULL && type->named_type() != name);
1483 return type->do_type_descriptor(gogo, name);
1484 }
1485
1486 // Make a builtin struct type from a list of fields. The fields are
1487 // pairs of a name and a type.
1488
1489 Struct_type*
1490 Type::make_builtin_struct_type(int nfields, ...)
1491 {
1492 va_list ap;
1493 va_start(ap, nfields);
1494
1495 Location bloc = Linemap::predeclared_location();
1496 Struct_field_list* sfl = new Struct_field_list();
1497 for (int i = 0; i < nfields; i++)
1498 {
1499 const char* field_name = va_arg(ap, const char *);
1500 Type* type = va_arg(ap, Type*);
1501 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1502 }
1503
1504 va_end(ap);
1505
1506 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1507 ret->set_is_struct_incomparable();
1508 return ret;
1509 }
1510
1511 // A list of builtin named types.
1512
1513 std::vector<Named_type*> Type::named_builtin_types;
1514
1515 // Make a builtin named type.
1516
1517 Named_type*
1518 Type::make_builtin_named_type(const char* name, Type* type)
1519 {
1520 Location bloc = Linemap::predeclared_location();
1521 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1522 Named_type* ret = no->type_value();
1523 Type::named_builtin_types.push_back(ret);
1524 return ret;
1525 }
1526
1527 // Convert the named builtin types.
1528
1529 void
1530 Type::convert_builtin_named_types(Gogo* gogo)
1531 {
1532 for (std::vector<Named_type*>::const_iterator p =
1533 Type::named_builtin_types.begin();
1534 p != Type::named_builtin_types.end();
1535 ++p)
1536 {
1537 bool r = (*p)->verify();
1538 go_assert(r);
1539 (*p)->convert(gogo);
1540 }
1541 }
1542
1543 // Values to store in the tflag field of a type descriptor. This must
1544 // match the definitions in libgo/go/runtime/type.go.
1545
1546 const int TFLAG_REGULAR_MEMORY = 1 << 3;
1547
1548 // Return the type of a type descriptor. We should really tie this to
1549 // runtime.Type rather than copying it. This must match the struct "_type"
1550 // declared in libgo/go/runtime/type.go.
1551
1552 Type*
1553 Type::make_type_descriptor_type()
1554 {
1555 static Type* ret;
1556 if (ret == NULL)
1557 {
1558 Location bloc = Linemap::predeclared_location();
1559
1560 Type* uint8_type = Type::lookup_integer_type("uint8");
1561 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1562 Type* uint32_type = Type::lookup_integer_type("uint32");
1563 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1564 Type* string_type = Type::lookup_string_type();
1565 Type* pointer_string_type = Type::make_pointer_type(string_type);
1566
1567 // This is an unnamed version of unsafe.Pointer. Perhaps we
1568 // should use the named version instead, although that would
1569 // require us to create the unsafe package if it has not been
1570 // imported. It probably doesn't matter.
1571 Type* void_type = Type::make_void_type();
1572 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1573
1574 Typed_identifier_list* params = new Typed_identifier_list();
1575 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1576 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1577
1578 Typed_identifier_list* results = new Typed_identifier_list();
1579 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1580
1581 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1582 bloc);
1583
1584 // Forward declaration for the type descriptor type.
1585 Named_object* named_type_descriptor_type =
1586 Named_object::make_type_declaration("_type", NULL, bloc);
1587 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1588 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1589
1590 // The type of a method on a concrete type.
1591 Struct_type* method_type =
1592 Type::make_builtin_struct_type(5,
1593 "name", pointer_string_type,
1594 "pkgPath", pointer_string_type,
1595 "mtyp", pointer_type_descriptor_type,
1596 "typ", pointer_type_descriptor_type,
1597 "tfn", unsafe_pointer_type);
1598 Named_type* named_method_type =
1599 Type::make_builtin_named_type("method", method_type);
1600
1601 // Information for types with a name or methods.
1602 Type* slice_named_method_type =
1603 Type::make_array_type(named_method_type, NULL);
1604 Struct_type* uncommon_type =
1605 Type::make_builtin_struct_type(3,
1606 "name", pointer_string_type,
1607 "pkgPath", pointer_string_type,
1608 "methods", slice_named_method_type);
1609 Named_type* named_uncommon_type =
1610 Type::make_builtin_named_type("uncommonType", uncommon_type);
1611
1612 Type* pointer_uncommon_type =
1613 Type::make_pointer_type(named_uncommon_type);
1614
1615 // The type descriptor type.
1616
1617 Struct_type* type_descriptor_type =
1618 Type::make_builtin_struct_type(12,
1619 "size", uintptr_type,
1620 "ptrdata", uintptr_type,
1621 "hash", uint32_type,
1622 "tflag", uint8_type,
1623 "align", uint8_type,
1624 "fieldAlign", uint8_type,
1625 "kind", uint8_type,
1626 "equal", equal_fntype,
1627 "gcdata", pointer_uint8_type,
1628 "string", pointer_string_type,
1629 "", pointer_uncommon_type,
1630 "ptrToThis",
1631 pointer_type_descriptor_type);
1632
1633 Named_type* named = Type::make_builtin_named_type("_type",
1634 type_descriptor_type);
1635
1636 named_type_descriptor_type->set_type_value(named);
1637
1638 ret = named;
1639 }
1640
1641 return ret;
1642 }
1643
1644 // Make the type of a pointer to a type descriptor as represented in
1645 // Go.
1646
1647 Type*
1648 Type::make_type_descriptor_ptr_type()
1649 {
1650 static Type* ret;
1651 if (ret == NULL)
1652 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1653 return ret;
1654 }
1655
1656 // Return the alignment required by the memequalN function. N is a
1657 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1658 // in libgo/go/runtime/alg.go.
1659
1660 int64_t
1661 Type::memequal_align(Gogo* gogo, int size)
1662 {
1663 const char* tn;
1664 switch (size)
1665 {
1666 case 16:
1667 tn = "int16";
1668 break;
1669 case 32:
1670 tn = "int32";
1671 break;
1672 case 64:
1673 tn = "int64";
1674 break;
1675 case 128:
1676 // The code uses [2]int64, which must have the same alignment as
1677 // int64.
1678 tn = "int64";
1679 break;
1680 default:
1681 go_unreachable();
1682 }
1683
1684 Type* t = Type::lookup_integer_type(tn);
1685
1686 int64_t ret;
1687 if (!t->backend_type_align(gogo, &ret))
1688 go_unreachable();
1689 return ret;
1690 }
1691
1692 // Return whether this type needs specially built type functions.
1693 // This returns true for types that are comparable and either can not
1694 // use an identity comparison, or are a non-standard size.
1695
1696 bool
1697 Type::needs_specific_type_functions(Gogo* gogo)
1698 {
1699 Named_type* nt = this->named_type();
1700 if (nt != NULL && nt->is_alias())
1701 return false;
1702 if (!this->is_comparable())
1703 return false;
1704 if (!this->compare_is_identity(gogo))
1705 return true;
1706
1707 // We create a few predeclared types for type descriptors; they are
1708 // really just for the backend and don't need hash or equality
1709 // functions.
1710 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1711 return false;
1712
1713 int64_t size, align;
1714 if (!this->backend_type_size(gogo, &size)
1715 || !this->backend_type_align(gogo, &align))
1716 {
1717 go_assert(saw_errors());
1718 return false;
1719 }
1720 // This switch matches the one in Type::equal_function.
1721 switch (size)
1722 {
1723 case 0:
1724 case 1:
1725 case 2:
1726 return align < Type::memequal_align(gogo, 16);
1727 case 4:
1728 return align < Type::memequal_align(gogo, 32);
1729 case 8:
1730 return align < Type::memequal_align(gogo, 64);
1731 case 16:
1732 return align < Type::memequal_align(gogo, 128);
1733 default:
1734 return true;
1735 }
1736 }
1737
1738 // Return the runtime function that computes the hash of this type.
1739 // HASH_FNTYPE is the type of the hash function function, for
1740 // convenience; it may be NULL. This returns NULL if the type is not
1741 // comparable.
1742
1743 Named_object*
1744 Type::hash_function(Gogo* gogo, Function_type* hash_fntype)
1745 {
1746 if (!this->is_comparable())
1747 return NULL;
1748
1749 if (hash_fntype == NULL)
1750 {
1751 Location bloc = Linemap::predeclared_location();
1752 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1753 Type* void_type = Type::make_void_type();
1754 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1755 Typed_identifier_list* params = new Typed_identifier_list();
1756 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1757 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1758 Typed_identifier_list* results = new Typed_identifier_list();
1759 results->push_back(Typed_identifier("", uintptr_type, bloc));
1760 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1761 }
1762
1763 const char* hash_fnname;
1764 if (this->compare_is_identity(gogo))
1765 {
1766 int64_t size;
1767 if (!this->backend_type_size(gogo, &size))
1768 {
1769 go_assert(saw_errors());
1770 return NULL;
1771 }
1772 switch (size)
1773 {
1774 case 0:
1775 hash_fnname = "runtime.memhash0";
1776 break;
1777 case 1:
1778 hash_fnname = "runtime.memhash8";
1779 break;
1780 case 2:
1781 hash_fnname = "runtime.memhash16";
1782 break;
1783 case 4:
1784 hash_fnname = "runtime.memhash32";
1785 break;
1786 case 8:
1787 hash_fnname = "runtime.memhash64";
1788 break;
1789 case 16:
1790 hash_fnname = "runtime.memhash128";
1791 break;
1792 default:
1793 // We don't have a built-in function for a type of this
1794 // size. Build a function to use that calls the generic
1795 // hash functions for identity, passing the size.
1796 return this->build_hash_function(gogo, size, hash_fntype);
1797 }
1798 }
1799 else
1800 {
1801 switch (this->base()->classification())
1802 {
1803 case Type::TYPE_ERROR:
1804 case Type::TYPE_VOID:
1805 case Type::TYPE_NIL:
1806 case Type::TYPE_FUNCTION:
1807 case Type::TYPE_MAP:
1808 // For these types is_comparable should have returned false.
1809 go_unreachable();
1810
1811 case Type::TYPE_BOOLEAN:
1812 case Type::TYPE_INTEGER:
1813 case Type::TYPE_POINTER:
1814 case Type::TYPE_CHANNEL:
1815 // For these types compare_is_identity should have returned true.
1816 go_unreachable();
1817
1818 case Type::TYPE_FLOAT:
1819 switch (this->float_type()->bits())
1820 {
1821 case 32:
1822 hash_fnname = "runtime.f32hash";
1823 break;
1824 case 64:
1825 hash_fnname = "runtime.f64hash";
1826 break;
1827 default:
1828 go_unreachable();
1829 }
1830 break;
1831
1832 case Type::TYPE_COMPLEX:
1833 switch (this->complex_type()->bits())
1834 {
1835 case 64:
1836 hash_fnname = "runtime.c64hash";
1837 break;
1838 case 128:
1839 hash_fnname = "runtime.c128hash";
1840 break;
1841 default:
1842 go_unreachable();
1843 }
1844 break;
1845
1846 case Type::TYPE_STRING:
1847 hash_fnname = "runtime.strhash";
1848 break;
1849
1850 case Type::TYPE_STRUCT:
1851 // This is a struct which can not be compared using a simple
1852 // identity function. We need to build a function to
1853 // compute the hash.
1854 return this->build_hash_function(gogo, -1, hash_fntype);
1855
1856 case Type::TYPE_ARRAY:
1857 if (this->is_slice_type())
1858 {
1859 // Type::is_compatible_for_comparison should have
1860 // returned false.
1861 go_unreachable();
1862 }
1863 else
1864 {
1865 // This is an array which can not be compared using a
1866 // simple identity function. We need to build a
1867 // function to compute the hash.
1868 return this->build_hash_function(gogo, -1, hash_fntype);
1869 }
1870 break;
1871
1872 case Type::TYPE_INTERFACE:
1873 if (this->interface_type()->is_empty())
1874 hash_fnname = "runtime.nilinterhash";
1875 else
1876 hash_fnname = "runtime.interhash";
1877 break;
1878
1879 case Type::TYPE_NAMED:
1880 case Type::TYPE_FORWARD:
1881 go_unreachable();
1882
1883 default:
1884 go_unreachable();
1885 }
1886 }
1887
1888 Location bloc = Linemap::predeclared_location();
1889 Named_object *hash_fn = Named_object::make_function_declaration(hash_fnname,
1890 NULL,
1891 hash_fntype,
1892 bloc);
1893 hash_fn->func_declaration_value()->set_asm_name(hash_fnname);
1894 return hash_fn;
1895 }
1896
1897 // A hash table mapping types to the specific hash functions.
1898
1899 Type::Type_function Type::type_hash_functions_table;
1900
1901 // Build a hash function that is specific to a type: if SIZE == -1,
1902 // this is a struct or array type that cannot use an identity
1903 // comparison. Otherwise, it is a type that uses an identity
1904 // comparison but is not one of the standard supported sizes.
1905 //
1906 // Unlike an equality function, hash functions are not in type
1907 // descriptors, so we can't assume that a named type has defined a
1908 // hash function in the package that defines the type. So hash
1909 // functions are always defined locally. FIXME: It would be better to
1910 // define hash functions with comdat linkage so that duplicate hash
1911 // functions can be coalesced at link time.
1912
1913 Named_object*
1914 Type::build_hash_function(Gogo* gogo, int64_t size, Function_type* hash_fntype)
1915 {
1916 Type* type = this->base();
1917
1918 std::pair<Type*, Named_object*> val(type, NULL);
1919 std::pair<Type_function::iterator, bool> ins =
1920 Type::type_hash_functions_table.insert(val);
1921 if (!ins.second)
1922 {
1923 // We already have a function for this type.
1924 return ins.first->second;
1925 }
1926
1927 std::string hash_name = gogo->hash_function_name(type);
1928
1929 Location bloc = Linemap::predeclared_location();
1930
1931 Named_object* hash_fn = gogo->declare_package_function(hash_name,
1932 hash_fntype, bloc);
1933
1934 ins.first->second = hash_fn;
1935
1936 if (gogo->in_global_scope())
1937 type->write_hash_function(gogo, size, hash_name, hash_fntype);
1938 else
1939 gogo->queue_hash_function(type, size, hash_name, hash_fntype);
1940
1941 return hash_fn;
1942 }
1943
1944 // Write the hash function for a type that needs it written specially.
1945
1946 void
1947 Type::write_hash_function(Gogo* gogo, int64_t size,
1948 const std::string& hash_name,
1949 Function_type* hash_fntype)
1950 {
1951 Location bloc = Linemap::predeclared_location();
1952
1953 if (gogo->specific_type_functions_are_written())
1954 {
1955 go_assert(saw_errors());
1956 return;
1957 }
1958
1959 go_assert(this->is_comparable());
1960
1961 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1962 bloc);
1963 hash_fn->func_value()->set_is_type_specific_function();
1964 gogo->start_block(bloc);
1965
1966 if (size != -1)
1967 this->write_identity_hash(gogo, size);
1968 else if (this->struct_type() != NULL)
1969 this->struct_type()->write_hash_function(gogo, hash_fntype);
1970 else if (this->array_type() != NULL)
1971 this->array_type()->write_hash_function(gogo, hash_fntype);
1972 else
1973 go_unreachable();
1974
1975 Block* b = gogo->finish_block(bloc);
1976 gogo->add_block(b, bloc);
1977 gogo->lower_block(hash_fn, b);
1978 gogo->order_block(b);
1979 gogo->remove_shortcuts_in_block(b);
1980 gogo->finish_function(bloc);
1981
1982 // Build the function descriptor for the type descriptor to refer to.
1983 hash_fn->func_value()->descriptor(gogo, hash_fn);
1984 }
1985
1986 // Write a hash function for a type that can use an identity hash but
1987 // is not one of the standard supported sizes. For example, this
1988 // would be used for the type [3]byte. This builds a return statement
1989 // that returns a call to the memhash function, passing the key and
1990 // seed from the function arguments (already constructed before this
1991 // is called), and the constant size.
1992
1993 void
1994 Type::write_identity_hash(Gogo* gogo, int64_t size)
1995 {
1996 Location bloc = Linemap::predeclared_location();
1997
1998 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
1999 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2000
2001 Typed_identifier_list* params = new Typed_identifier_list();
2002 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2003 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2004 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2005
2006 Typed_identifier_list* results = new Typed_identifier_list();
2007 results->push_back(Typed_identifier("", uintptr_type, bloc));
2008
2009 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2010 results, bloc);
2011
2012 Named_object* memhash =
2013 Named_object::make_function_declaration("runtime.memhash", NULL,
2014 memhash_fntype, bloc);
2015 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2016
2017 Named_object* key_arg = gogo->lookup("key", NULL);
2018 go_assert(key_arg != NULL);
2019 Named_object* seed_arg = gogo->lookup("seed", NULL);
2020 go_assert(seed_arg != NULL);
2021
2022 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2023 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2024 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2025 bloc);
2026 Expression_list* args = new Expression_list();
2027 args->push_back(key_ref);
2028 args->push_back(seed_ref);
2029 args->push_back(size_arg);
2030 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2031 Expression* call = Expression::make_call(func, args, false, bloc);
2032
2033 Expression_list* vals = new Expression_list();
2034 vals->push_back(call);
2035 Statement* s = Statement::make_return_statement(vals, bloc);
2036 gogo->add_statement(s);
2037 }
2038
2039 // Return the runtime function that compares whether two values of
2040 // this type are equal. If NAME is not NULL it is the name of this
2041 // type. EQUAL_FNTYPE is the type of the equality function, for
2042 // convenience; it may be NULL. This returns NULL if the type is not
2043 // comparable.
2044
2045 Named_object*
2046 Type::equal_function(Gogo* gogo, Named_type* name, Function_type* equal_fntype)
2047 {
2048 // If the unaliased type is not a named type, then the type does not
2049 // have a name after all.
2050 if (name != NULL)
2051 name = name->unalias()->named_type();
2052
2053 if (!this->is_comparable())
2054 return NULL;
2055
2056 if (equal_fntype == NULL)
2057 {
2058 Location bloc = Linemap::predeclared_location();
2059 Type* void_type = Type::make_void_type();
2060 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
2061 Typed_identifier_list* params = new Typed_identifier_list();
2062 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2063 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2064 Typed_identifier_list* results = new Typed_identifier_list();
2065 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2066 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
2067 }
2068
2069 const char* equal_fnname;
2070 if (this->compare_is_identity(gogo))
2071 {
2072 int64_t size, align;
2073 if (!this->backend_type_size(gogo, &size)
2074 || !this->backend_type_align(gogo, &align))
2075 {
2076 go_assert(saw_errors());
2077 return NULL;
2078 }
2079 bool build_function = false;
2080 // This switch matches the one in Type::needs_specific_type_functions.
2081 // The alignment tests are because of the memequal functions,
2082 // which assume that the values are aligned as required for an
2083 // integer of that size.
2084 switch (size)
2085 {
2086 case 0:
2087 equal_fnname = "runtime.memequal0";
2088 break;
2089 case 1:
2090 equal_fnname = "runtime.memequal8";
2091 break;
2092 case 2:
2093 if (align < Type::memequal_align(gogo, 16))
2094 build_function = true;
2095 else
2096 equal_fnname = "runtime.memequal16";
2097 break;
2098 case 4:
2099 if (align < Type::memequal_align(gogo, 32))
2100 build_function = true;
2101 else
2102 equal_fnname = "runtime.memequal32";
2103 break;
2104 case 8:
2105 if (align < Type::memequal_align(gogo, 64))
2106 build_function = true;
2107 else
2108 equal_fnname = "runtime.memequal64";
2109 break;
2110 case 16:
2111 if (align < Type::memequal_align(gogo, 128))
2112 build_function = true;
2113 else
2114 equal_fnname = "runtime.memequal128";
2115 break;
2116 default:
2117 build_function = true;
2118 break;
2119 }
2120 if (build_function)
2121 {
2122 // We don't have a built-in function for a type of this size
2123 // and alignment. Build a function to use that calls the
2124 // generic equality functions for identity, passing the size.
2125 return this->build_equal_function(gogo, name, size, equal_fntype);
2126 }
2127 }
2128 else
2129 {
2130 switch (this->base()->classification())
2131 {
2132 case Type::TYPE_ERROR:
2133 case Type::TYPE_VOID:
2134 case Type::TYPE_NIL:
2135 case Type::TYPE_FUNCTION:
2136 case Type::TYPE_MAP:
2137 // For these types is_comparable should have returned false.
2138 go_unreachable();
2139
2140 case Type::TYPE_BOOLEAN:
2141 case Type::TYPE_INTEGER:
2142 case Type::TYPE_POINTER:
2143 case Type::TYPE_CHANNEL:
2144 // For these types compare_is_identity should have returned true.
2145 go_unreachable();
2146
2147 case Type::TYPE_FLOAT:
2148 switch (this->float_type()->bits())
2149 {
2150 case 32:
2151 equal_fnname = "runtime.f32equal";
2152 break;
2153 case 64:
2154 equal_fnname = "runtime.f64equal";
2155 break;
2156 default:
2157 go_unreachable();
2158 }
2159 break;
2160
2161 case Type::TYPE_COMPLEX:
2162 switch (this->complex_type()->bits())
2163 {
2164 case 64:
2165 equal_fnname = "runtime.c64equal";
2166 break;
2167 case 128:
2168 equal_fnname = "runtime.c128equal";
2169 break;
2170 default:
2171 go_unreachable();
2172 }
2173 break;
2174
2175 case Type::TYPE_STRING:
2176 equal_fnname = "runtime.strequal";
2177 break;
2178
2179 case Type::TYPE_STRUCT:
2180 // This is a struct which can not be compared using a simple
2181 // identity function. We need to build a function for
2182 // comparison.
2183 return this->build_equal_function(gogo, name, -1, equal_fntype);
2184
2185 case Type::TYPE_ARRAY:
2186 if (this->is_slice_type())
2187 {
2188 // Type::is_compatible_for_comparison should have
2189 // returned false.
2190 go_unreachable();
2191 }
2192 else
2193 {
2194 // This is an array which can not be compared using a
2195 // simple identity function. We need to build a
2196 // function for comparison.
2197 return this->build_equal_function(gogo, name, -1, equal_fntype);
2198 }
2199 break;
2200
2201 case Type::TYPE_INTERFACE:
2202 if (this->interface_type()->is_empty())
2203 equal_fnname = "runtime.nilinterequal";
2204 else
2205 equal_fnname = "runtime.interequal";
2206 break;
2207
2208 case Type::TYPE_NAMED:
2209 case Type::TYPE_FORWARD:
2210 go_unreachable();
2211
2212 default:
2213 go_unreachable();
2214 }
2215 }
2216
2217 Location bloc = Linemap::predeclared_location();
2218 Named_object* equal_fn =
2219 Named_object::make_function_declaration(equal_fnname, NULL, equal_fntype,
2220 bloc);
2221 equal_fn->func_declaration_value()->set_asm_name(equal_fnname);
2222 return equal_fn;
2223 }
2224
2225 // A hash table mapping types to the specific equal functions.
2226
2227 Type::Type_function Type::type_equal_functions_table;
2228
2229 // Build an equality function that is specific to a type: if SIZE ==
2230 // -1, this is a struct or array type that cannot use an identity
2231 // comparison. Otherwise, it is a type that uses an identity
2232 // comparison but is not one of the standard supported sizes or it is
2233 // not aligned as needed.
2234
2235 Named_object*
2236 Type::build_equal_function(Gogo* gogo, Named_type* name, int64_t size,
2237 Function_type* equal_fntype)
2238 {
2239 std::pair<Type*, Named_object*> val(name != NULL ? name : this, NULL);
2240 std::pair<Type_function::iterator, bool> ins =
2241 Type::type_equal_functions_table.insert(val);
2242 if (!ins.second)
2243 {
2244 // We already have a function for this type.
2245 return ins.first->second;
2246 }
2247
2248 std::string equal_name = gogo->equal_function_name(this, name);
2249
2250 Location bloc = Linemap::predeclared_location();
2251
2252 const Package* package = NULL;
2253 bool is_defined_elsewhere =
2254 this->type_descriptor_defined_elsewhere(name, &package);
2255
2256 Named_object* equal_fn;
2257 if (is_defined_elsewhere)
2258 equal_fn = Named_object::make_function_declaration(equal_name, package,
2259 equal_fntype, bloc);
2260 else
2261 equal_fn = gogo->declare_package_function(equal_name, equal_fntype, bloc);
2262
2263 ins.first->second = equal_fn;
2264
2265 if (!is_defined_elsewhere)
2266 {
2267 if (gogo->in_global_scope())
2268 this->write_equal_function(gogo, name, size, equal_name, equal_fntype);
2269 else
2270 gogo->queue_equal_function(this, name, size, equal_name, equal_fntype);
2271 }
2272
2273 return equal_fn;
2274 }
2275
2276 // Write the equal function for a type that needs it written
2277 // specially.
2278
2279 void
2280 Type::write_equal_function(Gogo* gogo, Named_type* name, int64_t size,
2281 const std::string& equal_name,
2282 Function_type* equal_fntype)
2283 {
2284 Location bloc = Linemap::predeclared_location();
2285
2286 if (gogo->specific_type_functions_are_written())
2287 {
2288 go_assert(saw_errors());
2289 return;
2290 }
2291
2292 go_assert(this->is_comparable());
2293
2294 Named_object* equal_fn = gogo->start_function(equal_name, equal_fntype,
2295 false, bloc);
2296 equal_fn->func_value()->set_is_type_specific_function();
2297 gogo->start_block(bloc);
2298
2299 if (size != -1)
2300 this->write_identity_equal(gogo, size);
2301 else if (name != NULL && name->real_type()->named_type() != NULL)
2302 this->write_named_equal(gogo, name);
2303 else if (this->struct_type() != NULL)
2304 this->struct_type()->write_equal_function(gogo, name);
2305 else if (this->array_type() != NULL)
2306 this->array_type()->write_equal_function(gogo, name);
2307 else
2308 go_unreachable();
2309
2310 Block* b = gogo->finish_block(bloc);
2311 gogo->add_block(b, bloc);
2312 gogo->lower_block(equal_fn, b);
2313 gogo->order_block(b);
2314 gogo->remove_shortcuts_in_block(b);
2315 gogo->finish_function(bloc);
2316
2317 // Build the function descriptor for the type descriptor to refer to.
2318 equal_fn->func_value()->descriptor(gogo, equal_fn);
2319 }
2320
2321 // Write an equality function for a type that can use an identity
2322 // equality comparison but is not one of the standard supported sizes.
2323 // For example, this would be used for the type [3]byte. This builds
2324 // a return statement that returns a call to the memequal function,
2325 // passing the two keys from the function arguments (already
2326 // constructed before this is called), and the constant size.
2327
2328 void
2329 Type::write_identity_equal(Gogo* gogo, int64_t size)
2330 {
2331 Location bloc = Linemap::predeclared_location();
2332
2333 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2334 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2335
2336 Typed_identifier_list* params = new Typed_identifier_list();
2337 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2338 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2339 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2340
2341 Typed_identifier_list* results = new Typed_identifier_list();
2342 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2343
2344 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2345 results, bloc);
2346
2347 Named_object* memequal =
2348 Named_object::make_function_declaration("runtime.memequal", NULL,
2349 memequal_fntype, bloc);
2350 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2351
2352 Named_object* key1_arg = gogo->lookup("key1", NULL);
2353 go_assert(key1_arg != NULL);
2354 Named_object* key2_arg = gogo->lookup("key2", NULL);
2355 go_assert(key2_arg != NULL);
2356
2357 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2358 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2359 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2360 bloc);
2361 Expression_list* args = new Expression_list();
2362 args->push_back(key1_ref);
2363 args->push_back(key2_ref);
2364 args->push_back(size_arg);
2365 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2366 Expression* call = Expression::make_call(func, args, false, bloc);
2367
2368 Expression_list* vals = new Expression_list();
2369 vals->push_back(call);
2370 Statement* s = Statement::make_return_statement(vals, bloc);
2371 gogo->add_statement(s);
2372 }
2373
2374 // Write an equality function that simply calls the equality function
2375 // for a named type. This is used when one named type is defined as
2376 // another. This ensures that this case works when the other named
2377 // type is defined in another package and relies on calling equality
2378 // functions defined only in that package.
2379
2380 void
2381 Type::write_named_equal(Gogo* gogo, Named_type* name)
2382 {
2383 Location bloc = Linemap::predeclared_location();
2384
2385 // The pointers to the types we are going to compare. These have
2386 // type unsafe.Pointer.
2387 Named_object* key1_arg = gogo->lookup("key1", NULL);
2388 Named_object* key2_arg = gogo->lookup("key2", NULL);
2389 go_assert(key1_arg != NULL && key2_arg != NULL);
2390
2391 Named_type* base_type = name->real_type()->named_type();
2392 go_assert(base_type != NULL);
2393
2394 // Build temporaries with the base type.
2395 Type* pt = Type::make_pointer_type(base_type);
2396
2397 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2398 ref = Expression::make_cast(pt, ref, bloc);
2399 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2400 gogo->add_statement(p1);
2401
2402 ref = Expression::make_var_reference(key2_arg, bloc);
2403 ref = Expression::make_cast(pt, ref, bloc);
2404 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2405 gogo->add_statement(p2);
2406
2407 // Compare the values for equality.
2408 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2409 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2410
2411 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2412 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2413
2414 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2415
2416 // Return the equality comparison.
2417 Expression_list* vals = new Expression_list();
2418 vals->push_back(cond);
2419 Statement* s = Statement::make_return_statement(vals, bloc);
2420 gogo->add_statement(s);
2421 }
2422
2423 // Return whether this type is stored directly in an interface's
2424 // data word.
2425 //
2426 // Since finalize_methods runs before type checking, we may see a
2427 // malformed type like 'type T struct { x T }'. Use a visited map
2428 // to avoid infinite recursion.
2429
2430 bool
2431 Type::is_direct_iface_type() const
2432 {
2433 Unordered_set(const Type*) visited;
2434 return this->is_direct_iface_type_helper(&visited);
2435 }
2436
2437 bool
2438 Type::is_direct_iface_type_helper(Unordered_set(const Type*)* visited) const
2439 {
2440 if (this->points_to() != NULL
2441 || this->channel_type() != NULL
2442 || this->function_type() != NULL
2443 || this->map_type() != NULL)
2444 return true;
2445
2446 std::pair<Unordered_set(const Type*)::iterator, bool> ins
2447 = visited->insert(this);
2448 if (!ins.second)
2449 // malformed circular type
2450 return false;
2451
2452 const Struct_type* st = this->struct_type();
2453 if (st != NULL)
2454 return (st->field_count() == 1
2455 && st->field(0)->type()->is_direct_iface_type_helper(visited));
2456 const Array_type* at = this->array_type();
2457 if (at != NULL && !at->is_slice_type())
2458 {
2459 int64_t len;
2460 return (at->int_length(&len) && len == 1
2461 && at->element_type()->is_direct_iface_type_helper(visited));
2462 }
2463 return false;
2464 }
2465
2466 // Return a composite literal for the type descriptor for a plain type
2467 // of kind RUNTIME_TYPE_KIND named NAME.
2468
2469 Expression*
2470 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2471 Named_type* name, const Methods* methods,
2472 bool only_value_methods)
2473 {
2474 Location bloc = Linemap::predeclared_location();
2475
2476 Type* td_type = Type::make_type_descriptor_type();
2477 const Struct_field_list* fields = td_type->struct_type()->fields();
2478
2479 Expression_list* vals = new Expression_list();
2480 vals->reserve(12);
2481
2482 if (!this->has_pointer())
2483 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2484 if (this->is_direct_iface_type())
2485 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2486 int64_t ptrsize;
2487 int64_t ptrdata;
2488 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2489 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2490
2491 Struct_field_list::const_iterator p = fields->begin();
2492 go_assert(p->is_field_name("size"));
2493 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2494 vals->push_back(Expression::make_type_info(this, type_info));
2495
2496 ++p;
2497 go_assert(p->is_field_name("ptrdata"));
2498 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2499 vals->push_back(Expression::make_type_info(this, type_info));
2500
2501 ++p;
2502 go_assert(p->is_field_name("hash"));
2503 unsigned int h;
2504 if (name != NULL)
2505 h = name->hash_for_method(gogo, Type::COMPARE_TAGS);
2506 else
2507 h = this->hash_for_method(gogo, Type::COMPARE_TAGS);
2508 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2509
2510 ++p;
2511 go_assert(p->is_field_name("tflag"));
2512 unsigned long tflag = 0;
2513 if (this->compare_is_identity(gogo))
2514 tflag |= TFLAG_REGULAR_MEMORY;
2515 vals->push_back(Expression::make_integer_ul(tflag, p->type(), bloc));
2516
2517 ++p;
2518 go_assert(p->is_field_name("align"));
2519 type_info = Expression::TYPE_INFO_ALIGNMENT;
2520 vals->push_back(Expression::make_type_info(this, type_info));
2521
2522 ++p;
2523 go_assert(p->is_field_name("fieldAlign"));
2524 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2525 vals->push_back(Expression::make_type_info(this, type_info));
2526
2527 ++p;
2528 go_assert(p->is_field_name("kind"));
2529 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2530 bloc));
2531
2532 ++p;
2533 go_assert(p->is_field_name("equal"));
2534 Function_type* equal_fntype = p->type()->function_type();
2535 Named_object* equal_fn = this->equal_function(gogo, name, equal_fntype);
2536 if (equal_fn == NULL)
2537 vals->push_back(Expression::make_cast(equal_fntype,
2538 Expression::make_nil(bloc),
2539 bloc));
2540 else
2541 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2542
2543 ++p;
2544 go_assert(p->is_field_name("gcdata"));
2545 vals->push_back(Expression::make_gc_symbol(this));
2546
2547 ++p;
2548 go_assert(p->is_field_name("string"));
2549 Expression* s = Expression::make_string((name != NULL
2550 ? name->reflection(gogo)
2551 : this->reflection(gogo)),
2552 bloc);
2553 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2554
2555 ++p;
2556 go_assert(p->is_field_name("uncommonType"));
2557 if (name == NULL && methods == NULL)
2558 vals->push_back(Expression::make_nil(bloc));
2559 else
2560 {
2561 if (methods == NULL)
2562 methods = name->methods();
2563 vals->push_back(this->uncommon_type_constructor(gogo,
2564 p->type()->deref(),
2565 name, methods,
2566 only_value_methods));
2567 }
2568
2569 ++p;
2570 go_assert(p->is_field_name("ptrToThis"));
2571 if (name == NULL && methods == NULL)
2572 vals->push_back(Expression::make_nil(bloc));
2573 else
2574 {
2575 Type* pt;
2576 if (name != NULL)
2577 pt = Type::make_pointer_type(name);
2578 else
2579 pt = Type::make_pointer_type(this);
2580 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2581 }
2582
2583 ++p;
2584 go_assert(p == fields->end());
2585
2586 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2587 }
2588
2589 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2590 // length used by the gc toolchain, and also appears in
2591 // libgo/go/reflect/type.go.
2592
2593 static const int64_t max_ptrmask_bytes = 2048;
2594
2595 // Return a pointer to the Garbage Collection information for this type.
2596
2597 Bexpression*
2598 Type::gc_symbol_pointer(Gogo* gogo)
2599 {
2600 Type* t = this->unalias();
2601
2602 if (!t->has_pointer())
2603 return gogo->backend()->nil_pointer_expression();
2604
2605 if (t->gc_symbol_var_ == NULL)
2606 {
2607 t->make_gc_symbol_var(gogo);
2608 go_assert(t->gc_symbol_var_ != NULL);
2609 }
2610 Location bloc = Linemap::predeclared_location();
2611 Bexpression* var_expr =
2612 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2613 Bexpression* addr_expr =
2614 gogo->backend()->address_expression(var_expr, bloc);
2615
2616 Type* uint8_type = Type::lookup_integer_type("uint8");
2617 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2618 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2619 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2620 }
2621
2622 // A mapping from unnamed types to GC symbol variables.
2623
2624 Type::GC_symbol_vars Type::gc_symbol_vars;
2625
2626 // Build the GC symbol for this type.
2627
2628 void
2629 Type::make_gc_symbol_var(Gogo* gogo)
2630 {
2631 go_assert(this->gc_symbol_var_ == NULL);
2632
2633 Named_type* nt = this->named_type();
2634
2635 // We can have multiple instances of unnamed types and similar to type
2636 // descriptors, we only want to the emit the GC data once, so we use a
2637 // hash table.
2638 Bvariable** phash = NULL;
2639 if (nt == NULL)
2640 {
2641 Bvariable* bvnull = NULL;
2642 std::pair<GC_symbol_vars::iterator, bool> ins =
2643 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2644 if (!ins.second)
2645 {
2646 // We've already built a gc symbol for this type.
2647 this->gc_symbol_var_ = ins.first->second;
2648 return;
2649 }
2650 phash = &ins.first->second;
2651 }
2652
2653 int64_t ptrsize;
2654 int64_t ptrdata;
2655 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2656 {
2657 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2658 if (phash != NULL)
2659 *phash = this->gc_symbol_var_;
2660 return;
2661 }
2662
2663 std::string sym_name = gogo->gc_symbol_name(this);
2664
2665 // Build the contents of the gc symbol.
2666 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2667 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2668
2669 // If the type descriptor for this type is defined somewhere else, so is the
2670 // GC symbol.
2671 const Package* dummy;
2672 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2673 {
2674 std::string asm_name(go_selectively_encode_id(sym_name));
2675 this->gc_symbol_var_ =
2676 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2677 sym_btype);
2678 if (phash != NULL)
2679 *phash = this->gc_symbol_var_;
2680 return;
2681 }
2682
2683 // See if this gc symbol can appear in multiple packages.
2684 bool is_common = false;
2685 if (nt != NULL)
2686 {
2687 // We create the symbol for a builtin type whenever we need
2688 // it.
2689 is_common = nt->is_builtin();
2690 }
2691 else
2692 {
2693 // This is an unnamed type. The descriptor could be defined in
2694 // any package where it is needed, and the linker will pick one
2695 // descriptor to keep.
2696 is_common = true;
2697 }
2698
2699 // Since we are building the GC symbol in this package, we must create the
2700 // variable before converting the initializer to its backend representation
2701 // because the initializer may refer to the GC symbol for this type.
2702 std::string asm_name(go_selectively_encode_id(sym_name));
2703 this->gc_symbol_var_ =
2704 gogo->backend()->implicit_variable(sym_name, asm_name,
2705 sym_btype, false, true, is_common, 0);
2706 if (phash != NULL)
2707 *phash = this->gc_symbol_var_;
2708
2709 Translate_context context(gogo, NULL, NULL, NULL);
2710 context.set_is_const();
2711 Bexpression* sym_binit = sym_init->get_backend(&context);
2712 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2713 sym_btype, false, true, is_common,
2714 sym_binit);
2715 }
2716
2717 // Return whether this type needs a GC program, and set *PTRDATA to
2718 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2719 // pointer.
2720
2721 bool
2722 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2723 {
2724 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2725 if (!voidptr->backend_type_size(gogo, ptrsize))
2726 go_unreachable();
2727
2728 if (!this->backend_type_ptrdata(gogo, ptrdata))
2729 {
2730 go_assert(saw_errors());
2731 return false;
2732 }
2733
2734 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2735 }
2736
2737 // A simple class used to build a GC ptrmask for a type.
2738
2739 class Ptrmask
2740 {
2741 public:
2742 Ptrmask(size_t count)
2743 : bits_((count + 7) / 8, 0)
2744 {}
2745
2746 void
2747 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2748
2749 std::string
2750 symname() const;
2751
2752 Expression*
2753 constructor(Gogo* gogo) const;
2754
2755 private:
2756 void
2757 set(size_t index)
2758 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2759
2760 // The actual bits.
2761 std::vector<unsigned char> bits_;
2762 };
2763
2764 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2765 // counts in bytes. PTRSIZE is the size of a pointer on the target
2766 // system.
2767
2768 void
2769 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2770 {
2771 switch (type->base()->classification())
2772 {
2773 default:
2774 case Type::TYPE_NIL:
2775 case Type::TYPE_CALL_MULTIPLE_RESULT:
2776 case Type::TYPE_NAMED:
2777 case Type::TYPE_FORWARD:
2778 go_unreachable();
2779
2780 case Type::TYPE_ERROR:
2781 case Type::TYPE_VOID:
2782 case Type::TYPE_BOOLEAN:
2783 case Type::TYPE_INTEGER:
2784 case Type::TYPE_FLOAT:
2785 case Type::TYPE_COMPLEX:
2786 case Type::TYPE_SINK:
2787 break;
2788
2789 case Type::TYPE_FUNCTION:
2790 case Type::TYPE_POINTER:
2791 case Type::TYPE_MAP:
2792 case Type::TYPE_CHANNEL:
2793 // These types are all a single pointer.
2794 go_assert((offset % ptrsize) == 0);
2795 this->set(offset / ptrsize);
2796 break;
2797
2798 case Type::TYPE_STRING:
2799 // A string starts with a single pointer.
2800 go_assert((offset % ptrsize) == 0);
2801 this->set(offset / ptrsize);
2802 break;
2803
2804 case Type::TYPE_INTERFACE:
2805 // An interface is two pointers.
2806 go_assert((offset % ptrsize) == 0);
2807 this->set(offset / ptrsize);
2808 this->set((offset / ptrsize) + 1);
2809 break;
2810
2811 case Type::TYPE_STRUCT:
2812 {
2813 if (!type->has_pointer())
2814 return;
2815
2816 const Struct_field_list* fields = type->struct_type()->fields();
2817 int64_t soffset = 0;
2818 for (Struct_field_list::const_iterator pf = fields->begin();
2819 pf != fields->end();
2820 ++pf)
2821 {
2822 int64_t field_align;
2823 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2824 {
2825 go_assert(saw_errors());
2826 return;
2827 }
2828 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2829
2830 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2831
2832 int64_t field_size;
2833 if (!pf->type()->backend_type_size(gogo, &field_size))
2834 {
2835 go_assert(saw_errors());
2836 return;
2837 }
2838 soffset += field_size;
2839 }
2840 }
2841 break;
2842
2843 case Type::TYPE_ARRAY:
2844 if (type->is_slice_type())
2845 {
2846 // A slice starts with a single pointer.
2847 go_assert((offset % ptrsize) == 0);
2848 this->set(offset / ptrsize);
2849 break;
2850 }
2851 else
2852 {
2853 if (!type->has_pointer())
2854 return;
2855
2856 int64_t len;
2857 if (!type->array_type()->int_length(&len))
2858 {
2859 go_assert(saw_errors());
2860 return;
2861 }
2862
2863 Type* element_type = type->array_type()->element_type();
2864 int64_t ele_size;
2865 if (!element_type->backend_type_size(gogo, &ele_size))
2866 {
2867 go_assert(saw_errors());
2868 return;
2869 }
2870
2871 int64_t eoffset = 0;
2872 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2873 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2874 break;
2875 }
2876 }
2877 }
2878
2879 // Return a symbol name for this ptrmask. This is used to coalesce identical
2880 // ptrmasks, which are common. The symbol name must use only characters that are
2881 // valid in symbols. It's nice if it's short. For smaller ptrmasks, we convert
2882 // it to a string that uses only 32 characters, avoiding digits and u and U. For
2883 // longer pointer masks, apply the same process to the SHA1 digest of the bits,
2884 // so as to avoid pathologically long symbol names (see related Go issues #32083
2885 // and #11583 for more on this). To avoid collisions between the two encoding
2886 // schemes, use a prefix ("X") for the SHA form to disambiguate.
2887 std::string
2888 Ptrmask::symname() const
2889 {
2890 const std::vector<unsigned char>* bits(&this->bits_);
2891 std::vector<unsigned char> shabits;
2892 std::string prefix;
2893
2894 if (this->bits_.size() > 128)
2895 {
2896 // Produce a SHA1 digest of the data.
2897 Go_sha1_helper* sha1_helper = go_create_sha1_helper();
2898 sha1_helper->process_bytes(&this->bits_[0], this->bits_.size());
2899 std::string digest = sha1_helper->finish();
2900 delete sha1_helper;
2901
2902 // Redirect the bits vector to the digest, and update the prefix.
2903 prefix = "X";
2904 for (std::string::const_iterator p = digest.begin();
2905 p != digest.end();
2906 ++p)
2907 {
2908 unsigned char c = *p;
2909 shabits.push_back(c);
2910 }
2911 bits = &shabits;
2912 }
2913
2914 const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2915 go_assert(chars[32] == '\0');
2916 std::string ret(prefix);
2917 unsigned int b = 0;
2918 int remaining = 0;
2919 for (std::vector<unsigned char>::const_iterator p = bits->begin();
2920 p != bits->end();
2921 ++p)
2922 {
2923 b |= *p << remaining;
2924 remaining += 8;
2925 while (remaining >= 5)
2926 {
2927 ret += chars[b & 0x1f];
2928 b >>= 5;
2929 remaining -= 5;
2930 }
2931 }
2932 while (remaining > 0)
2933 {
2934 ret += chars[b & 0x1f];
2935 b >>= 5;
2936 remaining -= 5;
2937 }
2938 return ret;
2939 }
2940
2941 // Return a constructor for this ptrmask. This will be used to
2942 // initialize the runtime ptrmask value.
2943
2944 Expression*
2945 Ptrmask::constructor(Gogo* gogo) const
2946 {
2947 Location bloc = Linemap::predeclared_location();
2948 Type* byte_type = gogo->lookup_global("byte")->type_value();
2949 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2950 bloc);
2951 Array_type* at = Type::make_array_type(byte_type, len);
2952 Expression_list* vals = new Expression_list();
2953 vals->reserve(this->bits_.size());
2954 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2955 p != this->bits_.end();
2956 ++p)
2957 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2958 return Expression::make_array_composite_literal(at, vals, bloc);
2959 }
2960
2961 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2962 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2963
2964 // Return a ptrmask variable for a type. For a type descriptor this
2965 // is only used for variables that are small enough to not need a
2966 // gcprog, but for a global variable this is used for a variable of
2967 // any size. PTRDATA is the number of bytes of the type that contain
2968 // pointer data. PTRSIZE is the size of a pointer on the target
2969 // system.
2970
2971 Bvariable*
2972 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2973 {
2974 Ptrmask ptrmask(ptrdata / ptrsize);
2975 if (ptrdata >= ptrsize)
2976 ptrmask.set_from(gogo, this, ptrsize, 0);
2977 else
2978 {
2979 // This can happen in error cases. Just build an empty gcbits.
2980 go_assert(saw_errors());
2981 }
2982
2983 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2984 Bvariable* bvnull = NULL;
2985 std::pair<GC_gcbits_vars::iterator, bool> ins =
2986 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2987 if (!ins.second)
2988 {
2989 // We've already built a GC symbol for this set of gcbits.
2990 return ins.first->second;
2991 }
2992
2993 Expression* val = ptrmask.constructor(gogo);
2994 Translate_context context(gogo, NULL, NULL, NULL);
2995 context.set_is_const();
2996 Bexpression* bval = val->get_backend(&context);
2997
2998 std::string asm_name(go_selectively_encode_id(sym_name));
2999 Btype *btype = val->type()->get_backend(gogo);
3000 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
3001 btype, false, true,
3002 true, 0);
3003 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
3004 true, true, bval);
3005 ins.first->second = ret;
3006 return ret;
3007 }
3008
3009 // A GCProg is used to build a program for the garbage collector.
3010 // This is used for types with a lot of pointer data, to reduce the
3011 // size of the data in the compiled program. The program is expanded
3012 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
3013
3014 class GCProg
3015 {
3016 public:
3017 GCProg()
3018 : bytes_(), index_(0), nb_(0)
3019 {}
3020
3021 // The number of bits described so far.
3022 int64_t
3023 bit_index() const
3024 { return this->index_; }
3025
3026 void
3027 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
3028
3029 void
3030 end();
3031
3032 Expression*
3033 constructor(Gogo* gogo) const;
3034
3035 private:
3036 void
3037 ptr(int64_t);
3038
3039 bool
3040 should_repeat(int64_t, int64_t);
3041
3042 void
3043 repeat(int64_t, int64_t);
3044
3045 void
3046 zero_until(int64_t);
3047
3048 void
3049 lit(unsigned char);
3050
3051 void
3052 varint(int64_t);
3053
3054 void
3055 flushlit();
3056
3057 // Add a byte to the program.
3058 void
3059 byte(unsigned char x)
3060 { this->bytes_.push_back(x); }
3061
3062 // The maximum number of bytes of literal bits.
3063 static const int max_literal = 127;
3064
3065 // The program.
3066 std::vector<unsigned char> bytes_;
3067 // The index of the last bit described.
3068 int64_t index_;
3069 // The current set of literal bits.
3070 unsigned char b_[max_literal];
3071 // The current number of literal bits.
3072 int nb_;
3073 };
3074
3075 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
3076 // counts in bytes. PTRSIZE is the size of a pointer on the target
3077 // system.
3078
3079 void
3080 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
3081 {
3082 switch (type->base()->classification())
3083 {
3084 default:
3085 case Type::TYPE_NIL:
3086 case Type::TYPE_CALL_MULTIPLE_RESULT:
3087 case Type::TYPE_NAMED:
3088 case Type::TYPE_FORWARD:
3089 go_unreachable();
3090
3091 case Type::TYPE_ERROR:
3092 case Type::TYPE_VOID:
3093 case Type::TYPE_BOOLEAN:
3094 case Type::TYPE_INTEGER:
3095 case Type::TYPE_FLOAT:
3096 case Type::TYPE_COMPLEX:
3097 case Type::TYPE_SINK:
3098 break;
3099
3100 case Type::TYPE_FUNCTION:
3101 case Type::TYPE_POINTER:
3102 case Type::TYPE_MAP:
3103 case Type::TYPE_CHANNEL:
3104 // These types are all a single pointer.
3105 go_assert((offset % ptrsize) == 0);
3106 this->ptr(offset / ptrsize);
3107 break;
3108
3109 case Type::TYPE_STRING:
3110 // A string starts with a single pointer.
3111 go_assert((offset % ptrsize) == 0);
3112 this->ptr(offset / ptrsize);
3113 break;
3114
3115 case Type::TYPE_INTERFACE:
3116 // An interface is two pointers.
3117 go_assert((offset % ptrsize) == 0);
3118 this->ptr(offset / ptrsize);
3119 this->ptr((offset / ptrsize) + 1);
3120 break;
3121
3122 case Type::TYPE_STRUCT:
3123 {
3124 if (!type->has_pointer())
3125 return;
3126
3127 const Struct_field_list* fields = type->struct_type()->fields();
3128 int64_t soffset = 0;
3129 for (Struct_field_list::const_iterator pf = fields->begin();
3130 pf != fields->end();
3131 ++pf)
3132 {
3133 int64_t field_align;
3134 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3135 {
3136 go_assert(saw_errors());
3137 return;
3138 }
3139 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
3140
3141 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
3142
3143 int64_t field_size;
3144 if (!pf->type()->backend_type_size(gogo, &field_size))
3145 {
3146 go_assert(saw_errors());
3147 return;
3148 }
3149 soffset += field_size;
3150 }
3151 }
3152 break;
3153
3154 case Type::TYPE_ARRAY:
3155 if (type->is_slice_type())
3156 {
3157 // A slice starts with a single pointer.
3158 go_assert((offset % ptrsize) == 0);
3159 this->ptr(offset / ptrsize);
3160 break;
3161 }
3162 else
3163 {
3164 if (!type->has_pointer())
3165 return;
3166
3167 int64_t len;
3168 if (!type->array_type()->int_length(&len))
3169 {
3170 go_assert(saw_errors());
3171 return;
3172 }
3173
3174 Type* element_type = type->array_type()->element_type();
3175
3176 // Flatten array of array to a big array by multiplying counts.
3177 while (element_type->array_type() != NULL
3178 && !element_type->is_slice_type())
3179 {
3180 int64_t ele_len;
3181 if (!element_type->array_type()->int_length(&ele_len))
3182 {
3183 go_assert(saw_errors());
3184 return;
3185 }
3186
3187 len *= ele_len;
3188 element_type = element_type->array_type()->element_type();
3189 }
3190
3191 int64_t ele_size;
3192 if (!element_type->backend_type_size(gogo, &ele_size))
3193 {
3194 go_assert(saw_errors());
3195 return;
3196 }
3197
3198 go_assert(len > 0 && ele_size > 0);
3199
3200 if (!this->should_repeat(ele_size / ptrsize, len))
3201 {
3202 // Cheaper to just emit the bits.
3203 int64_t eoffset = 0;
3204 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3205 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3206 }
3207 else
3208 {
3209 go_assert((offset % ptrsize) == 0);
3210 go_assert((ele_size % ptrsize) == 0);
3211 this->set_from(gogo, element_type, ptrsize, offset);
3212 this->zero_until((offset + ele_size) / ptrsize);
3213 this->repeat(ele_size / ptrsize, len - 1);
3214 }
3215
3216 break;
3217 }
3218 }
3219 }
3220
3221 // Emit a 1 into the bit stream of a GC program at the given bit index.
3222
3223 void
3224 GCProg::ptr(int64_t index)
3225 {
3226 go_assert(index >= this->index_);
3227 this->zero_until(index);
3228 this->lit(1);
3229 }
3230
3231 // Return whether it is worthwhile to use a repeat to describe c
3232 // elements of n bits each, compared to just emitting c copies of the
3233 // n-bit description.
3234
3235 bool
3236 GCProg::should_repeat(int64_t n, int64_t c)
3237 {
3238 // Repeat if there is more than 1 item and if the total data doesn't
3239 // fit into four bytes.
3240 return c > 1 && c * n > 4 * 8;
3241 }
3242
3243 // Emit an instruction to repeat the description of the last n words c
3244 // times (including the initial description, so c + 1 times in total).
3245
3246 void
3247 GCProg::repeat(int64_t n, int64_t c)
3248 {
3249 if (n == 0 || c == 0)
3250 return;
3251 this->flushlit();
3252 if (n < 128)
3253 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3254 else
3255 {
3256 this->byte(0x80);
3257 this->varint(n);
3258 }
3259 this->varint(c);
3260 this->index_ += n * c;
3261 }
3262
3263 // Add zeros to the bit stream up to the given index.
3264
3265 void
3266 GCProg::zero_until(int64_t index)
3267 {
3268 go_assert(index >= this->index_);
3269 int64_t skip = index - this->index_;
3270 if (skip == 0)
3271 return;
3272 if (skip < 4 * 8)
3273 {
3274 for (int64_t i = 0; i < skip; ++i)
3275 this->lit(0);
3276 return;
3277 }
3278 this->lit(0);
3279 this->flushlit();
3280 this->repeat(1, skip - 1);
3281 }
3282
3283 // Add a single literal bit to the program.
3284
3285 void
3286 GCProg::lit(unsigned char x)
3287 {
3288 if (this->nb_ == GCProg::max_literal)
3289 this->flushlit();
3290 this->b_[this->nb_] = x;
3291 ++this->nb_;
3292 ++this->index_;
3293 }
3294
3295 // Emit the varint encoding of x.
3296
3297 void
3298 GCProg::varint(int64_t x)
3299 {
3300 go_assert(x >= 0);
3301 while (x >= 0x80)
3302 {
3303 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3304 x >>= 7;
3305 }
3306 this->byte(static_cast<unsigned char>(x & 0x7f));
3307 }
3308
3309 // Flush any pending literal bits.
3310
3311 void
3312 GCProg::flushlit()
3313 {
3314 if (this->nb_ == 0)
3315 return;
3316 this->byte(static_cast<unsigned char>(this->nb_));
3317 unsigned char bits = 0;
3318 for (int i = 0; i < this->nb_; ++i)
3319 {
3320 bits |= this->b_[i] << (i % 8);
3321 if ((i + 1) % 8 == 0)
3322 {
3323 this->byte(bits);
3324 bits = 0;
3325 }
3326 }
3327 if (this->nb_ % 8 != 0)
3328 this->byte(bits);
3329 this->nb_ = 0;
3330 }
3331
3332 // Mark the end of a GC program.
3333
3334 void
3335 GCProg::end()
3336 {
3337 this->flushlit();
3338 this->byte(0);
3339 }
3340
3341 // Return an Expression for the bytes in a GC program.
3342
3343 Expression*
3344 GCProg::constructor(Gogo* gogo) const
3345 {
3346 Location bloc = Linemap::predeclared_location();
3347
3348 // The first four bytes are the length of the program in target byte
3349 // order. Build a struct whose first type is uint32 to make this
3350 // work.
3351
3352 Type* uint32_type = Type::lookup_integer_type("uint32");
3353
3354 Type* byte_type = gogo->lookup_global("byte")->type_value();
3355 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3356 bloc);
3357 Array_type* at = Type::make_array_type(byte_type, len);
3358
3359 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3360 "bytes", at);
3361
3362 Expression_list* vals = new Expression_list();
3363 vals->reserve(this->bytes_.size());
3364 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3365 p != this->bytes_.end();
3366 ++p)
3367 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3368 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3369
3370 vals = new Expression_list();
3371 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3372 bloc));
3373 vals->push_back(bytes);
3374
3375 return Expression::make_struct_composite_literal(st, vals, bloc);
3376 }
3377
3378 // Return a composite literal for the garbage collection program for
3379 // this type. This is only used for types that are too large to use a
3380 // ptrmask.
3381
3382 Expression*
3383 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3384 {
3385 Location bloc = Linemap::predeclared_location();
3386
3387 GCProg prog;
3388 prog.set_from(gogo, this, ptrsize, 0);
3389 int64_t offset = prog.bit_index() * ptrsize;
3390 prog.end();
3391
3392 int64_t type_size;
3393 if (!this->backend_type_size(gogo, &type_size))
3394 {
3395 go_assert(saw_errors());
3396 return Expression::make_error(bloc);
3397 }
3398
3399 go_assert(offset >= ptrdata && offset <= type_size);
3400
3401 return prog.constructor(gogo);
3402 }
3403
3404 // Return a composite literal for the uncommon type information for
3405 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3406 // struct. If name is not NULL, it is the name of the type. If
3407 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3408 // is true if only value methods should be included. At least one of
3409 // NAME and METHODS must not be NULL.
3410
3411 Expression*
3412 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3413 Named_type* name, const Methods* methods,
3414 bool only_value_methods) const
3415 {
3416 Location bloc = Linemap::predeclared_location();
3417
3418 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3419
3420 Expression_list* vals = new Expression_list();
3421 vals->reserve(3);
3422
3423 Struct_field_list::const_iterator p = fields->begin();
3424 go_assert(p->is_field_name("name"));
3425
3426 ++p;
3427 go_assert(p->is_field_name("pkgPath"));
3428
3429 if (name == NULL)
3430 {
3431 vals->push_back(Expression::make_nil(bloc));
3432 vals->push_back(Expression::make_nil(bloc));
3433 }
3434 else
3435 {
3436 Named_object* no = name->named_object();
3437 std::string n = Gogo::unpack_hidden_name(no->name());
3438 Expression* s = Expression::make_string(n, bloc);
3439 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3440
3441 if (name->is_builtin())
3442 vals->push_back(Expression::make_nil(bloc));
3443 else
3444 {
3445 const Package* package = no->package();
3446 const std::string& pkgpath(package == NULL
3447 ? gogo->pkgpath()
3448 : package->pkgpath());
3449 s = Expression::make_string(pkgpath, bloc);
3450 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3451 }
3452 }
3453
3454 ++p;
3455 go_assert(p->is_field_name("methods"));
3456 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3457 only_value_methods));
3458
3459 ++p;
3460 go_assert(p == fields->end());
3461
3462 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3463 vals, bloc);
3464 return Expression::make_unary(OPERATOR_AND, r, bloc);
3465 }
3466
3467 // Sort methods by name.
3468
3469 class Sort_methods
3470 {
3471 public:
3472 bool
3473 operator()(const std::pair<std::string, const Method*>& m1,
3474 const std::pair<std::string, const Method*>& m2) const
3475 {
3476 return (Gogo::unpack_hidden_name(m1.first)
3477 < Gogo::unpack_hidden_name(m2.first));
3478 }
3479 };
3480
3481 // Return a composite literal for the type method table for this type.
3482 // METHODS_TYPE is the type of the table, and is a slice type.
3483 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3484 // then only value methods are used.
3485
3486 Expression*
3487 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3488 const Methods* methods,
3489 bool only_value_methods) const
3490 {
3491 Location bloc = Linemap::predeclared_location();
3492
3493 std::vector<std::pair<std::string, const Method*> > smethods;
3494 if (methods != NULL)
3495 {
3496 smethods.reserve(methods->count());
3497 for (Methods::const_iterator p = methods->begin();
3498 p != methods->end();
3499 ++p)
3500 {
3501 if (p->second->is_ambiguous())
3502 continue;
3503 if (only_value_methods && !p->second->is_value_method())
3504 continue;
3505
3506 // This is where we implement the magic //go:nointerface
3507 // comment. If we saw that comment, we don't add this
3508 // method to the type descriptor.
3509 if (p->second->nointerface())
3510 continue;
3511
3512 smethods.push_back(std::make_pair(p->first, p->second));
3513 }
3514 }
3515
3516 if (smethods.empty())
3517 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3518
3519 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3520
3521 Type* method_type = methods_type->array_type()->element_type();
3522
3523 Expression_list* vals = new Expression_list();
3524 vals->reserve(smethods.size());
3525 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3526 = smethods.begin();
3527 p != smethods.end();
3528 ++p)
3529 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3530 p->second, only_value_methods));
3531
3532 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3533 }
3534
3535 // Return a composite literal for a single method. METHOD_TYPE is the
3536 // type of the entry. METHOD_NAME is the name of the method and M is
3537 // the method information.
3538
3539 Expression*
3540 Type::method_constructor(Gogo*, Type* method_type,
3541 const std::string& method_name,
3542 const Method* m,
3543 bool only_value_methods) const
3544 {
3545 Location bloc = Linemap::predeclared_location();
3546
3547 const Struct_field_list* fields = method_type->struct_type()->fields();
3548
3549 Expression_list* vals = new Expression_list();
3550 vals->reserve(5);
3551
3552 Struct_field_list::const_iterator p = fields->begin();
3553 go_assert(p->is_field_name("name"));
3554 const std::string n = Gogo::unpack_hidden_name(method_name);
3555 Expression* s = Expression::make_string(n, bloc);
3556 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3557
3558 ++p;
3559 go_assert(p->is_field_name("pkgPath"));
3560 if (!Gogo::is_hidden_name(method_name))
3561 vals->push_back(Expression::make_nil(bloc));
3562 else
3563 {
3564 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3565 bloc);
3566 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3567 }
3568
3569 bool use_direct_iface_stub =
3570 this->points_to() != NULL
3571 && this->points_to()->is_direct_iface_type()
3572 && m->is_value_method();
3573 Named_object* no = (use_direct_iface_stub
3574 ? m->iface_stub_object()
3575 : (m->needs_stub_method()
3576 ? m->stub_object()
3577 : m->named_object()));
3578
3579 Function_type* mtype;
3580 if (no->is_function())
3581 mtype = no->func_value()->type();
3582 else
3583 mtype = no->func_declaration_value()->type();
3584 go_assert(mtype->is_method());
3585 Type* nonmethod_type = mtype->copy_without_receiver();
3586
3587 ++p;
3588 go_assert(p->is_field_name("mtyp"));
3589 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3590
3591 ++p;
3592 go_assert(p->is_field_name("typ"));
3593 bool want_pointer_receiver = (!only_value_methods && m->is_value_method()
3594 && !use_direct_iface_stub);
3595 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3596 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3597
3598 ++p;
3599 go_assert(p->is_field_name("tfn"));
3600 vals->push_back(Expression::make_func_code_reference(no, bloc));
3601
3602 ++p;
3603 go_assert(p == fields->end());
3604
3605 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3606 }
3607
3608 // Return a composite literal for the type descriptor of a plain type.
3609 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3610 // NULL, it is the name to use as well as the list of methods.
3611
3612 Expression*
3613 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3614 Named_type* name)
3615 {
3616 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3617 name, NULL, true);
3618 }
3619
3620 // Return the type reflection string for this type.
3621
3622 std::string
3623 Type::reflection(Gogo* gogo) const
3624 {
3625 std::string ret;
3626
3627 // The do_reflection virtual function should set RET to the
3628 // reflection string.
3629 this->do_reflection(gogo, &ret);
3630
3631 return ret;
3632 }
3633
3634 // Return whether the backend size of the type is known.
3635
3636 bool
3637 Type::is_backend_type_size_known(Gogo* gogo)
3638 {
3639 switch (this->classification_)
3640 {
3641 case TYPE_ERROR:
3642 case TYPE_VOID:
3643 case TYPE_BOOLEAN:
3644 case TYPE_INTEGER:
3645 case TYPE_FLOAT:
3646 case TYPE_COMPLEX:
3647 case TYPE_STRING:
3648 case TYPE_FUNCTION:
3649 case TYPE_POINTER:
3650 case TYPE_NIL:
3651 case TYPE_MAP:
3652 case TYPE_CHANNEL:
3653 case TYPE_INTERFACE:
3654 return true;
3655
3656 case TYPE_STRUCT:
3657 {
3658 const Struct_field_list* fields = this->struct_type()->fields();
3659 for (Struct_field_list::const_iterator pf = fields->begin();
3660 pf != fields->end();
3661 ++pf)
3662 if (!pf->type()->is_backend_type_size_known(gogo))
3663 return false;
3664 return true;
3665 }
3666
3667 case TYPE_ARRAY:
3668 {
3669 const Array_type* at = this->array_type();
3670 if (at->length() == NULL)
3671 return true;
3672 else
3673 {
3674 Numeric_constant nc;
3675 if (!at->length()->numeric_constant_value(&nc))
3676 return false;
3677 mpz_t ival;
3678 if (!nc.to_int(&ival))
3679 return false;
3680 mpz_clear(ival);
3681 return at->element_type()->is_backend_type_size_known(gogo);
3682 }
3683 }
3684
3685 case TYPE_NAMED:
3686 this->named_type()->convert(gogo);
3687 return this->named_type()->is_named_backend_type_size_known();
3688
3689 case TYPE_FORWARD:
3690 {
3691 Forward_declaration_type* fdt = this->forward_declaration_type();
3692 return fdt->real_type()->is_backend_type_size_known(gogo);
3693 }
3694
3695 case TYPE_SINK:
3696 case TYPE_CALL_MULTIPLE_RESULT:
3697 go_unreachable();
3698
3699 default:
3700 go_unreachable();
3701 }
3702 }
3703
3704 // If the size of the type can be determined, set *PSIZE to the size
3705 // in bytes and return true. Otherwise, return false. This queries
3706 // the backend.
3707
3708 bool
3709 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3710 {
3711 if (!this->is_backend_type_size_known(gogo))
3712 return false;
3713 if (this->is_error_type())
3714 return false;
3715 Btype* bt = this->get_backend_placeholder(gogo);
3716 *psize = gogo->backend()->type_size(bt);
3717 if (*psize == -1)
3718 {
3719 if (this->named_type() != NULL)
3720 go_error_at(this->named_type()->location(),
3721 "type %s larger than address space",
3722 Gogo::message_name(this->named_type()->name()).c_str());
3723 else
3724 go_error_at(Linemap::unknown_location(),
3725 "type %s larger than address space",
3726 this->reflection(gogo).c_str());
3727
3728 // Make this an error type to avoid knock-on errors.
3729 this->classification_ = TYPE_ERROR;
3730 return false;
3731 }
3732 return true;
3733 }
3734
3735 // If the alignment of the type can be determined, set *PALIGN to
3736 // the alignment in bytes and return true. Otherwise, return false.
3737
3738 bool
3739 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3740 {
3741 if (!this->is_backend_type_size_known(gogo))
3742 return false;
3743 Btype* bt = this->get_backend_placeholder(gogo);
3744 *palign = gogo->backend()->type_alignment(bt);
3745 return true;
3746 }
3747
3748 // Like backend_type_align, but return the alignment when used as a
3749 // field.
3750
3751 bool
3752 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3753 {
3754 if (!this->is_backend_type_size_known(gogo))
3755 return false;
3756 Btype* bt = this->get_backend_placeholder(gogo);
3757 *palign = gogo->backend()->type_field_alignment(bt);
3758 return true;
3759 }
3760
3761 // Get the ptrdata value for a type. This is the size of the prefix
3762 // of the type that contains all pointers. Store the ptrdata in
3763 // *PPTRDATA and return whether we found it.
3764
3765 bool
3766 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3767 {
3768 *pptrdata = 0;
3769
3770 if (!this->has_pointer())
3771 return true;
3772
3773 if (!this->is_backend_type_size_known(gogo))
3774 return false;
3775
3776 switch (this->classification_)
3777 {
3778 case TYPE_ERROR:
3779 return true;
3780
3781 case TYPE_FUNCTION:
3782 case TYPE_POINTER:
3783 case TYPE_MAP:
3784 case TYPE_CHANNEL:
3785 // These types are nothing but a pointer.
3786 return this->backend_type_size(gogo, pptrdata);
3787
3788 case TYPE_INTERFACE:
3789 // An interface is a struct of two pointers.
3790 return this->backend_type_size(gogo, pptrdata);
3791
3792 case TYPE_STRING:
3793 {
3794 // A string is a struct whose first field is a pointer, and
3795 // whose second field is not.
3796 Type* uint8_type = Type::lookup_integer_type("uint8");
3797 Type* ptr = Type::make_pointer_type(uint8_type);
3798 return ptr->backend_type_size(gogo, pptrdata);
3799 }
3800
3801 case TYPE_NAMED:
3802 case TYPE_FORWARD:
3803 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3804
3805 case TYPE_STRUCT:
3806 {
3807 const Struct_field_list* fields = this->struct_type()->fields();
3808 int64_t offset = 0;
3809 const Struct_field *ptr = NULL;
3810 int64_t ptr_offset = 0;
3811 for (Struct_field_list::const_iterator pf = fields->begin();
3812 pf != fields->end();
3813 ++pf)
3814 {
3815 int64_t field_align;
3816 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3817 return false;
3818 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3819
3820 if (pf->type()->has_pointer())
3821 {
3822 ptr = &*pf;
3823 ptr_offset = offset;
3824 }
3825
3826 int64_t field_size;
3827 if (!pf->type()->backend_type_size(gogo, &field_size))
3828 return false;
3829 offset += field_size;
3830 }
3831
3832 if (ptr != NULL)
3833 {
3834 int64_t ptr_ptrdata;
3835 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3836 return false;
3837 *pptrdata = ptr_offset + ptr_ptrdata;
3838 }
3839 return true;
3840 }
3841
3842 case TYPE_ARRAY:
3843 if (this->is_slice_type())
3844 {
3845 // A slice is a struct whose first field is a pointer, and
3846 // whose remaining fields are not.
3847 Type* element_type = this->array_type()->element_type();
3848 Type* ptr = Type::make_pointer_type(element_type);
3849 return ptr->backend_type_size(gogo, pptrdata);
3850 }
3851 else
3852 {
3853 Numeric_constant nc;
3854 if (!this->array_type()->length()->numeric_constant_value(&nc))
3855 return false;
3856 int64_t len;
3857 if (!nc.to_memory_size(&len))
3858 return false;
3859
3860 Type* element_type = this->array_type()->element_type();
3861 int64_t ele_size;
3862 int64_t ele_ptrdata;
3863 if (!element_type->backend_type_size(gogo, &ele_size)
3864 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3865 return false;
3866 go_assert(ele_size > 0 && ele_ptrdata > 0);
3867
3868 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3869 return true;
3870 }
3871
3872 default:
3873 case TYPE_VOID:
3874 case TYPE_BOOLEAN:
3875 case TYPE_INTEGER:
3876 case TYPE_FLOAT:
3877 case TYPE_COMPLEX:
3878 case TYPE_SINK:
3879 case TYPE_NIL:
3880 case TYPE_CALL_MULTIPLE_RESULT:
3881 go_unreachable();
3882 }
3883 }
3884
3885 // Get the ptrdata value to store in a type descriptor. This is
3886 // normally the same as backend_type_ptrdata, but for a type that is
3887 // large enough to use a gcprog we may need to store a different value
3888 // if it ends with an array. If the gcprog uses a repeat descriptor
3889 // for the array, and if the array element ends with non-pointer data,
3890 // then the gcprog will produce a value that describes the complete
3891 // array where the backend ptrdata will omit the non-pointer elements
3892 // of the final array element. This is a subtle difference but the
3893 // run time code checks it to verify that it has expanded a gcprog as
3894 // expected.
3895
3896 bool
3897 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3898 {
3899 int64_t backend_ptrdata;
3900 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3901 return false;
3902
3903 int64_t ptrsize;
3904 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3905 {
3906 *pptrdata = backend_ptrdata;
3907 return true;
3908 }
3909
3910 GCProg prog;
3911 prog.set_from(gogo, this, ptrsize, 0);
3912 int64_t offset = prog.bit_index() * ptrsize;
3913
3914 go_assert(offset >= backend_ptrdata);
3915 *pptrdata = offset;
3916 return true;
3917 }
3918
3919 // Default function to export a type.
3920
3921 void
3922 Type::do_export(Export*) const
3923 {
3924 go_unreachable();
3925 }
3926
3927 // Import a type.
3928
3929 Type*
3930 Type::import_type(Import* imp)
3931 {
3932 if (imp->match_c_string("("))
3933 return Function_type::do_import(imp);
3934 else if (imp->match_c_string("*"))
3935 return Pointer_type::do_import(imp);
3936 else if (imp->match_c_string("struct "))
3937 return Struct_type::do_import(imp);
3938 else if (imp->match_c_string("["))
3939 return Array_type::do_import(imp);
3940 else if (imp->match_c_string("map "))
3941 return Map_type::do_import(imp);
3942 else if (imp->match_c_string("chan "))
3943 return Channel_type::do_import(imp);
3944 else if (imp->match_c_string("interface"))
3945 return Interface_type::do_import(imp);
3946 else
3947 {
3948 go_error_at(imp->location(), "import error: expected type");
3949 return Type::make_error_type();
3950 }
3951 }
3952
3953 // Class Error_type.
3954
3955 // Return the backend representation of an Error type.
3956
3957 Btype*
3958 Error_type::do_get_backend(Gogo* gogo)
3959 {
3960 return gogo->backend()->error_type();
3961 }
3962
3963 // Return an expression for the type descriptor for an error type.
3964
3965
3966 Expression*
3967 Error_type::do_type_descriptor(Gogo*, Named_type*)
3968 {
3969 return Expression::make_error(Linemap::predeclared_location());
3970 }
3971
3972 // We should not be asked for the reflection string for an error type.
3973
3974 void
3975 Error_type::do_reflection(Gogo*, std::string*) const
3976 {
3977 go_assert(saw_errors());
3978 }
3979
3980 Type*
3981 Type::make_error_type()
3982 {
3983 static Error_type singleton_error_type;
3984 return &singleton_error_type;
3985 }
3986
3987 // Class Void_type.
3988
3989 // Get the backend representation of a void type.
3990
3991 Btype*
3992 Void_type::do_get_backend(Gogo* gogo)
3993 {
3994 return gogo->backend()->void_type();
3995 }
3996
3997 Type*
3998 Type::make_void_type()
3999 {
4000 static Void_type singleton_void_type;
4001 return &singleton_void_type;
4002 }
4003
4004 // Class Boolean_type.
4005
4006 // Return the backend representation of the boolean type.
4007
4008 Btype*
4009 Boolean_type::do_get_backend(Gogo* gogo)
4010 {
4011 return gogo->backend()->bool_type();
4012 }
4013
4014 // Make the type descriptor.
4015
4016 Expression*
4017 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4018 {
4019 if (name != NULL)
4020 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
4021 else
4022 {
4023 Named_object* no = gogo->lookup_global("bool");
4024 go_assert(no != NULL);
4025 return Type::type_descriptor(gogo, no->type_value());
4026 }
4027 }
4028
4029 Type*
4030 Type::make_boolean_type()
4031 {
4032 static Boolean_type boolean_type;
4033 return &boolean_type;
4034 }
4035
4036 // The named type "bool".
4037
4038 static Named_type* named_bool_type;
4039
4040 // Get the named type "bool".
4041
4042 Named_type*
4043 Type::lookup_bool_type()
4044 {
4045 return named_bool_type;
4046 }
4047
4048 // Make the named type "bool".
4049
4050 Named_type*
4051 Type::make_named_bool_type()
4052 {
4053 Type* bool_type = Type::make_boolean_type();
4054 Named_object* named_object =
4055 Named_object::make_type("bool", NULL, bool_type,
4056 Linemap::predeclared_location());
4057 Named_type* named_type = named_object->type_value();
4058 named_bool_type = named_type;
4059 return named_type;
4060 }
4061
4062 // Class Integer_type.
4063
4064 Integer_type::Named_integer_types Integer_type::named_integer_types;
4065
4066 // Create a new integer type. Non-abstract integer types always have
4067 // names.
4068
4069 Named_type*
4070 Integer_type::create_integer_type(const char* name, bool is_unsigned,
4071 int bits, int runtime_type_kind)
4072 {
4073 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
4074 runtime_type_kind);
4075 std::string sname(name);
4076 Named_object* named_object =
4077 Named_object::make_type(sname, NULL, integer_type,
4078 Linemap::predeclared_location());
4079 Named_type* named_type = named_object->type_value();
4080 std::pair<Named_integer_types::iterator, bool> ins =
4081 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
4082 go_assert(ins.second);
4083 return named_type;
4084 }
4085
4086 // Look up an existing integer type.
4087
4088 Named_type*
4089 Integer_type::lookup_integer_type(const char* name)
4090 {
4091 Named_integer_types::const_iterator p =
4092 Integer_type::named_integer_types.find(name);
4093 go_assert(p != Integer_type::named_integer_types.end());
4094 return p->second;
4095 }
4096
4097 // Create a new abstract integer type.
4098
4099 Integer_type*
4100 Integer_type::create_abstract_integer_type()
4101 {
4102 static Integer_type* abstract_type;
4103 if (abstract_type == NULL)
4104 {
4105 Type* int_type = Type::lookup_integer_type("int");
4106 abstract_type = new Integer_type(true, false,
4107 int_type->integer_type()->bits(),
4108 RUNTIME_TYPE_KIND_INT);
4109 }
4110 return abstract_type;
4111 }
4112
4113 // Create a new abstract character type.
4114
4115 Integer_type*
4116 Integer_type::create_abstract_character_type()
4117 {
4118 static Integer_type* abstract_type;
4119 if (abstract_type == NULL)
4120 {
4121 abstract_type = new Integer_type(true, false, 32,
4122 RUNTIME_TYPE_KIND_INT32);
4123 abstract_type->set_is_rune();
4124 }
4125 return abstract_type;
4126 }
4127
4128 // Integer type compatibility.
4129
4130 bool
4131 Integer_type::is_identical(const Integer_type* t) const
4132 {
4133 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
4134 return false;
4135 return this->is_abstract_ == t->is_abstract_;
4136 }
4137
4138 // Hash code.
4139
4140 unsigned int
4141 Integer_type::do_hash_for_method(Gogo*, int) const
4142 {
4143 return ((this->bits_ << 4)
4144 + ((this->is_unsigned_ ? 1 : 0) << 8)
4145 + ((this->is_abstract_ ? 1 : 0) << 9));
4146 }
4147
4148 // Convert an Integer_type to the backend representation.
4149
4150 Btype*
4151 Integer_type::do_get_backend(Gogo* gogo)
4152 {
4153 if (this->is_abstract_)
4154 {
4155 go_assert(saw_errors());
4156 return gogo->backend()->error_type();
4157 }
4158 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4159 }
4160
4161 // The type descriptor for an integer type. Integer types are always
4162 // named.
4163
4164 Expression*
4165 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4166 {
4167 go_assert(name != NULL || saw_errors());
4168 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4169 }
4170
4171 // We should not be asked for the reflection string of a basic type.
4172
4173 void
4174 Integer_type::do_reflection(Gogo*, std::string*) const
4175 {
4176 go_assert(saw_errors());
4177 }
4178
4179 // Make an integer type.
4180
4181 Named_type*
4182 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4183 int runtime_type_kind)
4184 {
4185 return Integer_type::create_integer_type(name, is_unsigned, bits,
4186 runtime_type_kind);
4187 }
4188
4189 // Make an abstract integer type.
4190
4191 Integer_type*
4192 Type::make_abstract_integer_type()
4193 {
4194 return Integer_type::create_abstract_integer_type();
4195 }
4196
4197 // Make an abstract character type.
4198
4199 Integer_type*
4200 Type::make_abstract_character_type()
4201 {
4202 return Integer_type::create_abstract_character_type();
4203 }
4204
4205 // Look up an integer type.
4206
4207 Named_type*
4208 Type::lookup_integer_type(const char* name)
4209 {
4210 return Integer_type::lookup_integer_type(name);
4211 }
4212
4213 // Class Float_type.
4214
4215 Float_type::Named_float_types Float_type::named_float_types;
4216
4217 // Create a new float type. Non-abstract float types always have
4218 // names.
4219
4220 Named_type*
4221 Float_type::create_float_type(const char* name, int bits,
4222 int runtime_type_kind)
4223 {
4224 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4225 std::string sname(name);
4226 Named_object* named_object =
4227 Named_object::make_type(sname, NULL, float_type,
4228 Linemap::predeclared_location());
4229 Named_type* named_type = named_object->type_value();
4230 std::pair<Named_float_types::iterator, bool> ins =
4231 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4232 go_assert(ins.second);
4233 return named_type;
4234 }
4235
4236 // Look up an existing float type.
4237
4238 Named_type*
4239 Float_type::lookup_float_type(const char* name)
4240 {
4241 Named_float_types::const_iterator p =
4242 Float_type::named_float_types.find(name);
4243 go_assert(p != Float_type::named_float_types.end());
4244 return p->second;
4245 }
4246
4247 // Create a new abstract float type.
4248
4249 Float_type*
4250 Float_type::create_abstract_float_type()
4251 {
4252 static Float_type* abstract_type;
4253 if (abstract_type == NULL)
4254 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4255 return abstract_type;
4256 }
4257
4258 // Whether this type is identical with T.
4259
4260 bool
4261 Float_type::is_identical(const Float_type* t) const
4262 {
4263 if (this->bits_ != t->bits_)
4264 return false;
4265 return this->is_abstract_ == t->is_abstract_;
4266 }
4267
4268 // Hash code.
4269
4270 unsigned int
4271 Float_type::do_hash_for_method(Gogo*, int) const
4272 {
4273 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4274 }
4275
4276 // Convert to the backend representation.
4277
4278 Btype*
4279 Float_type::do_get_backend(Gogo* gogo)
4280 {
4281 return gogo->backend()->float_type(this->bits_);
4282 }
4283
4284 // The type descriptor for a float type. Float types are always named.
4285
4286 Expression*
4287 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4288 {
4289 go_assert(name != NULL || saw_errors());
4290 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4291 }
4292
4293 // We should not be asked for the reflection string of a basic type.
4294
4295 void
4296 Float_type::do_reflection(Gogo*, std::string*) const
4297 {
4298 go_assert(saw_errors());
4299 }
4300
4301 // Make a floating point type.
4302
4303 Named_type*
4304 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4305 {
4306 return Float_type::create_float_type(name, bits, runtime_type_kind);
4307 }
4308
4309 // Make an abstract float type.
4310
4311 Float_type*
4312 Type::make_abstract_float_type()
4313 {
4314 return Float_type::create_abstract_float_type();
4315 }
4316
4317 // Look up a float type.
4318
4319 Named_type*
4320 Type::lookup_float_type(const char* name)
4321 {
4322 return Float_type::lookup_float_type(name);
4323 }
4324
4325 // Class Complex_type.
4326
4327 Complex_type::Named_complex_types Complex_type::named_complex_types;
4328
4329 // Create a new complex type. Non-abstract complex types always have
4330 // names.
4331
4332 Named_type*
4333 Complex_type::create_complex_type(const char* name, int bits,
4334 int runtime_type_kind)
4335 {
4336 Complex_type* complex_type = new Complex_type(false, bits,
4337 runtime_type_kind);
4338 std::string sname(name);
4339 Named_object* named_object =
4340 Named_object::make_type(sname, NULL, complex_type,
4341 Linemap::predeclared_location());
4342 Named_type* named_type = named_object->type_value();
4343 std::pair<Named_complex_types::iterator, bool> ins =
4344 Complex_type::named_complex_types.insert(std::make_pair(sname,
4345 named_type));
4346 go_assert(ins.second);
4347 return named_type;
4348 }
4349
4350 // Look up an existing complex type.
4351
4352 Named_type*
4353 Complex_type::lookup_complex_type(const char* name)
4354 {
4355 Named_complex_types::const_iterator p =
4356 Complex_type::named_complex_types.find(name);
4357 go_assert(p != Complex_type::named_complex_types.end());
4358 return p->second;
4359 }
4360
4361 // Create a new abstract complex type.
4362
4363 Complex_type*
4364 Complex_type::create_abstract_complex_type()
4365 {
4366 static Complex_type* abstract_type;
4367 if (abstract_type == NULL)
4368 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4369 return abstract_type;
4370 }
4371
4372 // Whether this type is identical with T.
4373
4374 bool
4375 Complex_type::is_identical(const Complex_type *t) const
4376 {
4377 if (this->bits_ != t->bits_)
4378 return false;
4379 return this->is_abstract_ == t->is_abstract_;
4380 }
4381
4382 // Hash code.
4383
4384 unsigned int
4385 Complex_type::do_hash_for_method(Gogo*, int) const
4386 {
4387 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4388 }
4389
4390 // Convert to the backend representation.
4391
4392 Btype*
4393 Complex_type::do_get_backend(Gogo* gogo)
4394 {
4395 return gogo->backend()->complex_type(this->bits_);
4396 }
4397
4398 // The type descriptor for a complex type. Complex types are always
4399 // named.
4400
4401 Expression*
4402 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4403 {
4404 go_assert(name != NULL || saw_errors());
4405 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4406 }
4407
4408 // We should not be asked for the reflection string of a basic type.
4409
4410 void
4411 Complex_type::do_reflection(Gogo*, std::string*) const
4412 {
4413 go_assert(saw_errors());
4414 }
4415
4416 // Make a complex type.
4417
4418 Named_type*
4419 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4420 {
4421 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4422 }
4423
4424 // Make an abstract complex type.
4425
4426 Complex_type*
4427 Type::make_abstract_complex_type()
4428 {
4429 return Complex_type::create_abstract_complex_type();
4430 }
4431
4432 // Look up a complex type.
4433
4434 Named_type*
4435 Type::lookup_complex_type(const char* name)
4436 {
4437 return Complex_type::lookup_complex_type(name);
4438 }
4439
4440 // Class String_type.
4441
4442 // Convert String_type to the backend representation. A string is a
4443 // struct with two fields: a pointer to the characters and a length.
4444
4445 Btype*
4446 String_type::do_get_backend(Gogo* gogo)
4447 {
4448 static Btype* backend_string_type;
4449 if (backend_string_type == NULL)
4450 {
4451 std::vector<Backend::Btyped_identifier> fields(2);
4452
4453 Type* b = gogo->lookup_global("byte")->type_value();
4454 Type* pb = Type::make_pointer_type(b);
4455
4456 // We aren't going to get back to this field to finish the
4457 // backend representation, so force it to be finished now.
4458 if (!gogo->named_types_are_converted())
4459 {
4460 Btype* bt = pb->get_backend_placeholder(gogo);
4461 pb->finish_backend(gogo, bt);
4462 }
4463
4464 fields[0].name = "__data";
4465 fields[0].btype = pb->get_backend(gogo);
4466 fields[0].location = Linemap::predeclared_location();
4467
4468 Type* int_type = Type::lookup_integer_type("int");
4469 fields[1].name = "__length";
4470 fields[1].btype = int_type->get_backend(gogo);
4471 fields[1].location = fields[0].location;
4472
4473 backend_string_type = gogo->backend()->struct_type(fields);
4474 }
4475 return backend_string_type;
4476 }
4477
4478 // The type descriptor for the string type.
4479
4480 Expression*
4481 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4482 {
4483 if (name != NULL)
4484 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4485 else
4486 {
4487 Named_object* no = gogo->lookup_global("string");
4488 go_assert(no != NULL);
4489 return Type::type_descriptor(gogo, no->type_value());
4490 }
4491 }
4492
4493 // We should not be asked for the reflection string of a basic type.
4494
4495 void
4496 String_type::do_reflection(Gogo*, std::string* ret) const
4497 {
4498 ret->append("string");
4499 }
4500
4501 // Make a string type.
4502
4503 Type*
4504 Type::make_string_type()
4505 {
4506 static String_type string_type;
4507 return &string_type;
4508 }
4509
4510 // The named type "string".
4511
4512 static Named_type* named_string_type;
4513
4514 // Get the named type "string".
4515
4516 Named_type*
4517 Type::lookup_string_type()
4518 {
4519 return named_string_type;
4520 }
4521
4522 // Make the named type string.
4523
4524 Named_type*
4525 Type::make_named_string_type()
4526 {
4527 Type* string_type = Type::make_string_type();
4528 Named_object* named_object =
4529 Named_object::make_type("string", NULL, string_type,
4530 Linemap::predeclared_location());
4531 Named_type* named_type = named_object->type_value();
4532 named_string_type = named_type;
4533 return named_type;
4534 }
4535
4536 // The sink type. This is the type of the blank identifier _. Any
4537 // type may be assigned to it.
4538
4539 class Sink_type : public Type
4540 {
4541 public:
4542 Sink_type()
4543 : Type(TYPE_SINK)
4544 { }
4545
4546 protected:
4547 bool
4548 do_compare_is_identity(Gogo*)
4549 { return false; }
4550
4551 Btype*
4552 do_get_backend(Gogo*)
4553 { go_unreachable(); }
4554
4555 Expression*
4556 do_type_descriptor(Gogo*, Named_type*)
4557 { go_unreachable(); }
4558
4559 void
4560 do_reflection(Gogo*, std::string*) const
4561 { go_unreachable(); }
4562
4563 void
4564 do_mangled_name(Gogo*, std::string*) const
4565 { go_unreachable(); }
4566 };
4567
4568 // Make the sink type.
4569
4570 Type*
4571 Type::make_sink_type()
4572 {
4573 static Sink_type sink_type;
4574 return &sink_type;
4575 }
4576
4577 // Class Function_type.
4578
4579 // Traversal.
4580
4581 int
4582 Function_type::do_traverse(Traverse* traverse)
4583 {
4584 if (this->receiver_ != NULL
4585 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4586 return TRAVERSE_EXIT;
4587 if (this->parameters_ != NULL
4588 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4589 return TRAVERSE_EXIT;
4590 if (this->results_ != NULL
4591 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4592 return TRAVERSE_EXIT;
4593 return TRAVERSE_CONTINUE;
4594 }
4595
4596 // Returns whether T is a valid redeclaration of this type. If this
4597 // returns false, and REASON is not NULL, *REASON may be set to a
4598 // brief explanation of why it returned false.
4599
4600 bool
4601 Function_type::is_valid_redeclaration(const Function_type* t,
4602 std::string* reason) const
4603 {
4604 if (!this->is_identical(t, false, COMPARE_TAGS, reason))
4605 return false;
4606
4607 // A redeclaration of a function is required to use the same names
4608 // for the receiver and parameters.
4609 if (this->receiver() != NULL
4610 && this->receiver()->name() != t->receiver()->name())
4611 {
4612 if (reason != NULL)
4613 *reason = "receiver name changed";
4614 return false;
4615 }
4616
4617 const Typed_identifier_list* parms1 = this->parameters();
4618 const Typed_identifier_list* parms2 = t->parameters();
4619 if (parms1 != NULL)
4620 {
4621 Typed_identifier_list::const_iterator p1 = parms1->begin();
4622 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4623 p2 != parms2->end();
4624 ++p2, ++p1)
4625 {
4626 if (p1->name() != p2->name())
4627 {
4628 if (reason != NULL)
4629 *reason = "parameter name changed";
4630 return false;
4631 }
4632
4633 // This is called at parse time, so we may have unknown
4634 // types.
4635 Type* t1 = p1->type()->forwarded();
4636 Type* t2 = p2->type()->forwarded();
4637 if (t1 != t2
4638 && t1->forward_declaration_type() != NULL
4639 && (t2->forward_declaration_type() == NULL
4640 || (t1->forward_declaration_type()->named_object()
4641 != t2->forward_declaration_type()->named_object())))
4642 return false;
4643 }
4644 }
4645
4646 const Typed_identifier_list* results1 = this->results();
4647 const Typed_identifier_list* results2 = t->results();
4648 if (results1 != NULL)
4649 {
4650 Typed_identifier_list::const_iterator res1 = results1->begin();
4651 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4652 res2 != results2->end();
4653 ++res2, ++res1)
4654 {
4655 if (res1->name() != res2->name())
4656 {
4657 if (reason != NULL)
4658 *reason = "result name changed";
4659 return false;
4660 }
4661
4662 // This is called at parse time, so we may have unknown
4663 // types.
4664 Type* t1 = res1->type()->forwarded();
4665 Type* t2 = res2->type()->forwarded();
4666 if (t1 != t2
4667 && t1->forward_declaration_type() != NULL
4668 && (t2->forward_declaration_type() == NULL
4669 || (t1->forward_declaration_type()->named_object()
4670 != t2->forward_declaration_type()->named_object())))
4671 return false;
4672 }
4673 }
4674
4675 return true;
4676 }
4677
4678 // Check whether T is the same as this type.
4679
4680 bool
4681 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4682 int flags, std::string* reason) const
4683 {
4684 if (this->is_backend_function_type() != t->is_backend_function_type())
4685 return false;
4686
4687 if (!ignore_receiver)
4688 {
4689 const Typed_identifier* r1 = this->receiver();
4690 const Typed_identifier* r2 = t->receiver();
4691 if ((r1 != NULL) != (r2 != NULL))
4692 {
4693 if (reason != NULL)
4694 *reason = _("different receiver types");
4695 return false;
4696 }
4697 if (r1 != NULL)
4698 {
4699 if (!Type::are_identical(r1->type(), r2->type(), flags, reason))
4700 {
4701 if (reason != NULL && !reason->empty())
4702 *reason = "receiver: " + *reason;
4703 return false;
4704 }
4705 }
4706 }
4707
4708 const Typed_identifier_list* parms1 = this->parameters();
4709 if (parms1 != NULL && parms1->empty())
4710 parms1 = NULL;
4711 const Typed_identifier_list* parms2 = t->parameters();
4712 if (parms2 != NULL && parms2->empty())
4713 parms2 = NULL;
4714 if ((parms1 != NULL) != (parms2 != NULL))
4715 {
4716 if (reason != NULL)
4717 *reason = _("different number of parameters");
4718 return false;
4719 }
4720 if (parms1 != NULL)
4721 {
4722 Typed_identifier_list::const_iterator p1 = parms1->begin();
4723 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4724 p2 != parms2->end();
4725 ++p2, ++p1)
4726 {
4727 if (p1 == parms1->end())
4728 {
4729 if (reason != NULL)
4730 *reason = _("different number of parameters");
4731 return false;
4732 }
4733
4734 if (!Type::are_identical(p1->type(), p2->type(), flags, NULL))
4735 {
4736 if (reason != NULL)
4737 *reason = _("different parameter types");
4738 return false;
4739 }
4740 }
4741 if (p1 != parms1->end())
4742 {
4743 if (reason != NULL)
4744 *reason = _("different number of parameters");
4745 return false;
4746 }
4747 }
4748
4749 if (this->is_varargs() != t->is_varargs())
4750 {
4751 if (reason != NULL)
4752 *reason = _("different varargs");
4753 return false;
4754 }
4755
4756 const Typed_identifier_list* results1 = this->results();
4757 if (results1 != NULL && results1->empty())
4758 results1 = NULL;
4759 const Typed_identifier_list* results2 = t->results();
4760 if (results2 != NULL && results2->empty())
4761 results2 = NULL;
4762 if ((results1 != NULL) != (results2 != NULL))
4763 {
4764 if (reason != NULL)
4765 *reason = _("different number of results");
4766 return false;
4767 }
4768 if (results1 != NULL)
4769 {
4770 Typed_identifier_list::const_iterator res1 = results1->begin();
4771 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4772 res2 != results2->end();
4773 ++res2, ++res1)
4774 {
4775 if (res1 == results1->end())
4776 {
4777 if (reason != NULL)
4778 *reason = _("different number of results");
4779 return false;
4780 }
4781
4782 if (!Type::are_identical(res1->type(), res2->type(), flags, NULL))
4783 {
4784 if (reason != NULL)
4785 *reason = _("different result types");
4786 return false;
4787 }
4788 }
4789 if (res1 != results1->end())
4790 {
4791 if (reason != NULL)
4792 *reason = _("different number of results");
4793 return false;
4794 }
4795 }
4796
4797 return true;
4798 }
4799
4800 // Hash code.
4801
4802 unsigned int
4803 Function_type::do_hash_for_method(Gogo* gogo, int flags) const
4804 {
4805 unsigned int ret = 0;
4806 // We ignore the receiver type for hash codes, because we need to
4807 // get the same hash code for a method in an interface and a method
4808 // declared for a type. The former will not have a receiver.
4809 if (this->parameters_ != NULL)
4810 {
4811 int shift = 1;
4812 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4813 p != this->parameters_->end();
4814 ++p, ++shift)
4815 ret += p->type()->hash_for_method(gogo, flags) << shift;
4816 }
4817 if (this->results_ != NULL)
4818 {
4819 int shift = 2;
4820 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4821 p != this->results_->end();
4822 ++p, ++shift)
4823 ret += p->type()->hash_for_method(gogo, flags) << shift;
4824 }
4825 if (this->is_varargs_)
4826 ret += 1;
4827 ret <<= 4;
4828 return ret;
4829 }
4830
4831 // Hash result parameters.
4832
4833 unsigned int
4834 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4835 {
4836 unsigned int hash = 0;
4837 for (Typed_identifier_list::const_iterator p = t->begin();
4838 p != t->end();
4839 ++p)
4840 {
4841 hash <<= 2;
4842 hash = Gogo::hash_string(p->name(), hash);
4843 hash += p->type()->hash_for_method(NULL, Type::COMPARE_TAGS);
4844 }
4845 return hash;
4846 }
4847
4848 // Compare result parameters so that can map identical result
4849 // parameters to a single struct type.
4850
4851 bool
4852 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4853 const Typed_identifier_list* b) const
4854 {
4855 if (a->size() != b->size())
4856 return false;
4857 Typed_identifier_list::const_iterator pa = a->begin();
4858 for (Typed_identifier_list::const_iterator pb = b->begin();
4859 pb != b->end();
4860 ++pa, ++pb)
4861 {
4862 if (pa->name() != pb->name()
4863 || !Type::are_identical(pa->type(), pb->type(), Type::COMPARE_TAGS,
4864 NULL))
4865 return false;
4866 }
4867 return true;
4868 }
4869
4870 // Hash from results to a backend struct type.
4871
4872 Function_type::Results_structs Function_type::results_structs;
4873
4874 // Get the backend representation for a function type.
4875
4876 Btype*
4877 Function_type::get_backend_fntype(Gogo* gogo)
4878 {
4879 if (this->fnbtype_ == NULL)
4880 {
4881 Backend::Btyped_identifier breceiver;
4882 if (this->receiver_ != NULL)
4883 {
4884 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4885
4886 // We always pass the address of the receiver parameter, in
4887 // order to make interface calls work with unknown types,
4888 // except for direct interface types where the interface call
4889 // actually passes the underlying pointer of the value.
4890 Type* rtype = this->receiver_->type();
4891 if (rtype->points_to() == NULL)
4892 {
4893 if (rtype->is_direct_iface_type())
4894 rtype = Type::make_pointer_type(Type::make_void_type());
4895 else
4896 rtype = Type::make_pointer_type(rtype);
4897 }
4898 breceiver.btype = rtype->get_backend(gogo);
4899 breceiver.location = this->receiver_->location();
4900 }
4901
4902 std::vector<Backend::Btyped_identifier> bparameters;
4903 if (this->parameters_ != NULL)
4904 {
4905 bparameters.resize(this->parameters_->size());
4906 size_t i = 0;
4907 for (Typed_identifier_list::const_iterator p =
4908 this->parameters_->begin(); p != this->parameters_->end();
4909 ++p, ++i)
4910 {
4911 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4912 bparameters[i].btype = p->type()->get_backend(gogo);
4913 bparameters[i].location = p->location();
4914 }
4915 go_assert(i == bparameters.size());
4916 }
4917
4918 std::vector<Backend::Btyped_identifier> bresults;
4919 Btype* bresult_struct = NULL;
4920 if (this->results_ != NULL)
4921 {
4922 bresults.resize(this->results_->size());
4923 size_t i = 0;
4924 for (Typed_identifier_list::const_iterator p =
4925 this->results_->begin();
4926 p != this->results_->end();
4927 ++p, ++i)
4928 {
4929 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4930 bresults[i].btype = p->type()->get_backend(gogo);
4931 bresults[i].location = p->location();
4932 }
4933 go_assert(i == bresults.size());
4934
4935 if (this->results_->size() > 1)
4936 {
4937 // Use the same results struct for all functions that
4938 // return the same set of results. This is useful to
4939 // unify calls to interface methods with other calls.
4940 std::pair<Typed_identifier_list*, Btype*> val;
4941 val.first = this->results_;
4942 val.second = NULL;
4943 std::pair<Results_structs::iterator, bool> ins =
4944 Function_type::results_structs.insert(val);
4945 if (ins.second)
4946 {
4947 // Build a new struct type.
4948 Struct_field_list* sfl = new Struct_field_list;
4949 for (Typed_identifier_list::const_iterator p =
4950 this->results_->begin();
4951 p != this->results_->end();
4952 ++p)
4953 {
4954 Typed_identifier tid = *p;
4955 if (tid.name().empty())
4956 tid = Typed_identifier("UNNAMED", tid.type(),
4957 tid.location());
4958 sfl->push_back(Struct_field(tid));
4959 }
4960 Struct_type* st = Type::make_struct_type(sfl,
4961 this->location());
4962 st->set_is_struct_incomparable();
4963 ins.first->second = st->get_backend(gogo);
4964 }
4965 bresult_struct = ins.first->second;
4966 }
4967 }
4968
4969 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4970 bresults, bresult_struct,
4971 this->location());
4972
4973 }
4974
4975 return this->fnbtype_;
4976 }
4977
4978 // Get the backend representation for a Go function type.
4979
4980 Btype*
4981 Function_type::do_get_backend(Gogo* gogo)
4982 {
4983 // When we do anything with a function value other than call it, it
4984 // is represented as a pointer to a struct whose first field is the
4985 // actual function. So that is what we return as the type of a Go
4986 // function.
4987
4988 Location loc = this->location();
4989 Btype* struct_type =
4990 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4991 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4992
4993 std::vector<Backend::Btyped_identifier> fields(1);
4994 fields[0].name = "code";
4995 fields[0].btype = this->get_backend_fntype(gogo);
4996 fields[0].location = loc;
4997 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4998 return gogo->backend()->error_type();
4999 return ptr_struct_type;
5000 }
5001
5002 // The type of a function type descriptor.
5003
5004 Type*
5005 Function_type::make_function_type_descriptor_type()
5006 {
5007 static Type* ret;
5008 if (ret == NULL)
5009 {
5010 Type* tdt = Type::make_type_descriptor_type();
5011 Type* ptdt = Type::make_type_descriptor_ptr_type();
5012
5013 Type* bool_type = Type::lookup_bool_type();
5014
5015 Type* slice_type = Type::make_array_type(ptdt, NULL);
5016
5017 Struct_type* s = Type::make_builtin_struct_type(4,
5018 "", tdt,
5019 "dotdotdot", bool_type,
5020 "in", slice_type,
5021 "out", slice_type);
5022
5023 ret = Type::make_builtin_named_type("FuncType", s);
5024 }
5025
5026 return ret;
5027 }
5028
5029 // The type descriptor for a function type.
5030
5031 Expression*
5032 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5033 {
5034 Location bloc = Linemap::predeclared_location();
5035
5036 Type* ftdt = Function_type::make_function_type_descriptor_type();
5037
5038 const Struct_field_list* fields = ftdt->struct_type()->fields();
5039
5040 Expression_list* vals = new Expression_list();
5041 vals->reserve(4);
5042
5043 Struct_field_list::const_iterator p = fields->begin();
5044 go_assert(p->is_field_name("_type"));
5045 vals->push_back(this->type_descriptor_constructor(gogo,
5046 RUNTIME_TYPE_KIND_FUNC,
5047 name, NULL, true));
5048
5049 ++p;
5050 go_assert(p->is_field_name("dotdotdot"));
5051 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
5052
5053 ++p;
5054 go_assert(p->is_field_name("in"));
5055 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
5056 this->parameters()));
5057
5058 ++p;
5059 go_assert(p->is_field_name("out"));
5060 vals->push_back(this->type_descriptor_params(p->type(), NULL,
5061 this->results()));
5062
5063 ++p;
5064 go_assert(p == fields->end());
5065
5066 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
5067 }
5068
5069 // Return a composite literal for the parameters or results of a type
5070 // descriptor.
5071
5072 Expression*
5073 Function_type::type_descriptor_params(Type* params_type,
5074 const Typed_identifier* receiver,
5075 const Typed_identifier_list* params)
5076 {
5077 Location bloc = Linemap::predeclared_location();
5078
5079 if (receiver == NULL && params == NULL)
5080 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
5081
5082 Expression_list* vals = new Expression_list();
5083 vals->reserve((params == NULL ? 0 : params->size())
5084 + (receiver != NULL ? 1 : 0));
5085
5086 if (receiver != NULL)
5087 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
5088
5089 if (params != NULL)
5090 {
5091 for (Typed_identifier_list::const_iterator p = params->begin();
5092 p != params->end();
5093 ++p)
5094 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
5095 }
5096
5097 return Expression::make_slice_composite_literal(params_type, vals, bloc);
5098 }
5099
5100 // The reflection string.
5101
5102 void
5103 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
5104 {
5105 // FIXME: Turn this off until we straighten out the type of the
5106 // struct field used in a go statement which calls a method.
5107 // go_assert(this->receiver_ == NULL);
5108
5109 ret->append("func");
5110
5111 if (this->receiver_ != NULL)
5112 {
5113 ret->push_back('(');
5114 this->append_reflection(this->receiver_->type(), gogo, ret);
5115 ret->push_back(')');
5116 }
5117
5118 ret->push_back('(');
5119 const Typed_identifier_list* params = this->parameters();
5120 if (params != NULL)
5121 {
5122 bool is_varargs = this->is_varargs_;
5123 for (Typed_identifier_list::const_iterator p = params->begin();
5124 p != params->end();
5125 ++p)
5126 {
5127 if (p != params->begin())
5128 ret->append(", ");
5129 if (!is_varargs || p + 1 != params->end())
5130 this->append_reflection(p->type(), gogo, ret);
5131 else
5132 {
5133 ret->append("...");
5134 this->append_reflection(p->type()->array_type()->element_type(),
5135 gogo, ret);
5136 }
5137 }
5138 }
5139 ret->push_back(')');
5140
5141 const Typed_identifier_list* results = this->results();
5142 if (results != NULL && !results->empty())
5143 {
5144 if (results->size() == 1)
5145 ret->push_back(' ');
5146 else
5147 ret->append(" (");
5148 for (Typed_identifier_list::const_iterator p = results->begin();
5149 p != results->end();
5150 ++p)
5151 {
5152 if (p != results->begin())
5153 ret->append(", ");
5154 this->append_reflection(p->type(), gogo, ret);
5155 }
5156 if (results->size() > 1)
5157 ret->push_back(')');
5158 }
5159 }
5160
5161 // Export a function type.
5162
5163 void
5164 Function_type::do_export(Export* exp) const
5165 {
5166 // We don't write out the receiver. The only function types which
5167 // should have a receiver are the ones associated with explicitly
5168 // defined methods. For those the receiver type is written out by
5169 // Function::export_func.
5170
5171 exp->write_c_string("(");
5172 bool first = true;
5173 if (this->parameters_ != NULL)
5174 {
5175 bool is_varargs = this->is_varargs_;
5176 for (Typed_identifier_list::const_iterator p =
5177 this->parameters_->begin();
5178 p != this->parameters_->end();
5179 ++p)
5180 {
5181 if (first)
5182 first = false;
5183 else
5184 exp->write_c_string(", ");
5185 exp->write_name(p->name());
5186 exp->write_c_string(" ");
5187 if (!is_varargs || p + 1 != this->parameters_->end())
5188 exp->write_type(p->type());
5189 else
5190 {
5191 exp->write_c_string("...");
5192 exp->write_type(p->type()->array_type()->element_type());
5193 }
5194 }
5195 }
5196 exp->write_c_string(")");
5197
5198 const Typed_identifier_list* results = this->results_;
5199 if (results != NULL)
5200 {
5201 exp->write_c_string(" ");
5202 if (results->size() == 1 && results->begin()->name().empty())
5203 exp->write_type(results->begin()->type());
5204 else
5205 {
5206 first = true;
5207 exp->write_c_string("(");
5208 for (Typed_identifier_list::const_iterator p = results->begin();
5209 p != results->end();
5210 ++p)
5211 {
5212 if (first)
5213 first = false;
5214 else
5215 exp->write_c_string(", ");
5216 exp->write_name(p->name());
5217 exp->write_c_string(" ");
5218 exp->write_type(p->type());
5219 }
5220 exp->write_c_string(")");
5221 }
5222 }
5223 }
5224
5225 // Import a function type.
5226
5227 Function_type*
5228 Function_type::do_import(Import* imp)
5229 {
5230 imp->require_c_string("(");
5231 Typed_identifier_list* parameters;
5232 bool is_varargs = false;
5233 if (imp->peek_char() == ')')
5234 parameters = NULL;
5235 else
5236 {
5237 parameters = new Typed_identifier_list();
5238 while (true)
5239 {
5240 std::string name = imp->read_name();
5241 imp->require_c_string(" ");
5242
5243 if (imp->match_c_string("..."))
5244 {
5245 imp->advance(3);
5246 is_varargs = true;
5247 }
5248
5249 Type* ptype = imp->read_type();
5250 if (is_varargs)
5251 ptype = Type::make_array_type(ptype, NULL);
5252 parameters->push_back(Typed_identifier(name, ptype,
5253 imp->location()));
5254 if (imp->peek_char() != ',')
5255 break;
5256 go_assert(!is_varargs);
5257 imp->require_c_string(", ");
5258 }
5259 }
5260 imp->require_c_string(")");
5261
5262 Typed_identifier_list* results;
5263 if (imp->peek_char() != ' ')
5264 results = NULL;
5265 else
5266 {
5267 imp->advance(1);
5268 results = new Typed_identifier_list;
5269 if (imp->peek_char() != '(')
5270 {
5271 Type* rtype = imp->read_type();
5272 results->push_back(Typed_identifier("", rtype, imp->location()));
5273 }
5274 else
5275 {
5276 imp->advance(1);
5277 while (true)
5278 {
5279 std::string name = imp->read_name();
5280 imp->require_c_string(" ");
5281 Type* rtype = imp->read_type();
5282 results->push_back(Typed_identifier(name, rtype,
5283 imp->location()));
5284 if (imp->peek_char() != ',')
5285 break;
5286 imp->require_c_string(", ");
5287 }
5288 imp->require_c_string(")");
5289 }
5290 }
5291
5292 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5293 imp->location());
5294 if (is_varargs)
5295 ret->set_is_varargs();
5296 return ret;
5297 }
5298
5299 // Make a copy of a function type without a receiver.
5300
5301 Function_type*
5302 Function_type::copy_without_receiver() const
5303 {
5304 go_assert(this->is_method());
5305 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5306 this->results_,
5307 this->location_);
5308 if (this->is_varargs())
5309 ret->set_is_varargs();
5310 if (this->is_builtin())
5311 ret->set_is_builtin();
5312 return ret;
5313 }
5314
5315 // Make a copy of a function type with a receiver.
5316
5317 Function_type*
5318 Function_type::copy_with_receiver(Type* receiver_type) const
5319 {
5320 go_assert(!this->is_method());
5321 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5322 this->location_);
5323 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5324 this->results_,
5325 this->location_);
5326 if (this->is_varargs_)
5327 ret->set_is_varargs();
5328 return ret;
5329 }
5330
5331 // Make a copy of a function type with the receiver as the first
5332 // parameter.
5333
5334 Function_type*
5335 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5336 {
5337 go_assert(this->is_method());
5338 Typed_identifier_list* new_params = new Typed_identifier_list();
5339 Type* rtype = this->receiver_->type();
5340 if (want_pointer_receiver)
5341 rtype = Type::make_pointer_type(rtype);
5342 Typed_identifier receiver(this->receiver_->name(), rtype,
5343 this->receiver_->location());
5344 new_params->push_back(receiver);
5345 const Typed_identifier_list* orig_params = this->parameters_;
5346 if (orig_params != NULL && !orig_params->empty())
5347 {
5348 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5349 p != orig_params->end();
5350 ++p)
5351 new_params->push_back(*p);
5352 }
5353 return Type::make_function_type(NULL, new_params, this->results_,
5354 this->location_);
5355 }
5356
5357 // Make a copy of a function type ignoring any receiver and adding a
5358 // closure parameter.
5359
5360 Function_type*
5361 Function_type::copy_with_names() const
5362 {
5363 Typed_identifier_list* new_params = new Typed_identifier_list();
5364 const Typed_identifier_list* orig_params = this->parameters_;
5365 if (orig_params != NULL && !orig_params->empty())
5366 {
5367 static int count;
5368 char buf[50];
5369 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5370 p != orig_params->end();
5371 ++p)
5372 {
5373 snprintf(buf, sizeof buf, "pt.%u", count);
5374 ++count;
5375 new_params->push_back(Typed_identifier(buf, p->type(),
5376 p->location()));
5377 }
5378 }
5379
5380 const Typed_identifier_list* orig_results = this->results_;
5381 Typed_identifier_list* new_results;
5382 if (orig_results == NULL || orig_results->empty())
5383 new_results = NULL;
5384 else
5385 {
5386 new_results = new Typed_identifier_list();
5387 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5388 p != orig_results->end();
5389 ++p)
5390 new_results->push_back(Typed_identifier("", p->type(),
5391 p->location()));
5392 }
5393
5394 return Type::make_function_type(NULL, new_params, new_results,
5395 this->location());
5396 }
5397
5398 // Make a function type.
5399
5400 Function_type*
5401 Type::make_function_type(Typed_identifier* receiver,
5402 Typed_identifier_list* parameters,
5403 Typed_identifier_list* results,
5404 Location location)
5405 {
5406 return new Function_type(receiver, parameters, results, location);
5407 }
5408
5409 // Make a backend function type.
5410
5411 Backend_function_type*
5412 Type::make_backend_function_type(Typed_identifier* receiver,
5413 Typed_identifier_list* parameters,
5414 Typed_identifier_list* results,
5415 Location location)
5416 {
5417 return new Backend_function_type(receiver, parameters, results, location);
5418 }
5419
5420 // Class Pointer_type.
5421
5422 // Traversal.
5423
5424 int
5425 Pointer_type::do_traverse(Traverse* traverse)
5426 {
5427 return Type::traverse(this->to_type_, traverse);
5428 }
5429
5430 // Hash code.
5431
5432 unsigned int
5433 Pointer_type::do_hash_for_method(Gogo* gogo, int flags) const
5434 {
5435 return this->to_type_->hash_for_method(gogo, flags) << 4;
5436 }
5437
5438 // Get the backend representation for a pointer type.
5439
5440 Btype*
5441 Pointer_type::do_get_backend(Gogo* gogo)
5442 {
5443 Btype* to_btype = this->to_type_->get_backend(gogo);
5444 return gogo->backend()->pointer_type(to_btype);
5445 }
5446
5447 // The type of a pointer type descriptor.
5448
5449 Type*
5450 Pointer_type::make_pointer_type_descriptor_type()
5451 {
5452 static Type* ret;
5453 if (ret == NULL)
5454 {
5455 Type* tdt = Type::make_type_descriptor_type();
5456 Type* ptdt = Type::make_type_descriptor_ptr_type();
5457
5458 Struct_type* s = Type::make_builtin_struct_type(2,
5459 "", tdt,
5460 "elem", ptdt);
5461
5462 ret = Type::make_builtin_named_type("PtrType", s);
5463 }
5464
5465 return ret;
5466 }
5467
5468 // The type descriptor for a pointer type.
5469
5470 Expression*
5471 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5472 {
5473 if (this->is_unsafe_pointer_type())
5474 {
5475 go_assert(name != NULL);
5476 return this->plain_type_descriptor(gogo,
5477 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5478 name);
5479 }
5480 else
5481 {
5482 Location bloc = Linemap::predeclared_location();
5483
5484 const Methods* methods;
5485 Type* deref = this->points_to();
5486 if (deref->named_type() != NULL)
5487 methods = deref->named_type()->methods();
5488 else if (deref->struct_type() != NULL)
5489 methods = deref->struct_type()->methods();
5490 else
5491 methods = NULL;
5492
5493 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5494
5495 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5496
5497 Expression_list* vals = new Expression_list();
5498 vals->reserve(2);
5499
5500 Struct_field_list::const_iterator p = fields->begin();
5501 go_assert(p->is_field_name("_type"));
5502 vals->push_back(this->type_descriptor_constructor(gogo,
5503 RUNTIME_TYPE_KIND_PTR,
5504 name, methods, false));
5505
5506 ++p;
5507 go_assert(p->is_field_name("elem"));
5508 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5509
5510 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5511 }
5512 }
5513
5514 // Reflection string.
5515
5516 void
5517 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5518 {
5519 ret->push_back('*');
5520 this->append_reflection(this->to_type_, gogo, ret);
5521 }
5522
5523 // Export.
5524
5525 void
5526 Pointer_type::do_export(Export* exp) const
5527 {
5528 exp->write_c_string("*");
5529 if (this->is_unsafe_pointer_type())
5530 exp->write_c_string("any");
5531 else
5532 exp->write_type(this->to_type_);
5533 }
5534
5535 // Import.
5536
5537 Pointer_type*
5538 Pointer_type::do_import(Import* imp)
5539 {
5540 imp->require_c_string("*");
5541 if (imp->match_c_string("any"))
5542 {
5543 imp->advance(3);
5544 return Type::make_pointer_type(Type::make_void_type());
5545 }
5546 Type* to = imp->read_type();
5547 return Type::make_pointer_type(to);
5548 }
5549
5550 // Cache of pointer types. Key is "to" type, value is pointer type
5551 // that points to key.
5552
5553 Type::Pointer_type_table Type::pointer_types;
5554
5555 // A list of placeholder pointer types; items on this list will be either be
5556 // Pointer_type or Function_type. We keep this so we can ensure they are
5557 // finalized.
5558
5559 std::vector<Type*> Type::placeholder_pointers;
5560
5561 // Make a pointer type.
5562
5563 Pointer_type*
5564 Type::make_pointer_type(Type* to_type)
5565 {
5566 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5567 if (p != pointer_types.end())
5568 return p->second;
5569 Pointer_type* ret = new Pointer_type(to_type);
5570 pointer_types[to_type] = ret;
5571 return ret;
5572 }
5573
5574 // This helper is invoked immediately after named types have been
5575 // converted, to clean up any unresolved pointer types remaining in
5576 // the pointer type cache.
5577 //
5578 // The motivation for this routine: occasionally the compiler creates
5579 // some specific pointer type as part of a lowering operation (ex:
5580 // pointer-to-void), then Type::backend_type_size() is invoked on the
5581 // type (which creates a Btype placeholder for it), that placeholder
5582 // passed somewhere along the line to the back end, but since there is
5583 // no reference to the type in user code, there is never a call to
5584 // Type::finish_backend for the type (hence the Btype remains as an
5585 // unresolved placeholder). Calling this routine will clean up such
5586 // instances.
5587
5588 void
5589 Type::finish_pointer_types(Gogo* gogo)
5590 {
5591 // We don't use begin() and end() because it is possible to add new
5592 // placeholder pointer types as we finalized existing ones.
5593 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5594 {
5595 Type* typ = Type::placeholder_pointers[i];
5596 Type_btypes::iterator tbti = Type::type_btypes.find(typ);
5597 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5598 {
5599 typ->finish_backend(gogo, tbti->second.btype);
5600 tbti->second.is_placeholder = false;
5601 }
5602 }
5603 }
5604
5605 // Class Nil_type.
5606
5607 // Get the backend representation of a nil type. FIXME: Is this ever
5608 // actually called?
5609
5610 Btype*
5611 Nil_type::do_get_backend(Gogo* gogo)
5612 {
5613 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5614 }
5615
5616 // Make the nil type.
5617
5618 Type*
5619 Type::make_nil_type()
5620 {
5621 static Nil_type singleton_nil_type;
5622 return &singleton_nil_type;
5623 }
5624
5625 // The type of a function call which returns multiple values. This is
5626 // really a struct, but we don't want to confuse a function call which
5627 // returns a struct with a function call which returns multiple
5628 // values.
5629
5630 class Call_multiple_result_type : public Type
5631 {
5632 public:
5633 Call_multiple_result_type(Call_expression* call)
5634 : Type(TYPE_CALL_MULTIPLE_RESULT),
5635 call_(call)
5636 { }
5637
5638 protected:
5639 bool
5640 do_has_pointer() const
5641 { return false; }
5642
5643 bool
5644 do_compare_is_identity(Gogo*)
5645 { return false; }
5646
5647 Btype*
5648 do_get_backend(Gogo* gogo)
5649 {
5650 go_assert(saw_errors());
5651 return gogo->backend()->error_type();
5652 }
5653
5654 Expression*
5655 do_type_descriptor(Gogo*, Named_type*)
5656 {
5657 go_assert(saw_errors());
5658 return Expression::make_error(Linemap::unknown_location());
5659 }
5660
5661 void
5662 do_reflection(Gogo*, std::string*) const
5663 { go_assert(saw_errors()); }
5664
5665 void
5666 do_mangled_name(Gogo*, std::string*) const
5667 { go_assert(saw_errors()); }
5668
5669 private:
5670 // The expression being called.
5671 Call_expression* call_;
5672 };
5673
5674 // Make a call result type.
5675
5676 Type*
5677 Type::make_call_multiple_result_type(Call_expression* call)
5678 {
5679 return new Call_multiple_result_type(call);
5680 }
5681
5682 // Class Struct_field.
5683
5684 // Get the name of a field.
5685
5686 const std::string&
5687 Struct_field::field_name() const
5688 {
5689 const std::string& name(this->typed_identifier_.name());
5690 if (!name.empty())
5691 return name;
5692 else
5693 {
5694 // This is called during parsing, before anything is lowered, so
5695 // we have to be pretty careful to avoid dereferencing an
5696 // unknown type name.
5697 Type* t = this->typed_identifier_.type();
5698 Type* dt = t;
5699 if (t->classification() == Type::TYPE_POINTER)
5700 {
5701 // Very ugly.
5702 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5703 dt = ptype->points_to();
5704 }
5705 if (dt->forward_declaration_type() != NULL)
5706 return dt->forward_declaration_type()->name();
5707 else if (dt->named_type() != NULL)
5708 {
5709 // Note that this can be an alias name.
5710 return dt->named_type()->name();
5711 }
5712 else if (t->is_error_type() || dt->is_error_type())
5713 {
5714 static const std::string error_string = "*error*";
5715 return error_string;
5716 }
5717 else
5718 {
5719 // Avoid crashing in the erroneous case where T is named but
5720 // DT is not.
5721 go_assert(t != dt);
5722 if (t->forward_declaration_type() != NULL)
5723 return t->forward_declaration_type()->name();
5724 else if (t->named_type() != NULL)
5725 return t->named_type()->name();
5726 else
5727 go_unreachable();
5728 }
5729 }
5730 }
5731
5732 // Return whether this field is named NAME.
5733
5734 bool
5735 Struct_field::is_field_name(const std::string& name) const
5736 {
5737 const std::string& me(this->typed_identifier_.name());
5738 if (!me.empty())
5739 return me == name;
5740 else
5741 {
5742 Type* t = this->typed_identifier_.type();
5743 if (t->points_to() != NULL)
5744 t = t->points_to();
5745 Named_type* nt = t->named_type();
5746 if (nt != NULL && nt->name() == name)
5747 return true;
5748
5749 // This is a horrible hack caused by the fact that we don't pack
5750 // the names of builtin types. FIXME.
5751 if (!this->is_imported_
5752 && nt != NULL
5753 && nt->is_builtin()
5754 && nt->name() == Gogo::unpack_hidden_name(name))
5755 return true;
5756
5757 return false;
5758 }
5759 }
5760
5761 // Return whether this field is an unexported field named NAME.
5762
5763 bool
5764 Struct_field::is_unexported_field_name(Gogo* gogo,
5765 const std::string& name) const
5766 {
5767 const std::string& field_name(this->field_name());
5768 if (Gogo::is_hidden_name(field_name)
5769 && name == Gogo::unpack_hidden_name(field_name)
5770 && gogo->pack_hidden_name(name, false) != field_name)
5771 return true;
5772
5773 // Check for the name of a builtin type. This is like the test in
5774 // is_field_name, only there we return false if this->is_imported_,
5775 // and here we return true.
5776 if (this->is_imported_ && this->is_anonymous())
5777 {
5778 Type* t = this->typed_identifier_.type();
5779 if (t->points_to() != NULL)
5780 t = t->points_to();
5781 Named_type* nt = t->named_type();
5782 if (nt != NULL
5783 && nt->is_builtin()
5784 && nt->name() == Gogo::unpack_hidden_name(name))
5785 return true;
5786 }
5787
5788 return false;
5789 }
5790
5791 // Return whether this field is an embedded built-in type.
5792
5793 bool
5794 Struct_field::is_embedded_builtin(Gogo* gogo) const
5795 {
5796 const std::string& name(this->field_name());
5797 // We know that a field is an embedded type if it is anonymous.
5798 // We can decide if it is a built-in type by checking to see if it is
5799 // registered globally under the field's name.
5800 // This allows us to distinguish between embedded built-in types and
5801 // embedded types that are aliases to built-in types.
5802 return (this->is_anonymous()
5803 && !Gogo::is_hidden_name(name)
5804 && gogo->lookup_global(name.c_str()) != NULL);
5805 }
5806
5807 // Class Struct_type.
5808
5809 // A hash table used to find identical unnamed structs so that they
5810 // share method tables.
5811
5812 Struct_type::Identical_structs Struct_type::identical_structs;
5813
5814 // A hash table used to merge method sets for identical unnamed
5815 // structs.
5816
5817 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5818
5819 // Traversal.
5820
5821 int
5822 Struct_type::do_traverse(Traverse* traverse)
5823 {
5824 Struct_field_list* fields = this->fields_;
5825 if (fields != NULL)
5826 {
5827 for (Struct_field_list::iterator p = fields->begin();
5828 p != fields->end();
5829 ++p)
5830 {
5831 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5832 return TRAVERSE_EXIT;
5833 }
5834 }
5835 return TRAVERSE_CONTINUE;
5836 }
5837
5838 // Verify that the struct type is complete and valid.
5839
5840 bool
5841 Struct_type::do_verify()
5842 {
5843 Struct_field_list* fields = this->fields_;
5844 if (fields == NULL)
5845 return true;
5846 for (Struct_field_list::iterator p = fields->begin();
5847 p != fields->end();
5848 ++p)
5849 {
5850 Type* t = p->type();
5851 if (p->is_anonymous())
5852 {
5853 if ((t->named_type() != NULL && t->points_to() != NULL)
5854 || (t->named_type() == NULL && t->points_to() != NULL
5855 && t->points_to()->points_to() != NULL))
5856 {
5857 go_error_at(p->location(), "embedded type may not be a pointer");
5858 p->set_type(Type::make_error_type());
5859 }
5860 else if (t->points_to() != NULL
5861 && t->points_to()->interface_type() != NULL)
5862 {
5863 go_error_at(p->location(),
5864 "embedded type may not be pointer to interface");
5865 p->set_type(Type::make_error_type());
5866 }
5867 }
5868 }
5869 return true;
5870 }
5871
5872 // Whether this contains a pointer.
5873
5874 bool
5875 Struct_type::do_has_pointer() const
5876 {
5877 const Struct_field_list* fields = this->fields();
5878 if (fields == NULL)
5879 return false;
5880 for (Struct_field_list::const_iterator p = fields->begin();
5881 p != fields->end();
5882 ++p)
5883 {
5884 if (p->type()->has_pointer())
5885 return true;
5886 }
5887 return false;
5888 }
5889
5890 // Whether this type is identical to T.
5891
5892 bool
5893 Struct_type::is_identical(const Struct_type* t, int flags) const
5894 {
5895 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5896 return false;
5897 const Struct_field_list* fields1 = this->fields();
5898 const Struct_field_list* fields2 = t->fields();
5899 if (fields1 == NULL || fields2 == NULL)
5900 return fields1 == fields2;
5901 Struct_field_list::const_iterator pf2 = fields2->begin();
5902 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5903 pf1 != fields1->end();
5904 ++pf1, ++pf2)
5905 {
5906 if (pf2 == fields2->end())
5907 return false;
5908 if (pf1->field_name() != pf2->field_name())
5909 return false;
5910 if (pf1->is_anonymous() != pf2->is_anonymous()
5911 || !Type::are_identical(pf1->type(), pf2->type(), flags, NULL))
5912 return false;
5913 if ((flags & Type::COMPARE_TAGS) != 0)
5914 {
5915 if (!pf1->has_tag())
5916 {
5917 if (pf2->has_tag())
5918 return false;
5919 }
5920 else
5921 {
5922 if (!pf2->has_tag())
5923 return false;
5924 if (pf1->tag() != pf2->tag())
5925 return false;
5926 }
5927 }
5928 }
5929 if (pf2 != fields2->end())
5930 return false;
5931 return true;
5932 }
5933
5934 // Whether comparisons of this struct type are simple identity
5935 // comparisons.
5936
5937 bool
5938 Struct_type::do_compare_is_identity(Gogo* gogo)
5939 {
5940 const Struct_field_list* fields = this->fields_;
5941 if (fields == NULL)
5942 return true;
5943 int64_t offset = 0;
5944 for (Struct_field_list::const_iterator pf = fields->begin();
5945 pf != fields->end();
5946 ++pf)
5947 {
5948 if (Gogo::is_sink_name(pf->field_name()))
5949 return false;
5950
5951 if (!pf->type()->compare_is_identity(gogo))
5952 return false;
5953
5954 int64_t field_align;
5955 if (!pf->type()->backend_type_align(gogo, &field_align))
5956 return false;
5957 if ((offset & (field_align - 1)) != 0)
5958 {
5959 // This struct has padding. We don't guarantee that that
5960 // padding is zero-initialized for a stack variable, so we
5961 // can't use memcmp to compare struct values.
5962 return false;
5963 }
5964
5965 int64_t field_size;
5966 if (!pf->type()->backend_type_size(gogo, &field_size))
5967 return false;
5968 offset += field_size;
5969 }
5970
5971 int64_t struct_size;
5972 if (!this->backend_type_size(gogo, &struct_size))
5973 return false;
5974 if (offset != struct_size)
5975 {
5976 // Trailing padding may not be zero when on the stack.
5977 return false;
5978 }
5979
5980 return true;
5981 }
5982
5983 // Return whether this struct type is reflexive--whether a value of
5984 // this type is always equal to itself.
5985
5986 bool
5987 Struct_type::do_is_reflexive()
5988 {
5989 const Struct_field_list* fields = this->fields_;
5990 if (fields == NULL)
5991 return true;
5992 for (Struct_field_list::const_iterator pf = fields->begin();
5993 pf != fields->end();
5994 ++pf)
5995 {
5996 if (!pf->type()->is_reflexive())
5997 return false;
5998 }
5999 return true;
6000 }
6001
6002 // Return whether this struct type needs a key update when used as a
6003 // map key.
6004
6005 bool
6006 Struct_type::do_needs_key_update()
6007 {
6008 const Struct_field_list* fields = this->fields_;
6009 if (fields == NULL)
6010 return false;
6011 for (Struct_field_list::const_iterator pf = fields->begin();
6012 pf != fields->end();
6013 ++pf)
6014 {
6015 if (pf->type()->needs_key_update())
6016 return true;
6017 }
6018 return false;
6019 }
6020
6021 // Return whether computing the hash value of an instance of this
6022 // struct type might panic.
6023
6024 bool
6025 Struct_type::do_hash_might_panic()
6026 {
6027 const Struct_field_list* fields = this->fields_;
6028 if (fields == NULL)
6029 return false;
6030 for (Struct_field_list::const_iterator pf = fields->begin();
6031 pf != fields->end();
6032 ++pf)
6033 {
6034 if (pf->type()->hash_might_panic())
6035 return true;
6036 }
6037 return false;
6038 }
6039
6040 // Return whether this struct type is permitted to be in the heap.
6041
6042 bool
6043 Struct_type::do_in_heap()
6044 {
6045 const Struct_field_list* fields = this->fields_;
6046 if (fields == NULL)
6047 return true;
6048 for (Struct_field_list::const_iterator pf = fields->begin();
6049 pf != fields->end();
6050 ++pf)
6051 {
6052 if (!pf->type()->in_heap())
6053 return false;
6054 }
6055 return true;
6056 }
6057
6058 // Build identity and hash functions for this struct.
6059
6060 // Hash code.
6061
6062 unsigned int
6063 Struct_type::do_hash_for_method(Gogo* gogo, int flags) const
6064 {
6065 unsigned int ret = 0;
6066 if (this->fields() != NULL)
6067 {
6068 for (Struct_field_list::const_iterator pf = this->fields()->begin();
6069 pf != this->fields()->end();
6070 ++pf)
6071 ret = (ret << 1) + pf->type()->hash_for_method(gogo, flags);
6072 }
6073 ret <<= 2;
6074 if (this->is_struct_incomparable_)
6075 ret <<= 1;
6076 return ret;
6077 }
6078
6079 // Find the local field NAME.
6080
6081 const Struct_field*
6082 Struct_type::find_local_field(const std::string& name,
6083 unsigned int *pindex) const
6084 {
6085 const Struct_field_list* fields = this->fields_;
6086 if (fields == NULL)
6087 return NULL;
6088 unsigned int i = 0;
6089 for (Struct_field_list::const_iterator pf = fields->begin();
6090 pf != fields->end();
6091 ++pf, ++i)
6092 {
6093 if (pf->is_field_name(name))
6094 {
6095 if (pindex != NULL)
6096 *pindex = i;
6097 return &*pf;
6098 }
6099 }
6100 return NULL;
6101 }
6102
6103 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
6104
6105 Field_reference_expression*
6106 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
6107 Location location) const
6108 {
6109 unsigned int depth;
6110 return this->field_reference_depth(struct_expr, name, location, NULL,
6111 &depth);
6112 }
6113
6114 // Return an expression for a field, along with the depth at which it
6115 // was found.
6116
6117 Field_reference_expression*
6118 Struct_type::field_reference_depth(Expression* struct_expr,
6119 const std::string& name,
6120 Location location,
6121 Saw_named_type* saw,
6122 unsigned int* depth) const
6123 {
6124 const Struct_field_list* fields = this->fields_;
6125 if (fields == NULL)
6126 return NULL;
6127
6128 // Look for a field with this name.
6129 unsigned int i = 0;
6130 for (Struct_field_list::const_iterator pf = fields->begin();
6131 pf != fields->end();
6132 ++pf, ++i)
6133 {
6134 if (pf->is_field_name(name))
6135 {
6136 *depth = 0;
6137 return Expression::make_field_reference(struct_expr, i, location);
6138 }
6139 }
6140
6141 // Look for an anonymous field which contains a field with this
6142 // name.
6143 unsigned int found_depth = 0;
6144 Field_reference_expression* ret = NULL;
6145 i = 0;
6146 for (Struct_field_list::const_iterator pf = fields->begin();
6147 pf != fields->end();
6148 ++pf, ++i)
6149 {
6150 if (!pf->is_anonymous())
6151 continue;
6152
6153 Struct_type* st = pf->type()->deref()->struct_type();
6154 if (st == NULL)
6155 continue;
6156
6157 Saw_named_type* hold_saw = saw;
6158 Saw_named_type saw_here;
6159 Named_type* nt = pf->type()->named_type();
6160 if (nt == NULL)
6161 nt = pf->type()->deref()->named_type();
6162 if (nt != NULL)
6163 {
6164 Saw_named_type* q;
6165 for (q = saw; q != NULL; q = q->next)
6166 {
6167 if (q->nt == nt)
6168 {
6169 // If this is an error, it will be reported
6170 // elsewhere.
6171 break;
6172 }
6173 }
6174 if (q != NULL)
6175 continue;
6176 saw_here.next = saw;
6177 saw_here.nt = nt;
6178 saw = &saw_here;
6179 }
6180
6181 // Look for a reference using a NULL struct expression. If we
6182 // find one, fill in the struct expression with a reference to
6183 // this field.
6184 unsigned int subdepth;
6185 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6186 location,
6187 saw,
6188 &subdepth);
6189
6190 saw = hold_saw;
6191
6192 if (sub == NULL)
6193 continue;
6194
6195 if (ret == NULL || subdepth < found_depth)
6196 {
6197 if (ret != NULL)
6198 delete ret;
6199 ret = sub;
6200 found_depth = subdepth;
6201 Expression* here = Expression::make_field_reference(struct_expr, i,
6202 location);
6203 if (pf->type()->points_to() != NULL)
6204 here = Expression::make_dereference(here,
6205 Expression::NIL_CHECK_DEFAULT,
6206 location);
6207 while (sub->expr() != NULL)
6208 {
6209 sub = sub->expr()->deref()->field_reference_expression();
6210 go_assert(sub != NULL);
6211 }
6212 sub->set_struct_expression(here);
6213 sub->set_implicit(true);
6214 }
6215 else if (subdepth > found_depth)
6216 delete sub;
6217 else
6218 {
6219 // We do not handle ambiguity here--it should be handled by
6220 // Type::bind_field_or_method.
6221 delete sub;
6222 found_depth = 0;
6223 ret = NULL;
6224 }
6225 }
6226
6227 if (ret != NULL)
6228 *depth = found_depth + 1;
6229
6230 return ret;
6231 }
6232
6233 // Return the total number of fields, including embedded fields.
6234
6235 unsigned int
6236 Struct_type::total_field_count() const
6237 {
6238 if (this->fields_ == NULL)
6239 return 0;
6240 unsigned int ret = 0;
6241 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6242 pf != this->fields_->end();
6243 ++pf)
6244 {
6245 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6246 ++ret;
6247 else
6248 ret += pf->type()->struct_type()->total_field_count();
6249 }
6250 return ret;
6251 }
6252
6253 // Return whether NAME is an unexported field, for better error reporting.
6254
6255 bool
6256 Struct_type::is_unexported_local_field(Gogo* gogo,
6257 const std::string& name) const
6258 {
6259 const Struct_field_list* fields = this->fields_;
6260 if (fields != NULL)
6261 {
6262 for (Struct_field_list::const_iterator pf = fields->begin();
6263 pf != fields->end();
6264 ++pf)
6265 if (pf->is_unexported_field_name(gogo, name))
6266 return true;
6267 }
6268 return false;
6269 }
6270
6271 // Finalize the methods of an unnamed struct.
6272
6273 void
6274 Struct_type::finalize_methods(Gogo* gogo)
6275 {
6276 if (this->all_methods_ != NULL)
6277 return;
6278
6279 // It is possible to have multiple identical structs that have
6280 // methods. We want them to share method tables. Otherwise we will
6281 // emit identical methods more than once, which is bad since they
6282 // will even have the same names.
6283 std::pair<Identical_structs::iterator, bool> ins =
6284 Struct_type::identical_structs.insert(std::make_pair(this, this));
6285 if (!ins.second)
6286 {
6287 // An identical struct was already entered into the hash table.
6288 // Note that finalize_methods is, fortunately, not recursive.
6289 this->all_methods_ = ins.first->second->all_methods_;
6290 return;
6291 }
6292
6293 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6294 }
6295
6296 // Return the method NAME, or NULL if there isn't one or if it is
6297 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6298 // ambiguous.
6299
6300 Method*
6301 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6302 {
6303 return Type::method_function(this->all_methods_, name, is_ambiguous);
6304 }
6305
6306 // Return a pointer to the interface method table for this type for
6307 // the interface INTERFACE. IS_POINTER is true if this is for a
6308 // pointer to THIS.
6309
6310 Expression*
6311 Struct_type::interface_method_table(Interface_type* interface,
6312 bool is_pointer)
6313 {
6314 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6315 val(this, NULL);
6316 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6317 Struct_type::struct_method_tables.insert(val);
6318
6319 Struct_method_table_pair* smtp;
6320 if (!ins.second)
6321 smtp = ins.first->second;
6322 else
6323 {
6324 smtp = new Struct_method_table_pair();
6325 smtp->first = NULL;
6326 smtp->second = NULL;
6327 ins.first->second = smtp;
6328 }
6329
6330 return Type::interface_method_table(this, interface, is_pointer,
6331 &smtp->first, &smtp->second);
6332 }
6333
6334 // Convert struct fields to the backend representation. This is not
6335 // declared in types.h so that types.h doesn't have to #include
6336 // backend.h.
6337
6338 static void
6339 get_backend_struct_fields(Gogo* gogo, Struct_type* type, bool use_placeholder,
6340 std::vector<Backend::Btyped_identifier>* bfields)
6341 {
6342 const Struct_field_list* fields = type->fields();
6343 bfields->resize(fields->size());
6344 size_t i = 0;
6345 int64_t lastsize = 0;
6346 bool saw_nonzero = false;
6347 for (Struct_field_list::const_iterator p = fields->begin();
6348 p != fields->end();
6349 ++p, ++i)
6350 {
6351 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6352 (*bfields)[i].btype = (use_placeholder
6353 ? p->type()->get_backend_placeholder(gogo)
6354 : p->type()->get_backend(gogo));
6355 (*bfields)[i].location = p->location();
6356 lastsize = gogo->backend()->type_size((*bfields)[i].btype);
6357 if (lastsize != 0)
6358 saw_nonzero = true;
6359 }
6360 go_assert(i == fields->size());
6361 if (saw_nonzero && lastsize == 0)
6362 {
6363 // For nonzero-sized structs which end in a zero-sized thing, we add
6364 // an extra byte of padding to the type. This padding ensures that
6365 // taking the address of the zero-sized thing can't manufacture a
6366 // pointer to the next object in the heap. See issue 9401.
6367 size_t n = fields->size();
6368 bfields->resize(n + 1);
6369 (*bfields)[n].name = "_";
6370 (*bfields)[n].btype = Type::lookup_integer_type("uint8")->get_backend(gogo);
6371 (*bfields)[n].location = (*bfields)[n-1].location;
6372 type->set_has_padding();
6373 }
6374 }
6375
6376 // Get the backend representation for a struct type.
6377
6378 Btype*
6379 Struct_type::do_get_backend(Gogo* gogo)
6380 {
6381 std::vector<Backend::Btyped_identifier> bfields;
6382 get_backend_struct_fields(gogo, this, false, &bfields);
6383 return gogo->backend()->struct_type(bfields);
6384 }
6385
6386 // Finish the backend representation of the fields of a struct.
6387
6388 void
6389 Struct_type::finish_backend_fields(Gogo* gogo)
6390 {
6391 const Struct_field_list* fields = this->fields_;
6392 if (fields != NULL)
6393 {
6394 for (Struct_field_list::const_iterator p = fields->begin();
6395 p != fields->end();
6396 ++p)
6397 p->type()->get_backend(gogo);
6398 }
6399 }
6400
6401 // The type of a struct type descriptor.
6402
6403 Type*
6404 Struct_type::make_struct_type_descriptor_type()
6405 {
6406 static Type* ret;
6407 if (ret == NULL)
6408 {
6409 Type* tdt = Type::make_type_descriptor_type();
6410 Type* ptdt = Type::make_type_descriptor_ptr_type();
6411
6412 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6413 Type* string_type = Type::lookup_string_type();
6414 Type* pointer_string_type = Type::make_pointer_type(string_type);
6415
6416 Struct_type* sf =
6417 Type::make_builtin_struct_type(5,
6418 "name", pointer_string_type,
6419 "pkgPath", pointer_string_type,
6420 "typ", ptdt,
6421 "tag", pointer_string_type,
6422 "offsetAnon", uintptr_type);
6423 Type* nsf = Type::make_builtin_named_type("structField", sf);
6424
6425 Type* slice_type = Type::make_array_type(nsf, NULL);
6426
6427 Struct_type* s = Type::make_builtin_struct_type(2,
6428 "", tdt,
6429 "fields", slice_type);
6430
6431 ret = Type::make_builtin_named_type("StructType", s);
6432 }
6433
6434 return ret;
6435 }
6436
6437 // Build a type descriptor for a struct type.
6438
6439 Expression*
6440 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6441 {
6442 Location bloc = Linemap::predeclared_location();
6443
6444 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6445
6446 const Struct_field_list* fields = stdt->struct_type()->fields();
6447
6448 Expression_list* vals = new Expression_list();
6449 vals->reserve(2);
6450
6451 const Methods* methods = this->methods();
6452 // A named struct should not have methods--the methods should attach
6453 // to the named type.
6454 go_assert(methods == NULL || name == NULL);
6455
6456 Struct_field_list::const_iterator ps = fields->begin();
6457 go_assert(ps->is_field_name("_type"));
6458 vals->push_back(this->type_descriptor_constructor(gogo,
6459 RUNTIME_TYPE_KIND_STRUCT,
6460 name, methods, true));
6461
6462 ++ps;
6463 go_assert(ps->is_field_name("fields"));
6464
6465 Expression_list* elements = new Expression_list();
6466 elements->reserve(this->fields_->size());
6467 Type* element_type = ps->type()->array_type()->element_type();
6468 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6469 pf != this->fields_->end();
6470 ++pf)
6471 {
6472 const Struct_field_list* f = element_type->struct_type()->fields();
6473
6474 Expression_list* fvals = new Expression_list();
6475 fvals->reserve(5);
6476
6477 Struct_field_list::const_iterator q = f->begin();
6478 go_assert(q->is_field_name("name"));
6479 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6480 Expression* s = Expression::make_string(n, bloc);
6481 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6482
6483 ++q;
6484 go_assert(q->is_field_name("pkgPath"));
6485 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6486 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6487 fvals->push_back(Expression::make_nil(bloc));
6488 else
6489 {
6490 if (is_embedded_builtin)
6491 n = gogo->package_name();
6492 else
6493 n = Gogo::hidden_name_pkgpath(pf->field_name());
6494 s = Expression::make_string(n, bloc);
6495 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6496 }
6497
6498 ++q;
6499 go_assert(q->is_field_name("typ"));
6500 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6501
6502 ++q;
6503 go_assert(q->is_field_name("tag"));
6504 if (!pf->has_tag())
6505 fvals->push_back(Expression::make_nil(bloc));
6506 else
6507 {
6508 s = Expression::make_string(pf->tag(), bloc);
6509 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6510 }
6511
6512 ++q;
6513 go_assert(q->is_field_name("offsetAnon"));
6514 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6515 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6516 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6517 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6518 int av = pf->is_anonymous() ? 1 : 0;
6519 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6520 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6521 fvals->push_back(o);
6522
6523 Expression* v = Expression::make_struct_composite_literal(element_type,
6524 fvals, bloc);
6525 elements->push_back(v);
6526 }
6527
6528 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6529 elements, bloc));
6530
6531 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6532 }
6533
6534 // Write the hash function for a struct which can not use the identity
6535 // function.
6536
6537 void
6538 Struct_type::write_hash_function(Gogo* gogo, Function_type* hash_fntype)
6539 {
6540 Location bloc = Linemap::predeclared_location();
6541
6542 // The pointer to the struct that we are going to hash. This is an
6543 // argument to the hash function we are implementing here.
6544 Named_object* key_arg = gogo->lookup("key", NULL);
6545 go_assert(key_arg != NULL);
6546 Type* key_arg_type = key_arg->var_value()->type();
6547
6548 // The seed argument to the hash function.
6549 Named_object* seed_arg = gogo->lookup("seed", NULL);
6550 go_assert(seed_arg != NULL);
6551
6552 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6553
6554 // Make a temporary to hold the return value, initialized to the seed.
6555 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6556 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6557 bloc);
6558 gogo->add_statement(retval);
6559
6560 // Make a temporary to hold the key as a uintptr.
6561 ref = Expression::make_var_reference(key_arg, bloc);
6562 ref = Expression::make_cast(uintptr_type, ref, bloc);
6563 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6564 bloc);
6565 gogo->add_statement(key);
6566
6567 // Loop over the struct fields.
6568 const Struct_field_list* fields = this->fields_;
6569 for (Struct_field_list::const_iterator pf = fields->begin();
6570 pf != fields->end();
6571 ++pf)
6572 {
6573 if (Gogo::is_sink_name(pf->field_name()))
6574 continue;
6575
6576 // Get a pointer to the value of this field.
6577 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6578 ref = Expression::make_temporary_reference(key, bloc);
6579 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6580 bloc);
6581 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6582
6583 // Get the hash function to use for the type of this field.
6584 Named_object* hash_fn = pf->type()->hash_function(gogo, hash_fntype);
6585
6586 // Call the hash function for the field, passing retval as the seed.
6587 ref = Expression::make_temporary_reference(retval, bloc);
6588 Expression_list* args = new Expression_list();
6589 args->push_back(subkey);
6590 args->push_back(ref);
6591 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6592 Expression* call = Expression::make_call(func, args, false, bloc);
6593
6594 // Set retval to the result.
6595 Temporary_reference_expression* tref =
6596 Expression::make_temporary_reference(retval, bloc);
6597 tref->set_is_lvalue();
6598 Statement* s = Statement::make_assignment(tref, call, bloc);
6599 gogo->add_statement(s);
6600 }
6601
6602 // Return retval to the caller of the hash function.
6603 Expression_list* vals = new Expression_list();
6604 ref = Expression::make_temporary_reference(retval, bloc);
6605 vals->push_back(ref);
6606 Statement* s = Statement::make_return_statement(vals, bloc);
6607 gogo->add_statement(s);
6608 }
6609
6610 // Write the equality function for a struct which can not use the
6611 // identity function.
6612
6613 void
6614 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6615 {
6616 Location bloc = Linemap::predeclared_location();
6617
6618 // The pointers to the structs we are going to compare.
6619 Named_object* key1_arg = gogo->lookup("key1", NULL);
6620 Named_object* key2_arg = gogo->lookup("key2", NULL);
6621 go_assert(key1_arg != NULL && key2_arg != NULL);
6622
6623 // Build temporaries with the right types.
6624 Type* pt = Type::make_pointer_type(name != NULL
6625 ? static_cast<Type*>(name)
6626 : static_cast<Type*>(this));
6627
6628 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6629 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6630 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6631 gogo->add_statement(p1);
6632
6633 ref = Expression::make_var_reference(key2_arg, bloc);
6634 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6635 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6636 gogo->add_statement(p2);
6637
6638 const Struct_field_list* fields = this->fields_;
6639 unsigned int field_index = 0;
6640 for (Struct_field_list::const_iterator pf = fields->begin();
6641 pf != fields->end();
6642 ++pf, ++field_index)
6643 {
6644 if (Gogo::is_sink_name(pf->field_name()))
6645 continue;
6646
6647 // Compare one field in both P1 and P2.
6648 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6649 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6650 bloc);
6651 f1 = Expression::make_field_reference(f1, field_index, bloc);
6652
6653 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6654 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6655 bloc);
6656 f2 = Expression::make_field_reference(f2, field_index, bloc);
6657
6658 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6659
6660 // If the values are not equal, return false.
6661 gogo->start_block(bloc);
6662 Expression_list* vals = new Expression_list();
6663 vals->push_back(Expression::make_boolean(false, bloc));
6664 Statement* s = Statement::make_return_statement(vals, bloc);
6665 gogo->add_statement(s);
6666 Block* then_block = gogo->finish_block(bloc);
6667
6668 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6669 gogo->add_statement(s);
6670 }
6671
6672 // All the fields are equal, so return true.
6673 Expression_list* vals = new Expression_list();
6674 vals->push_back(Expression::make_boolean(true, bloc));
6675 Statement* s = Statement::make_return_statement(vals, bloc);
6676 gogo->add_statement(s);
6677 }
6678
6679 // Reflection string.
6680
6681 void
6682 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6683 {
6684 ret->append("struct {");
6685
6686 for (Struct_field_list::const_iterator p = this->fields_->begin();
6687 p != this->fields_->end();
6688 ++p)
6689 {
6690 if (p != this->fields_->begin())
6691 ret->push_back(';');
6692 ret->push_back(' ');
6693 if (!p->is_anonymous())
6694 {
6695 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6696 ret->push_back(' ');
6697 }
6698 if (p->is_anonymous()
6699 && p->type()->named_type() != NULL
6700 && p->type()->named_type()->is_alias())
6701 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6702 else
6703 this->append_reflection(p->type(), gogo, ret);
6704
6705 if (p->has_tag())
6706 {
6707 const std::string& tag(p->tag());
6708 ret->append(" \"");
6709 for (std::string::const_iterator pt = tag.begin();
6710 pt != tag.end();
6711 ++pt)
6712 {
6713 if (*pt == '\0')
6714 ret->append("\\x00");
6715 else if (*pt == '\n')
6716 ret->append("\\n");
6717 else if (*pt == '\t')
6718 ret->append("\\t");
6719 else if (*pt == '"')
6720 ret->append("\\\"");
6721 else if (*pt == '\\')
6722 ret->append("\\\\");
6723 else
6724 ret->push_back(*pt);
6725 }
6726 ret->push_back('"');
6727 }
6728 }
6729
6730 if (!this->fields_->empty())
6731 ret->push_back(' ');
6732
6733 ret->push_back('}');
6734 }
6735
6736 // If the offset of field INDEX in the backend implementation can be
6737 // determined, set *POFFSET to the offset in bytes and return true.
6738 // Otherwise, return false.
6739
6740 bool
6741 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6742 int64_t* poffset)
6743 {
6744 if (!this->is_backend_type_size_known(gogo))
6745 return false;
6746 Btype* bt = this->get_backend_placeholder(gogo);
6747 *poffset = gogo->backend()->type_field_offset(bt, index);
6748 return true;
6749 }
6750
6751 // Export.
6752
6753 void
6754 Struct_type::do_export(Export* exp) const
6755 {
6756 exp->write_c_string("struct { ");
6757 const Struct_field_list* fields = this->fields_;
6758 go_assert(fields != NULL);
6759 for (Struct_field_list::const_iterator p = fields->begin();
6760 p != fields->end();
6761 ++p)
6762 {
6763 if (p->is_anonymous())
6764 exp->write_string("? ");
6765 else
6766 {
6767 exp->write_string(p->field_name());
6768 exp->write_c_string(" ");
6769 }
6770 exp->write_type(p->type());
6771
6772 if (p->has_tag())
6773 {
6774 exp->write_c_string(" ");
6775 Expression* expr =
6776 Expression::make_string(p->tag(), Linemap::predeclared_location());
6777
6778 Export_function_body efb(exp, 0);
6779 expr->export_expression(&efb);
6780 exp->write_string(efb.body());
6781
6782 delete expr;
6783 }
6784
6785 exp->write_c_string("; ");
6786 }
6787 exp->write_c_string("}");
6788 }
6789
6790 // Import.
6791
6792 Struct_type*
6793 Struct_type::do_import(Import* imp)
6794 {
6795 imp->require_c_string("struct { ");
6796 Struct_field_list* fields = new Struct_field_list;
6797 if (imp->peek_char() != '}')
6798 {
6799 while (true)
6800 {
6801 std::string name;
6802 if (imp->match_c_string("? "))
6803 imp->advance(2);
6804 else
6805 {
6806 name = imp->read_identifier();
6807 imp->require_c_string(" ");
6808 }
6809 Type* ftype = imp->read_type();
6810
6811 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6812 sf.set_is_imported();
6813
6814 if (imp->peek_char() == ' ')
6815 {
6816 imp->advance(1);
6817 Expression* expr = Expression::import_expression(imp,
6818 imp->location());
6819 String_expression* sexpr = expr->string_expression();
6820 go_assert(sexpr != NULL);
6821 sf.set_tag(sexpr->val());
6822 delete sexpr;
6823 }
6824
6825 imp->require_c_string("; ");
6826 fields->push_back(sf);
6827 if (imp->peek_char() == '}')
6828 break;
6829 }
6830 }
6831 imp->require_c_string("}");
6832
6833 return Type::make_struct_type(fields, imp->location());
6834 }
6835
6836 // Whether we can write this struct type to a C header file.
6837 // We can't if any of the fields are structs defined in a different package.
6838
6839 bool
6840 Struct_type::can_write_to_c_header(
6841 std::vector<const Named_object*>* requires,
6842 std::vector<const Named_object*>* declare) const
6843 {
6844 const Struct_field_list* fields = this->fields_;
6845 if (fields == NULL || fields->empty())
6846 return false;
6847 int sinks = 0;
6848 for (Struct_field_list::const_iterator p = fields->begin();
6849 p != fields->end();
6850 ++p)
6851 {
6852 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6853 return false;
6854 if (Gogo::message_name(p->field_name()) == "_")
6855 sinks++;
6856 }
6857 if (sinks > 1)
6858 return false;
6859 return true;
6860 }
6861
6862 // Whether we can write the type T to a C header file.
6863
6864 bool
6865 Struct_type::can_write_type_to_c_header(
6866 const Type* t,
6867 std::vector<const Named_object*>* requires,
6868 std::vector<const Named_object*>* declare) const
6869 {
6870 t = t->forwarded();
6871 switch (t->classification())
6872 {
6873 case TYPE_ERROR:
6874 case TYPE_FORWARD:
6875 return false;
6876
6877 case TYPE_VOID:
6878 case TYPE_BOOLEAN:
6879 case TYPE_INTEGER:
6880 case TYPE_FLOAT:
6881 case TYPE_COMPLEX:
6882 case TYPE_STRING:
6883 case TYPE_FUNCTION:
6884 case TYPE_MAP:
6885 case TYPE_CHANNEL:
6886 case TYPE_INTERFACE:
6887 return true;
6888
6889 case TYPE_POINTER:
6890 // Don't try to handle a pointer to an array.
6891 if (t->points_to()->array_type() != NULL
6892 && !t->points_to()->is_slice_type())
6893 return false;
6894
6895 if (t->points_to()->named_type() != NULL
6896 && t->points_to()->struct_type() != NULL)
6897 declare->push_back(t->points_to()->named_type()->named_object());
6898 return true;
6899
6900 case TYPE_STRUCT:
6901 return t->struct_type()->can_write_to_c_header(requires, declare);
6902
6903 case TYPE_ARRAY:
6904 if (t->is_slice_type())
6905 return true;
6906 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6907 requires, declare);
6908
6909 case TYPE_NAMED:
6910 {
6911 const Named_object* no = t->named_type()->named_object();
6912 if (no->package() != NULL)
6913 {
6914 if (t->is_unsafe_pointer_type())
6915 return true;
6916 return false;
6917 }
6918 if (t->struct_type() != NULL)
6919 {
6920 // We will accept empty struct fields, but not print them.
6921 if (t->struct_type()->total_field_count() == 0)
6922 return true;
6923 requires->push_back(no);
6924 return t->struct_type()->can_write_to_c_header(requires, declare);
6925 }
6926 return this->can_write_type_to_c_header(t->base(), requires, declare);
6927 }
6928
6929 case TYPE_CALL_MULTIPLE_RESULT:
6930 case TYPE_NIL:
6931 case TYPE_SINK:
6932 default:
6933 go_unreachable();
6934 }
6935 }
6936
6937 // Write this struct to a C header file.
6938
6939 void
6940 Struct_type::write_to_c_header(std::ostream& os) const
6941 {
6942 const Struct_field_list* fields = this->fields_;
6943 for (Struct_field_list::const_iterator p = fields->begin();
6944 p != fields->end();
6945 ++p)
6946 {
6947 // Skip fields that are empty struct types. The C code can't
6948 // refer to them anyhow.
6949 if (p->type()->struct_type() != NULL
6950 && p->type()->struct_type()->total_field_count() == 0)
6951 continue;
6952
6953 os << '\t';
6954 this->write_field_to_c_header(os, p->field_name(), p->type());
6955 os << ';' << std::endl;
6956 }
6957 }
6958
6959 // Write the type of a struct field to a C header file.
6960
6961 void
6962 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6963 const Type *t) const
6964 {
6965 bool print_name = true;
6966 t = t->forwarded();
6967 switch (t->classification())
6968 {
6969 case TYPE_VOID:
6970 os << "void";
6971 break;
6972
6973 case TYPE_BOOLEAN:
6974 os << "_Bool";
6975 break;
6976
6977 case TYPE_INTEGER:
6978 {
6979 const Integer_type* it = t->integer_type();
6980 if (it->is_unsigned())
6981 os << 'u';
6982 os << "int" << it->bits() << "_t";
6983 }
6984 break;
6985
6986 case TYPE_FLOAT:
6987 switch (t->float_type()->bits())
6988 {
6989 case 32:
6990 os << "float";
6991 break;
6992 case 64:
6993 os << "double";
6994 break;
6995 default:
6996 go_unreachable();
6997 }
6998 break;
6999
7000 case TYPE_COMPLEX:
7001 switch (t->complex_type()->bits())
7002 {
7003 case 64:
7004 os << "float _Complex";
7005 break;
7006 case 128:
7007 os << "double _Complex";
7008 break;
7009 default:
7010 go_unreachable();
7011 }
7012 break;
7013
7014 case TYPE_STRING:
7015 os << "String";
7016 break;
7017
7018 case TYPE_FUNCTION:
7019 os << "FuncVal*";
7020 break;
7021
7022 case TYPE_POINTER:
7023 {
7024 std::vector<const Named_object*> requires;
7025 std::vector<const Named_object*> declare;
7026 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
7027 &declare))
7028 os << "void*";
7029 else
7030 {
7031 this->write_field_to_c_header(os, "", t->points_to());
7032 os << '*';
7033 }
7034 }
7035 break;
7036
7037 case TYPE_MAP:
7038 os << "Map*";
7039 break;
7040
7041 case TYPE_CHANNEL:
7042 os << "Chan*";
7043 break;
7044
7045 case TYPE_INTERFACE:
7046 if (t->interface_type()->is_empty())
7047 os << "Eface";
7048 else
7049 os << "Iface";
7050 break;
7051
7052 case TYPE_STRUCT:
7053 os << "struct {" << std::endl;
7054 t->struct_type()->write_to_c_header(os);
7055 os << "\t}";
7056 break;
7057
7058 case TYPE_ARRAY:
7059 if (t->is_slice_type())
7060 os << "Slice";
7061 else
7062 {
7063 const Type *ele = t;
7064 std::vector<const Type*> array_types;
7065 while (ele->array_type() != NULL && !ele->is_slice_type())
7066 {
7067 array_types.push_back(ele);
7068 ele = ele->array_type()->element_type();
7069 }
7070 this->write_field_to_c_header(os, "", ele);
7071 os << ' ' << Gogo::message_name(name);
7072 print_name = false;
7073 while (!array_types.empty())
7074 {
7075 ele = array_types.back();
7076 array_types.pop_back();
7077 os << '[';
7078 Numeric_constant nc;
7079 if (!ele->array_type()->length()->numeric_constant_value(&nc))
7080 go_unreachable();
7081 mpz_t val;
7082 if (!nc.to_int(&val))
7083 go_unreachable();
7084 char* s = mpz_get_str(NULL, 10, val);
7085 os << s;
7086 free(s);
7087 mpz_clear(val);
7088 os << ']';
7089 }
7090 }
7091 break;
7092
7093 case TYPE_NAMED:
7094 {
7095 const Named_object* no = t->named_type()->named_object();
7096 if (t->struct_type() != NULL)
7097 os << "struct " << no->message_name();
7098 else if (t->is_unsafe_pointer_type())
7099 os << "void*";
7100 else if (t == Type::lookup_integer_type("uintptr"))
7101 os << "uintptr_t";
7102 else
7103 {
7104 this->write_field_to_c_header(os, name, t->base());
7105 print_name = false;
7106 }
7107 }
7108 break;
7109
7110 case TYPE_ERROR:
7111 case TYPE_FORWARD:
7112 case TYPE_CALL_MULTIPLE_RESULT:
7113 case TYPE_NIL:
7114 case TYPE_SINK:
7115 default:
7116 go_unreachable();
7117 }
7118
7119 if (print_name && !name.empty())
7120 os << ' ' << Gogo::message_name(name);
7121 }
7122
7123 // Make a struct type.
7124
7125 Struct_type*
7126 Type::make_struct_type(Struct_field_list* fields,
7127 Location location)
7128 {
7129 return new Struct_type(fields, location);
7130 }
7131
7132 // Class Array_type.
7133
7134 // Store the length of an array as an int64_t into *PLEN. Return
7135 // false if the length can not be determined. This will assert if
7136 // called for a slice.
7137
7138 bool
7139 Array_type::int_length(int64_t* plen) const
7140 {
7141 go_assert(this->length_ != NULL);
7142 Numeric_constant nc;
7143 if (!this->length_->numeric_constant_value(&nc))
7144 return false;
7145 return nc.to_memory_size(plen);
7146 }
7147
7148 // Whether two array types are identical.
7149
7150 bool
7151 Array_type::is_identical(const Array_type* t, int flags) const
7152 {
7153 if (!Type::are_identical(this->element_type(), t->element_type(),
7154 flags, NULL))
7155 return false;
7156
7157 if (this->is_array_incomparable_ != t->is_array_incomparable_)
7158 return false;
7159
7160 Expression* l1 = this->length();
7161 Expression* l2 = t->length();
7162
7163 // Slices of the same element type are identical.
7164 if (l1 == NULL && l2 == NULL)
7165 return true;
7166
7167 // Arrays of the same element type are identical if they have the
7168 // same length.
7169 if (l1 != NULL && l2 != NULL)
7170 {
7171 if (l1 == l2)
7172 return true;
7173
7174 // Try to determine the lengths. If we can't, assume the arrays
7175 // are not identical.
7176 bool ret = false;
7177 Numeric_constant nc1, nc2;
7178 if (l1->numeric_constant_value(&nc1)
7179 && l2->numeric_constant_value(&nc2))
7180 {
7181 mpz_t v1;
7182 if (nc1.to_int(&v1))
7183 {
7184 mpz_t v2;
7185 if (nc2.to_int(&v2))
7186 {
7187 ret = mpz_cmp(v1, v2) == 0;
7188 mpz_clear(v2);
7189 }
7190 mpz_clear(v1);
7191 }
7192 }
7193 return ret;
7194 }
7195
7196 // Otherwise the arrays are not identical.
7197 return false;
7198 }
7199
7200 // Traversal.
7201
7202 int
7203 Array_type::do_traverse(Traverse* traverse)
7204 {
7205 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7206 return TRAVERSE_EXIT;
7207 if (this->length_ != NULL
7208 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7209 return TRAVERSE_EXIT;
7210 return TRAVERSE_CONTINUE;
7211 }
7212
7213 // Check that the length is valid.
7214
7215 bool
7216 Array_type::verify_length()
7217 {
7218 if (this->length_ == NULL)
7219 return true;
7220
7221 Type_context context(Type::lookup_integer_type("int"), false);
7222 this->length_->determine_type(&context);
7223
7224 if (!this->length_->is_constant())
7225 {
7226 go_error_at(this->length_->location(), "array bound is not constant");
7227 return false;
7228 }
7229
7230 // For array types, the length expression can be an untyped constant
7231 // representable as an int, but we don't allow explicitly non-integer
7232 // values such as "float64(10)". See issues #13485 and #13486.
7233 if (this->length_->type()->integer_type() == NULL
7234 && !this->length_->type()->is_error_type())
7235 {
7236 go_error_at(this->length_->location(), "invalid array bound");
7237 return false;
7238 }
7239
7240 Numeric_constant nc;
7241 if (!this->length_->numeric_constant_value(&nc))
7242 {
7243 if (this->length_->type()->integer_type() != NULL
7244 || this->length_->type()->float_type() != NULL)
7245 go_error_at(this->length_->location(), "array bound is not constant");
7246 else
7247 go_error_at(this->length_->location(), "array bound is not numeric");
7248 return false;
7249 }
7250
7251 Type* int_type = Type::lookup_integer_type("int");
7252 unsigned int tbits = int_type->integer_type()->bits();
7253 unsigned long val;
7254 switch (nc.to_unsigned_long(&val))
7255 {
7256 case Numeric_constant::NC_UL_VALID:
7257 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7258 {
7259 go_error_at(this->length_->location(), "array bound overflows");
7260 return false;
7261 }
7262 break;
7263 case Numeric_constant::NC_UL_NOTINT:
7264 go_error_at(this->length_->location(), "array bound truncated to integer");
7265 return false;
7266 case Numeric_constant::NC_UL_NEGATIVE:
7267 go_error_at(this->length_->location(), "negative array bound");
7268 return false;
7269 case Numeric_constant::NC_UL_BIG:
7270 {
7271 mpz_t mval;
7272 if (!nc.to_int(&mval))
7273 go_unreachable();
7274 unsigned int bits = mpz_sizeinbase(mval, 2);
7275 mpz_clear(mval);
7276 if (bits >= tbits)
7277 {
7278 go_error_at(this->length_->location(), "array bound overflows");
7279 return false;
7280 }
7281 }
7282 break;
7283 default:
7284 go_unreachable();
7285 }
7286
7287 return true;
7288 }
7289
7290 // Verify the type.
7291
7292 bool
7293 Array_type::do_verify()
7294 {
7295 if (this->element_type()->is_error_type())
7296 return false;
7297 if (!this->verify_length())
7298 this->length_ = Expression::make_error(this->length_->location());
7299 return true;
7300 }
7301
7302 // Whether the type contains pointers. This is always true for a
7303 // slice. For an array it is true if the element type has pointers
7304 // and the length is greater than zero.
7305
7306 bool
7307 Array_type::do_has_pointer() const
7308 {
7309 if (this->length_ == NULL)
7310 return true;
7311 if (!this->element_type_->has_pointer())
7312 return false;
7313
7314 Numeric_constant nc;
7315 if (!this->length_->numeric_constant_value(&nc))
7316 {
7317 // Error reported elsewhere.
7318 return false;
7319 }
7320
7321 unsigned long val;
7322 switch (nc.to_unsigned_long(&val))
7323 {
7324 case Numeric_constant::NC_UL_VALID:
7325 return val > 0;
7326 case Numeric_constant::NC_UL_BIG:
7327 return true;
7328 default:
7329 // Error reported elsewhere.
7330 return false;
7331 }
7332 }
7333
7334 // Whether we can use memcmp to compare this array.
7335
7336 bool
7337 Array_type::do_compare_is_identity(Gogo* gogo)
7338 {
7339 if (this->length_ == NULL)
7340 return false;
7341
7342 // Check for [...], which indicates that this is not a real type.
7343 if (this->length_->is_nil_expression())
7344 return false;
7345
7346 if (!this->element_type_->compare_is_identity(gogo))
7347 return false;
7348
7349 // If there is any padding, then we can't use memcmp.
7350 int64_t size;
7351 int64_t align;
7352 if (!this->element_type_->backend_type_size(gogo, &size)
7353 || !this->element_type_->backend_type_align(gogo, &align))
7354 return false;
7355 if ((size & (align - 1)) != 0)
7356 return false;
7357
7358 return true;
7359 }
7360
7361 // Array type hash code.
7362
7363 unsigned int
7364 Array_type::do_hash_for_method(Gogo* gogo, int flags) const
7365 {
7366 unsigned int ret;
7367
7368 // There is no very convenient way to get a hash code for the
7369 // length.
7370 ret = this->element_type_->hash_for_method(gogo, flags) + 1;
7371 if (this->is_array_incomparable_)
7372 ret <<= 1;
7373 return ret;
7374 }
7375
7376 // Write the hash function for an array which can not use the identify
7377 // function.
7378
7379 void
7380 Array_type::write_hash_function(Gogo* gogo, Function_type* hash_fntype)
7381 {
7382 Location bloc = Linemap::predeclared_location();
7383
7384 // The pointer to the array that we are going to hash. This is an
7385 // argument to the hash function we are implementing here.
7386 Named_object* key_arg = gogo->lookup("key", NULL);
7387 go_assert(key_arg != NULL);
7388 Type* key_arg_type = key_arg->var_value()->type();
7389
7390 // The seed argument to the hash function.
7391 Named_object* seed_arg = gogo->lookup("seed", NULL);
7392 go_assert(seed_arg != NULL);
7393
7394 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7395
7396 // Make a temporary to hold the return value, initialized to the seed.
7397 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7398 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7399 bloc);
7400 gogo->add_statement(retval);
7401
7402 // Make a temporary to hold the key as a uintptr.
7403 ref = Expression::make_var_reference(key_arg, bloc);
7404 ref = Expression::make_cast(uintptr_type, ref, bloc);
7405 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7406 bloc);
7407 gogo->add_statement(key);
7408
7409 // Loop over the array elements.
7410 // for i = range a
7411 Type* int_type = Type::lookup_integer_type("int");
7412 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7413 gogo->add_statement(index);
7414
7415 Expression* iref = Expression::make_temporary_reference(index, bloc);
7416 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7417 Type* pt = Type::make_pointer_type(static_cast<Type*>(this));
7418 aref = Expression::make_cast(pt, aref, bloc);
7419 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7420 NULL,
7421 aref,
7422 bloc);
7423
7424 gogo->start_block(bloc);
7425
7426 // Get the hash function for the element type.
7427 Named_object* hash_fn = this->element_type_->hash_function(gogo,
7428 hash_fntype);
7429
7430 // Get a pointer to this element in the loop.
7431 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7432 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7433
7434 // Get the size of each element.
7435 Expression* ele_size = Expression::make_type_info(this->element_type_,
7436 Expression::TYPE_INFO_SIZE);
7437
7438 // Get the hash of this element, passing retval as the seed.
7439 ref = Expression::make_temporary_reference(retval, bloc);
7440 Expression_list* args = new Expression_list();
7441 args->push_back(subkey);
7442 args->push_back(ref);
7443 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7444 Expression* call = Expression::make_call(func, args, false, bloc);
7445
7446 // Set retval to the result.
7447 Temporary_reference_expression* tref =
7448 Expression::make_temporary_reference(retval, bloc);
7449 tref->set_is_lvalue();
7450 Statement* s = Statement::make_assignment(tref, call, bloc);
7451 gogo->add_statement(s);
7452
7453 // Increase the element pointer.
7454 tref = Expression::make_temporary_reference(key, bloc);
7455 tref->set_is_lvalue();
7456 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7457 bloc);
7458 Block* statements = gogo->finish_block(bloc);
7459
7460 for_range->add_statements(statements);
7461 gogo->add_statement(for_range);
7462
7463 // Return retval to the caller of the hash function.
7464 Expression_list* vals = new Expression_list();
7465 ref = Expression::make_temporary_reference(retval, bloc);
7466 vals->push_back(ref);
7467 s = Statement::make_return_statement(vals, bloc);
7468 gogo->add_statement(s);
7469 }
7470
7471 // Write the equality function for an array which can not use the
7472 // identity function.
7473
7474 void
7475 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7476 {
7477 Location bloc = Linemap::predeclared_location();
7478
7479 // The pointers to the arrays we are going to compare.
7480 Named_object* key1_arg = gogo->lookup("key1", NULL);
7481 Named_object* key2_arg = gogo->lookup("key2", NULL);
7482 go_assert(key1_arg != NULL && key2_arg != NULL);
7483
7484 // Build temporaries for the keys with the right types.
7485 Type* pt = Type::make_pointer_type(name != NULL
7486 ? static_cast<Type*>(name)
7487 : static_cast<Type*>(this));
7488
7489 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7490 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7491 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7492 gogo->add_statement(p1);
7493
7494 ref = Expression::make_var_reference(key2_arg, bloc);
7495 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7496 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7497 gogo->add_statement(p2);
7498
7499 // Loop over the array elements.
7500 // for i = range a
7501 Type* int_type = Type::lookup_integer_type("int");
7502 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7503 gogo->add_statement(index);
7504
7505 Expression* iref = Expression::make_temporary_reference(index, bloc);
7506 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7507 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7508 NULL,
7509 aref,
7510 bloc);
7511
7512 gogo->start_block(bloc);
7513
7514 // Compare element in P1 and P2.
7515 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7516 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7517 ref = Expression::make_temporary_reference(index, bloc);
7518 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7519
7520 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7521 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7522 ref = Expression::make_temporary_reference(index, bloc);
7523 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7524
7525 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7526
7527 // If the elements are not equal, return false.
7528 gogo->start_block(bloc);
7529 Expression_list* vals = new Expression_list();
7530 vals->push_back(Expression::make_boolean(false, bloc));
7531 Statement* s = Statement::make_return_statement(vals, bloc);
7532 gogo->add_statement(s);
7533 Block* then_block = gogo->finish_block(bloc);
7534
7535 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7536 gogo->add_statement(s);
7537
7538 Block* statements = gogo->finish_block(bloc);
7539
7540 for_range->add_statements(statements);
7541 gogo->add_statement(for_range);
7542
7543 // All the elements are equal, so return true.
7544 vals = new Expression_list();
7545 vals->push_back(Expression::make_boolean(true, bloc));
7546 s = Statement::make_return_statement(vals, bloc);
7547 gogo->add_statement(s);
7548 }
7549
7550 // Get the backend representation of the fields of a slice. This is
7551 // not declared in types.h so that types.h doesn't have to #include
7552 // backend.h.
7553 //
7554 // We use int for the count and capacity fields. This matches 6g.
7555 // The language more or less assumes that we can't allocate space of a
7556 // size which does not fit in int.
7557
7558 static void
7559 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7560 std::vector<Backend::Btyped_identifier>* bfields)
7561 {
7562 bfields->resize(3);
7563
7564 Type* pet = Type::make_pointer_type(type->element_type());
7565 Btype* pbet = (use_placeholder
7566 ? pet->get_backend_placeholder(gogo)
7567 : pet->get_backend(gogo));
7568 Location ploc = Linemap::predeclared_location();
7569
7570 Backend::Btyped_identifier* p = &(*bfields)[0];
7571 p->name = "__values";
7572 p->btype = pbet;
7573 p->location = ploc;
7574
7575 Type* int_type = Type::lookup_integer_type("int");
7576
7577 p = &(*bfields)[1];
7578 p->name = "__count";
7579 p->btype = int_type->get_backend(gogo);
7580 p->location = ploc;
7581
7582 p = &(*bfields)[2];
7583 p->name = "__capacity";
7584 p->btype = int_type->get_backend(gogo);
7585 p->location = ploc;
7586 }
7587
7588 // Get the backend representation for the type of this array. A fixed array is
7589 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7590 // just like an array in C. An open array is a struct with three
7591 // fields: a data pointer, the length, and the capacity.
7592
7593 Btype*
7594 Array_type::do_get_backend(Gogo* gogo)
7595 {
7596 if (this->length_ == NULL)
7597 {
7598 std::vector<Backend::Btyped_identifier> bfields;
7599 get_backend_slice_fields(gogo, this, false, &bfields);
7600 return gogo->backend()->struct_type(bfields);
7601 }
7602 else
7603 {
7604 Btype* element = this->get_backend_element(gogo, false);
7605 Bexpression* len = this->get_backend_length(gogo);
7606 return gogo->backend()->array_type(element, len);
7607 }
7608 }
7609
7610 // Return the backend representation of the element type.
7611
7612 Btype*
7613 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7614 {
7615 if (use_placeholder)
7616 return this->element_type_->get_backend_placeholder(gogo);
7617 else
7618 return this->element_type_->get_backend(gogo);
7619 }
7620
7621 // Return the backend representation of the length. The length may be
7622 // computed using a function call, so we must only evaluate it once.
7623
7624 Bexpression*
7625 Array_type::get_backend_length(Gogo* gogo)
7626 {
7627 go_assert(this->length_ != NULL);
7628 if (this->blength_ == NULL)
7629 {
7630 if (this->length_->is_error_expression())
7631 {
7632 this->blength_ = gogo->backend()->error_expression();
7633 return this->blength_;
7634 }
7635 Numeric_constant nc;
7636 mpz_t val;
7637 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7638 {
7639 if (mpz_sgn(val) < 0)
7640 {
7641 this->blength_ = gogo->backend()->error_expression();
7642 return this->blength_;
7643 }
7644 Type* t = nc.type();
7645 if (t == NULL)
7646 t = Type::lookup_integer_type("int");
7647 else if (t->is_abstract())
7648 t = t->make_non_abstract_type();
7649 Btype* btype = t->get_backend(gogo);
7650 this->blength_ =
7651 gogo->backend()->integer_constant_expression(btype, val);
7652 mpz_clear(val);
7653 }
7654 else
7655 {
7656 // Make up a translation context for the array length
7657 // expression. FIXME: This won't work in general.
7658 Translate_context context(gogo, NULL, NULL, NULL);
7659 this->blength_ = this->length_->get_backend(&context);
7660
7661 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7662 this->blength_ =
7663 gogo->backend()->convert_expression(ibtype, this->blength_,
7664 this->length_->location());
7665 }
7666 }
7667 return this->blength_;
7668 }
7669
7670 // Finish backend representation of the array.
7671
7672 void
7673 Array_type::finish_backend_element(Gogo* gogo)
7674 {
7675 Type* et = this->array_type()->element_type();
7676 et->get_backend(gogo);
7677 if (this->is_slice_type())
7678 {
7679 // This relies on the fact that we always use the same
7680 // structure for a pointer to any given type.
7681 Type* pet = Type::make_pointer_type(et);
7682 pet->get_backend(gogo);
7683 }
7684 }
7685
7686 // Return an expression for a pointer to the values in ARRAY.
7687
7688 Expression*
7689 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7690 {
7691 if (this->length() != NULL)
7692 {
7693 // Fixed array.
7694 go_assert(array->type()->array_type() != NULL);
7695 Type* etype = array->type()->array_type()->element_type();
7696 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7697 return Expression::make_cast(Type::make_pointer_type(etype), array,
7698 array->location());
7699 }
7700
7701 // Slice.
7702
7703 if (is_lvalue)
7704 {
7705 Temporary_reference_expression* tref =
7706 array->temporary_reference_expression();
7707 Var_expression* ve = array->var_expression();
7708 if (tref != NULL)
7709 {
7710 tref = tref->copy()->temporary_reference_expression();
7711 tref->set_is_lvalue();
7712 array = tref;
7713 }
7714 else if (ve != NULL)
7715 {
7716 ve = new Var_expression(ve->named_object(), ve->location());
7717 array = ve;
7718 }
7719 }
7720
7721 return Expression::make_slice_info(array,
7722 Expression::SLICE_INFO_VALUE_POINTER,
7723 array->location());
7724 }
7725
7726 // Return an expression for the length of the array ARRAY which has this
7727 // type.
7728
7729 Expression*
7730 Array_type::get_length(Gogo*, Expression* array) const
7731 {
7732 if (this->length_ != NULL)
7733 return this->length_;
7734
7735 // This is a slice. We need to read the length field.
7736 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7737 array->location());
7738 }
7739
7740 // Return an expression for the capacity of the array ARRAY which has this
7741 // type.
7742
7743 Expression*
7744 Array_type::get_capacity(Gogo*, Expression* array) const
7745 {
7746 if (this->length_ != NULL)
7747 return this->length_;
7748
7749 // This is a slice. We need to read the capacity field.
7750 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7751 array->location());
7752 }
7753
7754 // Export.
7755
7756 void
7757 Array_type::do_export(Export* exp) const
7758 {
7759 exp->write_c_string("[");
7760 if (this->length_ != NULL)
7761 {
7762 Numeric_constant nc;
7763 mpz_t val;
7764 if (!this->length_->numeric_constant_value(&nc) || !nc.to_int(&val))
7765 {
7766 go_assert(saw_errors());
7767 return;
7768 }
7769 char* s = mpz_get_str(NULL, 10, val);
7770 exp->write_string(s);
7771 free(s);
7772 exp->write_string(" ");
7773 mpz_clear(val);
7774 }
7775 exp->write_c_string("] ");
7776 exp->write_type(this->element_type_);
7777 }
7778
7779 // Import.
7780
7781 Array_type*
7782 Array_type::do_import(Import* imp)
7783 {
7784 imp->require_c_string("[");
7785 Expression* length;
7786 if (imp->peek_char() == ']')
7787 length = NULL;
7788 else
7789 length = Expression::import_expression(imp, imp->location());
7790 imp->require_c_string("] ");
7791 Type* element_type = imp->read_type();
7792 return Type::make_array_type(element_type, length);
7793 }
7794
7795 // The type of an array type descriptor.
7796
7797 Type*
7798 Array_type::make_array_type_descriptor_type()
7799 {
7800 static Type* ret;
7801 if (ret == NULL)
7802 {
7803 Type* tdt = Type::make_type_descriptor_type();
7804 Type* ptdt = Type::make_type_descriptor_ptr_type();
7805
7806 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7807
7808 Struct_type* sf =
7809 Type::make_builtin_struct_type(4,
7810 "", tdt,
7811 "elem", ptdt,
7812 "slice", ptdt,
7813 "len", uintptr_type);
7814
7815 ret = Type::make_builtin_named_type("ArrayType", sf);
7816 }
7817
7818 return ret;
7819 }
7820
7821 // The type of an slice type descriptor.
7822
7823 Type*
7824 Array_type::make_slice_type_descriptor_type()
7825 {
7826 static Type* ret;
7827 if (ret == NULL)
7828 {
7829 Type* tdt = Type::make_type_descriptor_type();
7830 Type* ptdt = Type::make_type_descriptor_ptr_type();
7831
7832 Struct_type* sf =
7833 Type::make_builtin_struct_type(2,
7834 "", tdt,
7835 "elem", ptdt);
7836
7837 ret = Type::make_builtin_named_type("SliceType", sf);
7838 }
7839
7840 return ret;
7841 }
7842
7843 // Build a type descriptor for an array/slice type.
7844
7845 Expression*
7846 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7847 {
7848 if (this->length_ != NULL)
7849 return this->array_type_descriptor(gogo, name);
7850 else
7851 return this->slice_type_descriptor(gogo, name);
7852 }
7853
7854 // Build a type descriptor for an array type.
7855
7856 Expression*
7857 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7858 {
7859 Location bloc = Linemap::predeclared_location();
7860
7861 Type* atdt = Array_type::make_array_type_descriptor_type();
7862
7863 const Struct_field_list* fields = atdt->struct_type()->fields();
7864
7865 Expression_list* vals = new Expression_list();
7866 vals->reserve(3);
7867
7868 Struct_field_list::const_iterator p = fields->begin();
7869 go_assert(p->is_field_name("_type"));
7870 vals->push_back(this->type_descriptor_constructor(gogo,
7871 RUNTIME_TYPE_KIND_ARRAY,
7872 name, NULL, true));
7873
7874 ++p;
7875 go_assert(p->is_field_name("elem"));
7876 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7877
7878 ++p;
7879 go_assert(p->is_field_name("slice"));
7880 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7881 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7882
7883 ++p;
7884 go_assert(p->is_field_name("len"));
7885 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7886
7887 ++p;
7888 go_assert(p == fields->end());
7889
7890 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7891 }
7892
7893 // Build a type descriptor for a slice type.
7894
7895 Expression*
7896 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7897 {
7898 Location bloc = Linemap::predeclared_location();
7899
7900 Type* stdt = Array_type::make_slice_type_descriptor_type();
7901
7902 const Struct_field_list* fields = stdt->struct_type()->fields();
7903
7904 Expression_list* vals = new Expression_list();
7905 vals->reserve(2);
7906
7907 Struct_field_list::const_iterator p = fields->begin();
7908 go_assert(p->is_field_name("_type"));
7909 vals->push_back(this->type_descriptor_constructor(gogo,
7910 RUNTIME_TYPE_KIND_SLICE,
7911 name, NULL, true));
7912
7913 ++p;
7914 go_assert(p->is_field_name("elem"));
7915 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7916
7917 ++p;
7918 go_assert(p == fields->end());
7919
7920 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7921 }
7922
7923 // Reflection string.
7924
7925 void
7926 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7927 {
7928 ret->push_back('[');
7929 if (this->length_ != NULL)
7930 {
7931 Numeric_constant nc;
7932 if (!this->length_->numeric_constant_value(&nc))
7933 {
7934 go_assert(saw_errors());
7935 return;
7936 }
7937 mpz_t val;
7938 if (!nc.to_int(&val))
7939 {
7940 go_assert(saw_errors());
7941 return;
7942 }
7943 char* s = mpz_get_str(NULL, 10, val);
7944 ret->append(s);
7945 free(s);
7946 mpz_clear(val);
7947 }
7948 ret->push_back(']');
7949
7950 this->append_reflection(this->element_type_, gogo, ret);
7951 }
7952
7953 // Make an array type.
7954
7955 Array_type*
7956 Type::make_array_type(Type* element_type, Expression* length)
7957 {
7958 return new Array_type(element_type, length);
7959 }
7960
7961 // Class Map_type.
7962
7963 Named_object* Map_type::zero_value;
7964 int64_t Map_type::zero_value_size;
7965 int64_t Map_type::zero_value_align;
7966
7967 // If this map requires the "fat" functions, return the pointer to
7968 // pass as the zero value to those functions. Otherwise, in the
7969 // normal case, return NULL. The map requires the "fat" functions if
7970 // the value size is larger than max_zero_size bytes. max_zero_size
7971 // must match maxZero in libgo/go/runtime/map.go.
7972
7973 Expression*
7974 Map_type::fat_zero_value(Gogo* gogo)
7975 {
7976 int64_t valsize;
7977 if (!this->val_type_->backend_type_size(gogo, &valsize))
7978 {
7979 go_assert(saw_errors());
7980 return NULL;
7981 }
7982 if (valsize <= Map_type::max_zero_size)
7983 return NULL;
7984
7985 if (Map_type::zero_value_size < valsize)
7986 Map_type::zero_value_size = valsize;
7987
7988 int64_t valalign;
7989 if (!this->val_type_->backend_type_align(gogo, &valalign))
7990 {
7991 go_assert(saw_errors());
7992 return NULL;
7993 }
7994
7995 if (Map_type::zero_value_align < valalign)
7996 Map_type::zero_value_align = valalign;
7997
7998 Location bloc = Linemap::predeclared_location();
7999
8000 if (Map_type::zero_value == NULL)
8001 {
8002 // The final type will be set in backend_zero_value.
8003 Type* uint8_type = Type::lookup_integer_type("uint8");
8004 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
8005 Array_type* array_type = Type::make_array_type(uint8_type, size);
8006 array_type->set_is_array_incomparable();
8007 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
8008 std::string name = gogo->map_zero_value_name();
8009 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
8010 }
8011
8012 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
8013 z = Expression::make_unary(OPERATOR_AND, z, bloc);
8014 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8015 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
8016 return z;
8017 }
8018
8019 // Map algorithm to use for this map type.
8020
8021 Map_type::Map_alg
8022 Map_type::algorithm(Gogo* gogo)
8023 {
8024 int64_t size;
8025 bool ok = this->val_type_->backend_type_size(gogo, &size);
8026 if (!ok || size > Map_type::max_val_size)
8027 return MAP_ALG_SLOW;
8028
8029 Type* key_type = this->key_type_;
8030 if (key_type->is_string_type())
8031 return MAP_ALG_FASTSTR;
8032 if (!key_type->compare_is_identity(gogo))
8033 return MAP_ALG_SLOW;
8034
8035 ok = key_type->backend_type_size(gogo, &size);
8036 if (!ok)
8037 return MAP_ALG_SLOW;
8038 if (size == 4)
8039 return (key_type->has_pointer()
8040 ? MAP_ALG_FAST32PTR
8041 : MAP_ALG_FAST32);
8042 if (size == 8)
8043 {
8044 if (!key_type->has_pointer())
8045 return MAP_ALG_FAST64;
8046 Type* ptr_type = Type::make_pointer_type(Type::make_void_type());
8047 ok = ptr_type->backend_type_size(gogo, &size);
8048 if (ok && size == 8)
8049 return MAP_ALG_FAST64PTR;
8050 // Key contains pointer but is not a single pointer.
8051 // Use slow version.
8052 }
8053 return MAP_ALG_SLOW;
8054 }
8055
8056 // Return whether VAR is the map zero value.
8057
8058 bool
8059 Map_type::is_zero_value(Variable* var)
8060 {
8061 return (Map_type::zero_value != NULL
8062 && Map_type::zero_value->var_value() == var);
8063 }
8064
8065 // Return the backend representation for the zero value.
8066
8067 Bvariable*
8068 Map_type::backend_zero_value(Gogo* gogo)
8069 {
8070 Location bloc = Linemap::predeclared_location();
8071
8072 go_assert(Map_type::zero_value != NULL);
8073
8074 Type* uint8_type = Type::lookup_integer_type("uint8");
8075 Btype* buint8_type = uint8_type->get_backend(gogo);
8076
8077 Type* int_type = Type::lookup_integer_type("int");
8078
8079 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
8080 int_type, bloc);
8081 Translate_context context(gogo, NULL, NULL, NULL);
8082 Bexpression* blength = e->get_backend(&context);
8083
8084 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
8085
8086 std::string zname = Map_type::zero_value->name();
8087 std::string asm_name(go_selectively_encode_id(zname));
8088 Bvariable* zvar =
8089 gogo->backend()->implicit_variable(zname, asm_name,
8090 barray_type, false, false, true,
8091 Map_type::zero_value_align);
8092 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
8093 false, false, true, NULL);
8094 return zvar;
8095 }
8096
8097 // Traversal.
8098
8099 int
8100 Map_type::do_traverse(Traverse* traverse)
8101 {
8102 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
8103 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
8104 return TRAVERSE_EXIT;
8105 return TRAVERSE_CONTINUE;
8106 }
8107
8108 // Check that the map type is OK.
8109
8110 bool
8111 Map_type::do_verify()
8112 {
8113 // The runtime support uses "map[void]void".
8114 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
8115 go_error_at(this->location_, "invalid map key type");
8116 if (!this->key_type_->in_heap())
8117 go_error_at(this->location_, "go:notinheap map key not allowed");
8118 if (!this->val_type_->in_heap())
8119 go_error_at(this->location_, "go:notinheap map value not allowed");
8120 return true;
8121 }
8122
8123 // Whether two map types are identical.
8124
8125 bool
8126 Map_type::is_identical(const Map_type* t, int flags) const
8127 {
8128 return (Type::are_identical(this->key_type(), t->key_type(), flags, NULL)
8129 && Type::are_identical(this->val_type(), t->val_type(), flags,
8130 NULL));
8131 }
8132
8133 // Hash code.
8134
8135 unsigned int
8136 Map_type::do_hash_for_method(Gogo* gogo, int flags) const
8137 {
8138 return (this->key_type_->hash_for_method(gogo, flags)
8139 + this->val_type_->hash_for_method(gogo, flags)
8140 + 2);
8141 }
8142
8143 // Get the backend representation for a map type. A map type is
8144 // represented as a pointer to a struct. The struct is hmap in
8145 // runtime/map.go.
8146
8147 Btype*
8148 Map_type::do_get_backend(Gogo* gogo)
8149 {
8150 static Btype* backend_map_type;
8151 if (backend_map_type == NULL)
8152 {
8153 std::vector<Backend::Btyped_identifier> bfields(9);
8154
8155 Location bloc = Linemap::predeclared_location();
8156
8157 Type* int_type = Type::lookup_integer_type("int");
8158 bfields[0].name = "count";
8159 bfields[0].btype = int_type->get_backend(gogo);
8160 bfields[0].location = bloc;
8161
8162 Type* uint8_type = Type::lookup_integer_type("uint8");
8163 bfields[1].name = "flags";
8164 bfields[1].btype = uint8_type->get_backend(gogo);
8165 bfields[1].location = bloc;
8166
8167 bfields[2].name = "B";
8168 bfields[2].btype = bfields[1].btype;
8169 bfields[2].location = bloc;
8170
8171 Type* uint16_type = Type::lookup_integer_type("uint16");
8172 bfields[3].name = "noverflow";
8173 bfields[3].btype = uint16_type->get_backend(gogo);
8174 bfields[3].location = bloc;
8175
8176 Type* uint32_type = Type::lookup_integer_type("uint32");
8177 bfields[4].name = "hash0";
8178 bfields[4].btype = uint32_type->get_backend(gogo);
8179 bfields[4].location = bloc;
8180
8181 Btype* bvt = gogo->backend()->void_type();
8182 Btype* bpvt = gogo->backend()->pointer_type(bvt);
8183 bfields[5].name = "buckets";
8184 bfields[5].btype = bpvt;
8185 bfields[5].location = bloc;
8186
8187 bfields[6].name = "oldbuckets";
8188 bfields[6].btype = bpvt;
8189 bfields[6].location = bloc;
8190
8191 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8192 bfields[7].name = "nevacuate";
8193 bfields[7].btype = uintptr_type->get_backend(gogo);
8194 bfields[7].location = bloc;
8195
8196 bfields[8].name = "extra";
8197 bfields[8].btype = bpvt;
8198 bfields[8].location = bloc;
8199
8200 Btype *bt = gogo->backend()->struct_type(bfields);
8201 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
8202 backend_map_type = gogo->backend()->pointer_type(bt);
8203 }
8204 return backend_map_type;
8205 }
8206
8207 // The type of a map type descriptor.
8208
8209 Type*
8210 Map_type::make_map_type_descriptor_type()
8211 {
8212 static Type* ret;
8213 if (ret == NULL)
8214 {
8215 Type* tdt = Type::make_type_descriptor_type();
8216 Type* ptdt = Type::make_type_descriptor_ptr_type();
8217 Type* uint8_type = Type::lookup_integer_type("uint8");
8218 Type* uint16_type = Type::lookup_integer_type("uint16");
8219 Type* uint32_type = Type::lookup_integer_type("uint32");
8220 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8221 Type* void_type = Type::make_void_type();
8222 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
8223
8224 Location bloc = Linemap::predeclared_location();
8225 Typed_identifier_list *params = new Typed_identifier_list();
8226 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
8227 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
8228
8229 Typed_identifier_list* results = new Typed_identifier_list();
8230 results->push_back(Typed_identifier("", uintptr_type, bloc));
8231
8232 Type* hasher_fntype = Type::make_function_type(NULL, params, results,
8233 bloc);
8234
8235 Struct_type* sf =
8236 Type::make_builtin_struct_type(9,
8237 "", tdt,
8238 "key", ptdt,
8239 "elem", ptdt,
8240 "bucket", ptdt,
8241 "hasher", hasher_fntype,
8242 "keysize", uint8_type,
8243 "valuesize", uint8_type,
8244 "bucketsize", uint16_type,
8245 "flags", uint32_type);
8246
8247 ret = Type::make_builtin_named_type("MapType", sf);
8248 }
8249
8250 return ret;
8251 }
8252
8253 // Build a type descriptor for a map type.
8254
8255 Expression*
8256 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8257 {
8258 Location bloc = Linemap::predeclared_location();
8259
8260 Type* mtdt = Map_type::make_map_type_descriptor_type();
8261 Type* uint8_type = Type::lookup_integer_type("uint8");
8262 Type* uint16_type = Type::lookup_integer_type("uint16");
8263 Type* uint32_type = Type::lookup_integer_type("uint32");
8264
8265 int64_t keysize;
8266 if (!this->key_type_->backend_type_size(gogo, &keysize))
8267 {
8268 go_error_at(this->location_, "error determining map key type size");
8269 return Expression::make_error(this->location_);
8270 }
8271
8272 int64_t valsize;
8273 if (!this->val_type_->backend_type_size(gogo, &valsize))
8274 {
8275 go_error_at(this->location_, "error determining map value type size");
8276 return Expression::make_error(this->location_);
8277 }
8278
8279 int64_t ptrsize;
8280 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8281 {
8282 go_assert(saw_errors());
8283 return Expression::make_error(this->location_);
8284 }
8285
8286 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8287 if (bucket_type == NULL)
8288 {
8289 go_assert(saw_errors());
8290 return Expression::make_error(this->location_);
8291 }
8292
8293 int64_t bucketsize;
8294 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8295 {
8296 go_assert(saw_errors());
8297 return Expression::make_error(this->location_);
8298 }
8299
8300 const Struct_field_list* fields = mtdt->struct_type()->fields();
8301
8302 Expression_list* vals = new Expression_list();
8303 vals->reserve(12);
8304
8305 Struct_field_list::const_iterator p = fields->begin();
8306 go_assert(p->is_field_name("_type"));
8307 vals->push_back(this->type_descriptor_constructor(gogo,
8308 RUNTIME_TYPE_KIND_MAP,
8309 name, NULL, true));
8310
8311 ++p;
8312 go_assert(p->is_field_name("key"));
8313 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8314
8315 ++p;
8316 go_assert(p->is_field_name("elem"));
8317 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8318
8319 ++p;
8320 go_assert(p->is_field_name("bucket"));
8321 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8322
8323 ++p;
8324 go_assert(p->is_field_name("hasher"));
8325 Function_type* hasher_fntype = p->type()->function_type();
8326 Named_object* hasher_fn = this->key_type_->hash_function(gogo,
8327 hasher_fntype);
8328 if (hasher_fn == NULL)
8329 vals->push_back(Expression::make_cast(hasher_fntype,
8330 Expression::make_nil(bloc),
8331 bloc));
8332 else
8333 vals->push_back(Expression::make_func_reference(hasher_fn, NULL, bloc));
8334
8335 ++p;
8336 go_assert(p->is_field_name("keysize"));
8337 if (keysize > Map_type::max_key_size)
8338 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8339 else
8340 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8341
8342 ++p;
8343 go_assert(p->is_field_name("valuesize"));
8344 if (valsize > Map_type::max_val_size)
8345 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8346 else
8347 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8348
8349 ++p;
8350 go_assert(p->is_field_name("bucketsize"));
8351 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8352 bloc));
8353
8354 ++p;
8355 go_assert(p->is_field_name("flags"));
8356 // As with the other fields, the flag bits must match the reflect
8357 // and runtime packages.
8358 unsigned long flags = 0;
8359 if (keysize > Map_type::max_key_size)
8360 flags |= 1;
8361 if (valsize > Map_type::max_val_size)
8362 flags |= 2;
8363 if (this->key_type_->is_reflexive())
8364 flags |= 4;
8365 if (this->key_type_->needs_key_update())
8366 flags |= 8;
8367 if (this->key_type_->hash_might_panic())
8368 flags |= 16;
8369 vals->push_back(Expression::make_integer_ul(flags, uint32_type, bloc));
8370
8371 ++p;
8372 go_assert(p == fields->end());
8373
8374 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8375 }
8376
8377 // Return the bucket type to use for a map type. This must correspond
8378 // to libgo/go/runtime/map.go.
8379
8380 Type*
8381 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8382 {
8383 if (this->bucket_type_ != NULL)
8384 return this->bucket_type_;
8385
8386 Type* key_type = this->key_type_;
8387 if (keysize > Map_type::max_key_size)
8388 key_type = Type::make_pointer_type(key_type);
8389
8390 Type* val_type = this->val_type_;
8391 if (valsize > Map_type::max_val_size)
8392 val_type = Type::make_pointer_type(val_type);
8393
8394 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8395 NULL, this->location_);
8396
8397 Type* uint8_type = Type::lookup_integer_type("uint8");
8398 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8399 topbits_type->set_is_array_incomparable();
8400 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8401 keys_type->set_is_array_incomparable();
8402 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8403 values_type->set_is_array_incomparable();
8404
8405 // If keys and values have no pointers, the map implementation can
8406 // keep a list of overflow pointers on the side so that buckets can
8407 // be marked as having no pointers. Arrange for the bucket to have
8408 // no pointers by changing the type of the overflow field to uintptr
8409 // in this case. See comment on the hmap.overflow field in
8410 // libgo/go/runtime/map.go.
8411 Type* overflow_type;
8412 if (!key_type->has_pointer() && !val_type->has_pointer())
8413 overflow_type = Type::lookup_integer_type("uintptr");
8414 else
8415 {
8416 // This should really be a pointer to the bucket type itself,
8417 // but that would require us to construct a Named_type for it to
8418 // give it a way to refer to itself. Since nothing really cares
8419 // (except perhaps for someone using a debugger) just use an
8420 // unsafe pointer.
8421 overflow_type = Type::make_pointer_type(Type::make_void_type());
8422 }
8423
8424 // Make sure the overflow pointer is the last memory in the struct,
8425 // because the runtime assumes it can use size-ptrSize as the offset
8426 // of the overflow pointer. We double-check that property below
8427 // once the offsets and size are computed.
8428
8429 int64_t topbits_field_size, topbits_field_align;
8430 int64_t keys_field_size, keys_field_align;
8431 int64_t values_field_size, values_field_align;
8432 int64_t overflow_field_size, overflow_field_align;
8433 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8434 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8435 || !keys_type->backend_type_size(gogo, &keys_field_size)
8436 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8437 || !values_type->backend_type_size(gogo, &values_field_size)
8438 || !values_type->backend_type_field_align(gogo, &values_field_align)
8439 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8440 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8441 {
8442 go_assert(saw_errors());
8443 return NULL;
8444 }
8445
8446 Struct_type* ret;
8447 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8448 values_field_align);
8449 if (max_align <= overflow_field_align)
8450 ret = make_builtin_struct_type(4,
8451 "topbits", topbits_type,
8452 "keys", keys_type,
8453 "values", values_type,
8454 "overflow", overflow_type);
8455 else
8456 {
8457 size_t off = topbits_field_size;
8458 off = ((off + keys_field_align - 1)
8459 &~ static_cast<size_t>(keys_field_align - 1));
8460 off += keys_field_size;
8461 off = ((off + values_field_align - 1)
8462 &~ static_cast<size_t>(values_field_align - 1));
8463 off += values_field_size;
8464
8465 int64_t padded_overflow_field_size =
8466 ((overflow_field_size + max_align - 1)
8467 &~ static_cast<size_t>(max_align - 1));
8468
8469 size_t ovoff = off;
8470 ovoff = ((ovoff + max_align - 1)
8471 &~ static_cast<size_t>(max_align - 1));
8472 size_t pad = (ovoff - off
8473 + padded_overflow_field_size - overflow_field_size);
8474
8475 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8476 this->location_);
8477 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8478 pad_type->set_is_array_incomparable();
8479
8480 ret = make_builtin_struct_type(5,
8481 "topbits", topbits_type,
8482 "keys", keys_type,
8483 "values", values_type,
8484 "pad", pad_type,
8485 "overflow", overflow_type);
8486 }
8487
8488 // Verify that the overflow field is just before the end of the
8489 // bucket type.
8490
8491 Btype* btype = ret->get_backend(gogo);
8492 int64_t offset = gogo->backend()->type_field_offset(btype,
8493 ret->field_count() - 1);
8494 int64_t size;
8495 if (!ret->backend_type_size(gogo, &size))
8496 {
8497 go_assert(saw_errors());
8498 return NULL;
8499 }
8500
8501 int64_t ptr_size;
8502 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8503 {
8504 go_assert(saw_errors());
8505 return NULL;
8506 }
8507
8508 go_assert(offset + ptr_size == size);
8509
8510 ret->set_is_struct_incomparable();
8511
8512 this->bucket_type_ = ret;
8513 return ret;
8514 }
8515
8516 // Return the hashmap type for a map type.
8517
8518 Type*
8519 Map_type::hmap_type(Type* bucket_type)
8520 {
8521 if (this->hmap_type_ != NULL)
8522 return this->hmap_type_;
8523
8524 Type* int_type = Type::lookup_integer_type("int");
8525 Type* uint8_type = Type::lookup_integer_type("uint8");
8526 Type* uint16_type = Type::lookup_integer_type("uint16");
8527 Type* uint32_type = Type::lookup_integer_type("uint32");
8528 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8529 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8530
8531 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8532
8533 Struct_type* ret = make_builtin_struct_type(9,
8534 "count", int_type,
8535 "flags", uint8_type,
8536 "B", uint8_type,
8537 "noverflow", uint16_type,
8538 "hash0", uint32_type,
8539 "buckets", ptr_bucket_type,
8540 "oldbuckets", ptr_bucket_type,
8541 "nevacuate", uintptr_type,
8542 "extra", void_ptr_type);
8543 ret->set_is_struct_incomparable();
8544 this->hmap_type_ = ret;
8545 return ret;
8546 }
8547
8548 // Return the iterator type for a map type. This is the type of the
8549 // value used when doing a range over a map.
8550
8551 Type*
8552 Map_type::hiter_type(Gogo* gogo)
8553 {
8554 if (this->hiter_type_ != NULL)
8555 return this->hiter_type_;
8556
8557 int64_t keysize, valsize;
8558 if (!this->key_type_->backend_type_size(gogo, &keysize)
8559 || !this->val_type_->backend_type_size(gogo, &valsize))
8560 {
8561 go_assert(saw_errors());
8562 return NULL;
8563 }
8564
8565 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8566 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8567 Type* uint8_type = Type::lookup_integer_type("uint8");
8568 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8569 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8570 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8571 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8572 Type* hmap_type = this->hmap_type(bucket_type);
8573 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8574 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8575 Type* bool_type = Type::lookup_bool_type();
8576
8577 Struct_type* ret = make_builtin_struct_type(15,
8578 "key", key_ptr_type,
8579 "val", val_ptr_type,
8580 "t", uint8_ptr_type,
8581 "h", hmap_ptr_type,
8582 "buckets", bucket_ptr_type,
8583 "bptr", bucket_ptr_type,
8584 "overflow", void_ptr_type,
8585 "oldoverflow", void_ptr_type,
8586 "startBucket", uintptr_type,
8587 "offset", uint8_type,
8588 "wrapped", bool_type,
8589 "B", uint8_type,
8590 "i", uint8_type,
8591 "bucket", uintptr_type,
8592 "checkBucket", uintptr_type);
8593 ret->set_is_struct_incomparable();
8594 this->hiter_type_ = ret;
8595 return ret;
8596 }
8597
8598 // Reflection string for a map.
8599
8600 void
8601 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8602 {
8603 ret->append("map[");
8604 this->append_reflection(this->key_type_, gogo, ret);
8605 ret->append("]");
8606 this->append_reflection(this->val_type_, gogo, ret);
8607 }
8608
8609 // Export a map type.
8610
8611 void
8612 Map_type::do_export(Export* exp) const
8613 {
8614 exp->write_c_string("map [");
8615 exp->write_type(this->key_type_);
8616 exp->write_c_string("] ");
8617 exp->write_type(this->val_type_);
8618 }
8619
8620 // Import a map type.
8621
8622 Map_type*
8623 Map_type::do_import(Import* imp)
8624 {
8625 imp->require_c_string("map [");
8626 Type* key_type = imp->read_type();
8627 imp->require_c_string("] ");
8628 Type* val_type = imp->read_type();
8629 return Type::make_map_type(key_type, val_type, imp->location());
8630 }
8631
8632 // Make a map type.
8633
8634 Map_type*
8635 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8636 {
8637 return new Map_type(key_type, val_type, location);
8638 }
8639
8640 // Class Channel_type.
8641
8642 // Verify.
8643
8644 bool
8645 Channel_type::do_verify()
8646 {
8647 // We have no location for this error, but this is not something the
8648 // ordinary user will see.
8649 if (!this->element_type_->in_heap())
8650 go_error_at(Linemap::unknown_location(),
8651 "chan of go:notinheap type not allowed");
8652 return true;
8653 }
8654
8655 // Hash code.
8656
8657 unsigned int
8658 Channel_type::do_hash_for_method(Gogo* gogo, int flags) const
8659 {
8660 unsigned int ret = 0;
8661 if (this->may_send_)
8662 ret += 1;
8663 if (this->may_receive_)
8664 ret += 2;
8665 if (this->element_type_ != NULL)
8666 ret += this->element_type_->hash_for_method(gogo, flags) << 2;
8667 return ret << 3;
8668 }
8669
8670 // Whether this type is the same as T.
8671
8672 bool
8673 Channel_type::is_identical(const Channel_type* t, int flags) const
8674 {
8675 if (!Type::are_identical(this->element_type(), t->element_type(), flags,
8676 NULL))
8677 return false;
8678 return (this->may_send_ == t->may_send_
8679 && this->may_receive_ == t->may_receive_);
8680 }
8681
8682 // Return the backend representation for a channel type. A channel is a pointer
8683 // to a __go_channel struct. The __go_channel struct is defined in
8684 // libgo/runtime/channel.h.
8685
8686 Btype*
8687 Channel_type::do_get_backend(Gogo* gogo)
8688 {
8689 static Btype* backend_channel_type;
8690 if (backend_channel_type == NULL)
8691 {
8692 std::vector<Backend::Btyped_identifier> bfields;
8693 Btype* bt = gogo->backend()->struct_type(bfields);
8694 bt = gogo->backend()->named_type("__go_channel", bt,
8695 Linemap::predeclared_location());
8696 backend_channel_type = gogo->backend()->pointer_type(bt);
8697 }
8698 return backend_channel_type;
8699 }
8700
8701 // Build a type descriptor for a channel type.
8702
8703 Type*
8704 Channel_type::make_chan_type_descriptor_type()
8705 {
8706 static Type* ret;
8707 if (ret == NULL)
8708 {
8709 Type* tdt = Type::make_type_descriptor_type();
8710 Type* ptdt = Type::make_type_descriptor_ptr_type();
8711
8712 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8713
8714 Struct_type* sf =
8715 Type::make_builtin_struct_type(3,
8716 "", tdt,
8717 "elem", ptdt,
8718 "dir", uintptr_type);
8719
8720 ret = Type::make_builtin_named_type("ChanType", sf);
8721 }
8722
8723 return ret;
8724 }
8725
8726 // Build a type descriptor for a map type.
8727
8728 Expression*
8729 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8730 {
8731 Location bloc = Linemap::predeclared_location();
8732
8733 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8734
8735 const Struct_field_list* fields = ctdt->struct_type()->fields();
8736
8737 Expression_list* vals = new Expression_list();
8738 vals->reserve(3);
8739
8740 Struct_field_list::const_iterator p = fields->begin();
8741 go_assert(p->is_field_name("_type"));
8742 vals->push_back(this->type_descriptor_constructor(gogo,
8743 RUNTIME_TYPE_KIND_CHAN,
8744 name, NULL, true));
8745
8746 ++p;
8747 go_assert(p->is_field_name("elem"));
8748 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8749
8750 ++p;
8751 go_assert(p->is_field_name("dir"));
8752 // These bits must match the ones in libgo/runtime/go-type.h.
8753 int val = 0;
8754 if (this->may_receive_)
8755 val |= 1;
8756 if (this->may_send_)
8757 val |= 2;
8758 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8759
8760 ++p;
8761 go_assert(p == fields->end());
8762
8763 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8764 }
8765
8766 // Reflection string.
8767
8768 void
8769 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8770 {
8771 if (!this->may_send_)
8772 ret->append("<-");
8773 ret->append("chan");
8774 if (!this->may_receive_)
8775 ret->append("<-");
8776 ret->push_back(' ');
8777 this->append_reflection(this->element_type_, gogo, ret);
8778 }
8779
8780 // Export.
8781
8782 void
8783 Channel_type::do_export(Export* exp) const
8784 {
8785 exp->write_c_string("chan ");
8786 if (this->may_send_ && !this->may_receive_)
8787 exp->write_c_string("-< ");
8788 else if (this->may_receive_ && !this->may_send_)
8789 exp->write_c_string("<- ");
8790 exp->write_type(this->element_type_);
8791 }
8792
8793 // Import.
8794
8795 Channel_type*
8796 Channel_type::do_import(Import* imp)
8797 {
8798 imp->require_c_string("chan ");
8799
8800 bool may_send;
8801 bool may_receive;
8802 if (imp->match_c_string("-< "))
8803 {
8804 imp->advance(3);
8805 may_send = true;
8806 may_receive = false;
8807 }
8808 else if (imp->match_c_string("<- "))
8809 {
8810 imp->advance(3);
8811 may_receive = true;
8812 may_send = false;
8813 }
8814 else
8815 {
8816 may_send = true;
8817 may_receive = true;
8818 }
8819
8820 Type* element_type = imp->read_type();
8821
8822 return Type::make_channel_type(may_send, may_receive, element_type);
8823 }
8824
8825 // Return the type that the runtime package uses for one case of a
8826 // select statement. An array of values of this type is allocated on
8827 // the stack. This must match scase in libgo/go/runtime/select.go.
8828
8829 Type*
8830 Channel_type::select_case_type()
8831 {
8832 static Struct_type* scase_type;
8833 if (scase_type == NULL)
8834 {
8835 Type* unsafe_pointer_type =
8836 Type::make_pointer_type(Type::make_void_type());
8837 Type* uint16_type = Type::lookup_integer_type("uint16");
8838 Type* int64_type = Type::lookup_integer_type("int64");
8839 scase_type =
8840 Type::make_builtin_struct_type(4,
8841 "c", unsafe_pointer_type,
8842 "elem", unsafe_pointer_type,
8843 "kind", uint16_type,
8844 "releasetime", int64_type);
8845 scase_type->set_is_struct_incomparable();
8846 }
8847 return scase_type;
8848 }
8849
8850 // Make a new channel type.
8851
8852 Channel_type*
8853 Type::make_channel_type(bool send, bool receive, Type* element_type)
8854 {
8855 return new Channel_type(send, receive, element_type);
8856 }
8857
8858 // Class Interface_type.
8859
8860 // Return the list of methods.
8861
8862 const Typed_identifier_list*
8863 Interface_type::methods() const
8864 {
8865 go_assert(this->methods_are_finalized_ || saw_errors());
8866 return this->all_methods_;
8867 }
8868
8869 // Return the number of methods.
8870
8871 size_t
8872 Interface_type::method_count() const
8873 {
8874 go_assert(this->methods_are_finalized_ || saw_errors());
8875 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8876 }
8877
8878 // Traversal.
8879
8880 int
8881 Interface_type::do_traverse(Traverse* traverse)
8882 {
8883 Typed_identifier_list* methods = (this->methods_are_finalized_
8884 ? this->all_methods_
8885 : this->parse_methods_);
8886 if (methods == NULL)
8887 return TRAVERSE_CONTINUE;
8888 return methods->traverse(traverse);
8889 }
8890
8891 // Finalize the methods. This handles interface inheritance.
8892
8893 void
8894 Interface_type::finalize_methods()
8895 {
8896 if (this->methods_are_finalized_)
8897 return;
8898 this->methods_are_finalized_ = true;
8899 if (this->parse_methods_ == NULL)
8900 return;
8901
8902 this->all_methods_ = new Typed_identifier_list();
8903 this->all_methods_->reserve(this->parse_methods_->size());
8904 Typed_identifier_list inherit;
8905 for (Typed_identifier_list::const_iterator pm =
8906 this->parse_methods_->begin();
8907 pm != this->parse_methods_->end();
8908 ++pm)
8909 {
8910 const Typed_identifier* p = &*pm;
8911 if (p->name().empty())
8912 inherit.push_back(*p);
8913 else if (this->find_method(p->name()) == NULL)
8914 this->all_methods_->push_back(*p);
8915 else
8916 go_error_at(p->location(), "duplicate method %qs",
8917 Gogo::message_name(p->name()).c_str());
8918 }
8919
8920 std::vector<Named_type*> seen;
8921 seen.reserve(inherit.size());
8922 bool issued_recursive_error = false;
8923 while (!inherit.empty())
8924 {
8925 Type* t = inherit.back().type();
8926 Location tl = inherit.back().location();
8927 inherit.pop_back();
8928
8929 Interface_type* it = t->interface_type();
8930 if (it == NULL)
8931 {
8932 if (!t->is_error())
8933 go_error_at(tl, "interface contains embedded non-interface");
8934 continue;
8935 }
8936 if (it == this)
8937 {
8938 if (!issued_recursive_error)
8939 {
8940 go_error_at(tl, "invalid recursive interface");
8941 issued_recursive_error = true;
8942 }
8943 continue;
8944 }
8945
8946 const Typed_identifier_list* imethods = it->parse_methods_;
8947 if (imethods == NULL)
8948 continue;
8949
8950 Named_type* nt = t->named_type();
8951 if (nt != NULL)
8952 {
8953 std::vector<Named_type*>::const_iterator q;
8954 for (q = seen.begin(); q != seen.end(); ++q)
8955 {
8956 if (*q == nt)
8957 {
8958 go_error_at(tl, "inherited interface loop");
8959 break;
8960 }
8961 }
8962 if (q != seen.end())
8963 continue;
8964 seen.push_back(nt);
8965 }
8966
8967 for (Typed_identifier_list::const_iterator q = imethods->begin();
8968 q != imethods->end();
8969 ++q)
8970 {
8971 if (q->name().empty())
8972 inherit.push_back(*q);
8973 else
8974 {
8975 const Typed_identifier* oldm = this->find_method(q->name());
8976 if (oldm == NULL)
8977 this->all_methods_->push_back(Typed_identifier(q->name(),
8978 q->type(), tl));
8979 else if (!Type::are_identical(q->type(), oldm->type(),
8980 Type::COMPARE_TAGS, NULL))
8981 go_error_at(tl, "duplicate method %qs",
8982 Gogo::message_name(q->name()).c_str());
8983 }
8984 }
8985
8986 seen.pop_back();
8987 }
8988
8989 if (!this->all_methods_->empty())
8990 this->all_methods_->sort_by_name();
8991 else
8992 {
8993 delete this->all_methods_;
8994 this->all_methods_ = NULL;
8995 }
8996 }
8997
8998 // Return the method NAME, or NULL.
8999
9000 const Typed_identifier*
9001 Interface_type::find_method(const std::string& name) const
9002 {
9003 go_assert(this->methods_are_finalized_);
9004 if (this->all_methods_ == NULL)
9005 return NULL;
9006 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9007 p != this->all_methods_->end();
9008 ++p)
9009 if (p->name() == name)
9010 return &*p;
9011 return NULL;
9012 }
9013
9014 // Return the method index.
9015
9016 size_t
9017 Interface_type::method_index(const std::string& name) const
9018 {
9019 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
9020 size_t ret = 0;
9021 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9022 p != this->all_methods_->end();
9023 ++p, ++ret)
9024 if (p->name() == name)
9025 return ret;
9026 go_unreachable();
9027 }
9028
9029 // Return whether NAME is an unexported method, for better error
9030 // reporting.
9031
9032 bool
9033 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
9034 {
9035 go_assert(this->methods_are_finalized_);
9036 if (this->all_methods_ == NULL)
9037 return false;
9038 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9039 p != this->all_methods_->end();
9040 ++p)
9041 {
9042 const std::string& method_name(p->name());
9043 if (Gogo::is_hidden_name(method_name)
9044 && name == Gogo::unpack_hidden_name(method_name)
9045 && gogo->pack_hidden_name(name, false) != method_name)
9046 return true;
9047 }
9048 return false;
9049 }
9050
9051 // Whether this type is identical with T.
9052
9053 bool
9054 Interface_type::is_identical(const Interface_type* t, int flags) const
9055 {
9056 // If methods have not been finalized, then we are asking whether
9057 // func redeclarations are the same. This is an error, so for
9058 // simplicity we say they are never the same.
9059 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
9060 return false;
9061
9062 // Consult a flag to see whether we need to compare based on
9063 // parse methods or all methods.
9064 Typed_identifier_list* methods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9065 ? this->parse_methods_
9066 : this->all_methods_);
9067 Typed_identifier_list* tmethods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9068 ? t->parse_methods_
9069 : t->all_methods_);
9070
9071 // We require the same methods with the same types. The methods
9072 // have already been sorted.
9073 if (methods == NULL || tmethods == NULL)
9074 return methods == tmethods;
9075
9076 if (this->assume_identical(this, t) || t->assume_identical(t, this))
9077 return true;
9078
9079 Assume_identical* hold_ai = this->assume_identical_;
9080 Assume_identical ai;
9081 ai.t1 = this;
9082 ai.t2 = t;
9083 ai.next = hold_ai;
9084 this->assume_identical_ = &ai;
9085
9086 Typed_identifier_list::const_iterator p1 = methods->begin();
9087 Typed_identifier_list::const_iterator p2;
9088 for (p2 = tmethods->begin(); p2 != tmethods->end(); ++p1, ++p2)
9089 {
9090 if (p1 == methods->end())
9091 break;
9092 if (p1->name() != p2->name()
9093 || !Type::are_identical(p1->type(), p2->type(), flags, NULL))
9094 break;
9095 }
9096
9097 this->assume_identical_ = hold_ai;
9098
9099 return p1 == methods->end() && p2 == tmethods->end();
9100 }
9101
9102 // Return true if T1 and T2 are assumed to be identical during a type
9103 // comparison.
9104
9105 bool
9106 Interface_type::assume_identical(const Interface_type* t1,
9107 const Interface_type* t2) const
9108 {
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;
9115 }
9116
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.
9121
9122 bool
9123 Interface_type::is_compatible_for_assign(const Interface_type* t,
9124 std::string* reason) const
9125 {
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)
9132 {
9133 const Typed_identifier* m = t->find_method(p->name());
9134 if (m == NULL)
9135 {
9136 if (reason != NULL)
9137 {
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);
9144 }
9145 return false;
9146 }
9147
9148 std::string subreason;
9149 if (!Type::are_identical(p->type(), m->type(), Type::COMPARE_TAGS,
9150 &subreason))
9151 {
9152 if (reason != NULL)
9153 {
9154 std::string n = Gogo::message_name(p->name());
9155 size_t len = 100 + n.length() + subreason.length();
9156 char* buf = new char[len];
9157 if (subreason.empty())
9158 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9159 go_open_quote(), n.c_str(), go_close_quote());
9160 else
9161 snprintf(buf, len,
9162 _("incompatible type for method %s%s%s (%s)"),
9163 go_open_quote(), n.c_str(), go_close_quote(),
9164 subreason.c_str());
9165 reason->assign(buf);
9166 delete[] buf;
9167 }
9168 return false;
9169 }
9170 }
9171
9172 return true;
9173 }
9174
9175 // Hash code.
9176
9177 unsigned int
9178 Interface_type::do_hash_for_method(Gogo*, int) const
9179 {
9180 go_assert(this->methods_are_finalized_);
9181 unsigned int ret = 0;
9182 if (this->all_methods_ != NULL)
9183 {
9184 for (Typed_identifier_list::const_iterator p =
9185 this->all_methods_->begin();
9186 p != this->all_methods_->end();
9187 ++p)
9188 {
9189 ret = Gogo::hash_string(p->name(), ret);
9190 // We don't use the method type in the hash, to avoid
9191 // infinite recursion if an interface method uses a type
9192 // which is an interface which inherits from the interface
9193 // itself.
9194 // type T interface { F() interface {T}}
9195 ret <<= 1;
9196 }
9197 }
9198 return ret;
9199 }
9200
9201 // Return true if T implements the interface. If it does not, and
9202 // REASON is not NULL, set *REASON to a useful error message.
9203
9204 bool
9205 Interface_type::implements_interface(const Type* t, std::string* reason) const
9206 {
9207 go_assert(this->methods_are_finalized_);
9208 if (this->all_methods_ == NULL)
9209 return true;
9210
9211 t = t->unalias();
9212 bool is_pointer = false;
9213 const Named_type* nt = t->named_type();
9214 const Struct_type* st = t->struct_type();
9215 // If we start with a named type, we don't dereference it to find
9216 // methods.
9217 if (nt == NULL)
9218 {
9219 const Type* pt = t->points_to();
9220 if (pt != NULL)
9221 {
9222 // If T is a pointer to a named type, then we need to look at
9223 // the type to which it points.
9224 pt = pt->unalias();
9225 is_pointer = true;
9226 nt = pt->named_type();
9227 st = pt->struct_type();
9228 }
9229 }
9230
9231 // If we have a named type, get the methods from it rather than from
9232 // any struct type.
9233 if (nt != NULL)
9234 st = NULL;
9235
9236 // Only named and struct types have methods.
9237 if (nt == NULL && st == NULL)
9238 {
9239 if (reason != NULL)
9240 {
9241 if (t->points_to() != NULL
9242 && t->points_to()->interface_type() != NULL)
9243 reason->assign(_("pointer to interface type has no methods"));
9244 else
9245 reason->assign(_("type has no methods"));
9246 }
9247 return false;
9248 }
9249
9250 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
9251 {
9252 if (reason != NULL)
9253 {
9254 if (t->points_to() != NULL
9255 && t->points_to()->interface_type() != NULL)
9256 reason->assign(_("pointer to interface type has no methods"));
9257 else
9258 reason->assign(_("type has no methods"));
9259 }
9260 return false;
9261 }
9262
9263 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9264 p != this->all_methods_->end();
9265 ++p)
9266 {
9267 bool is_ambiguous = false;
9268 Method* m = (nt != NULL
9269 ? nt->method_function(p->name(), &is_ambiguous)
9270 : st->method_function(p->name(), &is_ambiguous));
9271 if (m == NULL)
9272 {
9273 if (reason != NULL)
9274 {
9275 std::string n = Gogo::message_name(p->name());
9276 size_t len = n.length() + 100;
9277 char* buf = new char[len];
9278 if (is_ambiguous)
9279 snprintf(buf, len, _("ambiguous method %s%s%s"),
9280 go_open_quote(), n.c_str(), go_close_quote());
9281 else
9282 snprintf(buf, len, _("missing method %s%s%s"),
9283 go_open_quote(), n.c_str(), go_close_quote());
9284 reason->assign(buf);
9285 delete[] buf;
9286 }
9287 return false;
9288 }
9289
9290 Function_type *p_fn_type = p->type()->function_type();
9291 Function_type* m_fn_type = m->type()->function_type();
9292 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9293 std::string subreason;
9294 if (!p_fn_type->is_identical(m_fn_type, true, Type::COMPARE_TAGS,
9295 &subreason))
9296 {
9297 if (reason != NULL)
9298 {
9299 std::string n = Gogo::message_name(p->name());
9300 size_t len = 100 + n.length() + subreason.length();
9301 char* buf = new char[len];
9302 if (subreason.empty())
9303 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9304 go_open_quote(), n.c_str(), go_close_quote());
9305 else
9306 snprintf(buf, len,
9307 _("incompatible type for method %s%s%s (%s)"),
9308 go_open_quote(), n.c_str(), go_close_quote(),
9309 subreason.c_str());
9310 reason->assign(buf);
9311 delete[] buf;
9312 }
9313 return false;
9314 }
9315
9316 if (!is_pointer && !m->is_value_method())
9317 {
9318 if (reason != NULL)
9319 {
9320 std::string n = Gogo::message_name(p->name());
9321 size_t len = 100 + n.length();
9322 char* buf = new char[len];
9323 snprintf(buf, len,
9324 _("method %s%s%s requires a pointer receiver"),
9325 go_open_quote(), n.c_str(), go_close_quote());
9326 reason->assign(buf);
9327 delete[] buf;
9328 }
9329 return false;
9330 }
9331
9332 // If the magic //go:nointerface comment was used, the method
9333 // may not be used to implement interfaces.
9334 if (m->nointerface())
9335 {
9336 if (reason != NULL)
9337 {
9338 std::string n = Gogo::message_name(p->name());
9339 size_t len = 100 + n.length();
9340 char* buf = new char[len];
9341 snprintf(buf, len,
9342 _("method %s%s%s is marked go:nointerface"),
9343 go_open_quote(), n.c_str(), go_close_quote());
9344 reason->assign(buf);
9345 delete[] buf;
9346 }
9347 return false;
9348 }
9349 }
9350
9351 return true;
9352 }
9353
9354 // Return the backend representation of the empty interface type. We
9355 // use the same struct for all empty interfaces.
9356
9357 Btype*
9358 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9359 {
9360 static Btype* empty_interface_type;
9361 if (empty_interface_type == NULL)
9362 {
9363 std::vector<Backend::Btyped_identifier> bfields(2);
9364
9365 Location bloc = Linemap::predeclared_location();
9366
9367 Type* pdt = Type::make_type_descriptor_ptr_type();
9368 bfields[0].name = "__type_descriptor";
9369 bfields[0].btype = pdt->get_backend(gogo);
9370 bfields[0].location = bloc;
9371
9372 Type* vt = Type::make_pointer_type(Type::make_void_type());
9373 bfields[1].name = "__object";
9374 bfields[1].btype = vt->get_backend(gogo);
9375 bfields[1].location = bloc;
9376
9377 empty_interface_type = gogo->backend()->struct_type(bfields);
9378 }
9379 return empty_interface_type;
9380 }
9381
9382 Interface_type::Bmethods_map Interface_type::bmethods_map;
9383
9384 // Return a pointer to the backend representation of the method table.
9385
9386 Btype*
9387 Interface_type::get_backend_methods(Gogo* gogo)
9388 {
9389 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9390 return this->bmethods_;
9391
9392 std::pair<Interface_type*, Bmethods_map_entry> val;
9393 val.first = this;
9394 val.second.btype = NULL;
9395 val.second.is_placeholder = false;
9396 std::pair<Bmethods_map::iterator, bool> ins =
9397 Interface_type::bmethods_map.insert(val);
9398 if (!ins.second
9399 && ins.first->second.btype != NULL
9400 && !ins.first->second.is_placeholder)
9401 {
9402 this->bmethods_ = ins.first->second.btype;
9403 this->bmethods_is_placeholder_ = false;
9404 return this->bmethods_;
9405 }
9406
9407 Location loc = this->location();
9408
9409 std::vector<Backend::Btyped_identifier>
9410 mfields(this->all_methods_->size() + 1);
9411
9412 Type* pdt = Type::make_type_descriptor_ptr_type();
9413 mfields[0].name = "__type_descriptor";
9414 mfields[0].btype = pdt->get_backend(gogo);
9415 mfields[0].location = loc;
9416
9417 std::string last_name = "";
9418 size_t i = 1;
9419 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9420 p != this->all_methods_->end();
9421 ++p, ++i)
9422 {
9423 // The type of the method in Go only includes the parameters.
9424 // The actual method also has a receiver, which is always a
9425 // pointer. We need to add that pointer type here in order to
9426 // generate the correct type for the backend.
9427 Function_type* ft = p->type()->function_type();
9428 go_assert(ft->receiver() == NULL);
9429
9430 const Typed_identifier_list* params = ft->parameters();
9431 Typed_identifier_list* mparams = new Typed_identifier_list();
9432 if (params != NULL)
9433 mparams->reserve(params->size() + 1);
9434 Type* vt = Type::make_pointer_type(Type::make_void_type());
9435 mparams->push_back(Typed_identifier("", vt, ft->location()));
9436 if (params != NULL)
9437 {
9438 for (Typed_identifier_list::const_iterator pp = params->begin();
9439 pp != params->end();
9440 ++pp)
9441 mparams->push_back(*pp);
9442 }
9443
9444 Typed_identifier_list* mresults = (ft->results() == NULL
9445 ? NULL
9446 : ft->results()->copy());
9447 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9448 ft->location());
9449
9450 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9451 mfields[i].btype = mft->get_backend_fntype(gogo);
9452 mfields[i].location = loc;
9453
9454 // Sanity check: the names should be sorted.
9455 go_assert(Gogo::unpack_hidden_name(p->name())
9456 > Gogo::unpack_hidden_name(last_name));
9457 last_name = p->name();
9458 }
9459
9460 Btype* st = gogo->backend()->struct_type(mfields);
9461 Btype* ret = gogo->backend()->pointer_type(st);
9462
9463 if (ins.first->second.btype != NULL
9464 && ins.first->second.is_placeholder)
9465 gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9466 ret);
9467 this->bmethods_ = ret;
9468 ins.first->second.btype = ret;
9469 this->bmethods_is_placeholder_ = false;
9470 ins.first->second.is_placeholder = false;
9471 return ret;
9472 }
9473
9474 // Return a placeholder for the pointer to the backend methods table.
9475
9476 Btype*
9477 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9478 {
9479 if (this->bmethods_ == NULL)
9480 {
9481 std::pair<Interface_type*, Bmethods_map_entry> val;
9482 val.first = this;
9483 val.second.btype = NULL;
9484 val.second.is_placeholder = false;
9485 std::pair<Bmethods_map::iterator, bool> ins =
9486 Interface_type::bmethods_map.insert(val);
9487 if (!ins.second && ins.first->second.btype != NULL)
9488 {
9489 this->bmethods_ = ins.first->second.btype;
9490 this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9491 return this->bmethods_;
9492 }
9493
9494 Location loc = this->location();
9495 Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9496 this->bmethods_ = bt;
9497 ins.first->second.btype = bt;
9498 this->bmethods_is_placeholder_ = true;
9499 ins.first->second.is_placeholder = true;
9500 }
9501 return this->bmethods_;
9502 }
9503
9504 // Return the fields of a non-empty interface type. This is not
9505 // declared in types.h so that types.h doesn't have to #include
9506 // backend.h.
9507
9508 static void
9509 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9510 bool use_placeholder,
9511 std::vector<Backend::Btyped_identifier>* bfields)
9512 {
9513 Location loc = type->location();
9514
9515 bfields->resize(2);
9516
9517 (*bfields)[0].name = "__methods";
9518 (*bfields)[0].btype = (use_placeholder
9519 ? type->get_backend_methods_placeholder(gogo)
9520 : type->get_backend_methods(gogo));
9521 (*bfields)[0].location = loc;
9522
9523 Type* vt = Type::make_pointer_type(Type::make_void_type());
9524 (*bfields)[1].name = "__object";
9525 (*bfields)[1].btype = vt->get_backend(gogo);
9526 (*bfields)[1].location = Linemap::predeclared_location();
9527 }
9528
9529 // Return the backend representation for an interface type. An interface is a
9530 // pointer to a struct. The struct has three fields. The first field is a
9531 // pointer to the type descriptor for the dynamic type of the object.
9532 // The second field is a pointer to a table of methods for the
9533 // interface to be used with the object. The third field is the value
9534 // of the object itself.
9535
9536 Btype*
9537 Interface_type::do_get_backend(Gogo* gogo)
9538 {
9539 if (this->is_empty())
9540 return Interface_type::get_backend_empty_interface_type(gogo);
9541 else
9542 {
9543 if (this->interface_btype_ != NULL)
9544 return this->interface_btype_;
9545 this->interface_btype_ =
9546 gogo->backend()->placeholder_struct_type("", this->location_);
9547 std::vector<Backend::Btyped_identifier> bfields;
9548 get_backend_interface_fields(gogo, this, false, &bfields);
9549 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9550 bfields))
9551 this->interface_btype_ = gogo->backend()->error_type();
9552 return this->interface_btype_;
9553 }
9554 }
9555
9556 // Finish the backend representation of the methods.
9557
9558 void
9559 Interface_type::finish_backend_methods(Gogo* gogo)
9560 {
9561 if (!this->is_empty())
9562 {
9563 const Typed_identifier_list* methods = this->methods();
9564 if (methods != NULL)
9565 {
9566 for (Typed_identifier_list::const_iterator p = methods->begin();
9567 p != methods->end();
9568 ++p)
9569 p->type()->get_backend(gogo);
9570 }
9571
9572 // Getting the backend methods now will set the placeholder
9573 // pointer.
9574 this->get_backend_methods(gogo);
9575 }
9576 }
9577
9578 // The type of an interface type descriptor.
9579
9580 Type*
9581 Interface_type::make_interface_type_descriptor_type()
9582 {
9583 static Type* ret;
9584 if (ret == NULL)
9585 {
9586 Type* tdt = Type::make_type_descriptor_type();
9587 Type* ptdt = Type::make_type_descriptor_ptr_type();
9588
9589 Type* string_type = Type::lookup_string_type();
9590 Type* pointer_string_type = Type::make_pointer_type(string_type);
9591
9592 Struct_type* sm =
9593 Type::make_builtin_struct_type(3,
9594 "name", pointer_string_type,
9595 "pkgPath", pointer_string_type,
9596 "typ", ptdt);
9597
9598 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9599
9600 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9601
9602 Struct_type* s = Type::make_builtin_struct_type(2,
9603 "", tdt,
9604 "methods", slice_nsm);
9605
9606 ret = Type::make_builtin_named_type("InterfaceType", s);
9607 }
9608
9609 return ret;
9610 }
9611
9612 // Build a type descriptor for an interface type.
9613
9614 Expression*
9615 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9616 {
9617 Location bloc = Linemap::predeclared_location();
9618
9619 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9620
9621 const Struct_field_list* ifields = itdt->struct_type()->fields();
9622
9623 Expression_list* ivals = new Expression_list();
9624 ivals->reserve(2);
9625
9626 Struct_field_list::const_iterator pif = ifields->begin();
9627 go_assert(pif->is_field_name("_type"));
9628 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9629 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9630 true));
9631
9632 ++pif;
9633 go_assert(pif->is_field_name("methods"));
9634
9635 Expression_list* methods = new Expression_list();
9636 if (this->all_methods_ != NULL)
9637 {
9638 Type* elemtype = pif->type()->array_type()->element_type();
9639
9640 methods->reserve(this->all_methods_->size());
9641 for (Typed_identifier_list::const_iterator pm =
9642 this->all_methods_->begin();
9643 pm != this->all_methods_->end();
9644 ++pm)
9645 {
9646 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9647
9648 Expression_list* mvals = new Expression_list();
9649 mvals->reserve(3);
9650
9651 Struct_field_list::const_iterator pmf = mfields->begin();
9652 go_assert(pmf->is_field_name("name"));
9653 std::string s = Gogo::unpack_hidden_name(pm->name());
9654 Expression* e = Expression::make_string(s, bloc);
9655 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9656
9657 ++pmf;
9658 go_assert(pmf->is_field_name("pkgPath"));
9659 if (!Gogo::is_hidden_name(pm->name()))
9660 mvals->push_back(Expression::make_nil(bloc));
9661 else
9662 {
9663 s = Gogo::hidden_name_pkgpath(pm->name());
9664 e = Expression::make_string(s, bloc);
9665 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9666 }
9667
9668 ++pmf;
9669 go_assert(pmf->is_field_name("typ"));
9670 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9671
9672 ++pmf;
9673 go_assert(pmf == mfields->end());
9674
9675 e = Expression::make_struct_composite_literal(elemtype, mvals,
9676 bloc);
9677 methods->push_back(e);
9678 }
9679 }
9680
9681 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9682 methods, bloc));
9683
9684 ++pif;
9685 go_assert(pif == ifields->end());
9686
9687 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9688 }
9689
9690 // Reflection string.
9691
9692 void
9693 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9694 {
9695 ret->append("interface {");
9696 const Typed_identifier_list* methods = this->parse_methods_;
9697 if (methods != NULL)
9698 {
9699 ret->push_back(' ');
9700 for (Typed_identifier_list::const_iterator p = methods->begin();
9701 p != methods->end();
9702 ++p)
9703 {
9704 if (p != methods->begin())
9705 ret->append("; ");
9706 if (p->name().empty())
9707 this->append_reflection(p->type(), gogo, ret);
9708 else
9709 {
9710 if (!Gogo::is_hidden_name(p->name()))
9711 ret->append(p->name());
9712 else if (gogo->pkgpath_from_option())
9713 ret->append(p->name().substr(1));
9714 else
9715 {
9716 // If no -fgo-pkgpath option, backward compatibility
9717 // for how this used to work before -fgo-pkgpath was
9718 // introduced.
9719 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9720 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9721 ret->push_back('.');
9722 ret->append(Gogo::unpack_hidden_name(p->name()));
9723 }
9724 std::string sub = p->type()->reflection(gogo);
9725 go_assert(sub.compare(0, 4, "func") == 0);
9726 sub = sub.substr(4);
9727 ret->append(sub);
9728 }
9729 }
9730 ret->push_back(' ');
9731 }
9732 ret->append("}");
9733 }
9734
9735 // Export.
9736
9737 void
9738 Interface_type::do_export(Export* exp) const
9739 {
9740 exp->write_c_string("interface { ");
9741
9742 const Typed_identifier_list* methods = this->parse_methods_;
9743 if (methods != NULL)
9744 {
9745 for (Typed_identifier_list::const_iterator pm = methods->begin();
9746 pm != methods->end();
9747 ++pm)
9748 {
9749 if (pm->name().empty())
9750 {
9751 exp->write_c_string("? ");
9752 exp->write_type(pm->type());
9753 }
9754 else
9755 {
9756 exp->write_string(pm->name());
9757 exp->write_c_string(" (");
9758
9759 const Function_type* fntype = pm->type()->function_type();
9760
9761 bool first = true;
9762 const Typed_identifier_list* parameters = fntype->parameters();
9763 if (parameters != NULL)
9764 {
9765 bool is_varargs = fntype->is_varargs();
9766 for (Typed_identifier_list::const_iterator pp =
9767 parameters->begin();
9768 pp != parameters->end();
9769 ++pp)
9770 {
9771 if (first)
9772 first = false;
9773 else
9774 exp->write_c_string(", ");
9775 exp->write_name(pp->name());
9776 exp->write_c_string(" ");
9777 if (!is_varargs || pp + 1 != parameters->end())
9778 exp->write_type(pp->type());
9779 else
9780 {
9781 exp->write_c_string("...");
9782 Type *pptype = pp->type();
9783 exp->write_type(pptype->array_type()->element_type());
9784 }
9785 }
9786 }
9787
9788 exp->write_c_string(")");
9789
9790 const Typed_identifier_list* results = fntype->results();
9791 if (results != NULL)
9792 {
9793 exp->write_c_string(" ");
9794 if (results->size() == 1 && results->begin()->name().empty())
9795 exp->write_type(results->begin()->type());
9796 else
9797 {
9798 first = true;
9799 exp->write_c_string("(");
9800 for (Typed_identifier_list::const_iterator p =
9801 results->begin();
9802 p != results->end();
9803 ++p)
9804 {
9805 if (first)
9806 first = false;
9807 else
9808 exp->write_c_string(", ");
9809 exp->write_name(p->name());
9810 exp->write_c_string(" ");
9811 exp->write_type(p->type());
9812 }
9813 exp->write_c_string(")");
9814 }
9815 }
9816 }
9817
9818 exp->write_c_string("; ");
9819 }
9820 }
9821
9822 exp->write_c_string("}");
9823 }
9824
9825 // Import an interface type.
9826
9827 Interface_type*
9828 Interface_type::do_import(Import* imp)
9829 {
9830 imp->require_c_string("interface { ");
9831
9832 Typed_identifier_list* methods = new Typed_identifier_list;
9833 while (imp->peek_char() != '}')
9834 {
9835 std::string name = imp->read_identifier();
9836
9837 if (name == "?")
9838 {
9839 imp->require_c_string(" ");
9840 Type* t = imp->read_type();
9841 methods->push_back(Typed_identifier("", t, imp->location()));
9842 imp->require_c_string("; ");
9843 continue;
9844 }
9845
9846 imp->require_c_string(" (");
9847
9848 Typed_identifier_list* parameters;
9849 bool is_varargs = false;
9850 if (imp->peek_char() == ')')
9851 parameters = NULL;
9852 else
9853 {
9854 parameters = new Typed_identifier_list;
9855 while (true)
9856 {
9857 std::string pname = imp->read_name();
9858 imp->require_c_string(" ");
9859
9860 if (imp->match_c_string("..."))
9861 {
9862 imp->advance(3);
9863 is_varargs = true;
9864 }
9865
9866 Type* ptype = imp->read_type();
9867 if (is_varargs)
9868 ptype = Type::make_array_type(ptype, NULL);
9869 parameters->push_back(Typed_identifier(pname, ptype,
9870 imp->location()));
9871 if (imp->peek_char() != ',')
9872 break;
9873 go_assert(!is_varargs);
9874 imp->require_c_string(", ");
9875 }
9876 }
9877 imp->require_c_string(")");
9878
9879 Typed_identifier_list* results;
9880 if (imp->peek_char() != ' ')
9881 results = NULL;
9882 else
9883 {
9884 results = new Typed_identifier_list;
9885 imp->advance(1);
9886 if (imp->peek_char() != '(')
9887 {
9888 Type* rtype = imp->read_type();
9889 results->push_back(Typed_identifier("", rtype, imp->location()));
9890 }
9891 else
9892 {
9893 imp->advance(1);
9894 while (true)
9895 {
9896 std::string rname = imp->read_name();
9897 imp->require_c_string(" ");
9898 Type* rtype = imp->read_type();
9899 results->push_back(Typed_identifier(rname, rtype,
9900 imp->location()));
9901 if (imp->peek_char() != ',')
9902 break;
9903 imp->require_c_string(", ");
9904 }
9905 imp->require_c_string(")");
9906 }
9907 }
9908
9909 Function_type* fntype = Type::make_function_type(NULL, parameters,
9910 results,
9911 imp->location());
9912 if (is_varargs)
9913 fntype->set_is_varargs();
9914 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9915
9916 imp->require_c_string("; ");
9917 }
9918
9919 imp->require_c_string("}");
9920
9921 if (methods->empty())
9922 {
9923 delete methods;
9924 methods = NULL;
9925 }
9926
9927 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9928 ret->package_ = imp->package();
9929 return ret;
9930 }
9931
9932 // Make an interface type.
9933
9934 Interface_type*
9935 Type::make_interface_type(Typed_identifier_list* methods,
9936 Location location)
9937 {
9938 return new Interface_type(methods, location);
9939 }
9940
9941 // Make an empty interface type.
9942
9943 Interface_type*
9944 Type::make_empty_interface_type(Location location)
9945 {
9946 Interface_type* ret = new Interface_type(NULL, location);
9947 ret->finalize_methods();
9948 return ret;
9949 }
9950
9951 // Class Method.
9952
9953 // Bind a method to an object.
9954
9955 Expression*
9956 Method::bind_method(Expression* expr, Location location) const
9957 {
9958 if (this->stub_ == NULL)
9959 {
9960 // When there is no stub object, the binding is determined by
9961 // the child class.
9962 return this->do_bind_method(expr, location);
9963 }
9964 return Expression::make_bound_method(expr, this, this->stub_, location);
9965 }
9966
9967 // Return the named object associated with a method. This may only be
9968 // called after methods are finalized.
9969
9970 Named_object*
9971 Method::named_object() const
9972 {
9973 if (this->stub_ != NULL)
9974 return this->stub_;
9975 return this->do_named_object();
9976 }
9977
9978 // Class Named_method.
9979
9980 // The type of the method.
9981
9982 Function_type*
9983 Named_method::do_type() const
9984 {
9985 if (this->named_object_->is_function())
9986 return this->named_object_->func_value()->type();
9987 else if (this->named_object_->is_function_declaration())
9988 return this->named_object_->func_declaration_value()->type();
9989 else
9990 go_unreachable();
9991 }
9992
9993 // Return the location of the method receiver.
9994
9995 Location
9996 Named_method::do_receiver_location() const
9997 {
9998 return this->do_type()->receiver()->location();
9999 }
10000
10001 // Bind a method to an object.
10002
10003 Expression*
10004 Named_method::do_bind_method(Expression* expr, Location location) const
10005 {
10006 Named_object* no = this->named_object_;
10007 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
10008 no, location);
10009 // If this is not a local method, and it does not use a stub, then
10010 // the real method expects a different type. We need to cast the
10011 // first argument.
10012 if (this->depth() > 0 && !this->needs_stub_method())
10013 {
10014 Function_type* ftype = this->do_type();
10015 go_assert(ftype->is_method());
10016 Type* frtype = ftype->receiver()->type();
10017 bme->set_first_argument_type(frtype);
10018 }
10019 return bme;
10020 }
10021
10022 // Return whether this method should not participate in interfaces.
10023
10024 bool
10025 Named_method::do_nointerface() const
10026 {
10027 Named_object* no = this->named_object_;
10028 if (no->is_function())
10029 return no->func_value()->nointerface();
10030 else if (no->is_function_declaration())
10031 return no->func_declaration_value()->nointerface();
10032 else
10033 go_unreachable();
10034 }
10035
10036 // Class Interface_method.
10037
10038 // Bind a method to an object.
10039
10040 Expression*
10041 Interface_method::do_bind_method(Expression* expr,
10042 Location location) const
10043 {
10044 return Expression::make_interface_field_reference(expr, this->name_,
10045 location);
10046 }
10047
10048 // Class Methods.
10049
10050 // Insert a new method. Return true if it was inserted, false
10051 // otherwise.
10052
10053 bool
10054 Methods::insert(const std::string& name, Method* m)
10055 {
10056 std::pair<Method_map::iterator, bool> ins =
10057 this->methods_.insert(std::make_pair(name, m));
10058 if (ins.second)
10059 return true;
10060 else
10061 {
10062 Method* old_method = ins.first->second;
10063 if (m->depth() < old_method->depth())
10064 {
10065 delete old_method;
10066 ins.first->second = m;
10067 return true;
10068 }
10069 else
10070 {
10071 if (m->depth() == old_method->depth())
10072 old_method->set_is_ambiguous();
10073 return false;
10074 }
10075 }
10076 }
10077
10078 // Return the number of unambiguous methods.
10079
10080 size_t
10081 Methods::count() const
10082 {
10083 size_t ret = 0;
10084 for (Method_map::const_iterator p = this->methods_.begin();
10085 p != this->methods_.end();
10086 ++p)
10087 if (!p->second->is_ambiguous())
10088 ++ret;
10089 return ret;
10090 }
10091
10092 // Class Named_type.
10093
10094 // Return the name of the type.
10095
10096 const std::string&
10097 Named_type::name() const
10098 {
10099 return this->named_object_->name();
10100 }
10101
10102 // Return the name of the type to use in an error message.
10103
10104 std::string
10105 Named_type::message_name() const
10106 {
10107 return this->named_object_->message_name();
10108 }
10109
10110 // Return the base type for this type. We have to be careful about
10111 // circular type definitions, which are invalid but may be seen here.
10112
10113 Type*
10114 Named_type::named_base()
10115 {
10116 if (this->seen_)
10117 return this;
10118 this->seen_ = true;
10119 Type* ret = this->type_->base();
10120 this->seen_ = false;
10121 return ret;
10122 }
10123
10124 const Type*
10125 Named_type::named_base() const
10126 {
10127 if (this->seen_)
10128 return this;
10129 this->seen_ = true;
10130 const Type* ret = this->type_->base();
10131 this->seen_ = false;
10132 return ret;
10133 }
10134
10135 // Return whether this is an error type. We have to be careful about
10136 // circular type definitions, which are invalid but may be seen here.
10137
10138 bool
10139 Named_type::is_named_error_type() const
10140 {
10141 if (this->seen_)
10142 return false;
10143 this->seen_ = true;
10144 bool ret = this->type_->is_error_type();
10145 this->seen_ = false;
10146 return ret;
10147 }
10148
10149 // Whether this type is comparable. We have to be careful about
10150 // circular type definitions.
10151
10152 bool
10153 Named_type::named_type_is_comparable(std::string* reason) const
10154 {
10155 if (this->seen_)
10156 return false;
10157 this->seen_ = true;
10158 bool ret = Type::are_compatible_for_comparison(true, this->type_,
10159 this->type_, reason);
10160 this->seen_ = false;
10161 return ret;
10162 }
10163
10164 // Add a method to this type.
10165
10166 Named_object*
10167 Named_type::add_method(const std::string& name, Function* function)
10168 {
10169 go_assert(!this->is_alias_);
10170 if (this->local_methods_ == NULL)
10171 this->local_methods_ = new Bindings(NULL);
10172 return this->local_methods_->add_function(name,
10173 this->named_object_->package(),
10174 function);
10175 }
10176
10177 // Add a method declaration to this type.
10178
10179 Named_object*
10180 Named_type::add_method_declaration(const std::string& name, Package* package,
10181 Function_type* type,
10182 Location location)
10183 {
10184 go_assert(!this->is_alias_);
10185 if (this->local_methods_ == NULL)
10186 this->local_methods_ = new Bindings(NULL);
10187 return this->local_methods_->add_function_declaration(name, package, type,
10188 location);
10189 }
10190
10191 // Add an existing method to this type.
10192
10193 void
10194 Named_type::add_existing_method(Named_object* no)
10195 {
10196 go_assert(!this->is_alias_);
10197 if (this->local_methods_ == NULL)
10198 this->local_methods_ = new Bindings(NULL);
10199 this->local_methods_->add_named_object(no);
10200 }
10201
10202 // Look for a local method NAME, and returns its named object, or NULL
10203 // if not there.
10204
10205 Named_object*
10206 Named_type::find_local_method(const std::string& name) const
10207 {
10208 if (this->is_error_)
10209 return NULL;
10210 if (this->is_alias_)
10211 {
10212 Named_type* nt = this->type_->named_type();
10213 if (nt != NULL)
10214 {
10215 if (this->seen_alias_)
10216 return NULL;
10217 this->seen_alias_ = true;
10218 Named_object* ret = nt->find_local_method(name);
10219 this->seen_alias_ = false;
10220 return ret;
10221 }
10222 return NULL;
10223 }
10224 if (this->local_methods_ == NULL)
10225 return NULL;
10226 return this->local_methods_->lookup(name);
10227 }
10228
10229 // Return the list of local methods.
10230
10231 const Bindings*
10232 Named_type::local_methods() const
10233 {
10234 if (this->is_error_)
10235 return NULL;
10236 if (this->is_alias_)
10237 {
10238 Named_type* nt = this->type_->named_type();
10239 if (nt != NULL)
10240 {
10241 if (this->seen_alias_)
10242 return NULL;
10243 this->seen_alias_ = true;
10244 const Bindings* ret = nt->local_methods();
10245 this->seen_alias_ = false;
10246 return ret;
10247 }
10248 return NULL;
10249 }
10250 return this->local_methods_;
10251 }
10252
10253 // Return whether NAME is an unexported field or method, for better
10254 // error reporting.
10255
10256 bool
10257 Named_type::is_unexported_local_method(Gogo* gogo,
10258 const std::string& name) const
10259 {
10260 if (this->is_error_)
10261 return false;
10262 if (this->is_alias_)
10263 {
10264 Named_type* nt = this->type_->named_type();
10265 if (nt != NULL)
10266 {
10267 if (this->seen_alias_)
10268 return false;
10269 this->seen_alias_ = true;
10270 bool ret = nt->is_unexported_local_method(gogo, name);
10271 this->seen_alias_ = false;
10272 return ret;
10273 }
10274 return false;
10275 }
10276 Bindings* methods = this->local_methods_;
10277 if (methods != NULL)
10278 {
10279 for (Bindings::const_declarations_iterator p =
10280 methods->begin_declarations();
10281 p != methods->end_declarations();
10282 ++p)
10283 {
10284 if (Gogo::is_hidden_name(p->first)
10285 && name == Gogo::unpack_hidden_name(p->first)
10286 && gogo->pack_hidden_name(name, false) != p->first)
10287 return true;
10288 }
10289 }
10290 return false;
10291 }
10292
10293 // Build the complete list of methods for this type, which means
10294 // recursively including all methods for anonymous fields. Create all
10295 // stub methods.
10296
10297 void
10298 Named_type::finalize_methods(Gogo* gogo)
10299 {
10300 if (this->is_alias_)
10301 return;
10302 if (this->all_methods_ != NULL)
10303 return;
10304
10305 if (this->local_methods_ != NULL
10306 && (this->points_to() != NULL || this->interface_type() != NULL))
10307 {
10308 const Bindings* lm = this->local_methods_;
10309 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10310 p != lm->end_declarations();
10311 ++p)
10312 go_error_at(p->second->location(),
10313 "invalid pointer or interface receiver type");
10314 delete this->local_methods_;
10315 this->local_methods_ = NULL;
10316 return;
10317 }
10318
10319 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10320 }
10321
10322 // Return whether this type has any methods.
10323
10324 bool
10325 Named_type::has_any_methods() const
10326 {
10327 if (this->is_error_)
10328 return false;
10329 if (this->is_alias_)
10330 {
10331 if (this->type_->named_type() != NULL)
10332 {
10333 if (this->seen_alias_)
10334 return false;
10335 this->seen_alias_ = true;
10336 bool ret = this->type_->named_type()->has_any_methods();
10337 this->seen_alias_ = false;
10338 return ret;
10339 }
10340 if (this->type_->struct_type() != NULL)
10341 return this->type_->struct_type()->has_any_methods();
10342 return false;
10343 }
10344 return this->all_methods_ != NULL;
10345 }
10346
10347 // Return the methods for this type.
10348
10349 const Methods*
10350 Named_type::methods() const
10351 {
10352 if (this->is_error_)
10353 return NULL;
10354 if (this->is_alias_)
10355 {
10356 if (this->type_->named_type() != NULL)
10357 {
10358 if (this->seen_alias_)
10359 return NULL;
10360 this->seen_alias_ = true;
10361 const Methods* ret = this->type_->named_type()->methods();
10362 this->seen_alias_ = false;
10363 return ret;
10364 }
10365 if (this->type_->struct_type() != NULL)
10366 return this->type_->struct_type()->methods();
10367 return NULL;
10368 }
10369 return this->all_methods_;
10370 }
10371
10372 // Return the method NAME, or NULL if there isn't one or if it is
10373 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10374 // ambiguous.
10375
10376 Method*
10377 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10378 {
10379 if (this->is_error_)
10380 return NULL;
10381 if (this->is_alias_)
10382 {
10383 if (is_ambiguous != NULL)
10384 *is_ambiguous = false;
10385 if (this->type_->named_type() != NULL)
10386 {
10387 if (this->seen_alias_)
10388 return NULL;
10389 this->seen_alias_ = true;
10390 Named_type* nt = this->type_->named_type();
10391 Method* ret = nt->method_function(name, is_ambiguous);
10392 this->seen_alias_ = false;
10393 return ret;
10394 }
10395 if (this->type_->struct_type() != NULL)
10396 return this->type_->struct_type()->method_function(name, is_ambiguous);
10397 return NULL;
10398 }
10399 return Type::method_function(this->all_methods_, name, is_ambiguous);
10400 }
10401
10402 // Return a pointer to the interface method table for this type for
10403 // the interface INTERFACE. IS_POINTER is true if this is for a
10404 // pointer to THIS.
10405
10406 Expression*
10407 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10408 {
10409 if (this->is_error_)
10410 return Expression::make_error(this->location_);
10411 if (this->is_alias_)
10412 {
10413 Type* t = this->type_;
10414 if (!is_pointer && t->points_to() != NULL)
10415 {
10416 t = t->points_to();
10417 is_pointer = true;
10418 }
10419 if (t->named_type() != NULL)
10420 {
10421 if (this->seen_alias_)
10422 return Expression::make_error(this->location_);
10423 this->seen_alias_ = true;
10424 Named_type* nt = t->named_type();
10425 Expression* ret = nt->interface_method_table(interface, is_pointer);
10426 this->seen_alias_ = false;
10427 return ret;
10428 }
10429 if (t->struct_type() != NULL)
10430 return t->struct_type()->interface_method_table(interface, is_pointer);
10431 go_unreachable();
10432 }
10433 return Type::interface_method_table(this, interface, is_pointer,
10434 &this->interface_method_tables_,
10435 &this->pointer_interface_method_tables_);
10436 }
10437
10438 // Look for a use of a complete type within another type. This is
10439 // used to check that we don't try to use a type within itself.
10440
10441 class Find_type_use : public Traverse
10442 {
10443 public:
10444 Find_type_use(Named_type* find_type)
10445 : Traverse(traverse_types),
10446 find_type_(find_type), found_(false)
10447 { }
10448
10449 // Whether we found the type.
10450 bool
10451 found() const
10452 { return this->found_; }
10453
10454 protected:
10455 int
10456 type(Type*);
10457
10458 private:
10459 // The type we are looking for.
10460 Named_type* find_type_;
10461 // Whether we found the type.
10462 bool found_;
10463 };
10464
10465 // Check for FIND_TYPE in TYPE.
10466
10467 int
10468 Find_type_use::type(Type* type)
10469 {
10470 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10471 {
10472 this->found_ = true;
10473 return TRAVERSE_EXIT;
10474 }
10475
10476 // It's OK if we see a reference to the type in any type which is
10477 // essentially a pointer: a pointer, a slice, a function, a map, or
10478 // a channel.
10479 if (type->points_to() != NULL
10480 || type->is_slice_type()
10481 || type->function_type() != NULL
10482 || type->map_type() != NULL
10483 || type->channel_type() != NULL)
10484 return TRAVERSE_SKIP_COMPONENTS;
10485
10486 // For an interface, a reference to the type in a method type should
10487 // be ignored, but we have to consider direct inheritance. When
10488 // this is called, there may be cases of direct inheritance
10489 // represented as a method with no name.
10490 if (type->interface_type() != NULL)
10491 {
10492 const Typed_identifier_list* methods = type->interface_type()->methods();
10493 if (methods != NULL)
10494 {
10495 for (Typed_identifier_list::const_iterator p = methods->begin();
10496 p != methods->end();
10497 ++p)
10498 {
10499 if (p->name().empty())
10500 {
10501 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10502 return TRAVERSE_EXIT;
10503 }
10504 }
10505 }
10506 return TRAVERSE_SKIP_COMPONENTS;
10507 }
10508
10509 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10510 // to convert TYPE to the backend representation before we convert
10511 // FIND_TYPE_.
10512 if (type->named_type() != NULL)
10513 {
10514 switch (type->base()->classification())
10515 {
10516 case Type::TYPE_ERROR:
10517 case Type::TYPE_BOOLEAN:
10518 case Type::TYPE_INTEGER:
10519 case Type::TYPE_FLOAT:
10520 case Type::TYPE_COMPLEX:
10521 case Type::TYPE_STRING:
10522 case Type::TYPE_NIL:
10523 break;
10524
10525 case Type::TYPE_ARRAY:
10526 case Type::TYPE_STRUCT:
10527 this->find_type_->add_dependency(type->named_type());
10528 break;
10529
10530 case Type::TYPE_NAMED:
10531 if (type->named_type() == type->base()->named_type())
10532 {
10533 this->found_ = true;
10534 return TRAVERSE_EXIT;
10535 }
10536 else
10537 go_assert(saw_errors());
10538 break;
10539
10540 case Type::TYPE_FORWARD:
10541 go_assert(saw_errors());
10542 break;
10543
10544 case Type::TYPE_VOID:
10545 case Type::TYPE_SINK:
10546 case Type::TYPE_FUNCTION:
10547 case Type::TYPE_POINTER:
10548 case Type::TYPE_CALL_MULTIPLE_RESULT:
10549 case Type::TYPE_MAP:
10550 case Type::TYPE_CHANNEL:
10551 case Type::TYPE_INTERFACE:
10552 default:
10553 go_unreachable();
10554 }
10555 }
10556
10557 return TRAVERSE_CONTINUE;
10558 }
10559
10560 // Look for a circular reference of an alias.
10561
10562 class Find_alias : public Traverse
10563 {
10564 public:
10565 Find_alias(Named_type* find_type)
10566 : Traverse(traverse_types),
10567 find_type_(find_type), found_(false)
10568 { }
10569
10570 // Whether we found the type.
10571 bool
10572 found() const
10573 { return this->found_; }
10574
10575 protected:
10576 int
10577 type(Type*);
10578
10579 private:
10580 // The type we are looking for.
10581 Named_type* find_type_;
10582 // Whether we found the type.
10583 bool found_;
10584 };
10585
10586 int
10587 Find_alias::type(Type* type)
10588 {
10589 Named_type* nt = type->named_type();
10590 if (nt != NULL)
10591 {
10592 if (nt == this->find_type_)
10593 {
10594 this->found_ = true;
10595 return TRAVERSE_EXIT;
10596 }
10597
10598 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10599 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10600 // an alias itself, it's OK if whatever T2 is defined as refers
10601 // to T1.
10602 if (!nt->is_alias())
10603 return TRAVERSE_SKIP_COMPONENTS;
10604 }
10605
10606 // Check if there are recursive inherited interface aliases.
10607 Interface_type* ift = type->interface_type();
10608 if (ift != NULL)
10609 {
10610 const Typed_identifier_list* methods = ift->local_methods();
10611 if (methods == NULL)
10612 return TRAVERSE_CONTINUE;
10613 for (Typed_identifier_list::const_iterator p = methods->begin();
10614 p != methods->end();
10615 ++p)
10616 if (p->name().empty() && p->type()->named_type() == this->find_type_)
10617 {
10618 this->found_ = true;
10619 return TRAVERSE_EXIT;
10620 }
10621 }
10622
10623 return TRAVERSE_CONTINUE;
10624 }
10625
10626 // Verify that a named type does not refer to itself.
10627
10628 bool
10629 Named_type::do_verify()
10630 {
10631 if (this->is_verified_)
10632 return true;
10633 this->is_verified_ = true;
10634
10635 if (this->is_error_)
10636 return false;
10637
10638 if (this->is_alias_)
10639 {
10640 Find_alias find(this);
10641 Type::traverse(this->type_, &find);
10642 if (find.found())
10643 {
10644 go_error_at(this->location_, "invalid recursive alias %qs",
10645 this->message_name().c_str());
10646 this->is_error_ = true;
10647 return false;
10648 }
10649 }
10650
10651 Find_type_use find(this);
10652 Type::traverse(this->type_, &find);
10653 if (find.found())
10654 {
10655 go_error_at(this->location_, "invalid recursive type %qs",
10656 this->message_name().c_str());
10657 this->is_error_ = true;
10658 return false;
10659 }
10660
10661 // Check whether any of the local methods overloads an existing
10662 // struct field or interface method. We don't need to check the
10663 // list of methods against itself: that is handled by the Bindings
10664 // code.
10665 if (this->local_methods_ != NULL)
10666 {
10667 Struct_type* st = this->type_->struct_type();
10668 if (st != NULL)
10669 {
10670 for (Bindings::const_declarations_iterator p =
10671 this->local_methods_->begin_declarations();
10672 p != this->local_methods_->end_declarations();
10673 ++p)
10674 {
10675 const std::string& name(p->first);
10676 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10677 {
10678 go_error_at(p->second->location(),
10679 "method %qs redeclares struct field name",
10680 Gogo::message_name(name).c_str());
10681 }
10682 }
10683 }
10684 }
10685
10686 return true;
10687 }
10688
10689 // Return whether this type is or contains a pointer.
10690
10691 bool
10692 Named_type::do_has_pointer() const
10693 {
10694 if (this->seen_)
10695 return false;
10696 this->seen_ = true;
10697 bool ret = this->type_->has_pointer();
10698 this->seen_ = false;
10699 return ret;
10700 }
10701
10702 // Return whether comparisons for this type can use the identity
10703 // function.
10704
10705 bool
10706 Named_type::do_compare_is_identity(Gogo* gogo)
10707 {
10708 // We don't use this->seen_ here because compare_is_identity may
10709 // call base() later, and that will mess up if seen_ is set here.
10710 if (this->seen_in_compare_is_identity_)
10711 return false;
10712 this->seen_in_compare_is_identity_ = true;
10713 bool ret = this->type_->compare_is_identity(gogo);
10714 this->seen_in_compare_is_identity_ = false;
10715 return ret;
10716 }
10717
10718 // Return whether this type is reflexive--whether it is always equal
10719 // to itself.
10720
10721 bool
10722 Named_type::do_is_reflexive()
10723 {
10724 if (this->seen_in_compare_is_identity_)
10725 return false;
10726 this->seen_in_compare_is_identity_ = true;
10727 bool ret = this->type_->is_reflexive();
10728 this->seen_in_compare_is_identity_ = false;
10729 return ret;
10730 }
10731
10732 // Return whether this type needs a key update when used as a map key.
10733
10734 bool
10735 Named_type::do_needs_key_update()
10736 {
10737 if (this->seen_in_compare_is_identity_)
10738 return true;
10739 this->seen_in_compare_is_identity_ = true;
10740 bool ret = this->type_->needs_key_update();
10741 this->seen_in_compare_is_identity_ = false;
10742 return ret;
10743 }
10744
10745 // Return a hash code. This is used for method lookup. We simply
10746 // hash on the name itself.
10747
10748 unsigned int
10749 Named_type::do_hash_for_method(Gogo* gogo, int) const
10750 {
10751 if (this->is_error_)
10752 return 0;
10753
10754 // Aliases are handled in Type::hash_for_method.
10755 go_assert(!this->is_alias_);
10756
10757 const std::string& name(this->named_object()->name());
10758 unsigned int ret = Gogo::hash_string(name, 0);
10759
10760 // GOGO will be NULL here when called from Type_hash_identical.
10761 // That is OK because that is only used for internal hash tables
10762 // where we are going to be comparing named types for equality. In
10763 // other cases, which are cases where the runtime is going to
10764 // compare hash codes to see if the types are the same, we need to
10765 // include the pkgpath in the hash.
10766 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10767 {
10768 const Package* package = this->named_object()->package();
10769 if (package == NULL)
10770 ret = Gogo::hash_string(gogo->pkgpath(), ret);
10771 else
10772 ret = Gogo::hash_string(package->pkgpath(), ret);
10773 }
10774
10775 return ret;
10776 }
10777
10778 // Convert a named type to the backend representation. In order to
10779 // get dependencies right, we fill in a dummy structure for this type,
10780 // then convert all the dependencies, then complete this type. When
10781 // this function is complete, the size of the type is known.
10782
10783 void
10784 Named_type::convert(Gogo* gogo)
10785 {
10786 if (this->is_error_ || this->is_converted_)
10787 return;
10788
10789 this->create_placeholder(gogo);
10790
10791 // If we are called to turn unsafe.Sizeof into a constant, we may
10792 // not have verified the type yet. We have to make sure it is
10793 // verified, since that sets the list of dependencies.
10794 this->verify();
10795
10796 // Convert all the dependencies. If they refer indirectly back to
10797 // this type, they will pick up the intermediate representation we just
10798 // created.
10799 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10800 p != this->dependencies_.end();
10801 ++p)
10802 (*p)->convert(gogo);
10803
10804 // Complete this type.
10805 Btype* bt = this->named_btype_;
10806 Type* base = this->type_->base();
10807 switch (base->classification())
10808 {
10809 case TYPE_VOID:
10810 case TYPE_BOOLEAN:
10811 case TYPE_INTEGER:
10812 case TYPE_FLOAT:
10813 case TYPE_COMPLEX:
10814 case TYPE_STRING:
10815 case TYPE_NIL:
10816 break;
10817
10818 case TYPE_MAP:
10819 case TYPE_CHANNEL:
10820 break;
10821
10822 case TYPE_FUNCTION:
10823 case TYPE_POINTER:
10824 // The size of these types is already correct. We don't worry
10825 // about filling them in until later, when we also track
10826 // circular references.
10827 break;
10828
10829 case TYPE_STRUCT:
10830 {
10831 std::vector<Backend::Btyped_identifier> bfields;
10832 get_backend_struct_fields(gogo, base->struct_type(), true, &bfields);
10833 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10834 bt = gogo->backend()->error_type();
10835 }
10836 break;
10837
10838 case TYPE_ARRAY:
10839 // Slice types were completed in create_placeholder.
10840 if (!base->is_slice_type())
10841 {
10842 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10843 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10844 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10845 bt = gogo->backend()->error_type();
10846 }
10847 break;
10848
10849 case TYPE_INTERFACE:
10850 // Interface types were completed in create_placeholder.
10851 break;
10852
10853 case TYPE_ERROR:
10854 return;
10855
10856 default:
10857 case TYPE_SINK:
10858 case TYPE_CALL_MULTIPLE_RESULT:
10859 case TYPE_NAMED:
10860 case TYPE_FORWARD:
10861 go_unreachable();
10862 }
10863
10864 this->named_btype_ = bt;
10865 this->is_converted_ = true;
10866 this->is_placeholder_ = false;
10867 }
10868
10869 // Create the placeholder for a named type. This is the first step in
10870 // converting to the backend representation.
10871
10872 void
10873 Named_type::create_placeholder(Gogo* gogo)
10874 {
10875 if (this->is_error_)
10876 this->named_btype_ = gogo->backend()->error_type();
10877
10878 if (this->named_btype_ != NULL)
10879 return;
10880
10881 // Create the structure for this type. Note that because we call
10882 // base() here, we don't attempt to represent a named type defined
10883 // as another named type. Instead both named types will point to
10884 // different base representations.
10885 Type* base = this->type_->base();
10886 Btype* bt;
10887 bool set_name = true;
10888 switch (base->classification())
10889 {
10890 case TYPE_ERROR:
10891 this->is_error_ = true;
10892 this->named_btype_ = gogo->backend()->error_type();
10893 return;
10894
10895 case TYPE_VOID:
10896 case TYPE_BOOLEAN:
10897 case TYPE_INTEGER:
10898 case TYPE_FLOAT:
10899 case TYPE_COMPLEX:
10900 case TYPE_STRING:
10901 case TYPE_NIL:
10902 // These are simple basic types, we can just create them
10903 // directly.
10904 bt = Type::get_named_base_btype(gogo, base);
10905 break;
10906
10907 case TYPE_MAP:
10908 case TYPE_CHANNEL:
10909 // All maps and channels have the same backend representation.
10910 bt = Type::get_named_base_btype(gogo, base);
10911 break;
10912
10913 case TYPE_FUNCTION:
10914 case TYPE_POINTER:
10915 {
10916 bool for_function = base->classification() == TYPE_FUNCTION;
10917 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10918 this->location_,
10919 for_function);
10920 set_name = false;
10921 }
10922 break;
10923
10924 case TYPE_STRUCT:
10925 bt = gogo->backend()->placeholder_struct_type(this->name(),
10926 this->location_);
10927 this->is_placeholder_ = true;
10928 set_name = false;
10929 break;
10930
10931 case TYPE_ARRAY:
10932 if (base->is_slice_type())
10933 bt = gogo->backend()->placeholder_struct_type(this->name(),
10934 this->location_);
10935 else
10936 {
10937 bt = gogo->backend()->placeholder_array_type(this->name(),
10938 this->location_);
10939 this->is_placeholder_ = true;
10940 }
10941 set_name = false;
10942 break;
10943
10944 case TYPE_INTERFACE:
10945 if (base->interface_type()->is_empty())
10946 bt = Interface_type::get_backend_empty_interface_type(gogo);
10947 else
10948 {
10949 bt = gogo->backend()->placeholder_struct_type(this->name(),
10950 this->location_);
10951 set_name = false;
10952 }
10953 break;
10954
10955 default:
10956 case TYPE_SINK:
10957 case TYPE_CALL_MULTIPLE_RESULT:
10958 case TYPE_NAMED:
10959 case TYPE_FORWARD:
10960 go_unreachable();
10961 }
10962
10963 if (set_name)
10964 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10965
10966 this->named_btype_ = bt;
10967
10968 if (base->is_slice_type())
10969 {
10970 // We do not record slices as dependencies of other types,
10971 // because we can fill them in completely here with the final
10972 // size.
10973 std::vector<Backend::Btyped_identifier> bfields;
10974 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10975 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10976 this->named_btype_ = gogo->backend()->error_type();
10977 }
10978 else if (base->interface_type() != NULL
10979 && !base->interface_type()->is_empty())
10980 {
10981 // We do not record interfaces as dependencies of other types,
10982 // because we can fill them in completely here with the final
10983 // size.
10984 std::vector<Backend::Btyped_identifier> bfields;
10985 get_backend_interface_fields(gogo, base->interface_type(), true,
10986 &bfields);
10987 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10988 this->named_btype_ = gogo->backend()->error_type();
10989 }
10990 }
10991
10992 // Get the backend representation for a named type.
10993
10994 Btype*
10995 Named_type::do_get_backend(Gogo* gogo)
10996 {
10997 if (this->is_error_)
10998 return gogo->backend()->error_type();
10999
11000 Btype* bt = this->named_btype_;
11001
11002 if (!gogo->named_types_are_converted())
11003 {
11004 // We have not completed converting named types. NAMED_BTYPE_
11005 // is a placeholder and we shouldn't do anything further.
11006 if (bt != NULL)
11007 return bt;
11008
11009 // We don't build dependencies for types whose sizes do not
11010 // change or are not relevant, so we may see them here while
11011 // converting types.
11012 this->create_placeholder(gogo);
11013 bt = this->named_btype_;
11014 go_assert(bt != NULL);
11015 return bt;
11016 }
11017
11018 // We are not converting types. This should only be called if the
11019 // type has already been converted.
11020 if (!this->is_converted_)
11021 {
11022 go_assert(saw_errors());
11023 return gogo->backend()->error_type();
11024 }
11025
11026 go_assert(bt != NULL);
11027
11028 // Complete the backend representation.
11029 Type* base = this->type_->base();
11030 Btype* bt1;
11031 switch (base->classification())
11032 {
11033 case TYPE_ERROR:
11034 return gogo->backend()->error_type();
11035
11036 case TYPE_VOID:
11037 case TYPE_BOOLEAN:
11038 case TYPE_INTEGER:
11039 case TYPE_FLOAT:
11040 case TYPE_COMPLEX:
11041 case TYPE_STRING:
11042 case TYPE_NIL:
11043 case TYPE_MAP:
11044 case TYPE_CHANNEL:
11045 return bt;
11046
11047 case TYPE_STRUCT:
11048 if (!this->seen_in_get_backend_)
11049 {
11050 this->seen_in_get_backend_ = true;
11051 base->struct_type()->finish_backend_fields(gogo);
11052 this->seen_in_get_backend_ = false;
11053 }
11054 return bt;
11055
11056 case TYPE_ARRAY:
11057 if (!this->seen_in_get_backend_)
11058 {
11059 this->seen_in_get_backend_ = true;
11060 base->array_type()->finish_backend_element(gogo);
11061 this->seen_in_get_backend_ = false;
11062 }
11063 return bt;
11064
11065 case TYPE_INTERFACE:
11066 if (!this->seen_in_get_backend_)
11067 {
11068 this->seen_in_get_backend_ = true;
11069 base->interface_type()->finish_backend_methods(gogo);
11070 this->seen_in_get_backend_ = false;
11071 }
11072 return bt;
11073
11074 case TYPE_FUNCTION:
11075 // Don't build a circular data structure. GENERIC can't handle
11076 // it.
11077 if (this->seen_in_get_backend_)
11078 return gogo->backend()->circular_pointer_type(bt, true);
11079 this->seen_in_get_backend_ = true;
11080 bt1 = Type::get_named_base_btype(gogo, base);
11081 this->seen_in_get_backend_ = false;
11082 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11083 bt = gogo->backend()->error_type();
11084 return bt;
11085
11086 case TYPE_POINTER:
11087 // Don't build a circular data structure. GENERIC can't handle
11088 // it.
11089 if (this->seen_in_get_backend_)
11090 return gogo->backend()->circular_pointer_type(bt, false);
11091 this->seen_in_get_backend_ = true;
11092 bt1 = Type::get_named_base_btype(gogo, base);
11093 this->seen_in_get_backend_ = false;
11094 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11095 bt = gogo->backend()->error_type();
11096 return bt;
11097
11098 default:
11099 case TYPE_SINK:
11100 case TYPE_CALL_MULTIPLE_RESULT:
11101 case TYPE_NAMED:
11102 case TYPE_FORWARD:
11103 go_unreachable();
11104 }
11105
11106 go_unreachable();
11107 }
11108
11109 // Build a type descriptor for a named type.
11110
11111 Expression*
11112 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11113 {
11114 if (this->is_error_)
11115 return Expression::make_error(this->location_);
11116
11117 // We shouldn't see unnamed type aliases here. They should have
11118 // been removed by the call to unalias in Type::type_descriptor_pointer.
11119 // We can see named type aliases via Type::named_type_descriptor.
11120 go_assert(name != NULL || !this->is_alias_);
11121
11122 // If NAME is not NULL, then we don't really want the type
11123 // descriptor for this type; we want the descriptor for the
11124 // underlying type, giving it the name NAME.
11125 return this->named_type_descriptor(gogo, this->type_,
11126 name == NULL ? this : name);
11127 }
11128
11129 // Add to the reflection string. This is used mostly for the name of
11130 // the type used in a type descriptor, not for actual reflection
11131 // strings.
11132
11133 void
11134 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
11135 {
11136 this->append_reflection_type_name(gogo, false, ret);
11137 }
11138
11139 // Add to the reflection string. For an alias we normally use the
11140 // real name, but if USE_ALIAS is true we use the alias name itself.
11141
11142 void
11143 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
11144 std::string* ret) const
11145 {
11146 if (this->is_error_)
11147 return;
11148 if (this->is_alias_ && !use_alias)
11149 {
11150 if (this->seen_alias_)
11151 return;
11152 this->seen_alias_ = true;
11153 this->append_reflection(this->type_, gogo, ret);
11154 this->seen_alias_ = false;
11155 return;
11156 }
11157 if (!this->is_builtin())
11158 {
11159 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
11160 // make a unique reflection string, so that the type
11161 // canonicalization in the reflect package will work. In order
11162 // to be compatible with the gc compiler, we put tabs into the
11163 // package path, so that the reflect methods can discard it.
11164 const Package* package = this->named_object_->package();
11165 ret->push_back('\t');
11166 ret->append(package != NULL
11167 ? package->pkgpath_symbol()
11168 : gogo->pkgpath_symbol());
11169 ret->push_back('\t');
11170 ret->append(package != NULL
11171 ? package->package_name()
11172 : gogo->package_name());
11173 ret->push_back('.');
11174 }
11175 if (this->in_function_ != NULL)
11176 {
11177 ret->push_back('\t');
11178 const Typed_identifier* rcvr =
11179 this->in_function_->func_value()->type()->receiver();
11180 if (rcvr != NULL)
11181 {
11182 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11183 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
11184 ret->push_back('.');
11185 }
11186 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
11187 ret->push_back('$');
11188 if (this->in_function_index_ > 0)
11189 {
11190 char buf[30];
11191 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11192 ret->append(buf);
11193 ret->push_back('$');
11194 }
11195 ret->push_back('\t');
11196 }
11197 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
11198 }
11199
11200 // Import a named type. This is only used for export format versions
11201 // before version 3.
11202
11203 void
11204 Named_type::import_named_type(Import* imp, Named_type** ptype)
11205 {
11206 imp->require_c_string("type ");
11207 Type *type = imp->read_type();
11208 *ptype = type->named_type();
11209 go_assert(*ptype != NULL);
11210 imp->require_semicolon_if_old_version();
11211 imp->require_c_string("\n");
11212 }
11213
11214 // Export the type when it is referenced by another type. In this
11215 // case Export::export_type will already have issued the name. The
11216 // output always ends with a newline, since that is convenient if
11217 // there are methods.
11218
11219 void
11220 Named_type::do_export(Export* exp) const
11221 {
11222 exp->write_type(this->type_);
11223 exp->write_c_string("\n");
11224
11225 // To save space, we only export the methods directly attached to
11226 // this type.
11227 Bindings* methods = this->local_methods_;
11228 if (methods == NULL)
11229 return;
11230
11231 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
11232 p != methods->end_definitions();
11233 ++p)
11234 {
11235 exp->write_c_string(" ");
11236 (*p)->export_named_object(exp);
11237 }
11238
11239 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
11240 p != methods->end_declarations();
11241 ++p)
11242 {
11243 if (p->second->is_function_declaration())
11244 {
11245 exp->write_c_string(" ");
11246 p->second->export_named_object(exp);
11247 }
11248 }
11249 }
11250
11251 // Make a named type.
11252
11253 Named_type*
11254 Type::make_named_type(Named_object* named_object, Type* type,
11255 Location location)
11256 {
11257 return new Named_type(named_object, type, location);
11258 }
11259
11260 // Finalize the methods for TYPE. It will be a named type or a struct
11261 // type. This sets *ALL_METHODS to the list of methods, and builds
11262 // all required stubs.
11263
11264 void
11265 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
11266 Methods** all_methods)
11267 {
11268 *all_methods = new Methods();
11269 std::vector<const Named_type*> seen;
11270 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
11271 if ((*all_methods)->empty())
11272 {
11273 delete *all_methods;
11274 *all_methods = NULL;
11275 }
11276 Type::build_stub_methods(gogo, type, *all_methods, location);
11277 if (type->is_direct_iface_type())
11278 Type::build_direct_iface_stub_methods(gogo, type, *all_methods, location);
11279 }
11280
11281 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11282 // build up the struct field indexes as we go. DEPTH is the depth of
11283 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11284 // adding these methods for an anonymous field with pointer type.
11285 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11286 // calls the real method. TYPES_SEEN is used to avoid infinite
11287 // recursion.
11288
11289 void
11290 Type::add_methods_for_type(const Type* type,
11291 const Method::Field_indexes* field_indexes,
11292 unsigned int depth,
11293 bool is_embedded_pointer,
11294 bool needs_stub_method,
11295 std::vector<const Named_type*>* seen,
11296 Methods* methods)
11297 {
11298 // Pointer types may not have methods.
11299 if (type->points_to() != NULL)
11300 return;
11301
11302 const Named_type* nt = type->named_type();
11303 if (nt != NULL)
11304 {
11305 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11306 p != seen->end();
11307 ++p)
11308 {
11309 if (*p == nt)
11310 return;
11311 }
11312
11313 seen->push_back(nt);
11314
11315 Type::add_local_methods_for_type(nt, field_indexes, depth,
11316 is_embedded_pointer, needs_stub_method,
11317 methods);
11318 }
11319
11320 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11321 is_embedded_pointer, needs_stub_method,
11322 seen, methods);
11323
11324 // If we are called with depth > 0, then we are looking at an
11325 // anonymous field of a struct. If such a field has interface type,
11326 // then we need to add the interface methods. We don't want to add
11327 // them when depth == 0, because we will already handle them
11328 // following the usual rules for an interface type.
11329 if (depth > 0)
11330 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11331
11332 if (nt != NULL)
11333 seen->pop_back();
11334 }
11335
11336 // Add the local methods for the named type NT to *METHODS. The
11337 // parameters are as for add_methods_to_type.
11338
11339 void
11340 Type::add_local_methods_for_type(const Named_type* nt,
11341 const Method::Field_indexes* field_indexes,
11342 unsigned int depth,
11343 bool is_embedded_pointer,
11344 bool needs_stub_method,
11345 Methods* methods)
11346 {
11347 const Bindings* local_methods = nt->local_methods();
11348 if (local_methods == NULL)
11349 return;
11350
11351 for (Bindings::const_declarations_iterator p =
11352 local_methods->begin_declarations();
11353 p != local_methods->end_declarations();
11354 ++p)
11355 {
11356 Named_object* no = p->second;
11357 bool is_value_method = (is_embedded_pointer
11358 || !Type::method_expects_pointer(no));
11359 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11360 (needs_stub_method || depth > 0));
11361 if (!methods->insert(no->name(), m))
11362 delete m;
11363 }
11364 }
11365
11366 // Add the embedded methods for TYPE to *METHODS. These are the
11367 // methods attached to anonymous fields. The parameters are as for
11368 // add_methods_to_type.
11369
11370 void
11371 Type::add_embedded_methods_for_type(const Type* type,
11372 const Method::Field_indexes* field_indexes,
11373 unsigned int depth,
11374 bool is_embedded_pointer,
11375 bool needs_stub_method,
11376 std::vector<const Named_type*>* seen,
11377 Methods* methods)
11378 {
11379 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11380 // struct.
11381 const Struct_type* st = type->struct_type();
11382 if (st == NULL)
11383 return;
11384
11385 const Struct_field_list* fields = st->fields();
11386 if (fields == NULL)
11387 return;
11388
11389 unsigned int i = 0;
11390 for (Struct_field_list::const_iterator pf = fields->begin();
11391 pf != fields->end();
11392 ++pf, ++i)
11393 {
11394 if (!pf->is_anonymous())
11395 continue;
11396
11397 Type* ftype = pf->type();
11398 bool is_pointer = false;
11399 if (ftype->points_to() != NULL)
11400 {
11401 ftype = ftype->points_to();
11402 is_pointer = true;
11403 }
11404 Named_type* fnt = ftype->named_type();
11405 if (fnt == NULL)
11406 {
11407 // This is an error, but it will be diagnosed elsewhere.
11408 continue;
11409 }
11410
11411 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11412 sub_field_indexes->next = field_indexes;
11413 sub_field_indexes->field_index = i;
11414
11415 Methods tmp_methods;
11416 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11417 (is_embedded_pointer || is_pointer),
11418 (needs_stub_method
11419 || is_pointer
11420 || i > 0),
11421 seen,
11422 &tmp_methods);
11423 // Check if there are promoted methods that conflict with field names and
11424 // don't add them to the method map.
11425 for (Methods::const_iterator p = tmp_methods.begin();
11426 p != tmp_methods.end();
11427 ++p)
11428 {
11429 bool found = false;
11430 for (Struct_field_list::const_iterator fp = fields->begin();
11431 fp != fields->end();
11432 ++fp)
11433 {
11434 if (fp->field_name() == p->first)
11435 {
11436 found = true;
11437 break;
11438 }
11439 }
11440 if (!found &&
11441 !methods->insert(p->first, p->second))
11442 delete p->second;
11443 }
11444 }
11445 }
11446
11447 // If TYPE is an interface type, then add its method to *METHODS.
11448 // This is for interface methods attached to an anonymous field. The
11449 // parameters are as for add_methods_for_type.
11450
11451 void
11452 Type::add_interface_methods_for_type(const Type* type,
11453 const Method::Field_indexes* field_indexes,
11454 unsigned int depth,
11455 Methods* methods)
11456 {
11457 const Interface_type* it = type->interface_type();
11458 if (it == NULL)
11459 return;
11460
11461 const Typed_identifier_list* imethods = it->methods();
11462 if (imethods == NULL)
11463 return;
11464
11465 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11466 pm != imethods->end();
11467 ++pm)
11468 {
11469 Function_type* fntype = pm->type()->function_type();
11470 if (fntype == NULL)
11471 {
11472 // This is an error, but it should be reported elsewhere
11473 // when we look at the methods for IT.
11474 continue;
11475 }
11476 go_assert(!fntype->is_method());
11477 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11478 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11479 field_indexes, depth);
11480 if (!methods->insert(pm->name(), m))
11481 delete m;
11482 }
11483 }
11484
11485 // Build stub methods for TYPE as needed. METHODS is the set of
11486 // methods for the type. A stub method may be needed when a type
11487 // inherits a method from an anonymous field. When we need the
11488 // address of the method, as in a type descriptor, we need to build a
11489 // little stub which does the required field dereferences and jumps to
11490 // the real method. LOCATION is the location of the type definition.
11491
11492 void
11493 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11494 Location location)
11495 {
11496 if (methods == NULL)
11497 return;
11498 for (Methods::const_iterator p = methods->begin();
11499 p != methods->end();
11500 ++p)
11501 {
11502 Method* m = p->second;
11503 if (m->is_ambiguous() || !m->needs_stub_method())
11504 continue;
11505
11506 const std::string& name(p->first);
11507
11508 // Build a stub method.
11509
11510 const Function_type* fntype = m->type();
11511
11512 static unsigned int counter;
11513 char buf[100];
11514 snprintf(buf, sizeof buf, "$this%u", counter);
11515 ++counter;
11516
11517 Type* receiver_type = const_cast<Type*>(type);
11518 if (!m->is_value_method())
11519 receiver_type = Type::make_pointer_type(receiver_type);
11520 Location receiver_location = m->receiver_location();
11521 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11522 receiver_location);
11523
11524 const Typed_identifier_list* fnparams = fntype->parameters();
11525 Typed_identifier_list* stub_params;
11526 if (fnparams == NULL || fnparams->empty())
11527 stub_params = NULL;
11528 else
11529 {
11530 // We give each stub parameter a unique name.
11531 stub_params = new Typed_identifier_list();
11532 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11533 pp != fnparams->end();
11534 ++pp)
11535 {
11536 char pbuf[100];
11537 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11538 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11539 pp->location()));
11540 ++counter;
11541 }
11542 }
11543
11544 const Typed_identifier_list* fnresults = fntype->results();
11545 Typed_identifier_list* stub_results;
11546 if (fnresults == NULL || fnresults->empty())
11547 stub_results = NULL;
11548 else
11549 {
11550 // We create the result parameters without any names, since
11551 // we won't refer to them.
11552 stub_results = new Typed_identifier_list();
11553 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11554 pr != fnresults->end();
11555 ++pr)
11556 stub_results->push_back(Typed_identifier("", pr->type(),
11557 pr->location()));
11558 }
11559
11560 Function_type* stub_type = Type::make_function_type(receiver,
11561 stub_params,
11562 stub_results,
11563 fntype->location());
11564 if (fntype->is_varargs())
11565 stub_type->set_is_varargs();
11566
11567 // We only create the function in the package which creates the
11568 // type.
11569 const Package* package;
11570 if (type->named_type() == NULL)
11571 package = NULL;
11572 else
11573 package = type->named_type()->named_object()->package();
11574 std::string stub_name = gogo->stub_method_name(package, name);
11575 Named_object* stub;
11576 if (package != NULL)
11577 stub = Named_object::make_function_declaration(stub_name, package,
11578 stub_type, location);
11579 else
11580 {
11581 stub = gogo->start_function(stub_name, stub_type, false,
11582 fntype->location());
11583 Type::build_one_stub_method(gogo, m, buf, stub_params,
11584 fntype->is_varargs(), location);
11585 gogo->finish_function(fntype->location());
11586
11587 if (type->named_type() == NULL && stub->is_function())
11588 stub->func_value()->set_is_unnamed_type_stub_method();
11589 if (m->nointerface() && stub->is_function())
11590 stub->func_value()->set_nointerface();
11591 }
11592
11593 m->set_stub_object(stub);
11594 }
11595 }
11596
11597 // Build a stub method which adjusts the receiver as required to call
11598 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11599 // PARAMS is the list of function parameters.
11600
11601 void
11602 Type::build_one_stub_method(Gogo* gogo, Method* method,
11603 const char* receiver_name,
11604 const Typed_identifier_list* params,
11605 bool is_varargs,
11606 Location location)
11607 {
11608 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11609 go_assert(receiver_object != NULL);
11610
11611 Expression* expr = Expression::make_var_reference(receiver_object, location);
11612 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11613 if (expr->type()->points_to() == NULL)
11614 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11615
11616 Expression_list* arguments;
11617 if (params == NULL || params->empty())
11618 arguments = NULL;
11619 else
11620 {
11621 arguments = new Expression_list();
11622 for (Typed_identifier_list::const_iterator p = params->begin();
11623 p != params->end();
11624 ++p)
11625 {
11626 Named_object* param = gogo->lookup(p->name(), NULL);
11627 go_assert(param != NULL);
11628 Expression* param_ref = Expression::make_var_reference(param,
11629 location);
11630 arguments->push_back(param_ref);
11631 }
11632 }
11633
11634 Expression* func = method->bind_method(expr, location);
11635 go_assert(func != NULL);
11636 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11637 location);
11638
11639 gogo->add_statement(Statement::make_return_from_call(call, location));
11640 }
11641
11642 // Build direct interface stub methods for TYPE as needed. METHODS
11643 // is the set of methods for the type. LOCATION is the location of
11644 // the type definition.
11645 //
11646 // This is for an interface holding a pointer to the type and invoking
11647 // a value method. The interface data is the pointer, and is passed
11648 // to the stub, which dereferences it and passes to the actual method.
11649
11650 void
11651 Type::build_direct_iface_stub_methods(Gogo* gogo, const Type* type,
11652 Methods* methods, Location loc)
11653 {
11654 if (methods == NULL)
11655 return;
11656
11657 for (Methods::const_iterator p = methods->begin();
11658 p != methods->end();
11659 ++p)
11660 {
11661 Method* m = p->second;
11662 if (!m->is_value_method())
11663 continue;
11664
11665 Type* receiver_type = const_cast<Type*>(type);
11666 receiver_type = Type::make_pointer_type(receiver_type);
11667 const std::string& name(p->first);
11668 Function_type* fntype = m->type();
11669
11670 static unsigned int counter;
11671 char buf[100];
11672 snprintf(buf, sizeof buf, "$ptr%u", counter);
11673 ++counter;
11674 Typed_identifier* receiver =
11675 new Typed_identifier(buf, receiver_type, m->receiver_location());
11676
11677 const Typed_identifier_list* params = fntype->parameters();
11678 Typed_identifier_list* stub_params;
11679 if (params == NULL || params->empty())
11680 stub_params = NULL;
11681 else
11682 {
11683 // We give each stub parameter a unique name.
11684 stub_params = new Typed_identifier_list();
11685 for (Typed_identifier_list::const_iterator pp = params->begin();
11686 pp != params->end();
11687 ++pp)
11688 {
11689 char pbuf[100];
11690 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11691 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11692 pp->location()));
11693 ++counter;
11694 }
11695 }
11696
11697 const Typed_identifier_list* fnresults = fntype->results();
11698 Typed_identifier_list* stub_results;
11699 if (fnresults == NULL || fnresults->empty())
11700 stub_results = NULL;
11701 else
11702 {
11703 // We create the result parameters without any names, since
11704 // we won't refer to them.
11705 stub_results = new Typed_identifier_list();
11706 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11707 pr != fnresults->end();
11708 ++pr)
11709 stub_results->push_back(Typed_identifier("", pr->type(),
11710 pr->location()));
11711 }
11712
11713 Function_type* stub_type = Type::make_function_type(receiver,
11714 stub_params,
11715 stub_results,
11716 fntype->location());
11717 if (fntype->is_varargs())
11718 stub_type->set_is_varargs();
11719
11720 // We only create the function in the package which creates the
11721 // type.
11722 const Package* package;
11723 if (type->named_type() == NULL)
11724 package = NULL;
11725 else
11726 package = type->named_type()->named_object()->package();
11727
11728 std::string stub_name = gogo->stub_method_name(package, name) + "2";
11729 Named_object* stub;
11730 if (package != NULL)
11731 stub = Named_object::make_function_declaration(stub_name, package,
11732 stub_type, loc);
11733 else
11734 {
11735 stub = gogo->start_function(stub_name, stub_type, false,
11736 fntype->location());
11737 Type::build_one_iface_stub_method(gogo, m, buf, stub_params,
11738 fntype->is_varargs(), loc);
11739 gogo->finish_function(fntype->location());
11740
11741 if (type->named_type() == NULL && stub->is_function())
11742 stub->func_value()->set_is_unnamed_type_stub_method();
11743 if (m->nointerface() && stub->is_function())
11744 stub->func_value()->set_nointerface();
11745 }
11746
11747 m->set_iface_stub_object(stub);
11748 }
11749 }
11750
11751 // Build a stub method for METHOD of direct interface type T.
11752 // RECEIVER_NAME is the name we used for the receiver.
11753 // PARAMS is the list of function parameters.
11754 //
11755 // The stub looks like
11756 //
11757 // func ($ptr *T, PARAMS) {
11758 // (*$ptr).METHOD(PARAMS)
11759 // }
11760
11761 void
11762 Type::build_one_iface_stub_method(Gogo* gogo, Method* method,
11763 const char* receiver_name,
11764 const Typed_identifier_list* params,
11765 bool is_varargs, Location loc)
11766 {
11767 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11768 go_assert(receiver_object != NULL);
11769
11770 Expression* expr = Expression::make_var_reference(receiver_object, loc);
11771 expr = Expression::make_dereference(expr,
11772 Expression::NIL_CHECK_DEFAULT,
11773 loc);
11774
11775 Expression_list* arguments;
11776 if (params == NULL || params->empty())
11777 arguments = NULL;
11778 else
11779 {
11780 arguments = new Expression_list();
11781 for (Typed_identifier_list::const_iterator p = params->begin();
11782 p != params->end();
11783 ++p)
11784 {
11785 Named_object* param = gogo->lookup(p->name(), NULL);
11786 go_assert(param != NULL);
11787 Expression* param_ref = Expression::make_var_reference(param,
11788 loc);
11789 arguments->push_back(param_ref);
11790 }
11791 }
11792
11793 Expression* func = method->bind_method(expr, loc);
11794 go_assert(func != NULL);
11795 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11796 loc);
11797
11798 gogo->add_statement(Statement::make_return_from_call(call, loc));
11799 }
11800
11801 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11802 // in reverse order.
11803
11804 Expression*
11805 Type::apply_field_indexes(Expression* expr,
11806 const Method::Field_indexes* field_indexes,
11807 Location location)
11808 {
11809 if (field_indexes == NULL)
11810 return expr;
11811 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11812 Struct_type* stype = expr->type()->deref()->struct_type();
11813 go_assert(stype != NULL
11814 && field_indexes->field_index < stype->field_count());
11815 if (expr->type()->struct_type() == NULL)
11816 {
11817 go_assert(expr->type()->points_to() != NULL);
11818 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11819 location);
11820 go_assert(expr->type()->struct_type() == stype);
11821 }
11822 return Expression::make_field_reference(expr, field_indexes->field_index,
11823 location);
11824 }
11825
11826 // Return whether NO is a method for which the receiver is a pointer.
11827
11828 bool
11829 Type::method_expects_pointer(const Named_object* no)
11830 {
11831 const Function_type *fntype;
11832 if (no->is_function())
11833 fntype = no->func_value()->type();
11834 else if (no->is_function_declaration())
11835 fntype = no->func_declaration_value()->type();
11836 else
11837 go_unreachable();
11838 return fntype->receiver()->type()->points_to() != NULL;
11839 }
11840
11841 // Given a set of methods for a type, METHODS, return the method NAME,
11842 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11843 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11844 // but is ambiguous (and return NULL).
11845
11846 Method*
11847 Type::method_function(const Methods* methods, const std::string& name,
11848 bool* is_ambiguous)
11849 {
11850 if (is_ambiguous != NULL)
11851 *is_ambiguous = false;
11852 if (methods == NULL)
11853 return NULL;
11854 Methods::const_iterator p = methods->find(name);
11855 if (p == methods->end())
11856 return NULL;
11857 Method* m = p->second;
11858 if (m->is_ambiguous())
11859 {
11860 if (is_ambiguous != NULL)
11861 *is_ambiguous = true;
11862 return NULL;
11863 }
11864 return m;
11865 }
11866
11867 // Return a pointer to the interface method table for TYPE for the
11868 // interface INTERFACE.
11869
11870 Expression*
11871 Type::interface_method_table(Type* type,
11872 Interface_type *interface,
11873 bool is_pointer,
11874 Interface_method_tables** method_tables,
11875 Interface_method_tables** pointer_tables)
11876 {
11877 go_assert(!interface->is_empty());
11878
11879 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11880
11881 if (*pimt == NULL)
11882 *pimt = new Interface_method_tables(5);
11883
11884 std::pair<Interface_type*, Expression*> val(interface, NULL);
11885 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11886
11887 Location loc = Linemap::predeclared_location();
11888 if (ins.second)
11889 {
11890 // This is a new entry in the hash table.
11891 go_assert(ins.first->second == NULL);
11892 ins.first->second =
11893 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11894 }
11895 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11896 }
11897
11898 // Look for field or method NAME for TYPE. Return an Expression for
11899 // the field or method bound to EXPR. If there is no such field or
11900 // method, give an appropriate error and return an error expression.
11901
11902 Expression*
11903 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11904 const std::string& name,
11905 Location location)
11906 {
11907 if (type->deref()->is_error_type())
11908 return Expression::make_error(location);
11909
11910 const Named_type* nt = type->deref()->named_type();
11911 const Struct_type* st = type->deref()->struct_type();
11912 const Interface_type* it = type->interface_type();
11913
11914 // If this is a pointer to a pointer, then it is possible that the
11915 // pointed-to type has methods.
11916 bool dereferenced = false;
11917 if (nt == NULL
11918 && st == NULL
11919 && it == NULL
11920 && type->points_to() != NULL
11921 && type->points_to()->points_to() != NULL)
11922 {
11923 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11924 location);
11925 type = type->points_to();
11926 if (type->deref()->is_error_type())
11927 return Expression::make_error(location);
11928 nt = type->points_to()->named_type();
11929 st = type->points_to()->struct_type();
11930 dereferenced = true;
11931 }
11932
11933 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11934 || expr->is_addressable());
11935 std::vector<const Named_type*> seen;
11936 bool is_method = false;
11937 bool found_pointer_method = false;
11938 std::string ambig1;
11939 std::string ambig2;
11940 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11941 &seen, NULL, &is_method,
11942 &found_pointer_method, &ambig1, &ambig2))
11943 {
11944 Expression* ret;
11945 if (!is_method)
11946 {
11947 go_assert(st != NULL);
11948 if (type->struct_type() == NULL)
11949 {
11950 if (dereferenced)
11951 {
11952 go_error_at(location, "pointer type has no field %qs",
11953 Gogo::message_name(name).c_str());
11954 return Expression::make_error(location);
11955 }
11956 go_assert(type->points_to() != NULL);
11957 expr = Expression::make_dereference(expr,
11958 Expression::NIL_CHECK_DEFAULT,
11959 location);
11960 go_assert(expr->type()->struct_type() == st);
11961 }
11962 ret = st->field_reference(expr, name, location);
11963 if (ret == NULL)
11964 {
11965 go_error_at(location, "type has no field %qs",
11966 Gogo::message_name(name).c_str());
11967 return Expression::make_error(location);
11968 }
11969 }
11970 else if (it != NULL && it->find_method(name) != NULL)
11971 ret = Expression::make_interface_field_reference(expr, name,
11972 location);
11973 else
11974 {
11975 Method* m;
11976 if (nt != NULL)
11977 m = nt->method_function(name, NULL);
11978 else if (st != NULL)
11979 m = st->method_function(name, NULL);
11980 else
11981 go_unreachable();
11982 go_assert(m != NULL);
11983 if (dereferenced)
11984 {
11985 go_error_at(location,
11986 "calling method %qs requires explicit dereference",
11987 Gogo::message_name(name).c_str());
11988 return Expression::make_error(location);
11989 }
11990 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11991 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11992 ret = m->bind_method(expr, location);
11993 }
11994 go_assert(ret != NULL);
11995 return ret;
11996 }
11997 else
11998 {
11999 if (Gogo::is_erroneous_name(name))
12000 {
12001 // An error was already reported.
12002 }
12003 else if (!ambig1.empty())
12004 go_error_at(location, "%qs is ambiguous via %qs and %qs",
12005 Gogo::message_name(name).c_str(), ambig1.c_str(),
12006 ambig2.c_str());
12007 else if (found_pointer_method)
12008 go_error_at(location, "method requires a pointer receiver");
12009 else if (nt == NULL && st == NULL && it == NULL)
12010 go_error_at(location,
12011 ("reference to field %qs in object which "
12012 "has no fields or methods"),
12013 Gogo::message_name(name).c_str());
12014 else
12015 {
12016 bool is_unexported;
12017 // The test for 'a' and 'z' is to handle builtin names,
12018 // which are not hidden.
12019 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
12020 is_unexported = false;
12021 else
12022 {
12023 std::string unpacked = Gogo::unpack_hidden_name(name);
12024 seen.clear();
12025 is_unexported = Type::is_unexported_field_or_method(gogo, type,
12026 unpacked,
12027 &seen);
12028 }
12029 if (is_unexported)
12030 go_error_at(location, "reference to unexported field or method %qs",
12031 Gogo::message_name(name).c_str());
12032 else
12033 go_error_at(location, "reference to undefined field or method %qs",
12034 Gogo::message_name(name).c_str());
12035 }
12036 return Expression::make_error(location);
12037 }
12038 }
12039
12040 // Look in TYPE for a field or method named NAME, return true if one
12041 // is found. This looks through embedded anonymous fields and handles
12042 // ambiguity. If a method is found, sets *IS_METHOD to true;
12043 // otherwise, if a field is found, set it to false. If
12044 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
12045 // whose address can not be taken. SEEN is used to avoid infinite
12046 // recursion on invalid types.
12047
12048 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
12049 // method we couldn't use because it requires a pointer. LEVEL is
12050 // used for recursive calls, and can be NULL for a non-recursive call.
12051 // When this function returns false because it finds that the name is
12052 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
12053 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
12054 // will be unchanged.
12055
12056 // This function just returns whether or not there is a field or
12057 // method, and whether it is a field or method. It doesn't build an
12058 // expression to refer to it. If it is a method, we then look in the
12059 // list of all methods for the type. If it is a field, the search has
12060 // to be done again, looking only for fields, and building up the
12061 // expression as we go.
12062
12063 bool
12064 Type::find_field_or_method(const Type* type,
12065 const std::string& name,
12066 bool receiver_can_be_pointer,
12067 std::vector<const Named_type*>* seen,
12068 int* level,
12069 bool* is_method,
12070 bool* found_pointer_method,
12071 std::string* ambig1,
12072 std::string* ambig2)
12073 {
12074 // Named types can have locally defined methods.
12075 const Named_type* nt = type->unalias()->named_type();
12076 if (nt == NULL && type->points_to() != NULL)
12077 nt = type->points_to()->unalias()->named_type();
12078 if (nt != NULL)
12079 {
12080 Named_object* no = nt->find_local_method(name);
12081 if (no != NULL)
12082 {
12083 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
12084 {
12085 *is_method = true;
12086 return true;
12087 }
12088
12089 // Record that we have found a pointer method in order to
12090 // give a better error message if we don't find anything
12091 // else.
12092 *found_pointer_method = true;
12093 }
12094
12095 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12096 p != seen->end();
12097 ++p)
12098 {
12099 if (*p == nt)
12100 {
12101 // We've already seen this type when searching for methods.
12102 return false;
12103 }
12104 }
12105 }
12106
12107 // Interface types can have methods.
12108 const Interface_type* it = type->interface_type();
12109 if (it != NULL && it->find_method(name) != NULL)
12110 {
12111 *is_method = true;
12112 return true;
12113 }
12114
12115 // Struct types can have fields. They can also inherit fields and
12116 // methods from anonymous fields.
12117 const Struct_type* st = type->deref()->struct_type();
12118 if (st == NULL)
12119 return false;
12120 const Struct_field_list* fields = st->fields();
12121 if (fields == NULL)
12122 return false;
12123
12124 if (nt != NULL)
12125 seen->push_back(nt);
12126
12127 int found_level = 0;
12128 bool found_is_method = false;
12129 std::string found_ambig1;
12130 std::string found_ambig2;
12131 const Struct_field* found_parent = NULL;
12132 for (Struct_field_list::const_iterator pf = fields->begin();
12133 pf != fields->end();
12134 ++pf)
12135 {
12136 if (pf->is_field_name(name))
12137 {
12138 *is_method = false;
12139 if (nt != NULL)
12140 seen->pop_back();
12141 return true;
12142 }
12143
12144 if (!pf->is_anonymous())
12145 continue;
12146
12147 if (pf->type()->deref()->is_error_type()
12148 || pf->type()->deref()->is_undefined())
12149 continue;
12150
12151 Named_type* fnt = pf->type()->named_type();
12152 if (fnt == NULL)
12153 fnt = pf->type()->deref()->named_type();
12154 go_assert(fnt != NULL);
12155
12156 // Methods with pointer receivers on embedded field are
12157 // inherited by the pointer to struct, and also by the struct
12158 // type if the field itself is a pointer.
12159 bool can_be_pointer = (receiver_can_be_pointer
12160 || pf->type()->points_to() != NULL);
12161 int sublevel = level == NULL ? 1 : *level + 1;
12162 bool sub_is_method;
12163 std::string subambig1;
12164 std::string subambig2;
12165 bool subfound = Type::find_field_or_method(fnt,
12166 name,
12167 can_be_pointer,
12168 seen,
12169 &sublevel,
12170 &sub_is_method,
12171 found_pointer_method,
12172 &subambig1,
12173 &subambig2);
12174 if (!subfound)
12175 {
12176 if (!subambig1.empty())
12177 {
12178 // The name was found via this field, but is ambiguous.
12179 // if the ambiguity is lower or at the same level as
12180 // anything else we have already found, then we want to
12181 // pass the ambiguity back to the caller.
12182 if (found_level == 0 || sublevel <= found_level)
12183 {
12184 found_ambig1 = (Gogo::message_name(pf->field_name())
12185 + '.' + subambig1);
12186 found_ambig2 = (Gogo::message_name(pf->field_name())
12187 + '.' + subambig2);
12188 found_level = sublevel;
12189 }
12190 }
12191 }
12192 else
12193 {
12194 // The name was found via this field. Use the level to see
12195 // if we want to use this one, or whether it introduces an
12196 // ambiguity.
12197 if (found_level == 0 || sublevel < found_level)
12198 {
12199 found_level = sublevel;
12200 found_is_method = sub_is_method;
12201 found_ambig1.clear();
12202 found_ambig2.clear();
12203 found_parent = &*pf;
12204 }
12205 else if (sublevel > found_level)
12206 ;
12207 else if (found_ambig1.empty())
12208 {
12209 // We found an ambiguity.
12210 go_assert(found_parent != NULL);
12211 found_ambig1 = Gogo::message_name(found_parent->field_name());
12212 found_ambig2 = Gogo::message_name(pf->field_name());
12213 }
12214 else
12215 {
12216 // We found an ambiguity, but we already know of one.
12217 // Just report the earlier one.
12218 }
12219 }
12220 }
12221
12222 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
12223 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
12224 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
12225 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
12226
12227 if (nt != NULL)
12228 seen->pop_back();
12229
12230 if (found_level == 0)
12231 return false;
12232 else if (found_is_method
12233 && type->named_type() != NULL
12234 && type->points_to() != NULL)
12235 {
12236 // If this is a method inherited from a struct field in a named pointer
12237 // type, it is invalid to automatically dereference the pointer to the
12238 // struct to find this method.
12239 if (level != NULL)
12240 *level = found_level;
12241 *is_method = true;
12242 return false;
12243 }
12244 else if (!found_ambig1.empty())
12245 {
12246 go_assert(!found_ambig1.empty());
12247 ambig1->assign(found_ambig1);
12248 ambig2->assign(found_ambig2);
12249 if (level != NULL)
12250 *level = found_level;
12251 return false;
12252 }
12253 else
12254 {
12255 if (level != NULL)
12256 *level = found_level;
12257 *is_method = found_is_method;
12258 return true;
12259 }
12260 }
12261
12262 // Return whether NAME is an unexported field or method for TYPE.
12263
12264 bool
12265 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
12266 const std::string& name,
12267 std::vector<const Named_type*>* seen)
12268 {
12269 const Named_type* nt = type->named_type();
12270 if (nt == NULL)
12271 nt = type->deref()->named_type();
12272 if (nt != NULL)
12273 {
12274 if (nt->is_unexported_local_method(gogo, name))
12275 return true;
12276
12277 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12278 p != seen->end();
12279 ++p)
12280 {
12281 if (*p == nt)
12282 {
12283 // We've already seen this type.
12284 return false;
12285 }
12286 }
12287 }
12288
12289 const Interface_type* it = type->interface_type();
12290 if (it != NULL && it->is_unexported_method(gogo, name))
12291 return true;
12292
12293 type = type->deref();
12294
12295 const Struct_type* st = type->struct_type();
12296 if (st != NULL && st->is_unexported_local_field(gogo, name))
12297 return true;
12298
12299 if (st == NULL)
12300 return false;
12301
12302 const Struct_field_list* fields = st->fields();
12303 if (fields == NULL)
12304 return false;
12305
12306 if (nt != NULL)
12307 seen->push_back(nt);
12308
12309 for (Struct_field_list::const_iterator pf = fields->begin();
12310 pf != fields->end();
12311 ++pf)
12312 {
12313 if (pf->is_anonymous()
12314 && !pf->type()->deref()->is_error_type()
12315 && !pf->type()->deref()->is_undefined())
12316 {
12317 Named_type* subtype = pf->type()->named_type();
12318 if (subtype == NULL)
12319 subtype = pf->type()->deref()->named_type();
12320 if (subtype == NULL)
12321 {
12322 // This is an error, but it will be diagnosed elsewhere.
12323 continue;
12324 }
12325 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
12326 {
12327 if (nt != NULL)
12328 seen->pop_back();
12329 return true;
12330 }
12331 }
12332 }
12333
12334 if (nt != NULL)
12335 seen->pop_back();
12336
12337 return false;
12338 }
12339
12340 // Class Forward_declaration.
12341
12342 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
12343 : Type(TYPE_FORWARD),
12344 named_object_(named_object->resolve()), warned_(false)
12345 {
12346 go_assert(this->named_object_->is_unknown()
12347 || this->named_object_->is_type_declaration());
12348 }
12349
12350 // Return the named object.
12351
12352 Named_object*
12353 Forward_declaration_type::named_object()
12354 {
12355 return this->named_object_->resolve();
12356 }
12357
12358 const Named_object*
12359 Forward_declaration_type::named_object() const
12360 {
12361 return this->named_object_->resolve();
12362 }
12363
12364 // Return the name of the forward declared type.
12365
12366 const std::string&
12367 Forward_declaration_type::name() const
12368 {
12369 return this->named_object()->name();
12370 }
12371
12372 // Warn about a use of a type which has been declared but not defined.
12373
12374 void
12375 Forward_declaration_type::warn() const
12376 {
12377 Named_object* no = this->named_object_->resolve();
12378 if (no->is_unknown())
12379 {
12380 // The name was not defined anywhere.
12381 if (!this->warned_)
12382 {
12383 go_error_at(this->named_object_->location(),
12384 "use of undefined type %qs",
12385 no->message_name().c_str());
12386 this->warned_ = true;
12387 }
12388 }
12389 else if (no->is_type_declaration())
12390 {
12391 // The name was seen as a type, but the type was never defined.
12392 if (no->type_declaration_value()->using_type())
12393 {
12394 go_error_at(this->named_object_->location(),
12395 "use of undefined type %qs",
12396 no->message_name().c_str());
12397 this->warned_ = true;
12398 }
12399 }
12400 else
12401 {
12402 // The name was defined, but not as a type.
12403 if (!this->warned_)
12404 {
12405 go_error_at(this->named_object_->location(), "expected type");
12406 this->warned_ = true;
12407 }
12408 }
12409 }
12410
12411 // Get the base type of a declaration. This gives an error if the
12412 // type has not yet been defined.
12413
12414 Type*
12415 Forward_declaration_type::real_type()
12416 {
12417 if (this->is_defined())
12418 {
12419 Named_type* nt = this->named_object()->type_value();
12420 if (!nt->is_valid())
12421 return Type::make_error_type();
12422 return this->named_object()->type_value();
12423 }
12424 else
12425 {
12426 this->warn();
12427 return Type::make_error_type();
12428 }
12429 }
12430
12431 const Type*
12432 Forward_declaration_type::real_type() const
12433 {
12434 if (this->is_defined())
12435 {
12436 const Named_type* nt = this->named_object()->type_value();
12437 if (!nt->is_valid())
12438 return Type::make_error_type();
12439 return this->named_object()->type_value();
12440 }
12441 else
12442 {
12443 this->warn();
12444 return Type::make_error_type();
12445 }
12446 }
12447
12448 // Return whether the base type is defined.
12449
12450 bool
12451 Forward_declaration_type::is_defined() const
12452 {
12453 return this->named_object()->is_type();
12454 }
12455
12456 // Add a method. This is used when methods are defined before the
12457 // type.
12458
12459 Named_object*
12460 Forward_declaration_type::add_method(const std::string& name,
12461 Function* function)
12462 {
12463 Named_object* no = this->named_object();
12464 if (no->is_unknown())
12465 no->declare_as_type();
12466 return no->type_declaration_value()->add_method(name, function);
12467 }
12468
12469 // Add a method declaration. This is used when methods are declared
12470 // before the type.
12471
12472 Named_object*
12473 Forward_declaration_type::add_method_declaration(const std::string& name,
12474 Package* package,
12475 Function_type* type,
12476 Location location)
12477 {
12478 Named_object* no = this->named_object();
12479 if (no->is_unknown())
12480 no->declare_as_type();
12481 Type_declaration* td = no->type_declaration_value();
12482 return td->add_method_declaration(name, package, type, location);
12483 }
12484
12485 // Add an already created object as a method.
12486
12487 void
12488 Forward_declaration_type::add_existing_method(Named_object* nom)
12489 {
12490 Named_object* no = this->named_object();
12491 if (no->is_unknown())
12492 no->declare_as_type();
12493 no->type_declaration_value()->add_existing_method(nom);
12494 }
12495
12496 // Traversal.
12497
12498 int
12499 Forward_declaration_type::do_traverse(Traverse* traverse)
12500 {
12501 if (this->is_defined()
12502 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12503 return TRAVERSE_EXIT;
12504 return TRAVERSE_CONTINUE;
12505 }
12506
12507 // Verify the type.
12508
12509 bool
12510 Forward_declaration_type::do_verify()
12511 {
12512 if (!this->is_defined() && !this->is_nil_constant_as_type())
12513 {
12514 this->warn();
12515 return false;
12516 }
12517 return true;
12518 }
12519
12520 // Get the backend representation for the type.
12521
12522 Btype*
12523 Forward_declaration_type::do_get_backend(Gogo* gogo)
12524 {
12525 if (this->is_defined())
12526 return Type::get_named_base_btype(gogo, this->real_type());
12527
12528 if (this->warned_)
12529 return gogo->backend()->error_type();
12530
12531 // We represent an undefined type as a struct with no fields. That
12532 // should work fine for the backend, since the same case can arise
12533 // in C.
12534 std::vector<Backend::Btyped_identifier> fields;
12535 Btype* bt = gogo->backend()->struct_type(fields);
12536 return gogo->backend()->named_type(this->name(), bt,
12537 this->named_object()->location());
12538 }
12539
12540 // Build a type descriptor for a forwarded type.
12541
12542 Expression*
12543 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12544 {
12545 Location ploc = Linemap::predeclared_location();
12546 if (!this->is_defined())
12547 return Expression::make_error(ploc);
12548 else
12549 {
12550 Type* t = this->real_type();
12551 if (name != NULL)
12552 return this->named_type_descriptor(gogo, t, name);
12553 else
12554 return Expression::make_error(this->named_object_->location());
12555 }
12556 }
12557
12558 // The reflection string.
12559
12560 void
12561 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12562 {
12563 this->append_reflection(this->real_type(), gogo, ret);
12564 }
12565
12566 // Export a forward declaration. This can happen when a defined type
12567 // refers to a type which is only declared (and is presumably defined
12568 // in some other file in the same package).
12569
12570 void
12571 Forward_declaration_type::do_export(Export*) const
12572 {
12573 // If there is a base type, that should be exported instead of this.
12574 go_assert(!this->is_defined());
12575
12576 // We don't output anything.
12577 }
12578
12579 // Make a forward declaration.
12580
12581 Type*
12582 Type::make_forward_declaration(Named_object* named_object)
12583 {
12584 return new Forward_declaration_type(named_object);
12585 }
12586
12587 // Class Typed_identifier_list.
12588
12589 // Sort the entries by name.
12590
12591 struct Typed_identifier_list_sort
12592 {
12593 public:
12594 bool
12595 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12596 {
12597 return (Gogo::unpack_hidden_name(t1.name())
12598 < Gogo::unpack_hidden_name(t2.name()));
12599 }
12600 };
12601
12602 void
12603 Typed_identifier_list::sort_by_name()
12604 {
12605 std::sort(this->entries_.begin(), this->entries_.end(),
12606 Typed_identifier_list_sort());
12607 }
12608
12609 // Traverse types.
12610
12611 int
12612 Typed_identifier_list::traverse(Traverse* traverse) const
12613 {
12614 for (Typed_identifier_list::const_iterator p = this->begin();
12615 p != this->end();
12616 ++p)
12617 {
12618 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12619 return TRAVERSE_EXIT;
12620 }
12621 return TRAVERSE_CONTINUE;
12622 }
12623
12624 // Copy the list.
12625
12626 Typed_identifier_list*
12627 Typed_identifier_list::copy() const
12628 {
12629 Typed_identifier_list* ret = new Typed_identifier_list();
12630 for (Typed_identifier_list::const_iterator p = this->begin();
12631 p != this->end();
12632 ++p)
12633 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12634 return ret;
12635 }