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