OSDN Git Service

74bab411ac09878e3d87001bfac4fcdb5a344e31
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / types.cc
1 // types.cc -- Go frontend types.
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 #include "go-system.h"
8
9 #include <gmp.h>
10
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
13 {
14 #endif
15
16 #include "toplev.h"
17 #include "intl.h"
18 #include "tree.h"
19 #include "gimple.h"
20 #include "real.h"
21 #include "convert.h"
22
23 #ifndef ENABLE_BUILD_WITH_CXX
24 }
25 #endif
26
27 #include "go-c.h"
28 #include "gogo.h"
29 #include "operator.h"
30 #include "expressions.h"
31 #include "statements.h"
32 #include "export.h"
33 #include "import.h"
34 #include "backend.h"
35 #include "types.h"
36
37 // Forward declarations so that we don't have to make types.h #include
38 // backend.h.
39
40 static void
41 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
42                           bool use_placeholder,
43                           std::vector<Backend::Btyped_identifier>* bfields);
44
45 static void
46 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
47                          std::vector<Backend::Btyped_identifier>* bfields);
48
49 static void
50 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
51                              bool use_placeholder,
52                              std::vector<Backend::Btyped_identifier>* bfields);
53
54 // Class Type.
55
56 Type::Type(Type_classification classification)
57   : classification_(classification), btype_is_placeholder_(false),
58     btype_(NULL), type_descriptor_var_(NULL)
59 {
60 }
61
62 Type::~Type()
63 {
64 }
65
66 // Get the base type for a type--skip names and forward declarations.
67
68 Type*
69 Type::base()
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 const Type*
83 Type::base() const
84 {
85   switch (this->classification_)
86     {
87     case TYPE_NAMED:
88       return this->named_type()->named_base();
89     case TYPE_FORWARD:
90       return this->forward_declaration_type()->real_type()->base();
91     default:
92       return this;
93     }
94 }
95
96 // Skip defined forward declarations.
97
98 Type*
99 Type::forwarded()
100 {
101   Type* t = this;
102   Forward_declaration_type* ftype = t->forward_declaration_type();
103   while (ftype != NULL && ftype->is_defined())
104     {
105       t = ftype->real_type();
106       ftype = t->forward_declaration_type();
107     }
108   return t;
109 }
110
111 const Type*
112 Type::forwarded() const
113 {
114   const Type* t = this;
115   const Forward_declaration_type* ftype = t->forward_declaration_type();
116   while (ftype != NULL && ftype->is_defined())
117     {
118       t = ftype->real_type();
119       ftype = t->forward_declaration_type();
120     }
121   return t;
122 }
123
124 // If this is a named type, return it.  Otherwise, return NULL.
125
126 Named_type*
127 Type::named_type()
128 {
129   return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
130 }
131
132 const Named_type*
133 Type::named_type() const
134 {
135   return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
136 }
137
138 // Return true if this type is not defined.
139
140 bool
141 Type::is_undefined() const
142 {
143   return this->forwarded()->forward_declaration_type() != NULL;
144 }
145
146 // Return true if this is a basic type: a type which is not composed
147 // of other types, and is not void.
148
149 bool
150 Type::is_basic_type() const
151 {
152   switch (this->classification_)
153     {
154     case TYPE_INTEGER:
155     case TYPE_FLOAT:
156     case TYPE_COMPLEX:
157     case TYPE_BOOLEAN:
158     case TYPE_STRING:
159     case TYPE_NIL:
160       return true;
161
162     case TYPE_ERROR:
163     case TYPE_VOID:
164     case TYPE_FUNCTION:
165     case TYPE_POINTER:
166     case TYPE_STRUCT:
167     case TYPE_ARRAY:
168     case TYPE_MAP:
169     case TYPE_CHANNEL:
170     case TYPE_INTERFACE:
171       return false;
172
173     case TYPE_NAMED:
174     case TYPE_FORWARD:
175       return this->base()->is_basic_type();
176
177     default:
178       go_unreachable();
179     }
180 }
181
182 // Return true if this is an abstract type.
183
184 bool
185 Type::is_abstract() const
186 {
187   switch (this->classification())
188     {
189     case TYPE_INTEGER:
190       return this->integer_type()->is_abstract();
191     case TYPE_FLOAT:
192       return this->float_type()->is_abstract();
193     case TYPE_COMPLEX:
194       return this->complex_type()->is_abstract();
195     case TYPE_STRING:
196       return this->is_abstract_string_type();
197     case TYPE_BOOLEAN:
198       return this->is_abstract_boolean_type();
199     default:
200       return false;
201     }
202 }
203
204 // Return a non-abstract version of an abstract type.
205
206 Type*
207 Type::make_non_abstract_type()
208 {
209   go_assert(this->is_abstract());
210   switch (this->classification())
211     {
212     case TYPE_INTEGER:
213       if (this->integer_type()->is_rune())
214         return Type::lookup_integer_type("int32");
215       else
216         return Type::lookup_integer_type("int");
217     case TYPE_FLOAT:
218       return Type::lookup_float_type("float64");
219     case TYPE_COMPLEX:
220       return Type::lookup_complex_type("complex128");
221     case TYPE_STRING:
222       return Type::lookup_string_type();
223     case TYPE_BOOLEAN:
224       return Type::lookup_bool_type();
225     default:
226       go_unreachable();
227     }
228 }
229
230 // Return true if this is an error type.  Don't give an error if we
231 // try to dereference an undefined forwarding type, as this is called
232 // in the parser when the type may legitimately be undefined.
233
234 bool
235 Type::is_error_type() const
236 {
237   const Type* t = this->forwarded();
238   // Note that we return false for an undefined forward type.
239   switch (t->classification_)
240     {
241     case TYPE_ERROR:
242       return true;
243     case TYPE_NAMED:
244       return t->named_type()->is_named_error_type();
245     default:
246       return false;
247     }
248 }
249
250 // If this is a pointer type, return the type to which it points.
251 // Otherwise, return NULL.
252
253 Type*
254 Type::points_to() const
255 {
256   const Pointer_type* ptype = this->convert<const Pointer_type,
257                                             TYPE_POINTER>();
258   return ptype == NULL ? NULL : ptype->points_to();
259 }
260
261 // Return whether this is an open array type.
262
263 bool
264 Type::is_slice_type() const
265 {
266   return this->array_type() != NULL && this->array_type()->length() == NULL;
267 }
268
269 // Return whether this is the predeclared constant nil being used as a
270 // type.
271
272 bool
273 Type::is_nil_constant_as_type() const
274 {
275   const Type* t = this->forwarded();
276   if (t->forward_declaration_type() != NULL)
277     {
278       const Named_object* no = t->forward_declaration_type()->named_object();
279       if (no->is_unknown())
280         no = no->unknown_value()->real_named_object();
281       if (no != NULL
282           && no->is_const()
283           && no->const_value()->expr()->is_nil_expression())
284         return true;
285     }
286   return false;
287 }
288
289 // Traverse a type.
290
291 int
292 Type::traverse(Type* type, Traverse* traverse)
293 {
294   go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
295              || (traverse->traverse_mask()
296                  & Traverse::traverse_expressions) != 0);
297   if (traverse->remember_type(type))
298     {
299       // We have already traversed this type.
300       return TRAVERSE_CONTINUE;
301     }
302   if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
303     {
304       int t = traverse->type(type);
305       if (t == TRAVERSE_EXIT)
306         return TRAVERSE_EXIT;
307       else if (t == TRAVERSE_SKIP_COMPONENTS)
308         return TRAVERSE_CONTINUE;
309     }
310   // An array type has an expression which we need to traverse if
311   // traverse_expressions is set.
312   if (type->do_traverse(traverse) == TRAVERSE_EXIT)
313     return TRAVERSE_EXIT;
314   return TRAVERSE_CONTINUE;
315 }
316
317 // Default implementation for do_traverse for child class.
318
319 int
320 Type::do_traverse(Traverse*)
321 {
322   return TRAVERSE_CONTINUE;
323 }
324
325 // Return whether two types are identical.  If ERRORS_ARE_IDENTICAL,
326 // then return true for all erroneous types; this is used to avoid
327 // cascading errors.  If REASON is not NULL, optionally set *REASON to
328 // the reason the types are not identical.
329
330 bool
331 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
332                     std::string* reason)
333 {
334   if (t1 == NULL || t2 == NULL)
335     {
336       // Something is wrong.
337       return errors_are_identical ? true : t1 == t2;
338     }
339
340   // Skip defined forward declarations.
341   t1 = t1->forwarded();
342   t2 = t2->forwarded();
343
344   // Ignore aliases for purposes of type identity.
345   if (t1->named_type() != NULL && t1->named_type()->is_alias())
346     t1 = t1->named_type()->real_type();
347   if (t2->named_type() != NULL && t2->named_type()->is_alias())
348     t2 = t2->named_type()->real_type();
349
350   if (t1 == t2)
351     return true;
352
353   // An undefined forward declaration is an error.
354   if (t1->forward_declaration_type() != NULL
355       || t2->forward_declaration_type() != NULL)
356     return errors_are_identical;
357
358   // Avoid cascading errors with error types.
359   if (t1->is_error_type() || t2->is_error_type())
360     {
361       if (errors_are_identical)
362         return true;
363       return t1->is_error_type() && t2->is_error_type();
364     }
365
366   // Get a good reason for the sink type.  Note that the sink type on
367   // the left hand side of an assignment is handled in are_assignable.
368   if (t1->is_sink_type() || t2->is_sink_type())
369     {
370       if (reason != NULL)
371         *reason = "invalid use of _";
372       return false;
373     }
374
375   // A named type is only identical to itself.
376   if (t1->named_type() != NULL || t2->named_type() != NULL)
377     return false;
378
379   // Check type shapes.
380   if (t1->classification() != t2->classification())
381     return false;
382
383   switch (t1->classification())
384     {
385     case TYPE_VOID:
386     case TYPE_BOOLEAN:
387     case TYPE_STRING:
388     case TYPE_NIL:
389       // These types are always identical.
390       return true;
391
392     case TYPE_INTEGER:
393       return t1->integer_type()->is_identical(t2->integer_type());
394
395     case TYPE_FLOAT:
396       return t1->float_type()->is_identical(t2->float_type());
397
398     case TYPE_COMPLEX:
399       return t1->complex_type()->is_identical(t2->complex_type());
400
401     case TYPE_FUNCTION:
402       return t1->function_type()->is_identical(t2->function_type(),
403                                                false,
404                                                errors_are_identical,
405                                                reason);
406
407     case TYPE_POINTER:
408       return Type::are_identical(t1->points_to(), t2->points_to(),
409                                  errors_are_identical, reason);
410
411     case TYPE_STRUCT:
412       return t1->struct_type()->is_identical(t2->struct_type(),
413                                              errors_are_identical);
414
415     case TYPE_ARRAY:
416       return t1->array_type()->is_identical(t2->array_type(),
417                                             errors_are_identical);
418
419     case TYPE_MAP:
420       return t1->map_type()->is_identical(t2->map_type(),
421                                           errors_are_identical);
422
423     case TYPE_CHANNEL:
424       return t1->channel_type()->is_identical(t2->channel_type(),
425                                               errors_are_identical);
426
427     case TYPE_INTERFACE:
428       return t1->interface_type()->is_identical(t2->interface_type(),
429                                                 errors_are_identical);
430
431     case TYPE_CALL_MULTIPLE_RESULT:
432       if (reason != NULL)
433         *reason = "invalid use of multiple value function call";
434       return false;
435
436     default:
437       go_unreachable();
438     }
439 }
440
441 // Return true if it's OK to have a binary operation with types LHS
442 // and RHS.  This is not used for shifts or comparisons.
443
444 bool
445 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
446 {
447   if (Type::are_identical(lhs, rhs, true, NULL))
448     return true;
449
450   // A constant of abstract bool type may be mixed with any bool type.
451   if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
452       || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
453     return true;
454
455   // A constant of abstract string type may be mixed with any string
456   // type.
457   if ((rhs->is_abstract_string_type() && lhs->is_string_type())
458       || (lhs->is_abstract_string_type() && rhs->is_string_type()))
459     return true;
460
461   lhs = lhs->base();
462   rhs = rhs->base();
463
464   // A constant of abstract integer, float, or complex type may be
465   // mixed with an integer, float, or complex type.
466   if ((rhs->is_abstract()
467        && (rhs->integer_type() != NULL
468            || rhs->float_type() != NULL
469            || rhs->complex_type() != NULL)
470        && (lhs->integer_type() != NULL
471            || lhs->float_type() != NULL
472            || lhs->complex_type() != NULL))
473       || (lhs->is_abstract()
474           && (lhs->integer_type() != NULL
475               || lhs->float_type() != NULL
476               || lhs->complex_type() != NULL)
477           && (rhs->integer_type() != NULL
478               || rhs->float_type() != NULL
479               || rhs->complex_type() != NULL)))
480     return true;
481
482   // The nil type may be compared to a pointer, an interface type, a
483   // slice type, a channel type, a map type, or a function type.
484   if (lhs->is_nil_type()
485       && (rhs->points_to() != NULL
486           || rhs->interface_type() != NULL
487           || rhs->is_slice_type()
488           || rhs->map_type() != NULL
489           || rhs->channel_type() != NULL
490           || rhs->function_type() != NULL))
491     return true;
492   if (rhs->is_nil_type()
493       && (lhs->points_to() != NULL
494           || lhs->interface_type() != NULL
495           || lhs->is_slice_type()
496           || lhs->map_type() != NULL
497           || lhs->channel_type() != NULL
498           || lhs->function_type() != NULL))
499     return true;
500
501   return false;
502 }
503
504 // Return true if a value with type T1 may be compared with a value of
505 // type T2.  IS_EQUALITY_OP is true for == or !=, false for <, etc.
506
507 bool
508 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
509                                     const Type *t2, std::string *reason)
510 {
511   if (t1 != t2
512       && !Type::are_assignable(t1, t2, NULL)
513       && !Type::are_assignable(t2, t1, NULL))
514     {
515       if (reason != NULL)
516         *reason = "incompatible types in binary expression";
517       return false;
518     }
519
520   if (!is_equality_op)
521     {
522       if (t1->integer_type() == NULL
523           && t1->float_type() == NULL
524           && !t1->is_string_type())
525         {
526           if (reason != NULL)
527             *reason = _("invalid comparison of non-ordered type");
528           return false;
529         }
530     }
531   else if (t1->is_slice_type()
532            || t1->map_type() != NULL
533            || t1->function_type() != NULL
534            || t2->is_slice_type()
535            || t2->map_type() != NULL
536            || t2->function_type() != NULL)
537     {
538       if (!t1->is_nil_type() && !t2->is_nil_type())
539         {
540           if (reason != NULL)
541             {
542               if (t1->is_slice_type() || t2->is_slice_type())
543                 *reason = _("slice can only be compared to nil");
544               else if (t1->map_type() != NULL || t2->map_type() != NULL)
545                 *reason = _("map can only be compared to nil");
546               else
547                 *reason = _("func can only be compared to nil");
548
549               // Match 6g error messages.
550               if (t1->interface_type() != NULL || t2->interface_type() != NULL)
551                 {
552                   char buf[200];
553                   snprintf(buf, sizeof buf, _("invalid operation (%s)"),
554                            reason->c_str());
555                   *reason = buf;
556                 }
557             }
558           return false;
559         }
560     }
561   else
562     {
563       if (!t1->is_boolean_type()
564           && t1->integer_type() == NULL
565           && t1->float_type() == NULL
566           && t1->complex_type() == NULL
567           && !t1->is_string_type()
568           && t1->points_to() == NULL
569           && t1->channel_type() == NULL
570           && t1->interface_type() == NULL
571           && t1->struct_type() == NULL
572           && t1->array_type() == NULL
573           && !t1->is_nil_type())
574         {
575           if (reason != NULL)
576             *reason = _("invalid comparison of non-comparable type");
577           return false;
578         }
579
580       if (t1->named_type() != NULL)
581         return t1->named_type()->named_type_is_comparable(reason);
582       else if (t2->named_type() != NULL)
583         return t2->named_type()->named_type_is_comparable(reason);
584       else if (t1->struct_type() != NULL)
585         {
586           const Struct_field_list* fields = t1->struct_type()->fields();
587           for (Struct_field_list::const_iterator p = fields->begin();
588                p != fields->end();
589                ++p)
590             {
591               if (!p->type()->is_comparable())
592                 {
593                   if (reason != NULL)
594                     *reason = _("invalid comparison of non-comparable struct");
595                   return false;
596                 }
597             }
598         }
599       else if (t1->array_type() != NULL)
600         {
601           if (t1->array_type()->length()->is_nil_expression()
602               || !t1->array_type()->element_type()->is_comparable())
603             {
604               if (reason != NULL)
605                 *reason = _("invalid comparison of non-comparable array");
606               return false;
607             }
608         }
609     }
610
611   return true;
612 }
613
614 // Return true if a value with type RHS may be assigned to a variable
615 // with type LHS.  If CHECK_HIDDEN_FIELDS is true, check whether any
616 // hidden fields are modified.  If REASON is not NULL, set *REASON to
617 // the reason the types are not assignable.
618
619 bool
620 Type::are_assignable_check_hidden(const Type* lhs, const Type* rhs,
621                                   bool check_hidden_fields,
622                                   std::string* reason)
623 {
624   // Do some checks first.  Make sure the types are defined.
625   if (rhs != NULL && !rhs->is_undefined())
626     {
627       if (rhs->is_void_type())
628         {
629           if (reason != NULL)
630             *reason = "non-value used as value";
631           return false;
632         }
633       if (rhs->is_call_multiple_result_type())
634         {
635           if (reason != NULL)
636             reason->assign(_("multiple value function call in "
637                              "single value context"));
638           return false;
639         }
640     }
641
642   if (lhs != NULL && !lhs->is_undefined())
643     {
644       // Any value may be assigned to the blank identifier.
645       if (lhs->is_sink_type())
646         return true;
647
648       // All fields of a struct must be exported, or the assignment
649       // must be in the same package.
650       if (check_hidden_fields && rhs != NULL && !rhs->is_undefined())
651         {
652           if (lhs->has_hidden_fields(NULL, reason)
653               || rhs->has_hidden_fields(NULL, reason))
654             return false;
655         }
656     }
657
658   // Identical types are assignable.
659   if (Type::are_identical(lhs, rhs, true, reason))
660     return true;
661
662   // The types are assignable if they have identical underlying types
663   // and either LHS or RHS is not a named type.
664   if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
665        || (rhs->named_type() != NULL && lhs->named_type() == NULL))
666       && Type::are_identical(lhs->base(), rhs->base(), true, reason))
667     return true;
668
669   // The types are assignable if LHS is an interface type and RHS
670   // implements the required methods.
671   const Interface_type* lhs_interface_type = lhs->interface_type();
672   if (lhs_interface_type != NULL)
673     {
674       if (lhs_interface_type->implements_interface(rhs, reason))
675         return true;
676       const Interface_type* rhs_interface_type = rhs->interface_type();
677       if (rhs_interface_type != NULL
678           && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
679                                                           reason))
680         return true;
681     }
682
683   // The type are assignable if RHS is a bidirectional channel type,
684   // LHS is a channel type, they have identical element types, and
685   // either LHS or RHS is not a named type.
686   if (lhs->channel_type() != NULL
687       && rhs->channel_type() != NULL
688       && rhs->channel_type()->may_send()
689       && rhs->channel_type()->may_receive()
690       && (lhs->named_type() == NULL || rhs->named_type() == NULL)
691       && Type::are_identical(lhs->channel_type()->element_type(),
692                              rhs->channel_type()->element_type(),
693                              true,
694                              reason))
695     return true;
696
697   // The nil type may be assigned to a pointer, function, slice, map,
698   // channel, or interface type.
699   if (rhs->is_nil_type()
700       && (lhs->points_to() != NULL
701           || lhs->function_type() != NULL
702           || lhs->is_slice_type()
703           || lhs->map_type() != NULL
704           || lhs->channel_type() != NULL
705           || lhs->interface_type() != NULL))
706     return true;
707
708   // An untyped numeric constant may be assigned to a numeric type if
709   // it is representable in that type.
710   if ((rhs->is_abstract()
711        && (rhs->integer_type() != NULL
712            || rhs->float_type() != NULL
713            || rhs->complex_type() != NULL))
714       && (lhs->integer_type() != NULL
715           || lhs->float_type() != NULL
716           || lhs->complex_type() != NULL))
717     return true;
718
719   // Give some better error messages.
720   if (reason != NULL && reason->empty())
721     {
722       if (rhs->interface_type() != NULL)
723         reason->assign(_("need explicit conversion"));
724       else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
725         {
726           size_t len = (lhs->named_type()->name().length()
727                         + rhs->named_type()->name().length()
728                         + 100);
729           char* buf = new char[len];
730           snprintf(buf, len, _("cannot use type %s as type %s"),
731                    rhs->named_type()->message_name().c_str(),
732                    lhs->named_type()->message_name().c_str());
733           reason->assign(buf);
734           delete[] buf;
735         }
736     }
737
738   return false;
739 }
740
741 // Return true if a value with type RHS may be assigned to a variable
742 // with type LHS.  If REASON is not NULL, set *REASON to the reason
743 // the types are not assignable.
744
745 bool
746 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
747 {
748   return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
749 }
750
751 // Like are_assignable but don't check for hidden fields.
752
753 bool
754 Type::are_assignable_hidden_ok(const Type* lhs, const Type* rhs,
755                                std::string* reason)
756 {
757   return Type::are_assignable_check_hidden(lhs, rhs, false, reason);
758 }
759
760 // Return true if a value with type RHS may be converted to type LHS.
761 // If REASON is not NULL, set *REASON to the reason the types are not
762 // convertible.
763
764 bool
765 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
766 {
767   // The types are convertible if they are assignable.
768   if (Type::are_assignable(lhs, rhs, reason))
769     return true;
770
771   // The types are convertible if they have identical underlying
772   // types.
773   if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
774       && Type::are_identical(lhs->base(), rhs->base(), true, reason))
775     return true;
776
777   // The types are convertible if they are both unnamed pointer types
778   // and their pointer base types have identical underlying types.
779   if (lhs->named_type() == NULL
780       && rhs->named_type() == NULL
781       && lhs->points_to() != NULL
782       && rhs->points_to() != NULL
783       && (lhs->points_to()->named_type() != NULL
784           || rhs->points_to()->named_type() != NULL)
785       && Type::are_identical(lhs->points_to()->base(),
786                              rhs->points_to()->base(),
787                              true,
788                              reason))
789     return true;
790
791   // Integer and floating point types are convertible to each other.
792   if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
793       && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
794     return true;
795
796   // Complex types are convertible to each other.
797   if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
798     return true;
799
800   // An integer, or []byte, or []rune, may be converted to a string.
801   if (lhs->is_string_type())
802     {
803       if (rhs->integer_type() != NULL)
804         return true;
805       if (rhs->is_slice_type())
806         {
807           const Type* e = rhs->array_type()->element_type()->forwarded();
808           if (e->integer_type() != NULL
809               && (e->integer_type()->is_byte()
810                   || e->integer_type()->is_rune()))
811             return true;
812         }
813     }
814
815   // A string may be converted to []byte or []rune.
816   if (rhs->is_string_type() && lhs->is_slice_type())
817     {
818       const Type* e = lhs->array_type()->element_type()->forwarded();
819       if (e->integer_type() != NULL
820           && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
821         return true;
822     }
823
824   // An unsafe.Pointer type may be converted to any pointer type or to
825   // uintptr, and vice-versa.
826   if (lhs->is_unsafe_pointer_type()
827       && (rhs->points_to() != NULL
828           || (rhs->integer_type() != NULL
829               && rhs->forwarded() == Type::lookup_integer_type("uintptr"))))
830     return true;
831   if (rhs->is_unsafe_pointer_type()
832       && (lhs->points_to() != NULL
833           || (lhs->integer_type() != NULL
834               && lhs->forwarded() == Type::lookup_integer_type("uintptr"))))
835     return true;
836
837   // Give a better error message.
838   if (reason != NULL)
839     {
840       if (reason->empty())
841         *reason = "invalid type conversion";
842       else
843         {
844           std::string s = "invalid type conversion (";
845           s += *reason;
846           s += ')';
847           *reason = s;
848         }
849     }
850
851   return false;
852 }
853
854 // Return whether this type has any hidden fields.  This is only a
855 // possibility for a few types.
856
857 bool
858 Type::has_hidden_fields(const Named_type* within, std::string* reason) const
859 {
860   switch (this->forwarded()->classification_)
861     {
862     case TYPE_NAMED:
863       return this->named_type()->named_type_has_hidden_fields(reason);
864     case TYPE_STRUCT:
865       return this->struct_type()->struct_has_hidden_fields(within, reason);
866     case TYPE_ARRAY:
867       return this->array_type()->array_has_hidden_fields(within, reason);
868     default:
869       return false;
870     }
871 }
872
873 // Return a hash code for the type to be used for method lookup.
874
875 unsigned int
876 Type::hash_for_method(Gogo* gogo) const
877 {
878   unsigned int ret = 0;
879   if (this->classification_ != TYPE_FORWARD)
880     ret += this->classification_;
881   return ret + this->do_hash_for_method(gogo);
882 }
883
884 // Default implementation of do_hash_for_method.  This is appropriate
885 // for types with no subfields.
886
887 unsigned int
888 Type::do_hash_for_method(Gogo*) const
889 {
890   return 0;
891 }
892
893 // Return a hash code for a string, given a starting hash.
894
895 unsigned int
896 Type::hash_string(const std::string& s, unsigned int h)
897 {
898   const char* p = s.data();
899   size_t len = s.length();
900   for (; len > 0; --len)
901     {
902       h ^= *p++;
903       h*= 16777619;
904     }
905   return h;
906 }
907
908 // A hash table mapping unnamed types to the backend representation of
909 // those types.
910
911 Type::Type_btypes Type::type_btypes;
912
913 // Return a tree representing this type.
914
915 Btype*
916 Type::get_backend(Gogo* gogo)
917 {
918   if (this->btype_ != NULL)
919     {
920       if (this->btype_is_placeholder_ && gogo->named_types_are_converted())
921         this->finish_backend(gogo);
922       return this->btype_;
923     }
924
925   if (this->forward_declaration_type() != NULL
926       || this->named_type() != NULL)
927     return this->get_btype_without_hash(gogo);
928
929   if (this->is_error_type())
930     return gogo->backend()->error_type();
931
932   // To avoid confusing the backend, translate all identical Go types
933   // to the same backend representation.  We use a hash table to do
934   // that.  There is no need to use the hash table for named types, as
935   // named types are only identical to themselves.
936
937   std::pair<Type*, Btype*> val(this, NULL);
938   std::pair<Type_btypes::iterator, bool> ins =
939     Type::type_btypes.insert(val);
940   if (!ins.second && ins.first->second != NULL)
941     {
942       if (gogo != NULL && gogo->named_types_are_converted())
943         this->btype_ = ins.first->second;
944       return ins.first->second;
945     }
946
947   Btype* bt = this->get_btype_without_hash(gogo);
948
949   if (ins.first->second == NULL)
950     ins.first->second = bt;
951   else
952     {
953       // We have already created a backend representation for this
954       // type.  This can happen when an unnamed type is defined using
955       // a named type which in turns uses an identical unnamed type.
956       // Use the tree we created earlier and ignore the one we just
957       // built.
958       bt = ins.first->second;
959       if (gogo == NULL || !gogo->named_types_are_converted())
960         return bt;
961       this->btype_ = bt;
962     }
963
964   return bt;
965 }
966
967 // Return the backend representation for a type without looking in the
968 // hash table for identical types.  This is used for named types,
969 // since a named type is never identical to any other type.
970
971 Btype*
972 Type::get_btype_without_hash(Gogo* gogo)
973 {
974   if (this->btype_ == NULL)
975     {
976       Btype* bt = this->do_get_backend(gogo);
977
978       // For a recursive function or pointer type, we will temporarily
979       // return a circular pointer type during the recursion.  We
980       // don't want to record that for a forwarding type, as it may
981       // confuse us later.
982       if (this->forward_declaration_type() != NULL
983           && gogo->backend()->is_circular_pointer_type(bt))
984         return bt;
985
986       if (gogo == NULL || !gogo->named_types_are_converted())
987         return bt;
988
989       this->btype_ = bt;
990     }
991   return this->btype_;
992 }
993
994 // Get the backend representation of a type without forcing the
995 // creation of the backend representation of all supporting types.
996 // This will return a backend type that has the correct size but may
997 // be incomplete.  E.g., a pointer will just be a placeholder pointer,
998 // and will not contain the final representation of the type to which
999 // it points.  This is used while converting all named types to the
1000 // backend representation, to avoid problems with indirect references
1001 // to types which are not yet complete.  When this is called, the
1002 // sizes of all direct references (e.g., a struct field) should be
1003 // known, but the sizes of indirect references (e.g., the type to
1004 // which a pointer points) may not.
1005
1006 Btype*
1007 Type::get_backend_placeholder(Gogo* gogo)
1008 {
1009   if (gogo->named_types_are_converted())
1010     return this->get_backend(gogo);
1011   if (this->btype_ != NULL)
1012     return this->btype_;
1013
1014   Btype* bt;
1015   switch (this->classification_)
1016     {
1017     case TYPE_ERROR:
1018     case TYPE_VOID:
1019     case TYPE_BOOLEAN:
1020     case TYPE_INTEGER:
1021     case TYPE_FLOAT:
1022     case TYPE_COMPLEX:
1023     case TYPE_STRING:
1024     case TYPE_NIL:
1025       // These are simple types that can just be created directly.
1026       return this->get_backend(gogo);
1027
1028     case TYPE_FUNCTION:
1029       {
1030         Location loc = this->function_type()->location();
1031         bt = gogo->backend()->placeholder_pointer_type("", loc, true);
1032       }
1033       break;
1034
1035     case TYPE_POINTER:
1036       {
1037         Location loc = Linemap::unknown_location();
1038         bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1039       }
1040       break;
1041
1042     case TYPE_STRUCT:
1043       // We don't have to make the struct itself be a placeholder.  We
1044       // are promised that we know the sizes of the struct fields.
1045       // But we may have to use a placeholder for any particular
1046       // struct field.
1047       {
1048         std::vector<Backend::Btyped_identifier> bfields;
1049         get_backend_struct_fields(gogo, this->struct_type()->fields(),
1050                                   true, &bfields);
1051         bt = gogo->backend()->struct_type(bfields);
1052       }
1053       break;
1054
1055     case TYPE_ARRAY:
1056       if (this->is_slice_type())
1057         {
1058           std::vector<Backend::Btyped_identifier> bfields;
1059           get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1060           bt = gogo->backend()->struct_type(bfields);
1061         }
1062       else
1063         {
1064           Btype* element = this->array_type()->get_backend_element(gogo, true);
1065           Bexpression* len = this->array_type()->get_backend_length(gogo);
1066           bt = gogo->backend()->array_type(element, len);
1067         }
1068       break;
1069         
1070     case TYPE_MAP:
1071     case TYPE_CHANNEL:
1072       // All maps and channels have the same backend representation.
1073       return this->get_backend(gogo);
1074
1075     case TYPE_INTERFACE:
1076       if (this->interface_type()->is_empty())
1077         return Interface_type::get_backend_empty_interface_type(gogo);
1078       else
1079         {
1080           std::vector<Backend::Btyped_identifier> bfields;
1081           get_backend_interface_fields(gogo, this->interface_type(), true,
1082                                        &bfields);
1083           bt = gogo->backend()->struct_type(bfields);
1084         }
1085       break;
1086
1087     case TYPE_NAMED:
1088     case TYPE_FORWARD:
1089       // Named types keep track of their own dependencies and manage
1090       // their own placeholders.
1091       return this->get_backend(gogo);
1092
1093     case TYPE_SINK:
1094     case TYPE_CALL_MULTIPLE_RESULT:
1095     default:
1096       go_unreachable();
1097     }
1098
1099   this->btype_ = bt;
1100   this->btype_is_placeholder_ = true;
1101   return bt;
1102 }
1103
1104 // Complete the backend representation.  This is called for a type
1105 // using a placeholder type.
1106
1107 void
1108 Type::finish_backend(Gogo* gogo)
1109 {
1110   go_assert(this->btype_ != NULL);
1111   if (!this->btype_is_placeholder_)
1112     return;
1113
1114   switch (this->classification_)
1115     {
1116     case TYPE_ERROR:
1117     case TYPE_VOID:
1118     case TYPE_BOOLEAN:
1119     case TYPE_INTEGER:
1120     case TYPE_FLOAT:
1121     case TYPE_COMPLEX:
1122     case TYPE_STRING:
1123     case TYPE_NIL:
1124       go_unreachable();
1125
1126     case TYPE_FUNCTION:
1127       {
1128         Btype* bt = this->do_get_backend(gogo);
1129         if (!gogo->backend()->set_placeholder_function_type(this->btype_, bt))
1130           go_assert(saw_errors());
1131       }
1132       break;
1133
1134     case TYPE_POINTER:
1135       {
1136         Btype* bt = this->do_get_backend(gogo);
1137         if (!gogo->backend()->set_placeholder_pointer_type(this->btype_, bt))
1138           go_assert(saw_errors());
1139       }
1140       break;
1141
1142     case TYPE_STRUCT:
1143       // The struct type itself is done, but we have to make sure that
1144       // all the field types are converted.
1145       this->struct_type()->finish_backend_fields(gogo);
1146       break;
1147
1148     case TYPE_ARRAY:
1149       // The array type itself is done, but make sure the element type
1150       // is converted.
1151       this->array_type()->finish_backend_element(gogo);
1152       break;
1153         
1154     case TYPE_MAP:
1155     case TYPE_CHANNEL:
1156       go_unreachable();
1157
1158     case TYPE_INTERFACE:
1159       // The interface type itself is done, but make sure the method
1160       // types are converted.
1161       this->interface_type()->finish_backend_methods(gogo);
1162       break;
1163
1164     case TYPE_NAMED:
1165     case TYPE_FORWARD:
1166       go_unreachable();
1167
1168     case TYPE_SINK:
1169     case TYPE_CALL_MULTIPLE_RESULT:
1170     default:
1171       go_unreachable();
1172     }
1173
1174   this->btype_is_placeholder_ = false;
1175 }
1176
1177 // Return a pointer to the type descriptor for this type.
1178
1179 tree
1180 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1181 {
1182   Type* t = this->forwarded();
1183   if (t->named_type() != NULL && t->named_type()->is_alias())
1184     t = t->named_type()->real_type();
1185   if (t->type_descriptor_var_ == NULL)
1186     {
1187       t->make_type_descriptor_var(gogo);
1188       go_assert(t->type_descriptor_var_ != NULL);
1189     }
1190   tree var_tree = var_to_tree(t->type_descriptor_var_);
1191   if (var_tree == error_mark_node)
1192     return error_mark_node;
1193   return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
1194 }
1195
1196 // A mapping from unnamed types to type descriptor variables.
1197
1198 Type::Type_descriptor_vars Type::type_descriptor_vars;
1199
1200 // Build the type descriptor for this type.
1201
1202 void
1203 Type::make_type_descriptor_var(Gogo* gogo)
1204 {
1205   go_assert(this->type_descriptor_var_ == NULL);
1206
1207   Named_type* nt = this->named_type();
1208
1209   // We can have multiple instances of unnamed types, but we only want
1210   // to emit the type descriptor once.  We use a hash table.  This is
1211   // not necessary for named types, as they are unique, and we store
1212   // the type descriptor in the type itself.
1213   Bvariable** phash = NULL;
1214   if (nt == NULL)
1215     {
1216       Bvariable* bvnull = NULL;
1217       std::pair<Type_descriptor_vars::iterator, bool> ins =
1218         Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1219       if (!ins.second)
1220         {
1221           // We've already build a type descriptor for this type.
1222           this->type_descriptor_var_ = ins.first->second;
1223           return;
1224         }
1225       phash = &ins.first->second;
1226     }
1227
1228   std::string var_name = this->type_descriptor_var_name(gogo, nt);
1229
1230   // Build the contents of the type descriptor.
1231   Expression* initializer = this->do_type_descriptor(gogo, NULL);
1232
1233   Btype* initializer_btype = initializer->type()->get_backend(gogo);
1234
1235   Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1236
1237   const Package* dummy;
1238   if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1239     {
1240       this->type_descriptor_var_ =
1241         gogo->backend()->immutable_struct_reference(var_name,
1242                                                     initializer_btype,
1243                                                     loc);
1244       if (phash != NULL)
1245         *phash = this->type_descriptor_var_;
1246       return;
1247     }
1248
1249   // See if this type descriptor can appear in multiple packages.
1250   bool is_common = false;
1251   if (nt != NULL)
1252     {
1253       // We create the descriptor for a builtin type whenever we need
1254       // it.
1255       is_common = nt->is_builtin();
1256     }
1257   else
1258     {
1259       // This is an unnamed type.  The descriptor could be defined in
1260       // any package where it is needed, and the linker will pick one
1261       // descriptor to keep.
1262       is_common = true;
1263     }
1264
1265   // We are going to build the type descriptor in this package.  We
1266   // must create the variable before we convert the initializer to the
1267   // backend representation, because the initializer may refer to the
1268   // type descriptor of this type.  By setting type_descriptor_var_ we
1269   // ensure that type_descriptor_pointer will work if called while
1270   // converting INITIALIZER.
1271
1272   this->type_descriptor_var_ =
1273     gogo->backend()->immutable_struct(var_name, is_common, initializer_btype,
1274                                       loc);
1275   if (phash != NULL)
1276     *phash = this->type_descriptor_var_;
1277
1278   Translate_context context(gogo, NULL, NULL, NULL);
1279   context.set_is_const();
1280   Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
1281
1282   gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1283                                              var_name, is_common,
1284                                              initializer_btype, loc,
1285                                              binitializer);
1286 }
1287
1288 // Return the name of the type descriptor variable.  If NT is not
1289 // NULL, use it to get the name.  Otherwise this is an unnamed type.
1290
1291 std::string
1292 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1293 {
1294   if (nt == NULL)
1295     return "__go_td_" + this->mangled_name(gogo);
1296
1297   Named_object* no = nt->named_object();
1298   const Named_object* in_function = nt->in_function();
1299   std::string ret = "__go_tdn_";
1300   if (nt->is_builtin())
1301     go_assert(in_function == NULL);
1302   else
1303     {
1304       const std::string& unique_prefix(no->package() == NULL
1305                                        ? gogo->unique_prefix()
1306                                        : no->package()->unique_prefix());
1307       const std::string& package_name(no->package() == NULL
1308                                       ? gogo->package_name()
1309                                       : no->package()->name());
1310       ret.append(unique_prefix);
1311       ret.append(1, '.');
1312       ret.append(package_name);
1313       ret.append(1, '.');
1314       if (in_function != NULL)
1315         {
1316           ret.append(Gogo::unpack_hidden_name(in_function->name()));
1317           ret.append(1, '.');
1318         }
1319     }
1320   ret.append(no->name());
1321   return ret;
1322 }
1323
1324 // Return true if this type descriptor is defined in a different
1325 // package.  If this returns true it sets *PACKAGE to the package.
1326
1327 bool
1328 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1329                                         const Package** package)
1330 {
1331   if (nt != NULL)
1332     {
1333       if (nt->named_object()->package() != NULL)
1334         {
1335           // This is a named type defined in a different package.  The
1336           // type descriptor should be defined in that package.
1337           *package = nt->named_object()->package();
1338           return true;
1339         }
1340     }
1341   else
1342     {
1343       if (this->points_to() != NULL
1344           && this->points_to()->named_type() != NULL
1345           && this->points_to()->named_type()->named_object()->package() != NULL)
1346         {
1347           // This is an unnamed pointer to a named type defined in a
1348           // different package.  The descriptor should be defined in
1349           // that package.
1350           *package = this->points_to()->named_type()->named_object()->package();
1351           return true;
1352         }
1353     }
1354   return false;
1355 }
1356
1357 // Return a composite literal for a type descriptor.
1358
1359 Expression*
1360 Type::type_descriptor(Gogo* gogo, Type* type)
1361 {
1362   return type->do_type_descriptor(gogo, NULL);
1363 }
1364
1365 // Return a composite literal for a type descriptor with a name.
1366
1367 Expression*
1368 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1369 {
1370   go_assert(name != NULL && type->named_type() != name);
1371   return type->do_type_descriptor(gogo, name);
1372 }
1373
1374 // Make a builtin struct type from a list of fields.  The fields are
1375 // pairs of a name and a type.
1376
1377 Struct_type*
1378 Type::make_builtin_struct_type(int nfields, ...)
1379 {
1380   va_list ap;
1381   va_start(ap, nfields);
1382
1383   Location bloc = Linemap::predeclared_location();
1384   Struct_field_list* sfl = new Struct_field_list();
1385   for (int i = 0; i < nfields; i++)
1386     {
1387       const char* field_name = va_arg(ap, const char *);
1388       Type* type = va_arg(ap, Type*);
1389       sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1390     }
1391
1392   va_end(ap);
1393
1394   return Type::make_struct_type(sfl, bloc);
1395 }
1396
1397 // A list of builtin named types.
1398
1399 std::vector<Named_type*> Type::named_builtin_types;
1400
1401 // Make a builtin named type.
1402
1403 Named_type*
1404 Type::make_builtin_named_type(const char* name, Type* type)
1405 {
1406   Location bloc = Linemap::predeclared_location();
1407   Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1408   Named_type* ret = no->type_value();
1409   Type::named_builtin_types.push_back(ret);
1410   return ret;
1411 }
1412
1413 // Convert the named builtin types.
1414
1415 void
1416 Type::convert_builtin_named_types(Gogo* gogo)
1417 {
1418   for (std::vector<Named_type*>::const_iterator p =
1419          Type::named_builtin_types.begin();
1420        p != Type::named_builtin_types.end();
1421        ++p)
1422     {
1423       bool r = (*p)->verify();
1424       go_assert(r);
1425       (*p)->convert(gogo);
1426     }
1427 }
1428
1429 // Return the type of a type descriptor.  We should really tie this to
1430 // runtime.Type rather than copying it.  This must match commonType in
1431 // libgo/go/runtime/type.go.
1432
1433 Type*
1434 Type::make_type_descriptor_type()
1435 {
1436   static Type* ret;
1437   if (ret == NULL)
1438     {
1439       Location bloc = Linemap::predeclared_location();
1440
1441       Type* uint8_type = Type::lookup_integer_type("uint8");
1442       Type* uint32_type = Type::lookup_integer_type("uint32");
1443       Type* uintptr_type = Type::lookup_integer_type("uintptr");
1444       Type* string_type = Type::lookup_string_type();
1445       Type* pointer_string_type = Type::make_pointer_type(string_type);
1446
1447       // This is an unnamed version of unsafe.Pointer.  Perhaps we
1448       // should use the named version instead, although that would
1449       // require us to create the unsafe package if it has not been
1450       // imported.  It probably doesn't matter.
1451       Type* void_type = Type::make_void_type();
1452       Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1453
1454       // Forward declaration for the type descriptor type.
1455       Named_object* named_type_descriptor_type =
1456         Named_object::make_type_declaration("commonType", NULL, bloc);
1457       Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1458       Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1459
1460       // The type of a method on a concrete type.
1461       Struct_type* method_type =
1462         Type::make_builtin_struct_type(5,
1463                                        "name", pointer_string_type,
1464                                        "pkgPath", pointer_string_type,
1465                                        "mtyp", pointer_type_descriptor_type,
1466                                        "typ", pointer_type_descriptor_type,
1467                                        "tfn", unsafe_pointer_type);
1468       Named_type* named_method_type =
1469         Type::make_builtin_named_type("method", method_type);
1470
1471       // Information for types with a name or methods.
1472       Type* slice_named_method_type =
1473         Type::make_array_type(named_method_type, NULL);
1474       Struct_type* uncommon_type =
1475         Type::make_builtin_struct_type(3,
1476                                        "name", pointer_string_type,
1477                                        "pkgPath", pointer_string_type,
1478                                        "methods", slice_named_method_type);
1479       Named_type* named_uncommon_type =
1480         Type::make_builtin_named_type("uncommonType", uncommon_type);
1481
1482       Type* pointer_uncommon_type =
1483         Type::make_pointer_type(named_uncommon_type);
1484
1485       // The type descriptor type.
1486
1487       Typed_identifier_list* params = new Typed_identifier_list();
1488       params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1489       params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1490
1491       Typed_identifier_list* results = new Typed_identifier_list();
1492       results->push_back(Typed_identifier("", uintptr_type, bloc));
1493
1494       Type* hashfn_type = Type::make_function_type(NULL, params, results, bloc);
1495
1496       params = new Typed_identifier_list();
1497       params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1498       params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1499       params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1500
1501       results = new Typed_identifier_list();
1502       results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1503
1504       Type* equalfn_type = Type::make_function_type(NULL, params, results,
1505                                                     bloc);
1506
1507       Struct_type* type_descriptor_type =
1508         Type::make_builtin_struct_type(10,
1509                                        "Kind", uint8_type,
1510                                        "align", uint8_type,
1511                                        "fieldAlign", uint8_type,
1512                                        "size", uintptr_type,
1513                                        "hash", uint32_type,
1514                                        "hashfn", hashfn_type,
1515                                        "equalfn", equalfn_type,
1516                                        "string", pointer_string_type,
1517                                        "", pointer_uncommon_type,
1518                                        "ptrToThis",
1519                                        pointer_type_descriptor_type);
1520
1521       Named_type* named = Type::make_builtin_named_type("commonType",
1522                                                         type_descriptor_type);
1523
1524       named_type_descriptor_type->set_type_value(named);
1525
1526       ret = named;
1527     }
1528
1529   return ret;
1530 }
1531
1532 // Make the type of a pointer to a type descriptor as represented in
1533 // Go.
1534
1535 Type*
1536 Type::make_type_descriptor_ptr_type()
1537 {
1538   static Type* ret;
1539   if (ret == NULL)
1540     ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1541   return ret;
1542 }
1543
1544 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1545 // hash code for this type and which compare whether two values of
1546 // this type are equal.  If NAME is not NULL it is the name of this
1547 // type.  HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1548 // functions, for convenience; they may be NULL.
1549
1550 void
1551 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1552                      Function_type* equal_fntype, Named_object** hash_fn,
1553                      Named_object** equal_fn)
1554 {
1555   if (hash_fntype == NULL || equal_fntype == NULL)
1556     {
1557       Location bloc = Linemap::predeclared_location();
1558
1559       Type* uintptr_type = Type::lookup_integer_type("uintptr");
1560       Type* void_type = Type::make_void_type();
1561       Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1562
1563       if (hash_fntype == NULL)
1564         {
1565           Typed_identifier_list* params = new Typed_identifier_list();
1566           params->push_back(Typed_identifier("key", unsafe_pointer_type,
1567                                              bloc));
1568           params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1569
1570           Typed_identifier_list* results = new Typed_identifier_list();
1571           results->push_back(Typed_identifier("", uintptr_type, bloc));
1572
1573           hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1574         }
1575       if (equal_fntype == NULL)
1576         {
1577           Typed_identifier_list* params = new Typed_identifier_list();
1578           params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1579                                              bloc));
1580           params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1581                                              bloc));
1582           params->push_back(Typed_identifier("key_size", uintptr_type, bloc));
1583
1584           Typed_identifier_list* results = new Typed_identifier_list();
1585           results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1586                                               bloc));
1587
1588           equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1589         }
1590     }
1591
1592   const char* hash_fnname;
1593   const char* equal_fnname;
1594   if (this->compare_is_identity(gogo))
1595     {
1596       hash_fnname = "__go_type_hash_identity";
1597       equal_fnname = "__go_type_equal_identity";
1598     }
1599   else if (!this->is_comparable())
1600     {
1601       hash_fnname = "__go_type_hash_error";
1602       equal_fnname = "__go_type_equal_error";
1603     }
1604   else
1605     {
1606       switch (this->base()->classification())
1607         {
1608         case Type::TYPE_ERROR:
1609         case Type::TYPE_VOID:
1610         case Type::TYPE_NIL:
1611         case Type::TYPE_FUNCTION:
1612         case Type::TYPE_MAP:
1613           // For these types is_comparable should have returned false.
1614           go_unreachable();
1615
1616         case Type::TYPE_BOOLEAN:
1617         case Type::TYPE_INTEGER:
1618         case Type::TYPE_POINTER:
1619         case Type::TYPE_CHANNEL:
1620           // For these types compare_is_identity should have returned true.
1621           go_unreachable();
1622
1623         case Type::TYPE_FLOAT:
1624           hash_fnname = "__go_type_hash_float";
1625           equal_fnname = "__go_type_equal_float";
1626           break;
1627
1628         case Type::TYPE_COMPLEX:
1629           hash_fnname = "__go_type_hash_complex";
1630           equal_fnname = "__go_type_equal_complex";
1631           break;
1632
1633         case Type::TYPE_STRING:
1634           hash_fnname = "__go_type_hash_string";
1635           equal_fnname = "__go_type_equal_string";
1636           break;
1637
1638         case Type::TYPE_STRUCT:
1639           {
1640             // This is a struct which can not be compared using a
1641             // simple identity function.  We need to build a function
1642             // for comparison.
1643             this->specific_type_functions(gogo, name, hash_fntype,
1644                                           equal_fntype, hash_fn, equal_fn);
1645             return;
1646           }
1647
1648         case Type::TYPE_ARRAY:
1649           if (this->is_slice_type())
1650             {
1651               // Type::is_compatible_for_comparison should have
1652               // returned false.
1653               go_unreachable();
1654             }
1655           else
1656             {
1657               // This is an array which can not be compared using a
1658               // simple identity function.  We need to build a
1659               // function for comparison.
1660               this->specific_type_functions(gogo, name, hash_fntype,
1661                                             equal_fntype, hash_fn, equal_fn);
1662               return;
1663             }
1664           break;
1665
1666         case Type::TYPE_INTERFACE:
1667           if (this->interface_type()->is_empty())
1668             {
1669               hash_fnname = "__go_type_hash_empty_interface";
1670               equal_fnname = "__go_type_equal_empty_interface";
1671             }
1672           else
1673             {
1674               hash_fnname = "__go_type_hash_interface";
1675               equal_fnname = "__go_type_equal_interface";
1676             }
1677           break;
1678
1679         case Type::TYPE_NAMED:
1680         case Type::TYPE_FORWARD:
1681           go_unreachable();
1682
1683         default:
1684           go_unreachable();
1685         }
1686     }
1687
1688
1689   Location bloc = Linemap::predeclared_location();
1690   *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1691                                                      hash_fntype, bloc);
1692   (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1693   *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1694                                                       equal_fntype, bloc);
1695   (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1696 }
1697
1698 // A hash table mapping types to the specific hash functions.
1699
1700 Type::Type_functions Type::type_functions_table;
1701
1702 // Handle a type function which is specific to a type: a struct or
1703 // array which can not use an identity comparison.
1704
1705 void
1706 Type::specific_type_functions(Gogo* gogo, Named_type* name,
1707                               Function_type* hash_fntype,
1708                               Function_type* equal_fntype,
1709                               Named_object** hash_fn,
1710                               Named_object** equal_fn)
1711 {
1712   Hash_equal_fn fnull(NULL, NULL);
1713   std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1714   std::pair<Type_functions::iterator, bool> ins =
1715     Type::type_functions_table.insert(val);
1716   if (!ins.second)
1717     {
1718       // We already have functions for this type
1719       *hash_fn = ins.first->second.first;
1720       *equal_fn = ins.first->second.second;
1721       return;
1722     }
1723
1724   std::string base_name;
1725   if (name == NULL)
1726     {
1727       // Mangled names can have '.' if they happen to refer to named
1728       // types in some way.  That's fine if this is simply a named
1729       // type, but otherwise it will confuse the code that builds
1730       // function identifiers.  Remove '.' when necessary.
1731       base_name = this->mangled_name(gogo);
1732       size_t i;
1733       while ((i = base_name.find('.')) != std::string::npos)
1734         base_name[i] = '$';
1735       base_name = gogo->pack_hidden_name(base_name, false);
1736     }
1737   else
1738     {
1739       // This name is already hidden or not as appropriate.
1740       base_name = name->name();
1741       const Named_object* in_function = name->in_function();
1742       if (in_function != NULL)
1743         base_name += '$' + in_function->name();
1744     }
1745   std::string hash_name = base_name + "$hash";
1746   std::string equal_name = base_name + "$equal";
1747
1748   Location bloc = Linemap::predeclared_location();
1749
1750   const Package* package = NULL;
1751   bool is_defined_elsewhere =
1752     this->type_descriptor_defined_elsewhere(name, &package);
1753   if (is_defined_elsewhere)
1754     {
1755       *hash_fn = Named_object::make_function_declaration(hash_name, package,
1756                                                          hash_fntype, bloc);
1757       *equal_fn = Named_object::make_function_declaration(equal_name, package,
1758                                                           equal_fntype, bloc);
1759     }
1760   else
1761     {
1762       *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1763       *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1764                                                  bloc);
1765     }
1766
1767   ins.first->second.first = *hash_fn;
1768   ins.first->second.second = *equal_fn;
1769
1770   if (!is_defined_elsewhere)
1771     {
1772       if (gogo->in_global_scope())
1773         this->write_specific_type_functions(gogo, name, hash_name, hash_fntype,
1774                                             equal_name, equal_fntype);
1775       else
1776         gogo->queue_specific_type_function(this, name, hash_name, hash_fntype,
1777                                            equal_name, equal_fntype);
1778     }
1779 }
1780
1781 // Write the hash and equality functions for a type which needs to be
1782 // written specially.
1783
1784 void
1785 Type::write_specific_type_functions(Gogo* gogo, Named_type* name,
1786                                     const std::string& hash_name,
1787                                     Function_type* hash_fntype,
1788                                     const std::string& equal_name,
1789                                     Function_type* equal_fntype)
1790 {
1791   Location bloc = Linemap::predeclared_location();
1792
1793   if (gogo->specific_type_functions_are_written())
1794     {
1795       go_assert(saw_errors());
1796       return;
1797     }
1798
1799   Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1800                                                bloc);
1801   gogo->start_block(bloc);
1802
1803   if (this->struct_type() != NULL)
1804     this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1805                                              equal_fntype);
1806   else if (this->array_type() != NULL)
1807     this->array_type()->write_hash_function(gogo, name, hash_fntype,
1808                                             equal_fntype);
1809   else
1810     go_unreachable();
1811
1812   Block* b = gogo->finish_block(bloc);
1813   gogo->add_block(b, bloc);
1814   gogo->lower_block(hash_fn, b);
1815   gogo->finish_function(bloc);
1816
1817   Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
1818                                                 false, bloc);
1819   gogo->start_block(bloc);
1820
1821   if (this->struct_type() != NULL)
1822     this->struct_type()->write_equal_function(gogo, name);
1823   else if (this->array_type() != NULL)
1824     this->array_type()->write_equal_function(gogo, name);
1825   else
1826     go_unreachable();
1827
1828   b = gogo->finish_block(bloc);
1829   gogo->add_block(b, bloc);
1830   gogo->lower_block(equal_fn, b);
1831   gogo->finish_function(bloc);
1832 }
1833
1834 // Return a composite literal for the type descriptor for a plain type
1835 // of kind RUNTIME_TYPE_KIND named NAME.
1836
1837 Expression*
1838 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
1839                                   Named_type* name, const Methods* methods,
1840                                   bool only_value_methods)
1841 {
1842   Location bloc = Linemap::predeclared_location();
1843
1844   Type* td_type = Type::make_type_descriptor_type();
1845   const Struct_field_list* fields = td_type->struct_type()->fields();
1846
1847   Expression_list* vals = new Expression_list();
1848   vals->reserve(9);
1849
1850   if (!this->has_pointer())
1851     runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
1852   Struct_field_list::const_iterator p = fields->begin();
1853   go_assert(p->is_field_name("Kind"));
1854   mpz_t iv;
1855   mpz_init_set_ui(iv, runtime_type_kind);
1856   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1857
1858   ++p;
1859   go_assert(p->is_field_name("align"));
1860   Expression::Type_info type_info = Expression::TYPE_INFO_ALIGNMENT;
1861   vals->push_back(Expression::make_type_info(this, type_info));
1862
1863   ++p;
1864   go_assert(p->is_field_name("fieldAlign"));
1865   type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
1866   vals->push_back(Expression::make_type_info(this, type_info));
1867
1868   ++p;
1869   go_assert(p->is_field_name("size"));
1870   type_info = Expression::TYPE_INFO_SIZE;
1871   vals->push_back(Expression::make_type_info(this, type_info));
1872
1873   ++p;
1874   go_assert(p->is_field_name("hash"));
1875   unsigned int h;
1876   if (name != NULL)
1877     h = name->hash_for_method(gogo);
1878   else
1879     h = this->hash_for_method(gogo);
1880   mpz_set_ui(iv, h);
1881   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
1882
1883   ++p;
1884   go_assert(p->is_field_name("hashfn"));
1885   Function_type* hash_fntype = p->type()->function_type();
1886
1887   ++p;
1888   go_assert(p->is_field_name("equalfn"));
1889   Function_type* equal_fntype = p->type()->function_type();
1890
1891   Named_object* hash_fn;
1892   Named_object* equal_fn;
1893   this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
1894                        &equal_fn);
1895   vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
1896   vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
1897
1898   ++p;
1899   go_assert(p->is_field_name("string"));
1900   Expression* s = Expression::make_string((name != NULL
1901                                            ? name->reflection(gogo)
1902                                            : this->reflection(gogo)),
1903                                           bloc);
1904   vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1905
1906   ++p;
1907   go_assert(p->is_field_name("uncommonType"));
1908   if (name == NULL && methods == NULL)
1909     vals->push_back(Expression::make_nil(bloc));
1910   else
1911     {
1912       if (methods == NULL)
1913         methods = name->methods();
1914       vals->push_back(this->uncommon_type_constructor(gogo,
1915                                                       p->type()->deref(),
1916                                                       name, methods,
1917                                                       only_value_methods));
1918     }
1919
1920   ++p;
1921   go_assert(p->is_field_name("ptrToThis"));
1922   if (name == NULL)
1923     vals->push_back(Expression::make_nil(bloc));
1924   else
1925     {
1926       Type* pt = Type::make_pointer_type(name);
1927       vals->push_back(Expression::make_type_descriptor(pt, bloc));
1928     }
1929
1930   ++p;
1931   go_assert(p == fields->end());
1932
1933   mpz_clear(iv);
1934
1935   return Expression::make_struct_composite_literal(td_type, vals, bloc);
1936 }
1937
1938 // Return a composite literal for the uncommon type information for
1939 // this type.  UNCOMMON_STRUCT_TYPE is the type of the uncommon type
1940 // struct.  If name is not NULL, it is the name of the type.  If
1941 // METHODS is not NULL, it is the list of methods.  ONLY_VALUE_METHODS
1942 // is true if only value methods should be included.  At least one of
1943 // NAME and METHODS must not be NULL.
1944
1945 Expression*
1946 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
1947                                 Named_type* name, const Methods* methods,
1948                                 bool only_value_methods) const
1949 {
1950   Location bloc = Linemap::predeclared_location();
1951
1952   const Struct_field_list* fields = uncommon_type->struct_type()->fields();
1953
1954   Expression_list* vals = new Expression_list();
1955   vals->reserve(3);
1956
1957   Struct_field_list::const_iterator p = fields->begin();
1958   go_assert(p->is_field_name("name"));
1959
1960   ++p;
1961   go_assert(p->is_field_name("pkgPath"));
1962
1963   if (name == NULL)
1964     {
1965       vals->push_back(Expression::make_nil(bloc));
1966       vals->push_back(Expression::make_nil(bloc));
1967     }
1968   else
1969     {
1970       Named_object* no = name->named_object();
1971       std::string n = Gogo::unpack_hidden_name(no->name());
1972       Expression* s = Expression::make_string(n, bloc);
1973       vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1974
1975       if (name->is_builtin())
1976         vals->push_back(Expression::make_nil(bloc));
1977       else
1978         {
1979           const Package* package = no->package();
1980           const std::string& unique_prefix(package == NULL
1981                                            ? gogo->unique_prefix()
1982                                            : package->unique_prefix());
1983           const std::string& package_name(package == NULL
1984                                           ? gogo->package_name()
1985                                           : package->name());
1986           n.assign(unique_prefix);
1987           n.append(1, '.');
1988           n.append(package_name);
1989           if (name->in_function() != NULL)
1990             {
1991               n.append(1, '.');
1992               n.append(Gogo::unpack_hidden_name(name->in_function()->name()));
1993             }
1994           s = Expression::make_string(n, bloc);
1995           vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
1996         }
1997     }
1998
1999   ++p;
2000   go_assert(p->is_field_name("methods"));
2001   vals->push_back(this->methods_constructor(gogo, p->type(), methods,
2002                                             only_value_methods));
2003
2004   ++p;
2005   go_assert(p == fields->end());
2006
2007   Expression* r = Expression::make_struct_composite_literal(uncommon_type,
2008                                                             vals, bloc);
2009   return Expression::make_unary(OPERATOR_AND, r, bloc);
2010 }
2011
2012 // Sort methods by name.
2013
2014 class Sort_methods
2015 {
2016  public:
2017   bool
2018   operator()(const std::pair<std::string, const Method*>& m1,
2019              const std::pair<std::string, const Method*>& m2) const
2020   { return m1.first < m2.first; }
2021 };
2022
2023 // Return a composite literal for the type method table for this type.
2024 // METHODS_TYPE is the type of the table, and is a slice type.
2025 // METHODS is the list of methods.  If ONLY_VALUE_METHODS is true,
2026 // then only value methods are used.
2027
2028 Expression*
2029 Type::methods_constructor(Gogo* gogo, Type* methods_type,
2030                           const Methods* methods,
2031                           bool only_value_methods) const
2032 {
2033   Location bloc = Linemap::predeclared_location();
2034
2035   std::vector<std::pair<std::string, const Method*> > smethods;
2036   if (methods != NULL)
2037     {
2038       smethods.reserve(methods->count());
2039       for (Methods::const_iterator p = methods->begin();
2040            p != methods->end();
2041            ++p)
2042         {
2043           if (p->second->is_ambiguous())
2044             continue;
2045           if (only_value_methods && !p->second->is_value_method())
2046             continue;
2047           smethods.push_back(std::make_pair(p->first, p->second));
2048         }
2049     }
2050
2051   if (smethods.empty())
2052     return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
2053
2054   std::sort(smethods.begin(), smethods.end(), Sort_methods());
2055
2056   Type* method_type = methods_type->array_type()->element_type();
2057
2058   Expression_list* vals = new Expression_list();
2059   vals->reserve(smethods.size());
2060   for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
2061          = smethods.begin();
2062        p != smethods.end();
2063        ++p)
2064     vals->push_back(this->method_constructor(gogo, method_type, p->first,
2065                                              p->second, only_value_methods));
2066
2067   return Expression::make_slice_composite_literal(methods_type, vals, bloc);
2068 }
2069
2070 // Return a composite literal for a single method.  METHOD_TYPE is the
2071 // type of the entry.  METHOD_NAME is the name of the method and M is
2072 // the method information.
2073
2074 Expression*
2075 Type::method_constructor(Gogo*, Type* method_type,
2076                          const std::string& method_name,
2077                          const Method* m,
2078                          bool only_value_methods) const
2079 {
2080   Location bloc = Linemap::predeclared_location();
2081
2082   const Struct_field_list* fields = method_type->struct_type()->fields();
2083
2084   Expression_list* vals = new Expression_list();
2085   vals->reserve(5);
2086
2087   Struct_field_list::const_iterator p = fields->begin();
2088   go_assert(p->is_field_name("name"));
2089   const std::string n = Gogo::unpack_hidden_name(method_name);
2090   Expression* s = Expression::make_string(n, bloc);
2091   vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2092
2093   ++p;
2094   go_assert(p->is_field_name("pkgPath"));
2095   if (!Gogo::is_hidden_name(method_name))
2096     vals->push_back(Expression::make_nil(bloc));
2097   else
2098     {
2099       s = Expression::make_string(Gogo::hidden_name_prefix(method_name), bloc);
2100       vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2101     }
2102
2103   Named_object* no = (m->needs_stub_method()
2104                       ? m->stub_object()
2105                       : m->named_object());
2106
2107   Function_type* mtype;
2108   if (no->is_function())
2109     mtype = no->func_value()->type();
2110   else
2111     mtype = no->func_declaration_value()->type();
2112   go_assert(mtype->is_method());
2113   Type* nonmethod_type = mtype->copy_without_receiver();
2114
2115   ++p;
2116   go_assert(p->is_field_name("mtyp"));
2117   vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
2118
2119   ++p;
2120   go_assert(p->is_field_name("typ"));
2121   if (!only_value_methods && m->is_value_method())
2122     {
2123       // This is a value method on a pointer type.  Change the type of
2124       // the method to use a pointer receiver.  The implementation
2125       // always uses a pointer receiver anyhow.
2126       Type* rtype = mtype->receiver()->type();
2127       Type* prtype = Type::make_pointer_type(rtype);
2128       Typed_identifier* receiver =
2129         new Typed_identifier(mtype->receiver()->name(), prtype,
2130                              mtype->receiver()->location());
2131       mtype = Type::make_function_type(receiver,
2132                                        (mtype->parameters() == NULL
2133                                         ? NULL
2134                                         : mtype->parameters()->copy()),
2135                                        (mtype->results() == NULL
2136                                         ? NULL
2137                                         : mtype->results()->copy()),
2138                                        mtype->location());
2139     }
2140   vals->push_back(Expression::make_type_descriptor(mtype, bloc));
2141
2142   ++p;
2143   go_assert(p->is_field_name("tfn"));
2144   vals->push_back(Expression::make_func_reference(no, NULL, bloc));
2145
2146   ++p;
2147   go_assert(p == fields->end());
2148
2149   return Expression::make_struct_composite_literal(method_type, vals, bloc);
2150 }
2151
2152 // Return a composite literal for the type descriptor of a plain type.
2153 // RUNTIME_TYPE_KIND is the value of the kind field.  If NAME is not
2154 // NULL, it is the name to use as well as the list of methods.
2155
2156 Expression*
2157 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
2158                             Named_type* name)
2159 {
2160   return this->type_descriptor_constructor(gogo, runtime_type_kind,
2161                                            name, NULL, true);
2162 }
2163
2164 // Return the type reflection string for this type.
2165
2166 std::string
2167 Type::reflection(Gogo* gogo) const
2168 {
2169   std::string ret;
2170
2171   // The do_reflection virtual function should set RET to the
2172   // reflection string.
2173   this->do_reflection(gogo, &ret);
2174
2175   return ret;
2176 }
2177
2178 // Return a mangled name for the type.
2179
2180 std::string
2181 Type::mangled_name(Gogo* gogo) const
2182 {
2183   std::string ret;
2184
2185   // The do_mangled_name virtual function should set RET to the
2186   // mangled name.  For a composite type it should append a code for
2187   // the composition and then call do_mangled_name on the components.
2188   this->do_mangled_name(gogo, &ret);
2189
2190   return ret;
2191 }
2192
2193 // Return whether the backend size of the type is known.
2194
2195 bool
2196 Type::is_backend_type_size_known(Gogo* gogo)
2197 {
2198   switch (this->classification_)
2199     {
2200     case TYPE_ERROR:
2201     case TYPE_VOID:
2202     case TYPE_BOOLEAN:
2203     case TYPE_INTEGER:
2204     case TYPE_FLOAT:
2205     case TYPE_COMPLEX:
2206     case TYPE_STRING:
2207     case TYPE_FUNCTION:
2208     case TYPE_POINTER:
2209     case TYPE_NIL:
2210     case TYPE_MAP:
2211     case TYPE_CHANNEL:
2212     case TYPE_INTERFACE:
2213       return true;
2214
2215     case TYPE_STRUCT:
2216       {
2217         const Struct_field_list* fields = this->struct_type()->fields();
2218         for (Struct_field_list::const_iterator pf = fields->begin();
2219              pf != fields->end();
2220              ++pf)
2221           if (!pf->type()->is_backend_type_size_known(gogo))
2222             return false;
2223         return true;
2224       }
2225
2226     case TYPE_ARRAY:
2227       {
2228         const Array_type* at = this->array_type();
2229         if (at->length() == NULL)
2230           return true;
2231         else
2232           {
2233             Numeric_constant nc;
2234             if (!at->length()->numeric_constant_value(&nc))
2235               return false;
2236             mpz_t ival;
2237             if (!nc.to_int(&ival))
2238               return false;
2239             mpz_clear(ival);
2240             return at->element_type()->is_backend_type_size_known(gogo);
2241           }
2242       }
2243
2244     case TYPE_NAMED:
2245       // Begin converting this type to the backend representation.
2246       // This will create a placeholder if necessary.
2247       this->get_backend(gogo);
2248       return this->named_type()->is_named_backend_type_size_known();
2249
2250     case TYPE_FORWARD:
2251       {
2252         Forward_declaration_type* fdt = this->forward_declaration_type();
2253         return fdt->real_type()->is_backend_type_size_known(gogo);
2254       }
2255
2256     case TYPE_SINK:
2257     case TYPE_CALL_MULTIPLE_RESULT:
2258       go_unreachable();
2259
2260     default:
2261       go_unreachable();
2262     }
2263 }
2264
2265 // If the size of the type can be determined, set *PSIZE to the size
2266 // in bytes and return true.  Otherwise, return false.  This queries
2267 // the backend.
2268
2269 bool
2270 Type::backend_type_size(Gogo* gogo, unsigned int *psize)
2271 {
2272   if (!this->is_backend_type_size_known(gogo))
2273     return false;
2274   Btype* bt = this->get_backend_placeholder(gogo);
2275   size_t size = gogo->backend()->type_size(bt);
2276   *psize = static_cast<unsigned int>(size);
2277   if (*psize != size)
2278     return false;
2279   return true;
2280 }
2281
2282 // If the alignment of the type can be determined, set *PALIGN to
2283 // the alignment in bytes and return true.  Otherwise, return false.
2284
2285 bool
2286 Type::backend_type_align(Gogo* gogo, unsigned int *palign)
2287 {
2288   if (!this->is_backend_type_size_known(gogo))
2289     return false;
2290   Btype* bt = this->get_backend_placeholder(gogo);
2291   size_t align = gogo->backend()->type_alignment(bt);
2292   *palign = static_cast<unsigned int>(align);
2293   if (*palign != align)
2294     return false;
2295   return true;
2296 }
2297
2298 // Like backend_type_align, but return the alignment when used as a
2299 // field.
2300
2301 bool
2302 Type::backend_type_field_align(Gogo* gogo, unsigned int *palign)
2303 {
2304   if (!this->is_backend_type_size_known(gogo))
2305     return false;
2306   Btype* bt = this->get_backend_placeholder(gogo);
2307   size_t a = gogo->backend()->type_field_alignment(bt);
2308   *palign = static_cast<unsigned int>(a);
2309   if (*palign != a)
2310     return false;
2311   return true;
2312 }
2313
2314 // Default function to export a type.
2315
2316 void
2317 Type::do_export(Export*) const
2318 {
2319   go_unreachable();
2320 }
2321
2322 // Import a type.
2323
2324 Type*
2325 Type::import_type(Import* imp)
2326 {
2327   if (imp->match_c_string("("))
2328     return Function_type::do_import(imp);
2329   else if (imp->match_c_string("*"))
2330     return Pointer_type::do_import(imp);
2331   else if (imp->match_c_string("struct "))
2332     return Struct_type::do_import(imp);
2333   else if (imp->match_c_string("["))
2334     return Array_type::do_import(imp);
2335   else if (imp->match_c_string("map "))
2336     return Map_type::do_import(imp);
2337   else if (imp->match_c_string("chan "))
2338     return Channel_type::do_import(imp);
2339   else if (imp->match_c_string("interface"))
2340     return Interface_type::do_import(imp);
2341   else
2342     {
2343       error_at(imp->location(), "import error: expected type");
2344       return Type::make_error_type();
2345     }
2346 }
2347
2348 // A type used to indicate a parsing error.  This exists to simplify
2349 // later error detection.
2350
2351 class Error_type : public Type
2352 {
2353  public:
2354   Error_type()
2355     : Type(TYPE_ERROR)
2356   { }
2357
2358  protected:
2359   bool
2360   do_compare_is_identity(Gogo*) const
2361   { return false; }
2362
2363   Btype*
2364   do_get_backend(Gogo* gogo)
2365   { return gogo->backend()->error_type(); }
2366
2367   Expression*
2368   do_type_descriptor(Gogo*, Named_type*)
2369   { return Expression::make_error(Linemap::predeclared_location()); }
2370
2371   void
2372   do_reflection(Gogo*, std::string*) const
2373   { go_assert(saw_errors()); }
2374
2375   void
2376   do_mangled_name(Gogo*, std::string* ret) const
2377   { ret->push_back('E'); }
2378 };
2379
2380 Type*
2381 Type::make_error_type()
2382 {
2383   static Error_type singleton_error_type;
2384   return &singleton_error_type;
2385 }
2386
2387 // The void type.
2388
2389 class Void_type : public Type
2390 {
2391  public:
2392   Void_type()
2393     : Type(TYPE_VOID)
2394   { }
2395
2396  protected:
2397   bool
2398   do_compare_is_identity(Gogo*) const
2399   { return false; }
2400
2401   Btype*
2402   do_get_backend(Gogo* gogo)
2403   { return gogo->backend()->void_type(); }
2404
2405   Expression*
2406   do_type_descriptor(Gogo*, Named_type*)
2407   { go_unreachable(); }
2408
2409   void
2410   do_reflection(Gogo*, std::string*) const
2411   { }
2412
2413   void
2414   do_mangled_name(Gogo*, std::string* ret) const
2415   { ret->push_back('v'); }
2416 };
2417
2418 Type*
2419 Type::make_void_type()
2420 {
2421   static Void_type singleton_void_type;
2422   return &singleton_void_type;
2423 }
2424
2425 // The boolean type.
2426
2427 class Boolean_type : public Type
2428 {
2429  public:
2430   Boolean_type()
2431     : Type(TYPE_BOOLEAN)
2432   { }
2433
2434  protected:
2435   bool
2436   do_compare_is_identity(Gogo*) const
2437   { return true; }
2438
2439   Btype*
2440   do_get_backend(Gogo* gogo)
2441   { return gogo->backend()->bool_type(); }
2442
2443   Expression*
2444   do_type_descriptor(Gogo*, Named_type* name);
2445
2446   // We should not be asked for the reflection string of a basic type.
2447   void
2448   do_reflection(Gogo*, std::string* ret) const
2449   { ret->append("bool"); }
2450
2451   void
2452   do_mangled_name(Gogo*, std::string* ret) const
2453   { ret->push_back('b'); }
2454 };
2455
2456 // Make the type descriptor.
2457
2458 Expression*
2459 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2460 {
2461   if (name != NULL)
2462     return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
2463   else
2464     {
2465       Named_object* no = gogo->lookup_global("bool");
2466       go_assert(no != NULL);
2467       return Type::type_descriptor(gogo, no->type_value());
2468     }
2469 }
2470
2471 Type*
2472 Type::make_boolean_type()
2473 {
2474   static Boolean_type boolean_type;
2475   return &boolean_type;
2476 }
2477
2478 // The named type "bool".
2479
2480 static Named_type* named_bool_type;
2481
2482 // Get the named type "bool".
2483
2484 Named_type*
2485 Type::lookup_bool_type()
2486 {
2487   return named_bool_type;
2488 }
2489
2490 // Make the named type "bool".
2491
2492 Named_type*
2493 Type::make_named_bool_type()
2494 {
2495   Type* bool_type = Type::make_boolean_type();
2496   Named_object* named_object =
2497     Named_object::make_type("bool", NULL, bool_type,
2498                             Linemap::predeclared_location());
2499   Named_type* named_type = named_object->type_value();
2500   named_bool_type = named_type;
2501   return named_type;
2502 }
2503
2504 // Class Integer_type.
2505
2506 Integer_type::Named_integer_types Integer_type::named_integer_types;
2507
2508 // Create a new integer type.  Non-abstract integer types always have
2509 // names.
2510
2511 Named_type*
2512 Integer_type::create_integer_type(const char* name, bool is_unsigned,
2513                                   int bits, int runtime_type_kind)
2514 {
2515   Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
2516                                                 runtime_type_kind);
2517   std::string sname(name);
2518   Named_object* named_object =
2519     Named_object::make_type(sname, NULL, integer_type,
2520                             Linemap::predeclared_location());
2521   Named_type* named_type = named_object->type_value();
2522   std::pair<Named_integer_types::iterator, bool> ins =
2523     Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
2524   go_assert(ins.second);
2525   return named_type;
2526 }
2527
2528 // Look up an existing integer type.
2529
2530 Named_type*
2531 Integer_type::lookup_integer_type(const char* name)
2532 {
2533   Named_integer_types::const_iterator p =
2534     Integer_type::named_integer_types.find(name);
2535   go_assert(p != Integer_type::named_integer_types.end());
2536   return p->second;
2537 }
2538
2539 // Create a new abstract integer type.
2540
2541 Integer_type*
2542 Integer_type::create_abstract_integer_type()
2543 {
2544   static Integer_type* abstract_type;
2545   if (abstract_type == NULL)
2546     abstract_type = new Integer_type(true, false, INT_TYPE_SIZE,
2547                                      RUNTIME_TYPE_KIND_INT);
2548   return abstract_type;
2549 }
2550
2551 // Create a new abstract character type.
2552
2553 Integer_type*
2554 Integer_type::create_abstract_character_type()
2555 {
2556   static Integer_type* abstract_type;
2557   if (abstract_type == NULL)
2558     {
2559       abstract_type = new Integer_type(true, false, 32,
2560                                        RUNTIME_TYPE_KIND_INT32);
2561       abstract_type->set_is_rune();
2562     }
2563   return abstract_type;
2564 }
2565
2566 // Integer type compatibility.
2567
2568 bool
2569 Integer_type::is_identical(const Integer_type* t) const
2570 {
2571   if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
2572     return false;
2573   return this->is_abstract_ == t->is_abstract_;
2574 }
2575
2576 // Hash code.
2577
2578 unsigned int
2579 Integer_type::do_hash_for_method(Gogo*) const
2580 {
2581   return ((this->bits_ << 4)
2582           + ((this->is_unsigned_ ? 1 : 0) << 8)
2583           + ((this->is_abstract_ ? 1 : 0) << 9));
2584 }
2585
2586 // Convert an Integer_type to the backend representation.
2587
2588 Btype*
2589 Integer_type::do_get_backend(Gogo* gogo)
2590 {
2591   if (this->is_abstract_)
2592     {
2593       go_assert(saw_errors());
2594       return gogo->backend()->error_type();
2595     }
2596   return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
2597 }
2598
2599 // The type descriptor for an integer type.  Integer types are always
2600 // named.
2601
2602 Expression*
2603 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2604 {
2605   go_assert(name != NULL || saw_errors());
2606   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2607 }
2608
2609 // We should not be asked for the reflection string of a basic type.
2610
2611 void
2612 Integer_type::do_reflection(Gogo*, std::string*) const
2613 {
2614   go_assert(saw_errors());
2615 }
2616
2617 // Mangled name.
2618
2619 void
2620 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
2621 {
2622   char buf[100];
2623   snprintf(buf, sizeof buf, "i%s%s%de",
2624            this->is_abstract_ ? "a" : "",
2625            this->is_unsigned_ ? "u" : "",
2626            this->bits_);
2627   ret->append(buf);
2628 }
2629
2630 // Make an integer type.
2631
2632 Named_type*
2633 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
2634                         int runtime_type_kind)
2635 {
2636   return Integer_type::create_integer_type(name, is_unsigned, bits,
2637                                            runtime_type_kind);
2638 }
2639
2640 // Make an abstract integer type.
2641
2642 Integer_type*
2643 Type::make_abstract_integer_type()
2644 {
2645   return Integer_type::create_abstract_integer_type();
2646 }
2647
2648 // Make an abstract character type.
2649
2650 Integer_type*
2651 Type::make_abstract_character_type()
2652 {
2653   return Integer_type::create_abstract_character_type();
2654 }
2655
2656 // Look up an integer type.
2657
2658 Named_type*
2659 Type::lookup_integer_type(const char* name)
2660 {
2661   return Integer_type::lookup_integer_type(name);
2662 }
2663
2664 // Class Float_type.
2665
2666 Float_type::Named_float_types Float_type::named_float_types;
2667
2668 // Create a new float type.  Non-abstract float types always have
2669 // names.
2670
2671 Named_type*
2672 Float_type::create_float_type(const char* name, int bits,
2673                               int runtime_type_kind)
2674 {
2675   Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
2676   std::string sname(name);
2677   Named_object* named_object =
2678     Named_object::make_type(sname, NULL, float_type,
2679                             Linemap::predeclared_location());
2680   Named_type* named_type = named_object->type_value();
2681   std::pair<Named_float_types::iterator, bool> ins =
2682     Float_type::named_float_types.insert(std::make_pair(sname, named_type));
2683   go_assert(ins.second);
2684   return named_type;
2685 }
2686
2687 // Look up an existing float type.
2688
2689 Named_type*
2690 Float_type::lookup_float_type(const char* name)
2691 {
2692   Named_float_types::const_iterator p =
2693     Float_type::named_float_types.find(name);
2694   go_assert(p != Float_type::named_float_types.end());
2695   return p->second;
2696 }
2697
2698 // Create a new abstract float type.
2699
2700 Float_type*
2701 Float_type::create_abstract_float_type()
2702 {
2703   static Float_type* abstract_type;
2704   if (abstract_type == NULL)
2705     abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
2706   return abstract_type;
2707 }
2708
2709 // Whether this type is identical with T.
2710
2711 bool
2712 Float_type::is_identical(const Float_type* t) const
2713 {
2714   if (this->bits_ != t->bits_)
2715     return false;
2716   return this->is_abstract_ == t->is_abstract_;
2717 }
2718
2719 // Hash code.
2720
2721 unsigned int
2722 Float_type::do_hash_for_method(Gogo*) const
2723 {
2724   return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2725 }
2726
2727 // Convert to the backend representation.
2728
2729 Btype*
2730 Float_type::do_get_backend(Gogo* gogo)
2731 {
2732   return gogo->backend()->float_type(this->bits_);
2733 }
2734
2735 // The type descriptor for a float type.  Float types are always named.
2736
2737 Expression*
2738 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2739 {
2740   go_assert(name != NULL || saw_errors());
2741   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2742 }
2743
2744 // We should not be asked for the reflection string of a basic type.
2745
2746 void
2747 Float_type::do_reflection(Gogo*, std::string*) const
2748 {
2749   go_assert(saw_errors());
2750 }
2751
2752 // Mangled name.
2753
2754 void
2755 Float_type::do_mangled_name(Gogo*, std::string* ret) const
2756 {
2757   char buf[100];
2758   snprintf(buf, sizeof buf, "f%s%de",
2759            this->is_abstract_ ? "a" : "",
2760            this->bits_);
2761   ret->append(buf);
2762 }
2763
2764 // Make a floating point type.
2765
2766 Named_type*
2767 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
2768 {
2769   return Float_type::create_float_type(name, bits, runtime_type_kind);
2770 }
2771
2772 // Make an abstract float type.
2773
2774 Float_type*
2775 Type::make_abstract_float_type()
2776 {
2777   return Float_type::create_abstract_float_type();
2778 }
2779
2780 // Look up a float type.
2781
2782 Named_type*
2783 Type::lookup_float_type(const char* name)
2784 {
2785   return Float_type::lookup_float_type(name);
2786 }
2787
2788 // Class Complex_type.
2789
2790 Complex_type::Named_complex_types Complex_type::named_complex_types;
2791
2792 // Create a new complex type.  Non-abstract complex types always have
2793 // names.
2794
2795 Named_type*
2796 Complex_type::create_complex_type(const char* name, int bits,
2797                                   int runtime_type_kind)
2798 {
2799   Complex_type* complex_type = new Complex_type(false, bits,
2800                                                 runtime_type_kind);
2801   std::string sname(name);
2802   Named_object* named_object =
2803     Named_object::make_type(sname, NULL, complex_type,
2804                             Linemap::predeclared_location());
2805   Named_type* named_type = named_object->type_value();
2806   std::pair<Named_complex_types::iterator, bool> ins =
2807     Complex_type::named_complex_types.insert(std::make_pair(sname,
2808                                                             named_type));
2809   go_assert(ins.second);
2810   return named_type;
2811 }
2812
2813 // Look up an existing complex type.
2814
2815 Named_type*
2816 Complex_type::lookup_complex_type(const char* name)
2817 {
2818   Named_complex_types::const_iterator p =
2819     Complex_type::named_complex_types.find(name);
2820   go_assert(p != Complex_type::named_complex_types.end());
2821   return p->second;
2822 }
2823
2824 // Create a new abstract complex type.
2825
2826 Complex_type*
2827 Complex_type::create_abstract_complex_type()
2828 {
2829   static Complex_type* abstract_type;
2830   if (abstract_type == NULL)
2831     abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
2832   return abstract_type;
2833 }
2834
2835 // Whether this type is identical with T.
2836
2837 bool
2838 Complex_type::is_identical(const Complex_type *t) const
2839 {
2840   if (this->bits_ != t->bits_)
2841     return false;
2842   return this->is_abstract_ == t->is_abstract_;
2843 }
2844
2845 // Hash code.
2846
2847 unsigned int
2848 Complex_type::do_hash_for_method(Gogo*) const
2849 {
2850   return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
2851 }
2852
2853 // Convert to the backend representation.
2854
2855 Btype*
2856 Complex_type::do_get_backend(Gogo* gogo)
2857 {
2858   return gogo->backend()->complex_type(this->bits_);
2859 }
2860
2861 // The type descriptor for a complex type.  Complex types are always
2862 // named.
2863
2864 Expression*
2865 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2866 {
2867   go_assert(name != NULL || saw_errors());
2868   return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
2869 }
2870
2871 // We should not be asked for the reflection string of a basic type.
2872
2873 void
2874 Complex_type::do_reflection(Gogo*, std::string*) const
2875 {
2876   go_assert(saw_errors());
2877 }
2878
2879 // Mangled name.
2880
2881 void
2882 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
2883 {
2884   char buf[100];
2885   snprintf(buf, sizeof buf, "c%s%de",
2886            this->is_abstract_ ? "a" : "",
2887            this->bits_);
2888   ret->append(buf);
2889 }
2890
2891 // Make a complex type.
2892
2893 Named_type*
2894 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
2895 {
2896   return Complex_type::create_complex_type(name, bits, runtime_type_kind);
2897 }
2898
2899 // Make an abstract complex type.
2900
2901 Complex_type*
2902 Type::make_abstract_complex_type()
2903 {
2904   return Complex_type::create_abstract_complex_type();
2905 }
2906
2907 // Look up a complex type.
2908
2909 Named_type*
2910 Type::lookup_complex_type(const char* name)
2911 {
2912   return Complex_type::lookup_complex_type(name);
2913 }
2914
2915 // Class String_type.
2916
2917 // Convert String_type to the backend representation.  A string is a
2918 // struct with two fields: a pointer to the characters and a length.
2919
2920 Btype*
2921 String_type::do_get_backend(Gogo* gogo)
2922 {
2923   static Btype* backend_string_type;
2924   if (backend_string_type == NULL)
2925     {
2926       std::vector<Backend::Btyped_identifier> fields(2);
2927
2928       Type* b = gogo->lookup_global("byte")->type_value();
2929       Type* pb = Type::make_pointer_type(b);
2930
2931       // We aren't going to get back to this field to finish the
2932       // backend representation, so force it to be finished now.
2933       if (!gogo->named_types_are_converted())
2934         {
2935           pb->get_backend_placeholder(gogo);
2936           pb->finish_backend(gogo);
2937         }
2938
2939       fields[0].name = "__data";
2940       fields[0].btype = pb->get_backend(gogo);
2941       fields[0].location = Linemap::predeclared_location();
2942
2943       Type* int_type = Type::lookup_integer_type("int");
2944       fields[1].name = "__length";
2945       fields[1].btype = int_type->get_backend(gogo);
2946       fields[1].location = fields[0].location;
2947
2948       backend_string_type = gogo->backend()->struct_type(fields);
2949     }
2950   return backend_string_type;
2951 }
2952
2953 // Return a tree for the length of STRING.
2954
2955 tree
2956 String_type::length_tree(Gogo*, tree string)
2957 {
2958   tree string_type = TREE_TYPE(string);
2959   go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2960   tree length_field = DECL_CHAIN(TYPE_FIELDS(string_type));
2961   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(length_field)),
2962                     "__length") == 0);
2963   return fold_build3(COMPONENT_REF, integer_type_node, string,
2964                      length_field, NULL_TREE);
2965 }
2966
2967 // Return a tree for a pointer to the bytes of STRING.
2968
2969 tree
2970 String_type::bytes_tree(Gogo*, tree string)
2971 {
2972   tree string_type = TREE_TYPE(string);
2973   go_assert(TREE_CODE(string_type) == RECORD_TYPE);
2974   tree bytes_field = TYPE_FIELDS(string_type);
2975   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(bytes_field)),
2976                     "__data") == 0);
2977   return fold_build3(COMPONENT_REF, TREE_TYPE(bytes_field), string,
2978                      bytes_field, NULL_TREE);
2979 }
2980
2981 // The type descriptor for the string type.
2982
2983 Expression*
2984 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
2985 {
2986   if (name != NULL)
2987     return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
2988   else
2989     {
2990       Named_object* no = gogo->lookup_global("string");
2991       go_assert(no != NULL);
2992       return Type::type_descriptor(gogo, no->type_value());
2993     }
2994 }
2995
2996 // We should not be asked for the reflection string of a basic type.
2997
2998 void
2999 String_type::do_reflection(Gogo*, std::string* ret) const
3000 {
3001   ret->append("string");
3002 }
3003
3004 // Mangled name of a string type.
3005
3006 void
3007 String_type::do_mangled_name(Gogo*, std::string* ret) const
3008 {
3009   ret->push_back('z');
3010 }
3011
3012 // Make a string type.
3013
3014 Type*
3015 Type::make_string_type()
3016 {
3017   static String_type string_type;
3018   return &string_type;
3019 }
3020
3021 // The named type "string".
3022
3023 static Named_type* named_string_type;
3024
3025 // Get the named type "string".
3026
3027 Named_type*
3028 Type::lookup_string_type()
3029 {
3030   return named_string_type;
3031 }
3032
3033 // Make the named type string.
3034
3035 Named_type*
3036 Type::make_named_string_type()
3037 {
3038   Type* string_type = Type::make_string_type();
3039   Named_object* named_object =
3040     Named_object::make_type("string", NULL, string_type,
3041                             Linemap::predeclared_location());
3042   Named_type* named_type = named_object->type_value();
3043   named_string_type = named_type;
3044   return named_type;
3045 }
3046
3047 // The sink type.  This is the type of the blank identifier _.  Any
3048 // type may be assigned to it.
3049
3050 class Sink_type : public Type
3051 {
3052  public:
3053   Sink_type()
3054     : Type(TYPE_SINK)
3055   { }
3056
3057  protected:
3058   bool
3059   do_compare_is_identity(Gogo*) const
3060   { return false; }
3061
3062   Btype*
3063   do_get_backend(Gogo*)
3064   { go_unreachable(); }
3065
3066   Expression*
3067   do_type_descriptor(Gogo*, Named_type*)
3068   { go_unreachable(); }
3069
3070   void
3071   do_reflection(Gogo*, std::string*) const
3072   { go_unreachable(); }
3073
3074   void
3075   do_mangled_name(Gogo*, std::string*) const
3076   { go_unreachable(); }
3077 };
3078
3079 // Make the sink type.
3080
3081 Type*
3082 Type::make_sink_type()
3083 {
3084   static Sink_type sink_type;
3085   return &sink_type;
3086 }
3087
3088 // Class Function_type.
3089
3090 // Traversal.
3091
3092 int
3093 Function_type::do_traverse(Traverse* traverse)
3094 {
3095   if (this->receiver_ != NULL
3096       && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
3097     return TRAVERSE_EXIT;
3098   if (this->parameters_ != NULL
3099       && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
3100     return TRAVERSE_EXIT;
3101   if (this->results_ != NULL
3102       && this->results_->traverse(traverse) == TRAVERSE_EXIT)
3103     return TRAVERSE_EXIT;
3104   return TRAVERSE_CONTINUE;
3105 }
3106
3107 // Returns whether T is a valid redeclaration of this type.  If this
3108 // returns false, and REASON is not NULL, *REASON may be set to a
3109 // brief explanation of why it returned false.
3110
3111 bool
3112 Function_type::is_valid_redeclaration(const Function_type* t,
3113                                       std::string* reason) const
3114 {
3115   if (!this->is_identical(t, false, true, reason))
3116     return false;
3117
3118   // A redeclaration of a function is required to use the same names
3119   // for the receiver and parameters.
3120   if (this->receiver() != NULL
3121       && this->receiver()->name() != t->receiver()->name())
3122     {
3123       if (reason != NULL)
3124         *reason = "receiver name changed";
3125       return false;
3126     }
3127
3128   const Typed_identifier_list* parms1 = this->parameters();
3129   const Typed_identifier_list* parms2 = t->parameters();
3130   if (parms1 != NULL)
3131     {
3132       Typed_identifier_list::const_iterator p1 = parms1->begin();
3133       for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3134            p2 != parms2->end();
3135            ++p2, ++p1)
3136         {
3137           if (p1->name() != p2->name())
3138             {
3139               if (reason != NULL)
3140                 *reason = "parameter name changed";
3141               return false;
3142             }
3143
3144           // This is called at parse time, so we may have unknown
3145           // types.
3146           Type* t1 = p1->type()->forwarded();
3147           Type* t2 = p2->type()->forwarded();
3148           if (t1 != t2
3149               && t1->forward_declaration_type() != NULL
3150               && (t2->forward_declaration_type() == NULL
3151                   || (t1->forward_declaration_type()->named_object()
3152                       != t2->forward_declaration_type()->named_object())))
3153             return false;
3154         }
3155     }
3156
3157   const Typed_identifier_list* results1 = this->results();
3158   const Typed_identifier_list* results2 = t->results();
3159   if (results1 != NULL)
3160     {
3161       Typed_identifier_list::const_iterator res1 = results1->begin();
3162       for (Typed_identifier_list::const_iterator res2 = results2->begin();
3163            res2 != results2->end();
3164            ++res2, ++res1)
3165         {
3166           if (res1->name() != res2->name())
3167             {
3168               if (reason != NULL)
3169                 *reason = "result name changed";
3170               return false;
3171             }
3172
3173           // This is called at parse time, so we may have unknown
3174           // types.
3175           Type* t1 = res1->type()->forwarded();
3176           Type* t2 = res2->type()->forwarded();
3177           if (t1 != t2
3178               && t1->forward_declaration_type() != NULL
3179               && (t2->forward_declaration_type() == NULL
3180                   || (t1->forward_declaration_type()->named_object()
3181                       != t2->forward_declaration_type()->named_object())))
3182             return false;
3183         }
3184     }
3185
3186   return true;
3187 }
3188
3189 // Check whether T is the same as this type.
3190
3191 bool
3192 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
3193                             bool errors_are_identical,
3194                             std::string* reason) const
3195 {
3196   if (!ignore_receiver)
3197     {
3198       const Typed_identifier* r1 = this->receiver();
3199       const Typed_identifier* r2 = t->receiver();
3200       if ((r1 != NULL) != (r2 != NULL))
3201         {
3202           if (reason != NULL)
3203             *reason = _("different receiver types");
3204           return false;
3205         }
3206       if (r1 != NULL)
3207         {
3208           if (!Type::are_identical(r1->type(), r2->type(), errors_are_identical,
3209                                    reason))
3210             {
3211               if (reason != NULL && !reason->empty())
3212                 *reason = "receiver: " + *reason;
3213               return false;
3214             }
3215         }
3216     }
3217
3218   const Typed_identifier_list* parms1 = this->parameters();
3219   const Typed_identifier_list* parms2 = t->parameters();
3220   if ((parms1 != NULL) != (parms2 != NULL))
3221     {
3222       if (reason != NULL)
3223         *reason = _("different number of parameters");
3224       return false;
3225     }
3226   if (parms1 != NULL)
3227     {
3228       Typed_identifier_list::const_iterator p1 = parms1->begin();
3229       for (Typed_identifier_list::const_iterator p2 = parms2->begin();
3230            p2 != parms2->end();
3231            ++p2, ++p1)
3232         {
3233           if (p1 == parms1->end())
3234             {
3235               if (reason != NULL)
3236                 *reason = _("different number of parameters");
3237               return false;
3238             }
3239
3240           if (!Type::are_identical(p1->type(), p2->type(),
3241                                    errors_are_identical, NULL))
3242             {
3243               if (reason != NULL)
3244                 *reason = _("different parameter types");
3245               return false;
3246             }
3247         }
3248       if (p1 != parms1->end())
3249         {
3250           if (reason != NULL)
3251             *reason = _("different number of parameters");
3252         return false;
3253         }
3254     }
3255
3256   if (this->is_varargs() != t->is_varargs())
3257     {
3258       if (reason != NULL)
3259         *reason = _("different varargs");
3260       return false;
3261     }
3262
3263   const Typed_identifier_list* results1 = this->results();
3264   const Typed_identifier_list* results2 = t->results();
3265   if ((results1 != NULL) != (results2 != NULL))
3266     {
3267       if (reason != NULL)
3268         *reason = _("different number of results");
3269       return false;
3270     }
3271   if (results1 != NULL)
3272     {
3273       Typed_identifier_list::const_iterator res1 = results1->begin();
3274       for (Typed_identifier_list::const_iterator res2 = results2->begin();
3275            res2 != results2->end();
3276            ++res2, ++res1)
3277         {
3278           if (res1 == results1->end())
3279             {
3280               if (reason != NULL)
3281                 *reason = _("different number of results");
3282               return false;
3283             }
3284
3285           if (!Type::are_identical(res1->type(), res2->type(),
3286                                    errors_are_identical, NULL))
3287             {
3288               if (reason != NULL)
3289                 *reason = _("different result types");
3290               return false;
3291             }
3292         }
3293       if (res1 != results1->end())
3294         {
3295           if (reason != NULL)
3296             *reason = _("different number of results");
3297           return false;
3298         }
3299     }
3300
3301   return true;
3302 }
3303
3304 // Hash code.
3305
3306 unsigned int
3307 Function_type::do_hash_for_method(Gogo* gogo) const
3308 {
3309   unsigned int ret = 0;
3310   // We ignore the receiver type for hash codes, because we need to
3311   // get the same hash code for a method in an interface and a method
3312   // declared for a type.  The former will not have a receiver.
3313   if (this->parameters_ != NULL)
3314     {
3315       int shift = 1;
3316       for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3317            p != this->parameters_->end();
3318            ++p, ++shift)
3319         ret += p->type()->hash_for_method(gogo) << shift;
3320     }
3321   if (this->results_ != NULL)
3322     {
3323       int shift = 2;
3324       for (Typed_identifier_list::const_iterator p = this->results_->begin();
3325            p != this->results_->end();
3326            ++p, ++shift)
3327         ret += p->type()->hash_for_method(gogo) << shift;
3328     }
3329   if (this->is_varargs_)
3330     ret += 1;
3331   ret <<= 4;
3332   return ret;
3333 }
3334
3335 // Get the backend representation for a function type.
3336
3337 Btype*
3338 Function_type::do_get_backend(Gogo* gogo)
3339 {
3340   Backend::Btyped_identifier breceiver;
3341   if (this->receiver_ != NULL)
3342     {
3343       breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
3344
3345       // We always pass the address of the receiver parameter, in
3346       // order to make interface calls work with unknown types.
3347       Type* rtype = this->receiver_->type();
3348       if (rtype->points_to() == NULL)
3349         rtype = Type::make_pointer_type(rtype);
3350       breceiver.btype = rtype->get_backend(gogo);
3351       breceiver.location = this->receiver_->location();
3352     }
3353
3354   std::vector<Backend::Btyped_identifier> bparameters;
3355   if (this->parameters_ != NULL)
3356     {
3357       bparameters.resize(this->parameters_->size());
3358       size_t i = 0;
3359       for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
3360            p != this->parameters_->end();
3361            ++p, ++i)
3362         {
3363           bparameters[i].name = Gogo::unpack_hidden_name(p->name());
3364           bparameters[i].btype = p->type()->get_backend(gogo);
3365           bparameters[i].location = p->location();
3366         }
3367       go_assert(i == bparameters.size());
3368     }
3369
3370   std::vector<Backend::Btyped_identifier> bresults;
3371   if (this->results_ != NULL)
3372     {
3373       bresults.resize(this->results_->size());
3374       size_t i = 0;
3375       for (Typed_identifier_list::const_iterator p = this->results_->begin();
3376            p != this->results_->end();
3377            ++p, ++i)
3378         {
3379           bresults[i].name = Gogo::unpack_hidden_name(p->name());
3380           bresults[i].btype = p->type()->get_backend(gogo);
3381           bresults[i].location = p->location();
3382         }
3383       go_assert(i == bresults.size());
3384     }
3385
3386   return gogo->backend()->function_type(breceiver, bparameters, bresults,
3387                                         this->location());
3388 }
3389
3390 // The type of a function type descriptor.
3391
3392 Type*
3393 Function_type::make_function_type_descriptor_type()
3394 {
3395   static Type* ret;
3396   if (ret == NULL)
3397     {
3398       Type* tdt = Type::make_type_descriptor_type();
3399       Type* ptdt = Type::make_type_descriptor_ptr_type();
3400
3401       Type* bool_type = Type::lookup_bool_type();
3402
3403       Type* slice_type = Type::make_array_type(ptdt, NULL);
3404
3405       Struct_type* s = Type::make_builtin_struct_type(4,
3406                                                       "", tdt,
3407                                                       "dotdotdot", bool_type,
3408                                                       "in", slice_type,
3409                                                       "out", slice_type);
3410
3411       ret = Type::make_builtin_named_type("FuncType", s);
3412     }
3413
3414   return ret;
3415 }
3416
3417 // The type descriptor for a function type.
3418
3419 Expression*
3420 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3421 {
3422   Location bloc = Linemap::predeclared_location();
3423
3424   Type* ftdt = Function_type::make_function_type_descriptor_type();
3425
3426   const Struct_field_list* fields = ftdt->struct_type()->fields();
3427
3428   Expression_list* vals = new Expression_list();
3429   vals->reserve(4);
3430
3431   Struct_field_list::const_iterator p = fields->begin();
3432   go_assert(p->is_field_name("commonType"));
3433   vals->push_back(this->type_descriptor_constructor(gogo,
3434                                                     RUNTIME_TYPE_KIND_FUNC,
3435                                                     name, NULL, true));
3436
3437   ++p;
3438   go_assert(p->is_field_name("dotdotdot"));
3439   vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
3440
3441   ++p;
3442   go_assert(p->is_field_name("in"));
3443   vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
3444                                                this->parameters()));
3445
3446   ++p;
3447   go_assert(p->is_field_name("out"));
3448   vals->push_back(this->type_descriptor_params(p->type(), NULL,
3449                                                this->results()));
3450
3451   ++p;
3452   go_assert(p == fields->end());
3453
3454   return Expression::make_struct_composite_literal(ftdt, vals, bloc);
3455 }
3456
3457 // Return a composite literal for the parameters or results of a type
3458 // descriptor.
3459
3460 Expression*
3461 Function_type::type_descriptor_params(Type* params_type,
3462                                       const Typed_identifier* receiver,
3463                                       const Typed_identifier_list* params)
3464 {
3465   Location bloc = Linemap::predeclared_location();
3466
3467   if (receiver == NULL && params == NULL)
3468     return Expression::make_slice_composite_literal(params_type, NULL, bloc);
3469
3470   Expression_list* vals = new Expression_list();
3471   vals->reserve((params == NULL ? 0 : params->size())
3472                 + (receiver != NULL ? 1 : 0));
3473
3474   if (receiver != NULL)
3475     vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
3476
3477   if (params != NULL)
3478     {
3479       for (Typed_identifier_list::const_iterator p = params->begin();
3480            p != params->end();
3481            ++p)
3482         vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
3483     }
3484
3485   return Expression::make_slice_composite_literal(params_type, vals, bloc);
3486 }
3487
3488 // The reflection string.
3489
3490 void
3491 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
3492 {
3493   // FIXME: Turn this off until we straighten out the type of the
3494   // struct field used in a go statement which calls a method.
3495   // go_assert(this->receiver_ == NULL);
3496
3497   ret->append("func");
3498
3499   if (this->receiver_ != NULL)
3500     {
3501       ret->push_back('(');
3502       this->append_reflection(this->receiver_->type(), gogo, ret);
3503       ret->push_back(')');
3504     }
3505
3506   ret->push_back('(');
3507   const Typed_identifier_list* params = this->parameters();
3508   if (params != NULL)
3509     {
3510       bool is_varargs = this->is_varargs_;
3511       for (Typed_identifier_list::const_iterator p = params->begin();
3512            p != params->end();
3513            ++p)
3514         {
3515           if (p != params->begin())
3516             ret->append(", ");
3517           if (!is_varargs || p + 1 != params->end())
3518             this->append_reflection(p->type(), gogo, ret);
3519           else
3520             {
3521               ret->append("...");
3522               this->append_reflection(p->type()->array_type()->element_type(),
3523                                       gogo, ret);
3524             }
3525         }
3526     }
3527   ret->push_back(')');
3528
3529   const Typed_identifier_list* results = this->results();
3530   if (results != NULL && !results->empty())
3531     {
3532       if (results->size() == 1)
3533         ret->push_back(' ');
3534       else
3535         ret->append(" (");
3536       for (Typed_identifier_list::const_iterator p = results->begin();
3537            p != results->end();
3538            ++p)
3539         {
3540           if (p != results->begin())
3541             ret->append(", ");
3542           this->append_reflection(p->type(), gogo, ret);
3543         }
3544       if (results->size() > 1)
3545         ret->push_back(')');
3546     }
3547 }
3548
3549 // Mangled name.
3550
3551 void
3552 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3553 {
3554   ret->push_back('F');
3555
3556   if (this->receiver_ != NULL)
3557     {
3558       ret->push_back('m');
3559       this->append_mangled_name(this->receiver_->type(), gogo, ret);
3560     }
3561
3562   const Typed_identifier_list* params = this->parameters();
3563   if (params != NULL)
3564     {
3565       ret->push_back('p');
3566       for (Typed_identifier_list::const_iterator p = params->begin();
3567            p != params->end();
3568            ++p)
3569         this->append_mangled_name(p->type(), gogo, ret);
3570       if (this->is_varargs_)
3571         ret->push_back('V');
3572       ret->push_back('e');
3573     }
3574
3575   const Typed_identifier_list* results = this->results();
3576   if (results != NULL)
3577     {
3578       ret->push_back('r');
3579       for (Typed_identifier_list::const_iterator p = results->begin();
3580            p != results->end();
3581            ++p)
3582         this->append_mangled_name(p->type(), gogo, ret);
3583       ret->push_back('e');
3584     }
3585
3586   ret->push_back('e');
3587 }
3588
3589 // Export a function type.
3590
3591 void
3592 Function_type::do_export(Export* exp) const
3593 {
3594   // We don't write out the receiver.  The only function types which
3595   // should have a receiver are the ones associated with explicitly
3596   // defined methods.  For those the receiver type is written out by
3597   // Function::export_func.
3598
3599   exp->write_c_string("(");
3600   bool first = true;
3601   if (this->parameters_ != NULL)
3602     {
3603       bool is_varargs = this->is_varargs_;
3604       for (Typed_identifier_list::const_iterator p =
3605              this->parameters_->begin();
3606            p != this->parameters_->end();
3607            ++p)
3608         {
3609           if (first)
3610             first = false;
3611           else
3612             exp->write_c_string(", ");
3613           exp->write_name(p->name());
3614           exp->write_c_string(" ");
3615           if (!is_varargs || p + 1 != this->parameters_->end())
3616             exp->write_type(p->type());
3617           else
3618             {
3619               exp->write_c_string("...");
3620               exp->write_type(p->type()->array_type()->element_type());
3621             }
3622         }
3623     }
3624   exp->write_c_string(")");
3625
3626   const Typed_identifier_list* results = this->results_;
3627   if (results != NULL)
3628     {
3629       exp->write_c_string(" ");
3630       if (results->size() == 1 && results->begin()->name().empty())
3631         exp->write_type(results->begin()->type());
3632       else
3633         {
3634           first = true;
3635           exp->write_c_string("(");
3636           for (Typed_identifier_list::const_iterator p = results->begin();
3637                p != results->end();
3638                ++p)
3639             {
3640               if (first)
3641                 first = false;
3642               else
3643                 exp->write_c_string(", ");
3644               exp->write_name(p->name());
3645               exp->write_c_string(" ");
3646               exp->write_type(p->type());
3647             }
3648           exp->write_c_string(")");
3649         }
3650     }
3651 }
3652
3653 // Import a function type.
3654
3655 Function_type*
3656 Function_type::do_import(Import* imp)
3657 {
3658   imp->require_c_string("(");
3659   Typed_identifier_list* parameters;
3660   bool is_varargs = false;
3661   if (imp->peek_char() == ')')
3662     parameters = NULL;
3663   else
3664     {
3665       parameters = new Typed_identifier_list();
3666       while (true)
3667         {
3668           std::string name = imp->read_name();
3669           imp->require_c_string(" ");
3670
3671           if (imp->match_c_string("..."))
3672             {
3673               imp->advance(3);
3674               is_varargs = true;
3675             }
3676
3677           Type* ptype = imp->read_type();
3678           if (is_varargs)
3679             ptype = Type::make_array_type(ptype, NULL);
3680           parameters->push_back(Typed_identifier(name, ptype,
3681                                                  imp->location()));
3682           if (imp->peek_char() != ',')
3683             break;
3684           go_assert(!is_varargs);
3685           imp->require_c_string(", ");
3686         }
3687     }
3688   imp->require_c_string(")");
3689
3690   Typed_identifier_list* results;
3691   if (imp->peek_char() != ' ')
3692     results = NULL;
3693   else
3694     {
3695       imp->advance(1);
3696       results = new Typed_identifier_list;
3697       if (imp->peek_char() != '(')
3698         {
3699           Type* rtype = imp->read_type();
3700           results->push_back(Typed_identifier("", rtype, imp->location()));
3701         }
3702       else
3703         {
3704           imp->advance(1);
3705           while (true)
3706             {
3707               std::string name = imp->read_name();
3708               imp->require_c_string(" ");
3709               Type* rtype = imp->read_type();
3710               results->push_back(Typed_identifier(name, rtype,
3711                                                   imp->location()));
3712               if (imp->peek_char() != ',')
3713                 break;
3714               imp->require_c_string(", ");
3715             }
3716           imp->require_c_string(")");
3717         }
3718     }
3719
3720   Function_type* ret = Type::make_function_type(NULL, parameters, results,
3721                                                 imp->location());
3722   if (is_varargs)
3723     ret->set_is_varargs();
3724   return ret;
3725 }
3726
3727 // Make a copy of a function type without a receiver.
3728
3729 Function_type*
3730 Function_type::copy_without_receiver() const
3731 {
3732   go_assert(this->is_method());
3733   Function_type *ret = Type::make_function_type(NULL, this->parameters_,
3734                                                 this->results_,
3735                                                 this->location_);
3736   if (this->is_varargs())
3737     ret->set_is_varargs();
3738   if (this->is_builtin())
3739     ret->set_is_builtin();
3740   return ret;
3741 }
3742
3743 // Make a copy of a function type with a receiver.
3744
3745 Function_type*
3746 Function_type::copy_with_receiver(Type* receiver_type) const
3747 {
3748   go_assert(!this->is_method());
3749   Typed_identifier* receiver = new Typed_identifier("", receiver_type,
3750                                                     this->location_);
3751   Function_type* ret = Type::make_function_type(receiver, this->parameters_,
3752                                                 this->results_,
3753                                                 this->location_);
3754   if (this->is_varargs_)
3755     ret->set_is_varargs();
3756   return ret;
3757 }
3758
3759 // Make a function type.
3760
3761 Function_type*
3762 Type::make_function_type(Typed_identifier* receiver,
3763                          Typed_identifier_list* parameters,
3764                          Typed_identifier_list* results,
3765                          Location location)
3766 {
3767   return new Function_type(receiver, parameters, results, location);
3768 }
3769
3770 // Class Pointer_type.
3771
3772 // Traversal.
3773
3774 int
3775 Pointer_type::do_traverse(Traverse* traverse)
3776 {
3777   return Type::traverse(this->to_type_, traverse);
3778 }
3779
3780 // Hash code.
3781
3782 unsigned int
3783 Pointer_type::do_hash_for_method(Gogo* gogo) const
3784 {
3785   return this->to_type_->hash_for_method(gogo) << 4;
3786 }
3787
3788 // Get the backend representation for a pointer type.
3789
3790 Btype*
3791 Pointer_type::do_get_backend(Gogo* gogo)
3792 {
3793   Btype* to_btype = this->to_type_->get_backend(gogo);
3794   return gogo->backend()->pointer_type(to_btype);
3795 }
3796
3797 // The type of a pointer type descriptor.
3798
3799 Type*
3800 Pointer_type::make_pointer_type_descriptor_type()
3801 {
3802   static Type* ret;
3803   if (ret == NULL)
3804     {
3805       Type* tdt = Type::make_type_descriptor_type();
3806       Type* ptdt = Type::make_type_descriptor_ptr_type();
3807
3808       Struct_type* s = Type::make_builtin_struct_type(2,
3809                                                       "", tdt,
3810                                                       "elem", ptdt);
3811
3812       ret = Type::make_builtin_named_type("PtrType", s);
3813     }
3814
3815   return ret;
3816 }
3817
3818 // The type descriptor for a pointer type.
3819
3820 Expression*
3821 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3822 {
3823   if (this->is_unsafe_pointer_type())
3824     {
3825       go_assert(name != NULL);
3826       return this->plain_type_descriptor(gogo,
3827                                          RUNTIME_TYPE_KIND_UNSAFE_POINTER,
3828                                          name);
3829     }
3830   else
3831     {
3832       Location bloc = Linemap::predeclared_location();
3833
3834       const Methods* methods;
3835       Type* deref = this->points_to();
3836       if (deref->named_type() != NULL)
3837         methods = deref->named_type()->methods();
3838       else if (deref->struct_type() != NULL)
3839         methods = deref->struct_type()->methods();
3840       else
3841         methods = NULL;
3842
3843       Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
3844
3845       const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
3846
3847       Expression_list* vals = new Expression_list();
3848       vals->reserve(2);
3849
3850       Struct_field_list::const_iterator p = fields->begin();
3851       go_assert(p->is_field_name("commonType"));
3852       vals->push_back(this->type_descriptor_constructor(gogo,
3853                                                         RUNTIME_TYPE_KIND_PTR,
3854                                                         name, methods, false));
3855
3856       ++p;
3857       go_assert(p->is_field_name("elem"));
3858       vals->push_back(Expression::make_type_descriptor(deref, bloc));
3859
3860       return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
3861     }
3862 }
3863
3864 // Reflection string.
3865
3866 void
3867 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
3868 {
3869   ret->push_back('*');
3870   this->append_reflection(this->to_type_, gogo, ret);
3871 }
3872
3873 // Mangled name.
3874
3875 void
3876 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
3877 {
3878   ret->push_back('p');
3879   this->append_mangled_name(this->to_type_, gogo, ret);
3880 }
3881
3882 // Export.
3883
3884 void
3885 Pointer_type::do_export(Export* exp) const
3886 {
3887   exp->write_c_string("*");
3888   if (this->is_unsafe_pointer_type())
3889     exp->write_c_string("any");
3890   else
3891     exp->write_type(this->to_type_);
3892 }
3893
3894 // Import.
3895
3896 Pointer_type*
3897 Pointer_type::do_import(Import* imp)
3898 {
3899   imp->require_c_string("*");
3900   if (imp->match_c_string("any"))
3901     {
3902       imp->advance(3);
3903       return Type::make_pointer_type(Type::make_void_type());
3904     }
3905   Type* to = imp->read_type();
3906   return Type::make_pointer_type(to);
3907 }
3908
3909 // Make a pointer type.
3910
3911 Pointer_type*
3912 Type::make_pointer_type(Type* to_type)
3913 {
3914   typedef Unordered_map(Type*, Pointer_type*) Hashtable;
3915   static Hashtable pointer_types;
3916   Hashtable::const_iterator p = pointer_types.find(to_type);
3917   if (p != pointer_types.end())
3918     return p->second;
3919   Pointer_type* ret = new Pointer_type(to_type);
3920   pointer_types[to_type] = ret;
3921   return ret;
3922 }
3923
3924 // The nil type.  We use a special type for nil because it is not the
3925 // same as any other type.  In C term nil has type void*, but there is
3926 // no such type in Go.
3927
3928 class Nil_type : public Type
3929 {
3930  public:
3931   Nil_type()
3932     : Type(TYPE_NIL)
3933   { }
3934
3935  protected:
3936   bool
3937   do_compare_is_identity(Gogo*) const
3938   { return false; }
3939
3940   Btype*
3941   do_get_backend(Gogo* gogo)
3942   { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
3943
3944   Expression*
3945   do_type_descriptor(Gogo*, Named_type*)
3946   { go_unreachable(); }
3947
3948   void
3949   do_reflection(Gogo*, std::string*) const
3950   { go_unreachable(); }
3951
3952   void
3953   do_mangled_name(Gogo*, std::string* ret) const
3954   { ret->push_back('n'); }
3955 };
3956
3957 // Make the nil type.
3958
3959 Type*
3960 Type::make_nil_type()
3961 {
3962   static Nil_type singleton_nil_type;
3963   return &singleton_nil_type;
3964 }
3965
3966 // The type of a function call which returns multiple values.  This is
3967 // really a struct, but we don't want to confuse a function call which
3968 // returns a struct with a function call which returns multiple
3969 // values.
3970
3971 class Call_multiple_result_type : public Type
3972 {
3973  public:
3974   Call_multiple_result_type(Call_expression* call)
3975     : Type(TYPE_CALL_MULTIPLE_RESULT),
3976       call_(call)
3977   { }
3978
3979  protected:
3980   bool
3981   do_has_pointer() const
3982   {
3983     go_assert(saw_errors());
3984     return false;
3985   }
3986
3987   bool
3988   do_compare_is_identity(Gogo*) const
3989   { return false; }
3990
3991   Btype*
3992   do_get_backend(Gogo* gogo)
3993   {
3994     go_assert(saw_errors());
3995     return gogo->backend()->error_type();
3996   }
3997
3998   Expression*
3999   do_type_descriptor(Gogo*, Named_type*)
4000   {
4001     go_assert(saw_errors());
4002     return Expression::make_error(Linemap::unknown_location());
4003   }
4004
4005   void
4006   do_reflection(Gogo*, std::string*) const
4007   { go_assert(saw_errors()); }
4008
4009   void
4010   do_mangled_name(Gogo*, std::string*) const
4011   { go_assert(saw_errors()); }
4012
4013  private:
4014   // The expression being called.
4015   Call_expression* call_;
4016 };
4017
4018 // Make a call result type.
4019
4020 Type*
4021 Type::make_call_multiple_result_type(Call_expression* call)
4022 {
4023   return new Call_multiple_result_type(call);
4024 }
4025
4026 // Class Struct_field.
4027
4028 // Get the name of a field.
4029
4030 const std::string&
4031 Struct_field::field_name() const
4032 {
4033   const std::string& name(this->typed_identifier_.name());
4034   if (!name.empty())
4035     return name;
4036   else
4037     {
4038       // This is called during parsing, before anything is lowered, so
4039       // we have to be pretty careful to avoid dereferencing an
4040       // unknown type name.
4041       Type* t = this->typed_identifier_.type();
4042       Type* dt = t;
4043       if (t->classification() == Type::TYPE_POINTER)
4044         {
4045           // Very ugly.
4046           Pointer_type* ptype = static_cast<Pointer_type*>(t);
4047           dt = ptype->points_to();
4048         }
4049       if (dt->forward_declaration_type() != NULL)
4050         return dt->forward_declaration_type()->name();
4051       else if (dt->named_type() != NULL)
4052         return dt->named_type()->name();
4053       else if (t->is_error_type() || dt->is_error_type())
4054         {
4055           static const std::string error_string = "*error*";
4056           return error_string;
4057         }
4058       else
4059         {
4060           // Avoid crashing in the erroneous case where T is named but
4061           // DT is not.
4062           go_assert(t != dt);
4063           if (t->forward_declaration_type() != NULL)
4064             return t->forward_declaration_type()->name();
4065           else if (t->named_type() != NULL)
4066             return t->named_type()->name();
4067           else
4068             go_unreachable();
4069         }
4070     }
4071 }
4072
4073 // Return whether this field is named NAME.
4074
4075 bool
4076 Struct_field::is_field_name(const std::string& name) const
4077 {
4078   const std::string& me(this->typed_identifier_.name());
4079   if (!me.empty())
4080     return me == name;
4081   else
4082     {
4083       Type* t = this->typed_identifier_.type();
4084       if (t->points_to() != NULL)
4085         t = t->points_to();
4086       Named_type* nt = t->named_type();
4087       if (nt != NULL && nt->name() == name)
4088         return true;
4089
4090       // This is a horrible hack caused by the fact that we don't pack
4091       // the names of builtin types.  FIXME.
4092       if (nt != NULL
4093           && nt->is_builtin()
4094           && nt->name() == Gogo::unpack_hidden_name(name))
4095         return true;
4096
4097       return false;
4098     }
4099 }
4100
4101 // Class Struct_type.
4102
4103 // Traversal.
4104
4105 int
4106 Struct_type::do_traverse(Traverse* traverse)
4107 {
4108   Struct_field_list* fields = this->fields_;
4109   if (fields != NULL)
4110     {
4111       for (Struct_field_list::iterator p = fields->begin();
4112            p != fields->end();
4113            ++p)
4114         {
4115           if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
4116             return TRAVERSE_EXIT;
4117         }
4118     }
4119   return TRAVERSE_CONTINUE;
4120 }
4121
4122 // Verify that the struct type is complete and valid.
4123
4124 bool
4125 Struct_type::do_verify()
4126 {
4127   Struct_field_list* fields = this->fields_;
4128   if (fields == NULL)
4129     return true;
4130   for (Struct_field_list::iterator p = fields->begin();
4131        p != fields->end();
4132        ++p)
4133     {
4134       Type* t = p->type();
4135       if (t->is_undefined())
4136         {
4137           error_at(p->location(), "struct field type is incomplete");
4138           p->set_type(Type::make_error_type());
4139         }
4140       else if (p->is_anonymous())
4141         {
4142           if (t->named_type() != NULL && t->points_to() != NULL)
4143             {
4144               error_at(p->location(), "embedded type may not be a pointer");
4145               p->set_type(Type::make_error_type());
4146             }
4147           else if (t->points_to() != NULL
4148                    && t->points_to()->interface_type() != NULL)
4149             {
4150               error_at(p->location(),
4151                        "embedded type may not be pointer to interface");
4152               p->set_type(Type::make_error_type());
4153             }
4154         }
4155     }
4156   return true;
4157 }
4158
4159 // Whether this contains a pointer.
4160
4161 bool
4162 Struct_type::do_has_pointer() const
4163 {
4164   const Struct_field_list* fields = this->fields();
4165   if (fields == NULL)
4166     return false;
4167   for (Struct_field_list::const_iterator p = fields->begin();
4168        p != fields->end();
4169        ++p)
4170     {
4171       if (p->type()->has_pointer())
4172         return true;
4173     }
4174   return false;
4175 }
4176
4177 // Whether this type is identical to T.
4178
4179 bool
4180 Struct_type::is_identical(const Struct_type* t,
4181                           bool errors_are_identical) const
4182 {
4183   const Struct_field_list* fields1 = this->fields();
4184   const Struct_field_list* fields2 = t->fields();
4185   if (fields1 == NULL || fields2 == NULL)
4186     return fields1 == fields2;
4187   Struct_field_list::const_iterator pf2 = fields2->begin();
4188   for (Struct_field_list::const_iterator pf1 = fields1->begin();
4189        pf1 != fields1->end();
4190        ++pf1, ++pf2)
4191     {
4192       if (pf2 == fields2->end())
4193         return false;
4194       if (pf1->field_name() != pf2->field_name())
4195         return false;
4196       if (pf1->is_anonymous() != pf2->is_anonymous()
4197           || !Type::are_identical(pf1->type(), pf2->type(),
4198                                   errors_are_identical, NULL))
4199         return false;
4200       if (!pf1->has_tag())
4201         {
4202           if (pf2->has_tag())
4203             return false;
4204         }
4205       else
4206         {
4207           if (!pf2->has_tag())
4208             return false;
4209           if (pf1->tag() != pf2->tag())
4210             return false;
4211         }
4212     }
4213   if (pf2 != fields2->end())
4214     return false;
4215   return true;
4216 }
4217
4218 // Whether this struct type has any hidden fields.
4219
4220 bool
4221 Struct_type::struct_has_hidden_fields(const Named_type* within,
4222                                       std::string* reason) const
4223 {
4224   const Struct_field_list* fields = this->fields();
4225   if (fields == NULL)
4226     return false;
4227   const Package* within_package = (within == NULL
4228                                    ? NULL
4229                                    : within->named_object()->package());
4230   for (Struct_field_list::const_iterator pf = fields->begin();
4231        pf != fields->end();
4232        ++pf)
4233     {
4234       if (within_package != NULL
4235           && !pf->is_anonymous()
4236           && Gogo::is_hidden_name(pf->field_name()))
4237         {
4238           if (reason != NULL)
4239             {
4240               std::string within_name = within->named_object()->message_name();
4241               std::string name = Gogo::message_name(pf->field_name());
4242               size_t bufsize = 200 + within_name.length() + name.length();
4243               char* buf = new char[bufsize];
4244               snprintf(buf, bufsize,
4245                        _("implicit assignment of %s%s%s hidden field %s%s%s"),
4246                        open_quote, within_name.c_str(), close_quote,
4247                        open_quote, name.c_str(), close_quote);
4248               reason->assign(buf);
4249               delete[] buf;
4250             }
4251           return true;
4252         }
4253
4254       if (pf->type()->has_hidden_fields(within, reason))
4255         return true;
4256     }
4257
4258   return false;
4259 }
4260
4261 // Whether comparisons of this struct type are simple identity
4262 // comparisons.
4263
4264 bool
4265 Struct_type::do_compare_is_identity(Gogo* gogo) const
4266 {
4267   const Struct_field_list* fields = this->fields_;
4268   if (fields == NULL)
4269     return true;
4270   unsigned int offset = 0;
4271   for (Struct_field_list::const_iterator pf = fields->begin();
4272        pf != fields->end();
4273        ++pf)
4274     {
4275       if (!pf->type()->compare_is_identity(gogo))
4276         return false;
4277
4278       unsigned int field_align;
4279       if (!pf->type()->backend_type_align(gogo, &field_align))
4280         return false;
4281       if ((offset & (field_align - 1)) != 0)
4282         {
4283           // This struct has padding.  We don't guarantee that that
4284           // padding is zero-initialized for a stack variable, so we
4285           // can't use memcmp to compare struct values.
4286           return false;
4287         }
4288
4289       unsigned int field_size;
4290       if (!pf->type()->backend_type_size(gogo, &field_size))
4291         return false;
4292       offset += field_size;
4293     }
4294   return true;
4295 }
4296
4297 // Build identity and hash functions for this struct.
4298
4299 // Hash code.
4300
4301 unsigned int
4302 Struct_type::do_hash_for_method(Gogo* gogo) const
4303 {
4304   unsigned int ret = 0;
4305   if (this->fields() != NULL)
4306     {
4307       for (Struct_field_list::const_iterator pf = this->fields()->begin();
4308            pf != this->fields()->end();
4309            ++pf)
4310         ret = (ret << 1) + pf->type()->hash_for_method(gogo);
4311     }
4312   return ret <<= 2;
4313 }
4314
4315 // Find the local field NAME.
4316
4317 const Struct_field*
4318 Struct_type::find_local_field(const std::string& name,
4319                               unsigned int *pindex) const
4320 {
4321   const Struct_field_list* fields = this->fields_;
4322   if (fields == NULL)
4323     return NULL;
4324   unsigned int i = 0;
4325   for (Struct_field_list::const_iterator pf = fields->begin();
4326        pf != fields->end();
4327        ++pf, ++i)
4328     {
4329       if (pf->is_field_name(name))
4330         {
4331           if (pindex != NULL)
4332             *pindex = i;
4333           return &*pf;
4334         }
4335     }
4336   return NULL;
4337 }
4338
4339 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
4340
4341 Field_reference_expression*
4342 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
4343                              Location location) const
4344 {
4345   unsigned int depth;
4346   return this->field_reference_depth(struct_expr, name, location, NULL,
4347                                      &depth);
4348 }
4349
4350 // Return an expression for a field, along with the depth at which it
4351 // was found.
4352
4353 Field_reference_expression*
4354 Struct_type::field_reference_depth(Expression* struct_expr,
4355                                    const std::string& name,
4356                                    Location location,
4357                                    Saw_named_type* saw,
4358                                    unsigned int* depth) const
4359 {
4360   const Struct_field_list* fields = this->fields_;
4361   if (fields == NULL)
4362     return NULL;
4363
4364   // Look for a field with this name.
4365   unsigned int i = 0;
4366   for (Struct_field_list::const_iterator pf = fields->begin();
4367        pf != fields->end();
4368        ++pf, ++i)
4369     {
4370       if (pf->is_field_name(name))
4371         {
4372           *depth = 0;
4373           return Expression::make_field_reference(struct_expr, i, location);
4374         }
4375     }
4376
4377   // Look for an anonymous field which contains a field with this
4378   // name.
4379   unsigned int found_depth = 0;
4380   Field_reference_expression* ret = NULL;
4381   i = 0;
4382   for (Struct_field_list::const_iterator pf = fields->begin();
4383        pf != fields->end();
4384        ++pf, ++i)
4385     {
4386       if (!pf->is_anonymous())
4387         continue;
4388
4389       Struct_type* st = pf->type()->deref()->struct_type();
4390       if (st == NULL)
4391         continue;
4392
4393       Saw_named_type* hold_saw = saw;
4394       Saw_named_type saw_here;
4395       Named_type* nt = pf->type()->named_type();
4396       if (nt == NULL)
4397         nt = pf->type()->deref()->named_type();
4398       if (nt != NULL)
4399         {
4400           Saw_named_type* q;
4401           for (q = saw; q != NULL; q = q->next)
4402             {
4403               if (q->nt == nt)
4404                 {
4405                   // If this is an error, it will be reported
4406                   // elsewhere.
4407                   break;
4408                 }
4409             }
4410           if (q != NULL)
4411             continue;
4412           saw_here.next = saw;
4413           saw_here.nt = nt;
4414           saw = &saw_here;
4415         }
4416
4417       // Look for a reference using a NULL struct expression.  If we
4418       // find one, fill in the struct expression with a reference to
4419       // this field.
4420       unsigned int subdepth;
4421       Field_reference_expression* sub = st->field_reference_depth(NULL, name,
4422                                                                   location,
4423                                                                   saw,
4424                                                                   &subdepth);
4425
4426       saw = hold_saw;
4427
4428       if (sub == NULL)
4429         continue;
4430
4431       if (ret == NULL || subdepth < found_depth)
4432         {
4433           if (ret != NULL)
4434             delete ret;
4435           ret = sub;
4436           found_depth = subdepth;
4437           Expression* here = Expression::make_field_reference(struct_expr, i,
4438                                                               location);
4439           if (pf->type()->points_to() != NULL)
4440             here = Expression::make_unary(OPERATOR_MULT, here, location);
4441           while (sub->expr() != NULL)
4442             {
4443               sub = sub->expr()->deref()->field_reference_expression();
4444               go_assert(sub != NULL);
4445             }
4446           sub->set_struct_expression(here);
4447         }
4448       else if (subdepth > found_depth)
4449         delete sub;
4450       else
4451         {
4452           // We do not handle ambiguity here--it should be handled by
4453           // Type::bind_field_or_method.
4454           delete sub;
4455           found_depth = 0;
4456           ret = NULL;
4457         }
4458     }
4459
4460   if (ret != NULL)
4461     *depth = found_depth + 1;
4462
4463   return ret;
4464 }
4465
4466 // Return the total number of fields, including embedded fields.
4467
4468 unsigned int
4469 Struct_type::total_field_count() const
4470 {
4471   if (this->fields_ == NULL)
4472     return 0;
4473   unsigned int ret = 0;
4474   for (Struct_field_list::const_iterator pf = this->fields_->begin();
4475        pf != this->fields_->end();
4476        ++pf)
4477     {
4478       if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
4479         ++ret;
4480       else
4481         ret += pf->type()->struct_type()->total_field_count();
4482     }
4483   return ret;
4484 }
4485
4486 // Return whether NAME is an unexported field, for better error reporting.
4487
4488 bool
4489 Struct_type::is_unexported_local_field(Gogo* gogo,
4490                                        const std::string& name) const
4491 {
4492   const Struct_field_list* fields = this->fields_;
4493   if (fields != NULL)
4494     {
4495       for (Struct_field_list::const_iterator pf = fields->begin();
4496            pf != fields->end();
4497            ++pf)
4498         {
4499           const std::string& field_name(pf->field_name());
4500           if (Gogo::is_hidden_name(field_name)
4501               && name == Gogo::unpack_hidden_name(field_name)
4502               && gogo->pack_hidden_name(name, false) != field_name)
4503             return true;
4504         }
4505     }
4506   return false;
4507 }
4508
4509 // Finalize the methods of an unnamed struct.
4510
4511 void
4512 Struct_type::finalize_methods(Gogo* gogo)
4513 {
4514   if (this->all_methods_ != NULL)
4515     return;
4516   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
4517 }
4518
4519 // Return the method NAME, or NULL if there isn't one or if it is
4520 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
4521 // ambiguous.
4522
4523 Method*
4524 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
4525 {
4526   return Type::method_function(this->all_methods_, name, is_ambiguous);
4527 }
4528
4529 // Convert struct fields to the backend representation.  This is not
4530 // declared in types.h so that types.h doesn't have to #include
4531 // backend.h.
4532
4533 static void
4534 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
4535                           bool use_placeholder,
4536                           std::vector<Backend::Btyped_identifier>* bfields)
4537 {
4538   bfields->resize(fields->size());
4539   size_t i = 0;
4540   for (Struct_field_list::const_iterator p = fields->begin();
4541        p != fields->end();
4542        ++p, ++i)
4543     {
4544       (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
4545       (*bfields)[i].btype = (use_placeholder
4546                              ? p->type()->get_backend_placeholder(gogo)
4547                              : p->type()->get_backend(gogo));
4548       (*bfields)[i].location = p->location();
4549     }
4550   go_assert(i == fields->size());
4551 }
4552
4553 // Get the tree for a struct type.
4554
4555 Btype*
4556 Struct_type::do_get_backend(Gogo* gogo)
4557 {
4558   std::vector<Backend::Btyped_identifier> bfields;
4559   get_backend_struct_fields(gogo, this->fields_, false, &bfields);
4560   return gogo->backend()->struct_type(bfields);
4561 }
4562
4563 // Finish the backend representation of the fields of a struct.
4564
4565 void
4566 Struct_type::finish_backend_fields(Gogo* gogo)
4567 {
4568   const Struct_field_list* fields = this->fields_;
4569   if (fields != NULL)
4570     {
4571       for (Struct_field_list::const_iterator p = fields->begin();
4572            p != fields->end();
4573            ++p)
4574         p->type()->get_backend(gogo);
4575     }
4576 }
4577
4578 // The type of a struct type descriptor.
4579
4580 Type*
4581 Struct_type::make_struct_type_descriptor_type()
4582 {
4583   static Type* ret;
4584   if (ret == NULL)
4585     {
4586       Type* tdt = Type::make_type_descriptor_type();
4587       Type* ptdt = Type::make_type_descriptor_ptr_type();
4588
4589       Type* uintptr_type = Type::lookup_integer_type("uintptr");
4590       Type* string_type = Type::lookup_string_type();
4591       Type* pointer_string_type = Type::make_pointer_type(string_type);
4592
4593       Struct_type* sf =
4594         Type::make_builtin_struct_type(5,
4595                                        "name", pointer_string_type,
4596                                        "pkgPath", pointer_string_type,
4597                                        "typ", ptdt,
4598                                        "tag", pointer_string_type,
4599                                        "offset", uintptr_type);
4600       Type* nsf = Type::make_builtin_named_type("structField", sf);
4601
4602       Type* slice_type = Type::make_array_type(nsf, NULL);
4603
4604       Struct_type* s = Type::make_builtin_struct_type(2,
4605                                                       "", tdt,
4606                                                       "fields", slice_type);
4607
4608       ret = Type::make_builtin_named_type("StructType", s);
4609     }
4610
4611   return ret;
4612 }
4613
4614 // Build a type descriptor for a struct type.
4615
4616 Expression*
4617 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4618 {
4619   Location bloc = Linemap::predeclared_location();
4620
4621   Type* stdt = Struct_type::make_struct_type_descriptor_type();
4622
4623   const Struct_field_list* fields = stdt->struct_type()->fields();
4624
4625   Expression_list* vals = new Expression_list();
4626   vals->reserve(2);
4627
4628   const Methods* methods = this->methods();
4629   // A named struct should not have methods--the methods should attach
4630   // to the named type.
4631   go_assert(methods == NULL || name == NULL);
4632
4633   Struct_field_list::const_iterator ps = fields->begin();
4634   go_assert(ps->is_field_name("commonType"));
4635   vals->push_back(this->type_descriptor_constructor(gogo,
4636                                                     RUNTIME_TYPE_KIND_STRUCT,
4637                                                     name, methods, true));
4638
4639   ++ps;
4640   go_assert(ps->is_field_name("fields"));
4641
4642   Expression_list* elements = new Expression_list();
4643   elements->reserve(this->fields_->size());
4644   Type* element_type = ps->type()->array_type()->element_type();
4645   for (Struct_field_list::const_iterator pf = this->fields_->begin();
4646        pf != this->fields_->end();
4647        ++pf)
4648     {
4649       const Struct_field_list* f = element_type->struct_type()->fields();
4650
4651       Expression_list* fvals = new Expression_list();
4652       fvals->reserve(5);
4653
4654       Struct_field_list::const_iterator q = f->begin();
4655       go_assert(q->is_field_name("name"));
4656       if (pf->is_anonymous())
4657         fvals->push_back(Expression::make_nil(bloc));
4658       else
4659         {
4660           std::string n = Gogo::unpack_hidden_name(pf->field_name());
4661           Expression* s = Expression::make_string(n, bloc);
4662           fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4663         }
4664
4665       ++q;
4666       go_assert(q->is_field_name("pkgPath"));
4667       if (!Gogo::is_hidden_name(pf->field_name()))
4668         fvals->push_back(Expression::make_nil(bloc));
4669       else
4670         {
4671           std::string n = Gogo::hidden_name_prefix(pf->field_name());
4672           Expression* s = Expression::make_string(n, bloc);
4673           fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4674         }
4675
4676       ++q;
4677       go_assert(q->is_field_name("typ"));
4678       fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
4679
4680       ++q;
4681       go_assert(q->is_field_name("tag"));
4682       if (!pf->has_tag())
4683         fvals->push_back(Expression::make_nil(bloc));
4684       else
4685         {
4686           Expression* s = Expression::make_string(pf->tag(), bloc);
4687           fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
4688         }
4689
4690       ++q;
4691       go_assert(q->is_field_name("offset"));
4692       fvals->push_back(Expression::make_struct_field_offset(this, &*pf));
4693
4694       Expression* v = Expression::make_struct_composite_literal(element_type,
4695                                                                 fvals, bloc);
4696       elements->push_back(v);
4697     }
4698
4699   vals->push_back(Expression::make_slice_composite_literal(ps->type(),
4700                                                            elements, bloc));
4701
4702   return Expression::make_struct_composite_literal(stdt, vals, bloc);
4703 }
4704
4705 // Write the hash function for a struct which can not use the identity
4706 // function.
4707
4708 void
4709 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
4710                                  Function_type* hash_fntype,
4711                                  Function_type* equal_fntype)
4712 {
4713   Location bloc = Linemap::predeclared_location();
4714
4715   // The pointer to the struct that we are going to hash.  This is an
4716   // argument to the hash function we are implementing here.
4717   Named_object* key_arg = gogo->lookup("key", NULL);
4718   go_assert(key_arg != NULL);
4719   Type* key_arg_type = key_arg->var_value()->type();
4720
4721   Type* uintptr_type = Type::lookup_integer_type("uintptr");
4722
4723   // Get a 0.
4724   mpz_t ival;
4725   mpz_init_set_ui(ival, 0);
4726   Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
4727   mpz_clear(ival);
4728
4729   // Make a temporary to hold the return value, initialized to 0.
4730   Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
4731                                                           bloc);
4732   gogo->add_statement(retval);
4733
4734   // Make a temporary to hold the key as a uintptr.
4735   Expression* ref = Expression::make_var_reference(key_arg, bloc);
4736   ref = Expression::make_cast(uintptr_type, ref, bloc);
4737   Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
4738                                                        bloc);
4739   gogo->add_statement(key);
4740
4741   // Loop over the struct fields.
4742   bool first = true;
4743   const Struct_field_list* fields = this->fields_;
4744   for (Struct_field_list::const_iterator pf = fields->begin();
4745        pf != fields->end();
4746        ++pf)
4747     {
4748       if (first)
4749         first = false;
4750       else
4751         {
4752           // Multiply retval by 33.
4753           mpz_init_set_ui(ival, 33);
4754           Expression* i33 = Expression::make_integer(&ival, uintptr_type,
4755                                                      bloc);
4756           mpz_clear(ival);
4757
4758           ref = Expression::make_temporary_reference(retval, bloc);
4759           Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ,
4760                                                               ref, i33, bloc);
4761           gogo->add_statement(s);
4762         }
4763
4764       // Get a pointer to the value of this field.
4765       Expression* offset = Expression::make_struct_field_offset(this, &*pf);
4766       ref = Expression::make_temporary_reference(key, bloc);
4767       Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
4768                                                    bloc);
4769       subkey = Expression::make_cast(key_arg_type, subkey, bloc);
4770
4771       // Get the size of this field.
4772       Expression* size = Expression::make_type_info(pf->type(),
4773                                                     Expression::TYPE_INFO_SIZE);
4774
4775       // Get the hash function to use for the type of this field.
4776       Named_object* hash_fn;
4777       Named_object* equal_fn;
4778       pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
4779                                  equal_fntype, &hash_fn, &equal_fn);
4780
4781       // Call the hash function for the field.
4782       Expression_list* args = new Expression_list();
4783       args->push_back(subkey);
4784       args->push_back(size);
4785       Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
4786       Expression* call = Expression::make_call(func, args, false, bloc);
4787
4788       // Add the field's hash value to retval.
4789       Temporary_reference_expression* tref =
4790         Expression::make_temporary_reference(retval, bloc);
4791       tref->set_is_lvalue();
4792       Statement* s = Statement::make_assignment_operation(OPERATOR_PLUSEQ,
4793                                                           tref, call, bloc);
4794       gogo->add_statement(s);
4795     }
4796
4797   // Return retval to the caller of the hash function.
4798   Expression_list* vals = new Expression_list();
4799   ref = Expression::make_temporary_reference(retval, bloc);
4800   vals->push_back(ref);
4801   Statement* s = Statement::make_return_statement(vals, bloc);
4802   gogo->add_statement(s);
4803 }
4804
4805 // Write the equality function for a struct which can not use the
4806 // identity function.
4807
4808 void
4809 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
4810 {
4811   Location bloc = Linemap::predeclared_location();
4812
4813   // The pointers to the structs we are going to compare.
4814   Named_object* key1_arg = gogo->lookup("key1", NULL);
4815   Named_object* key2_arg = gogo->lookup("key2", NULL);
4816   go_assert(key1_arg != NULL && key2_arg != NULL);
4817
4818   // Build temporaries with the right types.
4819   Type* pt = Type::make_pointer_type(name != NULL
4820                                      ? static_cast<Type*>(name)
4821                                      : static_cast<Type*>(this));
4822
4823   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
4824   ref = Expression::make_unsafe_cast(pt, ref, bloc);
4825   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
4826   gogo->add_statement(p1);
4827
4828   ref = Expression::make_var_reference(key2_arg, bloc);
4829   ref = Expression::make_unsafe_cast(pt, ref, bloc);
4830   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
4831   gogo->add_statement(p2);
4832
4833   const Struct_field_list* fields = this->fields_;
4834   unsigned int field_index = 0;
4835   for (Struct_field_list::const_iterator pf = fields->begin();
4836        pf != fields->end();
4837        ++pf, ++field_index)
4838     {
4839       // Compare one field in both P1 and P2.
4840       Expression* f1 = Expression::make_temporary_reference(p1, bloc);
4841       f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
4842       f1 = Expression::make_field_reference(f1, field_index, bloc);
4843
4844       Expression* f2 = Expression::make_temporary_reference(p2, bloc);
4845       f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
4846       f2 = Expression::make_field_reference(f2, field_index, bloc);
4847
4848       Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
4849
4850       // If the values are not equal, return false.
4851       gogo->start_block(bloc);
4852       Expression_list* vals = new Expression_list();
4853       vals->push_back(Expression::make_boolean(false, bloc));
4854       Statement* s = Statement::make_return_statement(vals, bloc);
4855       gogo->add_statement(s);
4856       Block* then_block = gogo->finish_block(bloc);
4857
4858       s = Statement::make_if_statement(cond, then_block, NULL, bloc);
4859       gogo->add_statement(s);
4860     }
4861
4862   // All the fields are equal, so return true.
4863   Expression_list* vals = new Expression_list();
4864   vals->push_back(Expression::make_boolean(true, bloc));
4865   Statement* s = Statement::make_return_statement(vals, bloc);
4866   gogo->add_statement(s);
4867 }
4868
4869 // Reflection string.
4870
4871 void
4872 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
4873 {
4874   ret->append("struct { ");
4875
4876   for (Struct_field_list::const_iterator p = this->fields_->begin();
4877        p != this->fields_->end();
4878        ++p)
4879     {
4880       if (p != this->fields_->begin())
4881         ret->append("; ");
4882       if (p->is_anonymous())
4883         ret->push_back('?');
4884       else
4885         ret->append(Gogo::unpack_hidden_name(p->field_name()));
4886       ret->push_back(' ');
4887       this->append_reflection(p->type(), gogo, ret);
4888
4889       if (p->has_tag())
4890         {
4891           const std::string& tag(p->tag());
4892           ret->append(" \"");
4893           for (std::string::const_iterator p = tag.begin();
4894                p != tag.end();
4895                ++p)
4896             {
4897               if (*p == '\0')
4898                 ret->append("\\x00");
4899               else if (*p == '\n')
4900                 ret->append("\\n");
4901               else if (*p == '\t')
4902                 ret->append("\\t");
4903               else if (*p == '"')
4904                 ret->append("\\\"");
4905               else if (*p == '\\')
4906                 ret->append("\\\\");
4907               else
4908                 ret->push_back(*p);
4909             }
4910           ret->push_back('"');
4911         }
4912     }
4913
4914   ret->append(" }");
4915 }
4916
4917 // Mangled name.
4918
4919 void
4920 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
4921 {
4922   ret->push_back('S');
4923
4924   const Struct_field_list* fields = this->fields_;
4925   if (fields != NULL)
4926     {
4927       for (Struct_field_list::const_iterator p = fields->begin();
4928            p != fields->end();
4929            ++p)
4930         {
4931           if (p->is_anonymous())
4932             ret->append("0_");
4933           else
4934             {
4935               std::string n = Gogo::unpack_hidden_name(p->field_name());
4936               char buf[20];
4937               snprintf(buf, sizeof buf, "%u_",
4938                        static_cast<unsigned int>(n.length()));
4939               ret->append(buf);
4940               ret->append(n);
4941             }
4942           this->append_mangled_name(p->type(), gogo, ret);
4943           if (p->has_tag())
4944             {
4945               const std::string& tag(p->tag());
4946               std::string out;
4947               for (std::string::const_iterator p = tag.begin();
4948                    p != tag.end();
4949                    ++p)
4950                 {
4951                   if (ISALNUM(*p) || *p == '_')
4952                     out.push_back(*p);
4953                   else
4954                     {
4955                       char buf[20];
4956                       snprintf(buf, sizeof buf, ".%x.",
4957                                static_cast<unsigned int>(*p));
4958                       out.append(buf);
4959                     }
4960                 }
4961               char buf[20];
4962               snprintf(buf, sizeof buf, "T%u_",
4963                        static_cast<unsigned int>(out.length()));
4964               ret->append(buf);
4965               ret->append(out);
4966             }
4967         }
4968     }
4969
4970   ret->push_back('e');
4971 }
4972
4973 // If the offset of field INDEX in the backend implementation can be
4974 // determined, set *POFFSET to the offset in bytes and return true.
4975 // Otherwise, return false.
4976
4977 bool
4978 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
4979                                   unsigned int* poffset)
4980 {
4981   if (!this->is_backend_type_size_known(gogo))
4982     return false;
4983   Btype* bt = this->get_backend_placeholder(gogo);
4984   size_t offset = gogo->backend()->type_field_offset(bt, index);
4985   *poffset = static_cast<unsigned int>(offset);
4986   if (*poffset != offset)
4987     return false;
4988   return true;
4989 }
4990
4991 // Export.
4992
4993 void
4994 Struct_type::do_export(Export* exp) const
4995 {
4996   exp->write_c_string("struct { ");
4997   const Struct_field_list* fields = this->fields_;
4998   go_assert(fields != NULL);
4999   for (Struct_field_list::const_iterator p = fields->begin();
5000        p != fields->end();
5001        ++p)
5002     {
5003       if (p->is_anonymous())
5004         exp->write_string("? ");
5005       else
5006         {
5007           exp->write_string(p->field_name());
5008           exp->write_c_string(" ");
5009         }
5010       exp->write_type(p->type());
5011
5012       if (p->has_tag())
5013         {
5014           exp->write_c_string(" ");
5015           Expression* expr =
5016             Expression::make_string(p->tag(), Linemap::predeclared_location());
5017           expr->export_expression(exp);
5018           delete expr;
5019         }
5020
5021       exp->write_c_string("; ");
5022     }
5023   exp->write_c_string("}");
5024 }
5025
5026 // Import.
5027
5028 Struct_type*
5029 Struct_type::do_import(Import* imp)
5030 {
5031   imp->require_c_string("struct { ");
5032   Struct_field_list* fields = new Struct_field_list;
5033   if (imp->peek_char() != '}')
5034     {
5035       while (true)
5036         {
5037           std::string name;
5038           if (imp->match_c_string("? "))
5039             imp->advance(2);
5040           else
5041             {
5042               name = imp->read_identifier();
5043               imp->require_c_string(" ");
5044             }
5045           Type* ftype = imp->read_type();
5046
5047           Struct_field sf(Typed_identifier(name, ftype, imp->location()));
5048
5049           if (imp->peek_char() == ' ')
5050             {
5051               imp->advance(1);
5052               Expression* expr = Expression::import_expression(imp);
5053               String_expression* sexpr = expr->string_expression();
5054               go_assert(sexpr != NULL);
5055               sf.set_tag(sexpr->val());
5056               delete sexpr;
5057             }
5058
5059           imp->require_c_string("; ");
5060           fields->push_back(sf);
5061           if (imp->peek_char() == '}')
5062             break;
5063         }
5064     }
5065   imp->require_c_string("}");
5066
5067   return Type::make_struct_type(fields, imp->location());
5068 }
5069
5070 // Make a struct type.
5071
5072 Struct_type*
5073 Type::make_struct_type(Struct_field_list* fields,
5074                        Location location)
5075 {
5076   return new Struct_type(fields, location);
5077 }
5078
5079 // Class Array_type.
5080
5081 // Whether two array types are identical.
5082
5083 bool
5084 Array_type::is_identical(const Array_type* t, bool errors_are_identical) const
5085 {
5086   if (!Type::are_identical(this->element_type(), t->element_type(),
5087                            errors_are_identical, NULL))
5088     return false;
5089
5090   Expression* l1 = this->length();
5091   Expression* l2 = t->length();
5092
5093   // Slices of the same element type are identical.
5094   if (l1 == NULL && l2 == NULL)
5095     return true;
5096
5097   // Arrays of the same element type are identical if they have the
5098   // same length.
5099   if (l1 != NULL && l2 != NULL)
5100     {
5101       if (l1 == l2)
5102         return true;
5103
5104       // Try to determine the lengths.  If we can't, assume the arrays
5105       // are not identical.
5106       bool ret = false;
5107       Numeric_constant nc1, nc2;
5108       if (l1->numeric_constant_value(&nc1)
5109           && l2->numeric_constant_value(&nc2))
5110         {
5111           mpz_t v1;
5112           if (nc1.to_int(&v1))
5113             {
5114               mpz_t v2;
5115               if (nc2.to_int(&v2))
5116                 {
5117                   ret = mpz_cmp(v1, v2) == 0;
5118                   mpz_clear(v2);
5119                 }
5120               mpz_clear(v1);
5121             }
5122         }
5123       return ret;
5124     }
5125
5126   // Otherwise the arrays are not identical.
5127   return false;
5128 }
5129
5130 // Traversal.
5131
5132 int
5133 Array_type::do_traverse(Traverse* traverse)
5134 {
5135   if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
5136     return TRAVERSE_EXIT;
5137   if (this->length_ != NULL
5138       && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
5139     return TRAVERSE_EXIT;
5140   return TRAVERSE_CONTINUE;
5141 }
5142
5143 // Check that the length is valid.
5144
5145 bool
5146 Array_type::verify_length()
5147 {
5148   if (this->length_ == NULL)
5149     return true;
5150
5151   Type_context context(Type::lookup_integer_type("int"), false);
5152   this->length_->determine_type(&context);
5153
5154   if (!this->length_->is_constant())
5155     {
5156       error_at(this->length_->location(), "array bound is not constant");
5157       return false;
5158     }
5159
5160   Numeric_constant nc;
5161   if (!this->length_->numeric_constant_value(&nc))
5162     {
5163       if (this->length_->type()->integer_type() != NULL
5164           || this->length_->type()->float_type() != NULL)
5165         error_at(this->length_->location(), "array bound is not constant");
5166       else
5167         error_at(this->length_->location(), "array bound is not numeric");
5168       return false;
5169     }
5170
5171   unsigned long val;
5172   switch (nc.to_unsigned_long(&val))
5173     {
5174     case Numeric_constant::NC_UL_VALID:
5175       break;
5176     case Numeric_constant::NC_UL_NOTINT:
5177       error_at(this->length_->location(), "array bound truncated to integer");
5178       return false;
5179     case Numeric_constant::NC_UL_NEGATIVE:
5180       error_at(this->length_->location(), "negative array bound");
5181       return false;
5182     case Numeric_constant::NC_UL_BIG:
5183       error_at(this->length_->location(), "array bound overflows");
5184       return false;
5185     default:
5186       go_unreachable();
5187     }
5188
5189   Type* int_type = Type::lookup_integer_type("int");
5190   unsigned int tbits = int_type->integer_type()->bits();
5191   if (sizeof(val) <= tbits * 8
5192       && val >> (tbits - 1) != 0)
5193     {
5194       error_at(this->length_->location(), "array bound overflows");
5195       return false;
5196     }
5197
5198   return true;
5199 }
5200
5201 // Verify the type.
5202
5203 bool
5204 Array_type::do_verify()
5205 {
5206   if (!this->verify_length())
5207     this->length_ = Expression::make_error(this->length_->location());
5208   return true;
5209 }
5210
5211 // Whether we can use memcmp to compare this array.
5212
5213 bool
5214 Array_type::do_compare_is_identity(Gogo* gogo) const
5215 {
5216   if (this->length_ == NULL)
5217     return false;
5218
5219   // Check for [...], which indicates that this is not a real type.
5220   if (this->length_->is_nil_expression())
5221     return false;
5222
5223   if (!this->element_type_->compare_is_identity(gogo))
5224     return false;
5225
5226   // If there is any padding, then we can't use memcmp.
5227   unsigned int size;
5228   unsigned int align;
5229   if (!this->element_type_->backend_type_size(gogo, &size)
5230       || !this->element_type_->backend_type_align(gogo, &align))
5231     return false;
5232   if ((size & (align - 1)) != 0)
5233     return false;
5234
5235   return true;
5236 }
5237
5238 // Array type hash code.
5239
5240 unsigned int
5241 Array_type::do_hash_for_method(Gogo* gogo) const
5242 {
5243   // There is no very convenient way to get a hash code for the
5244   // length.
5245   return this->element_type_->hash_for_method(gogo) + 1;
5246 }
5247
5248 // Write the hash function for an array which can not use the identify
5249 // function.
5250
5251 void
5252 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
5253                                 Function_type* hash_fntype,
5254                                 Function_type* equal_fntype)
5255 {
5256   Location bloc = Linemap::predeclared_location();
5257
5258   // The pointer to the array that we are going to hash.  This is an
5259   // argument to the hash function we are implementing here.
5260   Named_object* key_arg = gogo->lookup("key", NULL);
5261   go_assert(key_arg != NULL);
5262   Type* key_arg_type = key_arg->var_value()->type();
5263
5264   Type* uintptr_type = Type::lookup_integer_type("uintptr");
5265
5266   // Get a 0.
5267   mpz_t ival;
5268   mpz_init_set_ui(ival, 0);
5269   Expression* zero = Expression::make_integer(&ival, uintptr_type, bloc);
5270   mpz_clear(ival);
5271
5272   // Make a temporary to hold the return value, initialized to 0.
5273   Temporary_statement* retval = Statement::make_temporary(uintptr_type, zero,
5274                                                           bloc);
5275   gogo->add_statement(retval);
5276
5277   // Make a temporary to hold the key as a uintptr.
5278   Expression* ref = Expression::make_var_reference(key_arg, bloc);
5279   ref = Expression::make_cast(uintptr_type, ref, bloc);
5280   Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
5281                                                        bloc);
5282   gogo->add_statement(key);
5283
5284   // Loop over the array elements.
5285   // for i = range a
5286   Type* int_type = Type::lookup_integer_type("int");
5287   Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5288   gogo->add_statement(index);
5289
5290   Expression* iref = Expression::make_temporary_reference(index, bloc);
5291   Expression* aref = Expression::make_var_reference(key_arg, bloc);
5292   Type* pt = Type::make_pointer_type(name != NULL
5293                                      ? static_cast<Type*>(name)
5294                                      : static_cast<Type*>(this));
5295   aref = Expression::make_cast(pt, aref, bloc);
5296   For_range_statement* for_range = Statement::make_for_range_statement(iref,
5297                                                                        NULL,
5298                                                                        aref,
5299                                                                        bloc);
5300
5301   gogo->start_block(bloc);
5302
5303   // Multiply retval by 33.
5304   mpz_init_set_ui(ival, 33);
5305   Expression* i33 = Expression::make_integer(&ival, uintptr_type, bloc);
5306   mpz_clear(ival);
5307
5308   ref = Expression::make_temporary_reference(retval, bloc);
5309   Statement* s = Statement::make_assignment_operation(OPERATOR_MULTEQ, ref,
5310                                                       i33, bloc);
5311   gogo->add_statement(s);
5312
5313   // Get the hash function for the element type.
5314   Named_object* hash_fn;
5315   Named_object* equal_fn;
5316   this->element_type_->type_functions(gogo, this->element_type_->named_type(),
5317                                       hash_fntype, equal_fntype, &hash_fn,
5318                                       &equal_fn);
5319
5320   // Get a pointer to this element in the loop.
5321   Expression* subkey = Expression::make_temporary_reference(key, bloc);
5322   subkey = Expression::make_cast(key_arg_type, subkey, bloc);
5323
5324   // Get the size of each element.
5325   Expression* ele_size = Expression::make_type_info(this->element_type_,
5326                                                     Expression::TYPE_INFO_SIZE);
5327
5328   // Get the hash of this element.
5329   Expression_list* args = new Expression_list();
5330   args->push_back(subkey);
5331   args->push_back(ele_size);
5332   Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
5333   Expression* call = Expression::make_call(func, args, false, bloc);
5334
5335   // Add the element's hash value to retval.
5336   Temporary_reference_expression* tref =
5337     Expression::make_temporary_reference(retval, bloc);
5338   tref->set_is_lvalue();
5339   s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, call, bloc);
5340   gogo->add_statement(s);
5341
5342   // Increase the element pointer.
5343   tref = Expression::make_temporary_reference(key, bloc);
5344   tref->set_is_lvalue();
5345   s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
5346                                            bloc);
5347
5348   Block* statements = gogo->finish_block(bloc);
5349
5350   for_range->add_statements(statements);
5351   gogo->add_statement(for_range);
5352
5353   // Return retval to the caller of the hash function.
5354   Expression_list* vals = new Expression_list();
5355   ref = Expression::make_temporary_reference(retval, bloc);
5356   vals->push_back(ref);
5357   s = Statement::make_return_statement(vals, bloc);
5358   gogo->add_statement(s);
5359 }
5360
5361 // Write the equality function for an array which can not use the
5362 // identity function.
5363
5364 void
5365 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
5366 {
5367   Location bloc = Linemap::predeclared_location();
5368
5369   // The pointers to the arrays we are going to compare.
5370   Named_object* key1_arg = gogo->lookup("key1", NULL);
5371   Named_object* key2_arg = gogo->lookup("key2", NULL);
5372   go_assert(key1_arg != NULL && key2_arg != NULL);
5373
5374   // Build temporaries for the keys with the right types.
5375   Type* pt = Type::make_pointer_type(name != NULL
5376                                      ? static_cast<Type*>(name)
5377                                      : static_cast<Type*>(this));
5378
5379   Expression* ref = Expression::make_var_reference(key1_arg, bloc);
5380   ref = Expression::make_unsafe_cast(pt, ref, bloc);
5381   Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
5382   gogo->add_statement(p1);
5383
5384   ref = Expression::make_var_reference(key2_arg, bloc);
5385   ref = Expression::make_unsafe_cast(pt, ref, bloc);
5386   Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
5387   gogo->add_statement(p2);
5388
5389   // Loop over the array elements.
5390   // for i = range a
5391   Type* int_type = Type::lookup_integer_type("int");
5392   Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
5393   gogo->add_statement(index);
5394
5395   Expression* iref = Expression::make_temporary_reference(index, bloc);
5396   Expression* aref = Expression::make_temporary_reference(p1, bloc);
5397   For_range_statement* for_range = Statement::make_for_range_statement(iref,
5398                                                                        NULL,
5399                                                                        aref,
5400                                                                        bloc);
5401
5402   gogo->start_block(bloc);
5403
5404   // Compare element in P1 and P2.
5405   Expression* e1 = Expression::make_temporary_reference(p1, bloc);
5406   e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
5407   ref = Expression::make_temporary_reference(index, bloc);
5408   e1 = Expression::make_array_index(e1, ref, NULL, bloc);
5409
5410   Expression* e2 = Expression::make_temporary_reference(p2, bloc);
5411   e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
5412   ref = Expression::make_temporary_reference(index, bloc);
5413   e2 = Expression::make_array_index(e2, ref, NULL, bloc);
5414
5415   Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
5416
5417   // If the elements are not equal, return false.
5418   gogo->start_block(bloc);
5419   Expression_list* vals = new Expression_list();
5420   vals->push_back(Expression::make_boolean(false, bloc));
5421   Statement* s = Statement::make_return_statement(vals, bloc);
5422   gogo->add_statement(s);
5423   Block* then_block = gogo->finish_block(bloc);
5424
5425   s = Statement::make_if_statement(cond, then_block, NULL, bloc);
5426   gogo->add_statement(s);
5427
5428   Block* statements = gogo->finish_block(bloc);
5429
5430   for_range->add_statements(statements);
5431   gogo->add_statement(for_range);
5432
5433   // All the elements are equal, so return true.
5434   vals = new Expression_list();
5435   vals->push_back(Expression::make_boolean(true, bloc));
5436   s = Statement::make_return_statement(vals, bloc);
5437   gogo->add_statement(s);
5438 }
5439
5440 // Get a tree for the length of a fixed array.  The length may be
5441 // computed using a function call, so we must only evaluate it once.
5442
5443 tree
5444 Array_type::get_length_tree(Gogo* gogo)
5445 {
5446   go_assert(this->length_ != NULL);
5447   if (this->length_tree_ == NULL_TREE)
5448     {
5449       Numeric_constant nc;
5450       mpz_t val;
5451       if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
5452         {
5453           if (mpz_sgn(val) < 0)
5454             {
5455               this->length_tree_ = error_mark_node;
5456               return this->length_tree_;
5457             }
5458           Type* t = nc.type();
5459           if (t == NULL)
5460             t = Type::lookup_integer_type("int");
5461           else if (t->is_abstract())
5462             t = t->make_non_abstract_type();
5463           tree tt = type_to_tree(t->get_backend(gogo));
5464           this->length_tree_ = Expression::integer_constant_tree(val, tt);
5465           mpz_clear(val);
5466         }
5467       else
5468         {
5469           // Make up a translation context for the array length
5470           // expression.  FIXME: This won't work in general.
5471           Translate_context context(gogo, NULL, NULL, NULL);
5472           tree len = this->length_->get_tree(&context);
5473           if (len != error_mark_node)
5474             {
5475               len = convert_to_integer(integer_type_node, len);
5476               len = save_expr(len);
5477             }
5478           this->length_tree_ = len;
5479         }
5480     }
5481   return this->length_tree_;
5482 }
5483
5484 // Get the backend representation of the fields of a slice.  This is
5485 // not declared in types.h so that types.h doesn't have to #include
5486 // backend.h.
5487 //
5488 // We use int for the count and capacity fields.  This matches 6g.
5489 // The language more or less assumes that we can't allocate space of a
5490 // size which does not fit in int.
5491
5492 static void
5493 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
5494                          std::vector<Backend::Btyped_identifier>* bfields)
5495 {
5496   bfields->resize(3);
5497
5498   Type* pet = Type::make_pointer_type(type->element_type());
5499   Btype* pbet = (use_placeholder
5500                  ? pet->get_backend_placeholder(gogo)
5501                  : pet->get_backend(gogo));
5502   Location ploc = Linemap::predeclared_location();
5503
5504   Backend::Btyped_identifier* p = &(*bfields)[0];
5505   p->name = "__values";
5506   p->btype = pbet;
5507   p->location = ploc;
5508
5509   Type* int_type = Type::lookup_integer_type("int");
5510
5511   p = &(*bfields)[1];
5512   p->name = "__count";
5513   p->btype = int_type->get_backend(gogo);
5514   p->location = ploc;
5515
5516   p = &(*bfields)[2];
5517   p->name = "__capacity";
5518   p->btype = int_type->get_backend(gogo);
5519   p->location = ploc;
5520 }
5521
5522 // Get a tree for the type of this array.  A fixed array is simply
5523 // represented as ARRAY_TYPE with the appropriate index--i.e., it is
5524 // just like an array in C.  An open array is a struct with three
5525 // fields: a data pointer, the length, and the capacity.
5526
5527 Btype*
5528 Array_type::do_get_backend(Gogo* gogo)
5529 {
5530   if (this->length_ == NULL)
5531     {
5532       std::vector<Backend::Btyped_identifier> bfields;
5533       get_backend_slice_fields(gogo, this, false, &bfields);
5534       return gogo->backend()->struct_type(bfields);
5535     }
5536   else
5537     {
5538       Btype* element = this->get_backend_element(gogo, false);
5539       Bexpression* len = this->get_backend_length(gogo);
5540       return gogo->backend()->array_type(element, len);
5541     }
5542 }
5543
5544 // Return the backend representation of the element type.
5545
5546 Btype*
5547 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
5548 {
5549   if (use_placeholder)
5550     return this->element_type_->get_backend_placeholder(gogo);
5551   else
5552     return this->element_type_->get_backend(gogo);
5553 }
5554
5555 // Return the backend representation of the length.
5556
5557 Bexpression*
5558 Array_type::get_backend_length(Gogo* gogo)
5559 {
5560   return tree_to_expr(this->get_length_tree(gogo));
5561 }
5562
5563 // Finish backend representation of the array.
5564
5565 void
5566 Array_type::finish_backend_element(Gogo* gogo)
5567 {
5568   Type* et = this->array_type()->element_type();
5569   et->get_backend(gogo);
5570   if (this->is_slice_type())
5571     {
5572       // This relies on the fact that we always use the same
5573       // structure for a pointer to any given type.
5574       Type* pet = Type::make_pointer_type(et);
5575       pet->get_backend(gogo);
5576     }
5577 }
5578
5579 // Return a tree for a pointer to the values in ARRAY.
5580
5581 tree
5582 Array_type::value_pointer_tree(Gogo*, tree array) const
5583 {
5584   tree ret;
5585   if (this->length() != NULL)
5586     {
5587       // Fixed array.
5588       ret = fold_convert(build_pointer_type(TREE_TYPE(TREE_TYPE(array))),
5589                          build_fold_addr_expr(array));
5590     }
5591   else
5592     {
5593       // Open array.
5594       tree field = TYPE_FIELDS(TREE_TYPE(array));
5595       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
5596                         "__values") == 0);
5597       ret = fold_build3(COMPONENT_REF, TREE_TYPE(field), array, field,
5598                         NULL_TREE);
5599     }
5600   if (TREE_CONSTANT(array))
5601     TREE_CONSTANT(ret) = 1;
5602   return ret;
5603 }
5604
5605 // Return a tree for the length of the array ARRAY which has this
5606 // type.
5607
5608 tree
5609 Array_type::length_tree(Gogo* gogo, tree array)
5610 {
5611   if (this->length_ != NULL)
5612     {
5613       if (TREE_CODE(array) == SAVE_EXPR)
5614         return fold_convert(integer_type_node, this->get_length_tree(gogo));
5615       else
5616         return omit_one_operand(integer_type_node,
5617                                 this->get_length_tree(gogo), array);
5618     }
5619
5620   // This is an open array.  We need to read the length field.
5621
5622   tree type = TREE_TYPE(array);
5623   go_assert(TREE_CODE(type) == RECORD_TYPE);
5624
5625   tree field = DECL_CHAIN(TYPE_FIELDS(type));
5626   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
5627
5628   tree ret = build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5629   if (TREE_CONSTANT(array))
5630     TREE_CONSTANT(ret) = 1;
5631   return ret;
5632 }
5633
5634 // Return a tree for the capacity of the array ARRAY which has this
5635 // type.
5636
5637 tree
5638 Array_type::capacity_tree(Gogo* gogo, tree array)
5639 {
5640   if (this->length_ != NULL)
5641     return omit_one_operand(integer_type_node, this->get_length_tree(gogo),
5642                             array);
5643
5644   // This is an open array.  We need to read the capacity field.
5645
5646   tree type = TREE_TYPE(array);
5647   go_assert(TREE_CODE(type) == RECORD_TYPE);
5648
5649   tree field = DECL_CHAIN(DECL_CHAIN(TYPE_FIELDS(type)));
5650   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
5651
5652   return build3(COMPONENT_REF, TREE_TYPE(field), array, field, NULL_TREE);
5653 }
5654
5655 // Export.
5656
5657 void
5658 Array_type::do_export(Export* exp) const
5659 {
5660   exp->write_c_string("[");
5661   if (this->length_ != NULL)
5662     this->length_->export_expression(exp);
5663   exp->write_c_string("] ");
5664   exp->write_type(this->element_type_);
5665 }
5666
5667 // Import.
5668
5669 Array_type*
5670 Array_type::do_import(Import* imp)
5671 {
5672   imp->require_c_string("[");
5673   Expression* length;
5674   if (imp->peek_char() == ']')
5675     length = NULL;
5676   else
5677     length = Expression::import_expression(imp);
5678   imp->require_c_string("] ");
5679   Type* element_type = imp->read_type();
5680   return Type::make_array_type(element_type, length);
5681 }
5682
5683 // The type of an array type descriptor.
5684
5685 Type*
5686 Array_type::make_array_type_descriptor_type()
5687 {
5688   static Type* ret;
5689   if (ret == NULL)
5690     {
5691       Type* tdt = Type::make_type_descriptor_type();
5692       Type* ptdt = Type::make_type_descriptor_ptr_type();
5693
5694       Type* uintptr_type = Type::lookup_integer_type("uintptr");
5695
5696       Struct_type* sf =
5697         Type::make_builtin_struct_type(4,
5698                                        "", tdt,
5699                                        "elem", ptdt,
5700                                        "slice", ptdt,
5701                                        "len", uintptr_type);
5702
5703       ret = Type::make_builtin_named_type("ArrayType", sf);
5704     }
5705
5706   return ret;
5707 }
5708
5709 // The type of an slice type descriptor.
5710
5711 Type*
5712 Array_type::make_slice_type_descriptor_type()
5713 {
5714   static Type* ret;
5715   if (ret == NULL)
5716     {
5717       Type* tdt = Type::make_type_descriptor_type();
5718       Type* ptdt = Type::make_type_descriptor_ptr_type();
5719
5720       Struct_type* sf =
5721         Type::make_builtin_struct_type(2,
5722                                        "", tdt,
5723                                        "elem", ptdt);
5724
5725       ret = Type::make_builtin_named_type("SliceType", sf);
5726     }
5727
5728   return ret;
5729 }
5730
5731 // Build a type descriptor for an array/slice type.
5732
5733 Expression*
5734 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5735 {
5736   if (this->length_ != NULL)
5737     return this->array_type_descriptor(gogo, name);
5738   else
5739     return this->slice_type_descriptor(gogo, name);
5740 }
5741
5742 // Build a type descriptor for an array type.
5743
5744 Expression*
5745 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
5746 {
5747   Location bloc = Linemap::predeclared_location();
5748
5749   Type* atdt = Array_type::make_array_type_descriptor_type();
5750
5751   const Struct_field_list* fields = atdt->struct_type()->fields();
5752
5753   Expression_list* vals = new Expression_list();
5754   vals->reserve(3);
5755
5756   Struct_field_list::const_iterator p = fields->begin();
5757   go_assert(p->is_field_name("commonType"));
5758   vals->push_back(this->type_descriptor_constructor(gogo,
5759                                                     RUNTIME_TYPE_KIND_ARRAY,
5760                                                     name, NULL, true));
5761
5762   ++p;
5763   go_assert(p->is_field_name("elem"));
5764   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5765
5766   ++p;
5767   go_assert(p->is_field_name("slice"));
5768   Type* slice_type = Type::make_array_type(this->element_type_, NULL);
5769   vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
5770
5771   ++p;
5772   go_assert(p->is_field_name("len"));
5773   vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
5774
5775   ++p;
5776   go_assert(p == fields->end());
5777
5778   return Expression::make_struct_composite_literal(atdt, vals, bloc);
5779 }
5780
5781 // Build a type descriptor for a slice type.
5782
5783 Expression*
5784 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
5785 {
5786   Location bloc = Linemap::predeclared_location();
5787
5788   Type* stdt = Array_type::make_slice_type_descriptor_type();
5789
5790   const Struct_field_list* fields = stdt->struct_type()->fields();
5791
5792   Expression_list* vals = new Expression_list();
5793   vals->reserve(2);
5794
5795   Struct_field_list::const_iterator p = fields->begin();
5796   go_assert(p->is_field_name("commonType"));
5797   vals->push_back(this->type_descriptor_constructor(gogo,
5798                                                     RUNTIME_TYPE_KIND_SLICE,
5799                                                     name, NULL, true));
5800
5801   ++p;
5802   go_assert(p->is_field_name("elem"));
5803   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
5804
5805   ++p;
5806   go_assert(p == fields->end());
5807
5808   return Expression::make_struct_composite_literal(stdt, vals, bloc);
5809 }
5810
5811 // Reflection string.
5812
5813 void
5814 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
5815 {
5816   ret->push_back('[');
5817   if (this->length_ != NULL)
5818     {
5819       Numeric_constant nc;
5820       unsigned long val;
5821       if (!this->length_->numeric_constant_value(&nc)
5822           || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
5823         error_at(this->length_->location(), "invalid array length");
5824       else
5825         {
5826           char buf[50];
5827           snprintf(buf, sizeof buf, "%lu", val);
5828           ret->append(buf);
5829         }
5830     }
5831   ret->push_back(']');
5832
5833   this->append_reflection(this->element_type_, gogo, ret);
5834 }
5835
5836 // Mangled name.
5837
5838 void
5839 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5840 {
5841   ret->push_back('A');
5842   this->append_mangled_name(this->element_type_, gogo, ret);
5843   if (this->length_ != NULL)
5844     {
5845       Numeric_constant nc;
5846       unsigned long val;
5847       if (!this->length_->numeric_constant_value(&nc)
5848           || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
5849         error_at(this->length_->location(), "invalid array length");
5850       else
5851         {
5852           char buf[50];
5853           snprintf(buf, sizeof buf, "%lu", val);
5854           ret->append(buf);
5855         }
5856     }
5857   ret->push_back('e');
5858 }
5859
5860 // Make an array type.
5861
5862 Array_type*
5863 Type::make_array_type(Type* element_type, Expression* length)
5864 {
5865   return new Array_type(element_type, length);
5866 }
5867
5868 // Class Map_type.
5869
5870 // Traversal.
5871
5872 int
5873 Map_type::do_traverse(Traverse* traverse)
5874 {
5875   if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
5876       || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
5877     return TRAVERSE_EXIT;
5878   return TRAVERSE_CONTINUE;
5879 }
5880
5881 // Check that the map type is OK.
5882
5883 bool
5884 Map_type::do_verify()
5885 {
5886   // The runtime support uses "map[void]void".
5887   if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
5888     error_at(this->location_, "invalid map key type");
5889   return true;
5890 }
5891
5892 // Whether two map types are identical.
5893
5894 bool
5895 Map_type::is_identical(const Map_type* t, bool errors_are_identical) const
5896 {
5897   return (Type::are_identical(this->key_type(), t->key_type(),
5898                               errors_are_identical, NULL)
5899           && Type::are_identical(this->val_type(), t->val_type(),
5900                                  errors_are_identical, NULL));
5901 }
5902
5903 // Hash code.
5904
5905 unsigned int
5906 Map_type::do_hash_for_method(Gogo* gogo) const
5907 {
5908   return (this->key_type_->hash_for_method(gogo)
5909           + this->val_type_->hash_for_method(gogo)
5910           + 2);
5911 }
5912
5913 // Get the backend representation for a map type.  A map type is
5914 // represented as a pointer to a struct.  The struct is __go_map in
5915 // libgo/map.h.
5916
5917 Btype*
5918 Map_type::do_get_backend(Gogo* gogo)
5919 {
5920   static Btype* backend_map_type;
5921   if (backend_map_type == NULL)
5922     {
5923       std::vector<Backend::Btyped_identifier> bfields(4);
5924
5925       Location bloc = Linemap::predeclared_location();
5926
5927       Type* pdt = Type::make_type_descriptor_ptr_type();
5928       bfields[0].name = "__descriptor";
5929       bfields[0].btype = pdt->get_backend(gogo);
5930       bfields[0].location = bloc;
5931
5932       Type* uintptr_type = Type::lookup_integer_type("uintptr");
5933       bfields[1].name = "__element_count";
5934       bfields[1].btype = uintptr_type->get_backend(gogo);
5935       bfields[1].location = bloc;
5936
5937       bfields[2].name = "__bucket_count";
5938       bfields[2].btype = bfields[1].btype;
5939       bfields[2].location = bloc;
5940
5941       Btype* bvt = gogo->backend()->void_type();
5942       Btype* bpvt = gogo->backend()->pointer_type(bvt);
5943       Btype* bppvt = gogo->backend()->pointer_type(bpvt);
5944       bfields[3].name = "__buckets";
5945       bfields[3].btype = bppvt;
5946       bfields[3].location = bloc;
5947
5948       Btype *bt = gogo->backend()->struct_type(bfields);
5949       bt = gogo->backend()->named_type("__go_map", bt, bloc);
5950       backend_map_type = gogo->backend()->pointer_type(bt);
5951     }
5952   return backend_map_type;
5953 }
5954
5955 // The type of a map type descriptor.
5956
5957 Type*
5958 Map_type::make_map_type_descriptor_type()
5959 {
5960   static Type* ret;
5961   if (ret == NULL)
5962     {
5963       Type* tdt = Type::make_type_descriptor_type();
5964       Type* ptdt = Type::make_type_descriptor_ptr_type();
5965
5966       Struct_type* sf =
5967         Type::make_builtin_struct_type(3,
5968                                        "", tdt,
5969                                        "key", ptdt,
5970                                        "elem", ptdt);
5971
5972       ret = Type::make_builtin_named_type("MapType", sf);
5973     }
5974
5975   return ret;
5976 }
5977
5978 // Build a type descriptor for a map type.
5979
5980 Expression*
5981 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5982 {
5983   Location bloc = Linemap::predeclared_location();
5984
5985   Type* mtdt = Map_type::make_map_type_descriptor_type();
5986
5987   const Struct_field_list* fields = mtdt->struct_type()->fields();
5988
5989   Expression_list* vals = new Expression_list();
5990   vals->reserve(3);
5991
5992   Struct_field_list::const_iterator p = fields->begin();
5993   go_assert(p->is_field_name("commonType"));
5994   vals->push_back(this->type_descriptor_constructor(gogo,
5995                                                     RUNTIME_TYPE_KIND_MAP,
5996                                                     name, NULL, true));
5997
5998   ++p;
5999   go_assert(p->is_field_name("key"));
6000   vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
6001
6002   ++p;
6003   go_assert(p->is_field_name("elem"));
6004   vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
6005
6006   ++p;
6007   go_assert(p == fields->end());
6008
6009   return Expression::make_struct_composite_literal(mtdt, vals, bloc);
6010 }
6011
6012 // A mapping from map types to map descriptors.
6013
6014 Map_type::Map_descriptors Map_type::map_descriptors;
6015
6016 // Build a map descriptor for this type.  Return a pointer to it.
6017
6018 tree
6019 Map_type::map_descriptor_pointer(Gogo* gogo, Location location)
6020 {
6021   Bvariable* bvar = this->map_descriptor(gogo);
6022   tree var_tree = var_to_tree(bvar);
6023   if (var_tree == error_mark_node)
6024     return error_mark_node;
6025   return build_fold_addr_expr_loc(location.gcc_location(), var_tree);
6026 }
6027
6028 // Build a map descriptor for this type.
6029
6030 Bvariable*
6031 Map_type::map_descriptor(Gogo* gogo)
6032 {
6033   std::pair<Map_type*, Bvariable*> val(this, NULL);
6034   std::pair<Map_type::Map_descriptors::iterator, bool> ins =
6035     Map_type::map_descriptors.insert(val);
6036   if (!ins.second)
6037     return ins.first->second;
6038
6039   Type* key_type = this->key_type_;
6040   Type* val_type = this->val_type_;
6041
6042   // The map entry type is a struct with three fields.  Build that
6043   // struct so that we can get the offsets of the key and value within
6044   // a map entry.  The first field should technically be a pointer to
6045   // this type itself, but since we only care about field offsets we
6046   // just use pointer to bool.
6047   Type* pbool = Type::make_pointer_type(Type::make_boolean_type());
6048   Struct_type* map_entry_type =
6049     Type::make_builtin_struct_type(3,
6050                                    "__next", pbool,
6051                                    "__key", key_type,
6052                                    "__val", val_type);
6053
6054   Type* map_descriptor_type = Map_type::make_map_descriptor_type();
6055
6056   const Struct_field_list* fields =
6057     map_descriptor_type->struct_type()->fields();
6058
6059   Expression_list* vals = new Expression_list();
6060   vals->reserve(4);
6061
6062   Location bloc = Linemap::predeclared_location();
6063
6064   Struct_field_list::const_iterator p = fields->begin();
6065
6066   go_assert(p->is_field_name("__map_descriptor"));
6067   vals->push_back(Expression::make_type_descriptor(this, bloc));
6068
6069   ++p;
6070   go_assert(p->is_field_name("__entry_size"));
6071   Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
6072   vals->push_back(Expression::make_type_info(map_entry_type, type_info));
6073
6074   Struct_field_list::const_iterator pf = map_entry_type->fields()->begin();
6075   ++pf;
6076   go_assert(pf->is_field_name("__key"));
6077
6078   ++p;
6079   go_assert(p->is_field_name("__key_offset"));
6080   vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6081
6082   ++pf;
6083   go_assert(pf->is_field_name("__val"));
6084
6085   ++p;
6086   go_assert(p->is_field_name("__val_offset"));
6087   vals->push_back(Expression::make_struct_field_offset(map_entry_type, &*pf));
6088
6089   ++p;
6090   go_assert(p == fields->end());
6091
6092   Expression* initializer =
6093     Expression::make_struct_composite_literal(map_descriptor_type, vals, bloc);
6094
6095   std::string mangled_name = "__go_map_" + this->mangled_name(gogo);
6096   Btype* map_descriptor_btype = map_descriptor_type->get_backend(gogo);
6097   Bvariable* bvar = gogo->backend()->immutable_struct(mangled_name, true,
6098                                                       map_descriptor_btype,
6099                                                       bloc);
6100
6101   Translate_context context(gogo, NULL, NULL, NULL);
6102   context.set_is_const();
6103   Bexpression* binitializer = tree_to_expr(initializer->get_tree(&context));
6104
6105   gogo->backend()->immutable_struct_set_init(bvar, mangled_name, true,
6106                                              map_descriptor_btype, bloc,
6107                                              binitializer);
6108
6109   ins.first->second = bvar;
6110   return bvar;
6111 }
6112
6113 // Build the type of a map descriptor.  This must match the struct
6114 // __go_map_descriptor in libgo/runtime/map.h.
6115
6116 Type*
6117 Map_type::make_map_descriptor_type()
6118 {
6119   static Type* ret;
6120   if (ret == NULL)
6121     {
6122       Type* ptdt = Type::make_type_descriptor_ptr_type();
6123       Type* uintptr_type = Type::lookup_integer_type("uintptr");
6124       Struct_type* sf =
6125         Type::make_builtin_struct_type(4,
6126                                        "__map_descriptor", ptdt,
6127                                        "__entry_size", uintptr_type,
6128                                        "__key_offset", uintptr_type,
6129                                        "__val_offset", uintptr_type);
6130       ret = Type::make_builtin_named_type("__go_map_descriptor", sf);
6131     }
6132   return ret;
6133 }
6134
6135 // Reflection string for a map.
6136
6137 void
6138 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
6139 {
6140   ret->append("map[");
6141   this->append_reflection(this->key_type_, gogo, ret);
6142   ret->append("]");
6143   this->append_reflection(this->val_type_, gogo, ret);
6144 }
6145
6146 // Mangled name for a map.
6147
6148 void
6149 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6150 {
6151   ret->push_back('M');
6152   this->append_mangled_name(this->key_type_, gogo, ret);
6153   ret->append("__");
6154   this->append_mangled_name(this->val_type_, gogo, ret);
6155 }
6156
6157 // Export a map type.
6158
6159 void
6160 Map_type::do_export(Export* exp) const
6161 {
6162   exp->write_c_string("map [");
6163   exp->write_type(this->key_type_);
6164   exp->write_c_string("] ");
6165   exp->write_type(this->val_type_);
6166 }
6167
6168 // Import a map type.
6169
6170 Map_type*
6171 Map_type::do_import(Import* imp)
6172 {
6173   imp->require_c_string("map [");
6174   Type* key_type = imp->read_type();
6175   imp->require_c_string("] ");
6176   Type* val_type = imp->read_type();
6177   return Type::make_map_type(key_type, val_type, imp->location());
6178 }
6179
6180 // Make a map type.
6181
6182 Map_type*
6183 Type::make_map_type(Type* key_type, Type* val_type, Location location)
6184 {
6185   return new Map_type(key_type, val_type, location);
6186 }
6187
6188 // Class Channel_type.
6189
6190 // Hash code.
6191
6192 unsigned int
6193 Channel_type::do_hash_for_method(Gogo* gogo) const
6194 {
6195   unsigned int ret = 0;
6196   if (this->may_send_)
6197     ret += 1;
6198   if (this->may_receive_)
6199     ret += 2;
6200   if (this->element_type_ != NULL)
6201     ret += this->element_type_->hash_for_method(gogo) << 2;
6202   return ret << 3;
6203 }
6204
6205 // Whether this type is the same as T.
6206
6207 bool
6208 Channel_type::is_identical(const Channel_type* t,
6209                            bool errors_are_identical) const
6210 {
6211   if (!Type::are_identical(this->element_type(), t->element_type(),
6212                            errors_are_identical, NULL))
6213     return false;
6214   return (this->may_send_ == t->may_send_
6215           && this->may_receive_ == t->may_receive_);
6216 }
6217
6218 // Return the tree for a channel type.  A channel is a pointer to a
6219 // __go_channel struct.  The __go_channel struct is defined in
6220 // libgo/runtime/channel.h.
6221
6222 Btype*
6223 Channel_type::do_get_backend(Gogo* gogo)
6224 {
6225   static Btype* backend_channel_type;
6226   if (backend_channel_type == NULL)
6227     {
6228       std::vector<Backend::Btyped_identifier> bfields;
6229       Btype* bt = gogo->backend()->struct_type(bfields);
6230       bt = gogo->backend()->named_type("__go_channel", bt,
6231                                        Linemap::predeclared_location());
6232       backend_channel_type = gogo->backend()->pointer_type(bt);
6233     }
6234   return backend_channel_type;
6235 }
6236
6237 // Build a type descriptor for a channel type.
6238
6239 Type*
6240 Channel_type::make_chan_type_descriptor_type()
6241 {
6242   static Type* ret;
6243   if (ret == NULL)
6244     {
6245       Type* tdt = Type::make_type_descriptor_type();
6246       Type* ptdt = Type::make_type_descriptor_ptr_type();
6247
6248       Type* uintptr_type = Type::lookup_integer_type("uintptr");
6249
6250       Struct_type* sf =
6251         Type::make_builtin_struct_type(3,
6252                                        "", tdt,
6253                                        "elem", ptdt,
6254                                        "dir", uintptr_type);
6255
6256       ret = Type::make_builtin_named_type("ChanType", sf);
6257     }
6258
6259   return ret;
6260 }
6261
6262 // Build a type descriptor for a map type.
6263
6264 Expression*
6265 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6266 {
6267   Location bloc = Linemap::predeclared_location();
6268
6269   Type* ctdt = Channel_type::make_chan_type_descriptor_type();
6270
6271   const Struct_field_list* fields = ctdt->struct_type()->fields();
6272
6273   Expression_list* vals = new Expression_list();
6274   vals->reserve(3);
6275
6276   Struct_field_list::const_iterator p = fields->begin();
6277   go_assert(p->is_field_name("commonType"));
6278   vals->push_back(this->type_descriptor_constructor(gogo,
6279                                                     RUNTIME_TYPE_KIND_CHAN,
6280                                                     name, NULL, true));
6281
6282   ++p;
6283   go_assert(p->is_field_name("elem"));
6284   vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
6285
6286   ++p;
6287   go_assert(p->is_field_name("dir"));
6288   // These bits must match the ones in libgo/runtime/go-type.h.
6289   int val = 0;
6290   if (this->may_receive_)
6291     val |= 1;
6292   if (this->may_send_)
6293     val |= 2;
6294   mpz_t iv;
6295   mpz_init_set_ui(iv, val);
6296   vals->push_back(Expression::make_integer(&iv, p->type(), bloc));
6297   mpz_clear(iv);
6298
6299   ++p;
6300   go_assert(p == fields->end());
6301
6302   return Expression::make_struct_composite_literal(ctdt, vals, bloc);
6303 }
6304
6305 // Reflection string.
6306
6307 void
6308 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
6309 {
6310   if (!this->may_send_)
6311     ret->append("<-");
6312   ret->append("chan");
6313   if (!this->may_receive_)
6314     ret->append("<-");
6315   ret->push_back(' ');
6316   this->append_reflection(this->element_type_, gogo, ret);
6317 }
6318
6319 // Mangled name.
6320
6321 void
6322 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6323 {
6324   ret->push_back('C');
6325   this->append_mangled_name(this->element_type_, gogo, ret);
6326   if (this->may_send_)
6327     ret->push_back('s');
6328   if (this->may_receive_)
6329     ret->push_back('r');
6330   ret->push_back('e');
6331 }
6332
6333 // Export.
6334
6335 void
6336 Channel_type::do_export(Export* exp) const
6337 {
6338   exp->write_c_string("chan ");
6339   if (this->may_send_ && !this->may_receive_)
6340     exp->write_c_string("-< ");
6341   else if (this->may_receive_ && !this->may_send_)
6342     exp->write_c_string("<- ");
6343   exp->write_type(this->element_type_);
6344 }
6345
6346 // Import.
6347
6348 Channel_type*
6349 Channel_type::do_import(Import* imp)
6350 {
6351   imp->require_c_string("chan ");
6352
6353   bool may_send;
6354   bool may_receive;
6355   if (imp->match_c_string("-< "))
6356     {
6357       imp->advance(3);
6358       may_send = true;
6359       may_receive = false;
6360     }
6361   else if (imp->match_c_string("<- "))
6362     {
6363       imp->advance(3);
6364       may_receive = true;
6365       may_send = false;
6366     }
6367   else
6368     {
6369       may_send = true;
6370       may_receive = true;
6371     }
6372
6373   Type* element_type = imp->read_type();
6374
6375   return Type::make_channel_type(may_send, may_receive, element_type);
6376 }
6377
6378 // Make a new channel type.
6379
6380 Channel_type*
6381 Type::make_channel_type(bool send, bool receive, Type* element_type)
6382 {
6383   return new Channel_type(send, receive, element_type);
6384 }
6385
6386 // Class Interface_type.
6387
6388 // Traversal.
6389
6390 int
6391 Interface_type::do_traverse(Traverse* traverse)
6392 {
6393   Typed_identifier_list* methods = (this->methods_are_finalized_
6394                                     ? this->all_methods_
6395                                     : this->parse_methods_);
6396   if (methods == NULL)
6397     return TRAVERSE_CONTINUE;
6398   return methods->traverse(traverse);
6399 }
6400
6401 // Finalize the methods.  This handles interface inheritance.
6402
6403 void
6404 Interface_type::finalize_methods()
6405 {
6406   if (this->methods_are_finalized_)
6407     return;
6408   this->methods_are_finalized_ = true;
6409   if (this->parse_methods_ == NULL)
6410     return;
6411
6412   this->all_methods_ = new Typed_identifier_list();
6413   this->all_methods_->reserve(this->parse_methods_->size());
6414   Typed_identifier_list inherit;
6415   for (Typed_identifier_list::const_iterator pm =
6416          this->parse_methods_->begin();
6417        pm != this->parse_methods_->end();
6418        ++pm)
6419     {
6420       const Typed_identifier* p = &*pm;
6421       if (p->name().empty())
6422         inherit.push_back(*p);
6423       else if (this->find_method(p->name()) == NULL)
6424         this->all_methods_->push_back(*p);
6425       else
6426         error_at(p->location(), "duplicate method %qs",
6427                  Gogo::message_name(p->name()).c_str());
6428     }
6429
6430   std::vector<Named_type*> seen;
6431   seen.reserve(inherit.size());
6432   bool issued_recursive_error = false;
6433   while (!inherit.empty())
6434     {
6435       Type* t = inherit.back().type();
6436       Location tl = inherit.back().location();
6437       inherit.pop_back();
6438
6439       Interface_type* it = t->interface_type();
6440       if (it == NULL)
6441         {
6442           if (!t->is_error())
6443             error_at(tl, "interface contains embedded non-interface");
6444           continue;
6445         }
6446       if (it == this)
6447         {
6448           if (!issued_recursive_error)
6449             {
6450               error_at(tl, "invalid recursive interface");
6451               issued_recursive_error = true;
6452             }
6453           continue;
6454         }
6455
6456       Named_type* nt = t->named_type();
6457       if (nt != NULL && it->parse_methods_ != NULL)
6458         {
6459           std::vector<Named_type*>::const_iterator q;
6460           for (q = seen.begin(); q != seen.end(); ++q)
6461             {
6462               if (*q == nt)
6463                 {
6464                   error_at(tl, "inherited interface loop");
6465                   break;
6466                 }
6467             }
6468           if (q != seen.end())
6469             continue;
6470           seen.push_back(nt);
6471         }
6472
6473       const Typed_identifier_list* imethods = it->parse_methods_;
6474       if (imethods == NULL)
6475         continue;
6476       for (Typed_identifier_list::const_iterator q = imethods->begin();
6477            q != imethods->end();
6478            ++q)
6479         {
6480           if (q->name().empty())
6481             inherit.push_back(*q);
6482           else if (this->find_method(q->name()) == NULL)
6483             this->all_methods_->push_back(Typed_identifier(q->name(),
6484                                                            q->type(), tl));
6485           else
6486             error_at(tl, "inherited method %qs is ambiguous",
6487                      Gogo::message_name(q->name()).c_str());
6488         }
6489     }
6490
6491   if (!this->all_methods_->empty())
6492     this->all_methods_->sort_by_name();
6493   else
6494     {
6495       delete this->all_methods_;
6496       this->all_methods_ = NULL;
6497     }
6498 }
6499
6500 // Return the method NAME, or NULL.
6501
6502 const Typed_identifier*
6503 Interface_type::find_method(const std::string& name) const
6504 {
6505   go_assert(this->methods_are_finalized_);
6506   if (this->all_methods_ == NULL)
6507     return NULL;
6508   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6509        p != this->all_methods_->end();
6510        ++p)
6511     if (p->name() == name)
6512       return &*p;
6513   return NULL;
6514 }
6515
6516 // Return the method index.
6517
6518 size_t
6519 Interface_type::method_index(const std::string& name) const
6520 {
6521   go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
6522   size_t ret = 0;
6523   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6524        p != this->all_methods_->end();
6525        ++p, ++ret)
6526     if (p->name() == name)
6527       return ret;
6528   go_unreachable();
6529 }
6530
6531 // Return whether NAME is an unexported method, for better error
6532 // reporting.
6533
6534 bool
6535 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
6536 {
6537   go_assert(this->methods_are_finalized_);
6538   if (this->all_methods_ == NULL)
6539     return false;
6540   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6541        p != this->all_methods_->end();
6542        ++p)
6543     {
6544       const std::string& method_name(p->name());
6545       if (Gogo::is_hidden_name(method_name)
6546           && name == Gogo::unpack_hidden_name(method_name)
6547           && gogo->pack_hidden_name(name, false) != method_name)
6548         return true;
6549     }
6550   return false;
6551 }
6552
6553 // Whether this type is identical with T.
6554
6555 bool
6556 Interface_type::is_identical(const Interface_type* t,
6557                              bool errors_are_identical) const
6558 {
6559   // If methods have not been finalized, then we are asking whether
6560   // func redeclarations are the same.  This is an error, so for
6561   // simplicity we say they are never the same.
6562   if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
6563     return false;
6564
6565   // We require the same methods with the same types.  The methods
6566   // have already been sorted.
6567   if (this->all_methods_ == NULL || t->all_methods_ == NULL)
6568     return this->all_methods_ == t->all_methods_;
6569
6570   if (this->assume_identical(this, t) || t->assume_identical(t, this))
6571     return true;
6572
6573   Assume_identical* hold_ai = this->assume_identical_;
6574   Assume_identical ai;
6575   ai.t1 = this;
6576   ai.t2 = t;
6577   ai.next = hold_ai;
6578   this->assume_identical_ = &ai;
6579
6580   Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
6581   Typed_identifier_list::const_iterator p2;
6582   for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
6583     {
6584       if (p1 == this->all_methods_->end())
6585         break;
6586       if (p1->name() != p2->name()
6587           || !Type::are_identical(p1->type(), p2->type(),
6588                                   errors_are_identical, NULL))
6589         break;
6590     }
6591
6592   this->assume_identical_ = hold_ai;
6593
6594   return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
6595 }
6596
6597 // Return true if T1 and T2 are assumed to be identical during a type
6598 // comparison.
6599
6600 bool
6601 Interface_type::assume_identical(const Interface_type* t1,
6602                                  const Interface_type* t2) const
6603 {
6604   for (Assume_identical* p = this->assume_identical_;
6605        p != NULL;
6606        p = p->next)
6607     if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
6608       return true;
6609   return false;
6610 }
6611
6612 // Whether we can assign the interface type T to this type.  The types
6613 // are known to not be identical.  An interface assignment is only
6614 // permitted if T is known to implement all methods in THIS.
6615 // Otherwise a type guard is required.
6616
6617 bool
6618 Interface_type::is_compatible_for_assign(const Interface_type* t,
6619                                          std::string* reason) const
6620 {
6621   go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
6622   if (this->all_methods_ == NULL)
6623     return true;
6624   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6625        p != this->all_methods_->end();
6626        ++p)
6627     {
6628       const Typed_identifier* m = t->find_method(p->name());
6629       if (m == NULL)
6630         {
6631           if (reason != NULL)
6632             {
6633               char buf[200];
6634               snprintf(buf, sizeof buf,
6635                        _("need explicit conversion; missing method %s%s%s"),
6636                        open_quote, Gogo::message_name(p->name()).c_str(),
6637                        close_quote);
6638               reason->assign(buf);
6639             }
6640           return false;
6641         }
6642
6643       std::string subreason;
6644       if (!Type::are_identical(p->type(), m->type(), true, &subreason))
6645         {
6646           if (reason != NULL)
6647             {
6648               std::string n = Gogo::message_name(p->name());
6649               size_t len = 100 + n.length() + subreason.length();
6650               char* buf = new char[len];
6651               if (subreason.empty())
6652                 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6653                          open_quote, n.c_str(), close_quote);
6654               else
6655                 snprintf(buf, len,
6656                          _("incompatible type for method %s%s%s (%s)"),
6657                          open_quote, n.c_str(), close_quote,
6658                          subreason.c_str());
6659               reason->assign(buf);
6660               delete[] buf;
6661             }
6662           return false;
6663         }
6664     }
6665
6666   return true;
6667 }
6668
6669 // Hash code.
6670
6671 unsigned int
6672 Interface_type::do_hash_for_method(Gogo*) const
6673 {
6674   go_assert(this->methods_are_finalized_);
6675   unsigned int ret = 0;
6676   if (this->all_methods_ != NULL)
6677     {
6678       for (Typed_identifier_list::const_iterator p =
6679              this->all_methods_->begin();
6680            p != this->all_methods_->end();
6681            ++p)
6682         {
6683           ret = Type::hash_string(p->name(), ret);
6684           // We don't use the method type in the hash, to avoid
6685           // infinite recursion if an interface method uses a type
6686           // which is an interface which inherits from the interface
6687           // itself.
6688           // type T interface { F() interface {T}}
6689           ret <<= 1;
6690         }
6691     }
6692   return ret;
6693 }
6694
6695 // Return true if T implements the interface.  If it does not, and
6696 // REASON is not NULL, set *REASON to a useful error message.
6697
6698 bool
6699 Interface_type::implements_interface(const Type* t, std::string* reason) const
6700 {
6701   go_assert(this->methods_are_finalized_);
6702   if (this->all_methods_ == NULL)
6703     return true;
6704
6705   bool is_pointer = false;
6706   const Named_type* nt = t->named_type();
6707   const Struct_type* st = t->struct_type();
6708   // If we start with a named type, we don't dereference it to find
6709   // methods.
6710   if (nt == NULL)
6711     {
6712       const Type* pt = t->points_to();
6713       if (pt != NULL)
6714         {
6715           // If T is a pointer to a named type, then we need to look at
6716           // the type to which it points.
6717           is_pointer = true;
6718           nt = pt->named_type();
6719           st = pt->struct_type();
6720         }
6721     }
6722
6723   // If we have a named type, get the methods from it rather than from
6724   // any struct type.
6725   if (nt != NULL)
6726     st = NULL;
6727
6728   // Only named and struct types have methods.
6729   if (nt == NULL && st == NULL)
6730     {
6731       if (reason != NULL)
6732         {
6733           if (t->points_to() != NULL
6734               && t->points_to()->interface_type() != NULL)
6735             reason->assign(_("pointer to interface type has no methods"));
6736           else
6737             reason->assign(_("type has no methods"));
6738         }
6739       return false;
6740     }
6741
6742   if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
6743     {
6744       if (reason != NULL)
6745         {
6746           if (t->points_to() != NULL
6747               && t->points_to()->interface_type() != NULL)
6748             reason->assign(_("pointer to interface type has no methods"));
6749           else
6750             reason->assign(_("type has no methods"));
6751         }
6752       return false;
6753     }
6754
6755   for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
6756        p != this->all_methods_->end();
6757        ++p)
6758     {
6759       bool is_ambiguous = false;
6760       Method* m = (nt != NULL
6761                    ? nt->method_function(p->name(), &is_ambiguous)
6762                    : st->method_function(p->name(), &is_ambiguous));
6763       if (m == NULL)
6764         {
6765           if (reason != NULL)
6766             {
6767               std::string n = Gogo::message_name(p->name());
6768               size_t len = n.length() + 100;
6769               char* buf = new char[len];
6770               if (is_ambiguous)
6771                 snprintf(buf, len, _("ambiguous method %s%s%s"),
6772                          open_quote, n.c_str(), close_quote);
6773               else
6774                 snprintf(buf, len, _("missing method %s%s%s"),
6775                          open_quote, n.c_str(), close_quote);
6776               reason->assign(buf);
6777               delete[] buf;
6778             }
6779           return false;
6780         }
6781
6782       Function_type *p_fn_type = p->type()->function_type();
6783       Function_type* m_fn_type = m->type()->function_type();
6784       go_assert(p_fn_type != NULL && m_fn_type != NULL);
6785       std::string subreason;
6786       if (!p_fn_type->is_identical(m_fn_type, true, true, &subreason))
6787         {
6788           if (reason != NULL)
6789             {
6790               std::string n = Gogo::message_name(p->name());
6791               size_t len = 100 + n.length() + subreason.length();
6792               char* buf = new char[len];
6793               if (subreason.empty())
6794                 snprintf(buf, len, _("incompatible type for method %s%s%s"),
6795                          open_quote, n.c_str(), close_quote);
6796               else
6797                 snprintf(buf, len,
6798                          _("incompatible type for method %s%s%s (%s)"),
6799                          open_quote, n.c_str(), close_quote,
6800                          subreason.c_str());
6801               reason->assign(buf);
6802               delete[] buf;
6803             }
6804           return false;
6805         }
6806
6807       if (!is_pointer && !m->is_value_method())
6808         {
6809           if (reason != NULL)
6810             {
6811               std::string n = Gogo::message_name(p->name());
6812               size_t len = 100 + n.length();
6813               char* buf = new char[len];
6814               snprintf(buf, len, _("method %s%s%s requires a pointer"),
6815                        open_quote, n.c_str(), close_quote);
6816               reason->assign(buf);
6817               delete[] buf;
6818             }
6819           return false;
6820         }
6821     }
6822
6823   return true;
6824 }
6825
6826 // Return the backend representation of the empty interface type.  We
6827 // use the same struct for all empty interfaces.
6828
6829 Btype*
6830 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
6831 {
6832   static Btype* empty_interface_type;
6833   if (empty_interface_type == NULL)
6834     {
6835       std::vector<Backend::Btyped_identifier> bfields(2);
6836
6837       Location bloc = Linemap::predeclared_location();
6838
6839       Type* pdt = Type::make_type_descriptor_ptr_type();
6840       bfields[0].name = "__type_descriptor";
6841       bfields[0].btype = pdt->get_backend(gogo);
6842       bfields[0].location = bloc;
6843
6844       Type* vt = Type::make_pointer_type(Type::make_void_type());
6845       bfields[1].name = "__object";
6846       bfields[1].btype = vt->get_backend(gogo);
6847       bfields[1].location = bloc;
6848
6849       empty_interface_type = gogo->backend()->struct_type(bfields);
6850     }
6851   return empty_interface_type;
6852 }
6853
6854 // Return the fields of a non-empty interface type.  This is not
6855 // declared in types.h so that types.h doesn't have to #include
6856 // backend.h.
6857
6858 static void
6859 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
6860                              bool use_placeholder,
6861                              std::vector<Backend::Btyped_identifier>* bfields)
6862 {
6863   Location loc = type->location();
6864
6865   std::vector<Backend::Btyped_identifier> mfields(type->methods()->size() + 1);
6866
6867   Type* pdt = Type::make_type_descriptor_ptr_type();
6868   mfields[0].name = "__type_descriptor";
6869   mfields[0].btype = pdt->get_backend(gogo);
6870   mfields[0].location = loc;
6871
6872   std::string last_name = "";
6873   size_t i = 1;
6874   for (Typed_identifier_list::const_iterator p = type->methods()->begin();
6875        p != type->methods()->end();
6876        ++p, ++i)
6877     {
6878       // The type of the method in Go only includes the parameters.
6879       // The actual method also has a receiver, which is always a
6880       // pointer.  We need to add that pointer type here in order to
6881       // generate the correct type for the backend.
6882       Function_type* ft = p->type()->function_type();
6883       go_assert(ft->receiver() == NULL);
6884
6885       const Typed_identifier_list* params = ft->parameters();
6886       Typed_identifier_list* mparams = new Typed_identifier_list();
6887       if (params != NULL)
6888         mparams->reserve(params->size() + 1);
6889       Type* vt = Type::make_pointer_type(Type::make_void_type());
6890       mparams->push_back(Typed_identifier("", vt, ft->location()));
6891       if (params != NULL)
6892         {
6893           for (Typed_identifier_list::const_iterator pp = params->begin();
6894                pp != params->end();
6895                ++pp)
6896             mparams->push_back(*pp);
6897         }
6898
6899       Typed_identifier_list* mresults = (ft->results() == NULL
6900                                          ? NULL
6901                                          : ft->results()->copy());
6902       Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
6903                                                     ft->location());
6904
6905       mfields[i].name = Gogo::unpack_hidden_name(p->name());
6906       mfields[i].btype = (use_placeholder
6907                           ? mft->get_backend_placeholder(gogo)
6908                           : mft->get_backend(gogo));
6909       mfields[i].location = loc;
6910       // Sanity check: the names should be sorted.
6911       go_assert(p->name() > last_name);
6912       last_name = p->name();
6913     }
6914
6915   Btype* methods = gogo->backend()->struct_type(mfields);
6916
6917   bfields->resize(2);
6918
6919   (*bfields)[0].name = "__methods";
6920   (*bfields)[0].btype = gogo->backend()->pointer_type(methods);
6921   (*bfields)[0].location = loc;
6922
6923   Type* vt = Type::make_pointer_type(Type::make_void_type());
6924   (*bfields)[1].name = "__object";
6925   (*bfields)[1].btype = vt->get_backend(gogo);
6926   (*bfields)[1].location = Linemap::predeclared_location();
6927 }
6928
6929 // Return a tree for an interface type.  An interface is a pointer to
6930 // a struct.  The struct has three fields.  The first field is a
6931 // pointer to the type descriptor for the dynamic type of the object.
6932 // The second field is a pointer to a table of methods for the
6933 // interface to be used with the object.  The third field is the value
6934 // of the object itself.
6935
6936 Btype*
6937 Interface_type::do_get_backend(Gogo* gogo)
6938 {
6939   if (this->is_empty())
6940     return Interface_type::get_backend_empty_interface_type(gogo);
6941   else
6942     {
6943       if (this->interface_btype_ != NULL)
6944         return this->interface_btype_;
6945       this->interface_btype_ =
6946         gogo->backend()->placeholder_struct_type("", this->location_);
6947       std::vector<Backend::Btyped_identifier> bfields;
6948       get_backend_interface_fields(gogo, this, false, &bfields);
6949       if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
6950                                                         bfields))
6951         this->interface_btype_ = gogo->backend()->error_type();
6952       return this->interface_btype_;
6953     }
6954 }
6955
6956 // Finish the backend representation of the methods.
6957
6958 void
6959 Interface_type::finish_backend_methods(Gogo* gogo)
6960 {
6961   if (!this->interface_type()->is_empty())
6962     {
6963       const Typed_identifier_list* methods = this->methods();
6964       if (methods != NULL)
6965         {
6966           for (Typed_identifier_list::const_iterator p = methods->begin();
6967                p != methods->end();
6968                ++p)
6969             p->type()->get_backend(gogo);
6970         }
6971     }
6972 }
6973
6974 // The type of an interface type descriptor.
6975
6976 Type*
6977 Interface_type::make_interface_type_descriptor_type()
6978 {
6979   static Type* ret;
6980   if (ret == NULL)
6981     {
6982       Type* tdt = Type::make_type_descriptor_type();
6983       Type* ptdt = Type::make_type_descriptor_ptr_type();
6984
6985       Type* string_type = Type::lookup_string_type();
6986       Type* pointer_string_type = Type::make_pointer_type(string_type);
6987
6988       Struct_type* sm =
6989         Type::make_builtin_struct_type(3,
6990                                        "name", pointer_string_type,
6991                                        "pkgPath", pointer_string_type,
6992                                        "typ", ptdt);
6993
6994       Type* nsm = Type::make_builtin_named_type("imethod", sm);
6995
6996       Type* slice_nsm = Type::make_array_type(nsm, NULL);
6997
6998       Struct_type* s = Type::make_builtin_struct_type(2,
6999                                                       "", tdt,
7000                                                       "methods", slice_nsm);
7001
7002       ret = Type::make_builtin_named_type("InterfaceType", s);
7003     }
7004
7005   return ret;
7006 }
7007
7008 // Build a type descriptor for an interface type.
7009
7010 Expression*
7011 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7012 {
7013   Location bloc = Linemap::predeclared_location();
7014
7015   Type* itdt = Interface_type::make_interface_type_descriptor_type();
7016
7017   const Struct_field_list* ifields = itdt->struct_type()->fields();
7018
7019   Expression_list* ivals = new Expression_list();
7020   ivals->reserve(2);
7021
7022   Struct_field_list::const_iterator pif = ifields->begin();
7023   go_assert(pif->is_field_name("commonType"));
7024   const int rt = RUNTIME_TYPE_KIND_INTERFACE;
7025   ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
7026                                                      true));
7027
7028   ++pif;
7029   go_assert(pif->is_field_name("methods"));
7030
7031   Expression_list* methods = new Expression_list();
7032   if (this->all_methods_ != NULL)
7033     {
7034       Type* elemtype = pif->type()->array_type()->element_type();
7035
7036       methods->reserve(this->all_methods_->size());
7037       for (Typed_identifier_list::const_iterator pm =
7038              this->all_methods_->begin();
7039            pm != this->all_methods_->end();
7040            ++pm)
7041         {
7042           const Struct_field_list* mfields = elemtype->struct_type()->fields();
7043
7044           Expression_list* mvals = new Expression_list();
7045           mvals->reserve(3);
7046
7047           Struct_field_list::const_iterator pmf = mfields->begin();
7048           go_assert(pmf->is_field_name("name"));
7049           std::string s = Gogo::unpack_hidden_name(pm->name());
7050           Expression* e = Expression::make_string(s, bloc);
7051           mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7052
7053           ++pmf;
7054           go_assert(pmf->is_field_name("pkgPath"));
7055           if (!Gogo::is_hidden_name(pm->name()))
7056             mvals->push_back(Expression::make_nil(bloc));
7057           else
7058             {
7059               s = Gogo::hidden_name_prefix(pm->name());
7060               e = Expression::make_string(s, bloc);
7061               mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
7062             }
7063
7064           ++pmf;
7065           go_assert(pmf->is_field_name("typ"));
7066           mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
7067
7068           ++pmf;
7069           go_assert(pmf == mfields->end());
7070
7071           e = Expression::make_struct_composite_literal(elemtype, mvals,
7072                                                         bloc);
7073           methods->push_back(e);
7074         }
7075     }
7076
7077   ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
7078                                                             methods, bloc));
7079
7080   ++pif;
7081   go_assert(pif == ifields->end());
7082
7083   return Expression::make_struct_composite_literal(itdt, ivals, bloc);
7084 }
7085
7086 // Reflection string.
7087
7088 void
7089 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
7090 {
7091   ret->append("interface {");
7092   const Typed_identifier_list* methods = this->parse_methods_;
7093   if (methods != NULL)
7094     {
7095       ret->push_back(' ');
7096       for (Typed_identifier_list::const_iterator p = methods->begin();
7097            p != methods->end();
7098            ++p)
7099         {
7100           if (p != methods->begin())
7101             ret->append("; ");
7102           if (p->name().empty())
7103             this->append_reflection(p->type(), gogo, ret);
7104           else
7105             {
7106               if (!Gogo::is_hidden_name(p->name()))
7107                 ret->append(p->name());
7108               else
7109                 {
7110                   // This matches what the gc compiler does.
7111                   std::string prefix = Gogo::hidden_name_prefix(p->name());
7112                   ret->append(prefix.substr(prefix.find('.') + 1));
7113                   ret->push_back('.');
7114                   ret->append(Gogo::unpack_hidden_name(p->name()));
7115                 }
7116               std::string sub = p->type()->reflection(gogo);
7117               go_assert(sub.compare(0, 4, "func") == 0);
7118               sub = sub.substr(4);
7119               ret->append(sub);
7120             }
7121         }
7122       ret->push_back(' ');
7123     }
7124   ret->append("}");
7125 }
7126
7127 // Mangled name.
7128
7129 void
7130 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7131 {
7132   go_assert(this->methods_are_finalized_);
7133
7134   ret->push_back('I');
7135
7136   const Typed_identifier_list* methods = this->all_methods_;
7137   if (methods != NULL && !this->seen_)
7138     {
7139       this->seen_ = true;
7140       for (Typed_identifier_list::const_iterator p = methods->begin();
7141            p != methods->end();
7142            ++p)
7143         {
7144           if (!p->name().empty())
7145             {
7146               std::string n = Gogo::unpack_hidden_name(p->name());
7147               char buf[20];
7148               snprintf(buf, sizeof buf, "%u_",
7149                        static_cast<unsigned int>(n.length()));
7150               ret->append(buf);
7151               ret->append(n);
7152             }
7153           this->append_mangled_name(p->type(), gogo, ret);
7154         }
7155       this->seen_ = false;
7156     }
7157
7158   ret->push_back('e');
7159 }
7160
7161 // Export.
7162
7163 void
7164 Interface_type::do_export(Export* exp) const
7165 {
7166   exp->write_c_string("interface { ");
7167
7168   const Typed_identifier_list* methods = this->parse_methods_;
7169   if (methods != NULL)
7170     {
7171       for (Typed_identifier_list::const_iterator pm = methods->begin();
7172            pm != methods->end();
7173            ++pm)
7174         {
7175           if (pm->name().empty())
7176             {
7177               exp->write_c_string("? ");
7178               exp->write_type(pm->type());
7179             }
7180           else
7181             {
7182               exp->write_string(pm->name());
7183               exp->write_c_string(" (");
7184
7185               const Function_type* fntype = pm->type()->function_type();
7186
7187               bool first = true;
7188               const Typed_identifier_list* parameters = fntype->parameters();
7189               if (parameters != NULL)
7190                 {
7191                   bool is_varargs = fntype->is_varargs();
7192                   for (Typed_identifier_list::const_iterator pp =
7193                          parameters->begin();
7194                        pp != parameters->end();
7195                        ++pp)
7196                     {
7197                       if (first)
7198                         first = false;
7199                       else
7200                         exp->write_c_string(", ");
7201                       exp->write_name(pp->name());
7202                       exp->write_c_string(" ");
7203                       if (!is_varargs || pp + 1 != parameters->end())
7204                         exp->write_type(pp->type());
7205                       else
7206                         {
7207                           exp->write_c_string("...");
7208                           Type *pptype = pp->type();
7209                           exp->write_type(pptype->array_type()->element_type());
7210                         }
7211                     }
7212                 }
7213
7214               exp->write_c_string(")");
7215
7216               const Typed_identifier_list* results = fntype->results();
7217               if (results != NULL)
7218                 {
7219                   exp->write_c_string(" ");
7220                   if (results->size() == 1 && results->begin()->name().empty())
7221                     exp->write_type(results->begin()->type());
7222                   else
7223                     {
7224                       first = true;
7225                       exp->write_c_string("(");
7226                       for (Typed_identifier_list::const_iterator p =
7227                              results->begin();
7228                            p != results->end();
7229                            ++p)
7230                         {
7231                           if (first)
7232                             first = false;
7233                           else
7234                             exp->write_c_string(", ");
7235                           exp->write_name(p->name());
7236                           exp->write_c_string(" ");
7237                           exp->write_type(p->type());
7238                         }
7239                       exp->write_c_string(")");
7240                     }
7241                 }
7242             }
7243
7244           exp->write_c_string("; ");
7245         }
7246     }
7247
7248   exp->write_c_string("}");
7249 }
7250
7251 // Import an interface type.
7252
7253 Interface_type*
7254 Interface_type::do_import(Import* imp)
7255 {
7256   imp->require_c_string("interface { ");
7257
7258   Typed_identifier_list* methods = new Typed_identifier_list;
7259   while (imp->peek_char() != '}')
7260     {
7261       std::string name = imp->read_identifier();
7262
7263       if (name == "?")
7264         {
7265           imp->require_c_string(" ");
7266           Type* t = imp->read_type();
7267           methods->push_back(Typed_identifier("", t, imp->location()));
7268           imp->require_c_string("; ");
7269           continue;
7270         }
7271
7272       imp->require_c_string(" (");
7273
7274       Typed_identifier_list* parameters;
7275       bool is_varargs = false;
7276       if (imp->peek_char() == ')')
7277         parameters = NULL;
7278       else
7279         {
7280           parameters = new Typed_identifier_list;
7281           while (true)
7282             {
7283               std::string name = imp->read_name();
7284               imp->require_c_string(" ");
7285
7286               if (imp->match_c_string("..."))
7287                 {
7288                   imp->advance(3);
7289                   is_varargs = true;
7290                 }
7291
7292               Type* ptype = imp->read_type();
7293               if (is_varargs)
7294                 ptype = Type::make_array_type(ptype, NULL);
7295               parameters->push_back(Typed_identifier(name, ptype,
7296                                                      imp->location()));
7297               if (imp->peek_char() != ',')
7298                 break;
7299               go_assert(!is_varargs);
7300               imp->require_c_string(", ");
7301             }
7302         }
7303       imp->require_c_string(")");
7304
7305       Typed_identifier_list* results;
7306       if (imp->peek_char() != ' ')
7307         results = NULL;
7308       else
7309         {
7310           results = new Typed_identifier_list;
7311           imp->advance(1);
7312           if (imp->peek_char() != '(')
7313             {
7314               Type* rtype = imp->read_type();
7315               results->push_back(Typed_identifier("", rtype, imp->location()));
7316             }
7317           else
7318             {
7319               imp->advance(1);
7320               while (true)
7321                 {
7322                   std::string name = imp->read_name();
7323                   imp->require_c_string(" ");
7324                   Type* rtype = imp->read_type();
7325                   results->push_back(Typed_identifier(name, rtype,
7326                                                       imp->location()));
7327                   if (imp->peek_char() != ',')
7328                     break;
7329                   imp->require_c_string(", ");
7330                 }
7331               imp->require_c_string(")");
7332             }
7333         }
7334
7335       Function_type* fntype = Type::make_function_type(NULL, parameters,
7336                                                        results,
7337                                                        imp->location());
7338       if (is_varargs)
7339         fntype->set_is_varargs();
7340       methods->push_back(Typed_identifier(name, fntype, imp->location()));
7341
7342       imp->require_c_string("; ");
7343     }
7344
7345   imp->require_c_string("}");
7346
7347   if (methods->empty())
7348     {
7349       delete methods;
7350       methods = NULL;
7351     }
7352
7353   return Type::make_interface_type(methods, imp->location());
7354 }
7355
7356 // Make an interface type.
7357
7358 Interface_type*
7359 Type::make_interface_type(Typed_identifier_list* methods,
7360                           Location location)
7361 {
7362   return new Interface_type(methods, location);
7363 }
7364
7365 // Make an empty interface type.
7366
7367 Interface_type*
7368 Type::make_empty_interface_type(Location location)
7369 {
7370   Interface_type* ret = new Interface_type(NULL, location);
7371   ret->finalize_methods();
7372   return ret;
7373 }
7374
7375 // Class Method.
7376
7377 // Bind a method to an object.
7378
7379 Expression*
7380 Method::bind_method(Expression* expr, Location location) const
7381 {
7382   if (this->stub_ == NULL)
7383     {
7384       // When there is no stub object, the binding is determined by
7385       // the child class.
7386       return this->do_bind_method(expr, location);
7387     }
7388   return Expression::make_bound_method(expr, this->stub_, location);
7389 }
7390
7391 // Return the named object associated with a method.  This may only be
7392 // called after methods are finalized.
7393
7394 Named_object*
7395 Method::named_object() const
7396 {
7397   if (this->stub_ != NULL)
7398     return this->stub_;
7399   return this->do_named_object();
7400 }
7401
7402 // Class Named_method.
7403
7404 // The type of the method.
7405
7406 Function_type*
7407 Named_method::do_type() const
7408 {
7409   if (this->named_object_->is_function())
7410     return this->named_object_->func_value()->type();
7411   else if (this->named_object_->is_function_declaration())
7412     return this->named_object_->func_declaration_value()->type();
7413   else
7414     go_unreachable();
7415 }
7416
7417 // Return the location of the method receiver.
7418
7419 Location
7420 Named_method::do_receiver_location() const
7421 {
7422   return this->do_type()->receiver()->location();
7423 }
7424
7425 // Bind a method to an object.
7426
7427 Expression*
7428 Named_method::do_bind_method(Expression* expr, Location location) const
7429 {
7430   Named_object* no = this->named_object_;
7431   Bound_method_expression* bme = Expression::make_bound_method(expr, no,
7432                                                                location);
7433   // If this is not a local method, and it does not use a stub, then
7434   // the real method expects a different type.  We need to cast the
7435   // first argument.
7436   if (this->depth() > 0 && !this->needs_stub_method())
7437     {
7438       Function_type* ftype = this->do_type();
7439       go_assert(ftype->is_method());
7440       Type* frtype = ftype->receiver()->type();
7441       bme->set_first_argument_type(frtype);
7442     }
7443   return bme;
7444 }
7445
7446 // Class Interface_method.
7447
7448 // Bind a method to an object.
7449
7450 Expression*
7451 Interface_method::do_bind_method(Expression* expr,
7452                                  Location location) const
7453 {
7454   return Expression::make_interface_field_reference(expr, this->name_,
7455                                                     location);
7456 }
7457
7458 // Class Methods.
7459
7460 // Insert a new method.  Return true if it was inserted, false
7461 // otherwise.
7462
7463 bool
7464 Methods::insert(const std::string& name, Method* m)
7465 {
7466   std::pair<Method_map::iterator, bool> ins =
7467     this->methods_.insert(std::make_pair(name, m));
7468   if (ins.second)
7469     return true;
7470   else
7471     {
7472       Method* old_method = ins.first->second;
7473       if (m->depth() < old_method->depth())
7474         {
7475           delete old_method;
7476           ins.first->second = m;
7477           return true;
7478         }
7479       else
7480         {
7481           if (m->depth() == old_method->depth())
7482             old_method->set_is_ambiguous();
7483           return false;
7484         }
7485     }
7486 }
7487
7488 // Return the number of unambiguous methods.
7489
7490 size_t
7491 Methods::count() const
7492 {
7493   size_t ret = 0;
7494   for (Method_map::const_iterator p = this->methods_.begin();
7495        p != this->methods_.end();
7496        ++p)
7497     if (!p->second->is_ambiguous())
7498       ++ret;
7499   return ret;
7500 }
7501
7502 // Class Named_type.
7503
7504 // Return the name of the type.
7505
7506 const std::string&
7507 Named_type::name() const
7508 {
7509   return this->named_object_->name();
7510 }
7511
7512 // Return the name of the type to use in an error message.
7513
7514 std::string
7515 Named_type::message_name() const
7516 {
7517   return this->named_object_->message_name();
7518 }
7519
7520 // Whether this is an alias.  There are currently only two aliases so
7521 // we just recognize them by name.
7522
7523 bool
7524 Named_type::is_alias() const
7525 {
7526   if (!this->is_builtin())
7527     return false;
7528   const std::string& name(this->name());
7529   return name == "byte" || name == "rune";
7530 }
7531
7532 // Return the base type for this type.  We have to be careful about
7533 // circular type definitions, which are invalid but may be seen here.
7534
7535 Type*
7536 Named_type::named_base()
7537 {
7538   if (this->seen_)
7539     return this;
7540   this->seen_ = true;
7541   Type* ret = this->type_->base();
7542   this->seen_ = false;
7543   return ret;
7544 }
7545
7546 const Type*
7547 Named_type::named_base() const
7548 {
7549   if (this->seen_)
7550     return this;
7551   this->seen_ = true;
7552   const Type* ret = this->type_->base();
7553   this->seen_ = false;
7554   return ret;
7555 }
7556
7557 // Return whether this is an error type.  We have to be careful about
7558 // circular type definitions, which are invalid but may be seen here.
7559
7560 bool
7561 Named_type::is_named_error_type() const
7562 {
7563   if (this->seen_)
7564     return false;
7565   this->seen_ = true;
7566   bool ret = this->type_->is_error_type();
7567   this->seen_ = false;
7568   return ret;
7569 }
7570
7571 // Whether this type is comparable.  We have to be careful about
7572 // circular type definitions.
7573
7574 bool
7575 Named_type::named_type_is_comparable(std::string* reason) const
7576 {
7577   if (this->seen_)
7578     return false;
7579   this->seen_ = true;
7580   bool ret = Type::are_compatible_for_comparison(true, this->type_,
7581                                                  this->type_, reason);
7582   this->seen_ = false;
7583   return ret;
7584 }
7585
7586 // Add a method to this type.
7587
7588 Named_object*
7589 Named_type::add_method(const std::string& name, Function* function)
7590 {
7591   if (this->local_methods_ == NULL)
7592     this->local_methods_ = new Bindings(NULL);
7593   return this->local_methods_->add_function(name, NULL, function);
7594 }
7595
7596 // Add a method declaration to this type.
7597
7598 Named_object*
7599 Named_type::add_method_declaration(const std::string& name, Package* package,
7600                                    Function_type* type,
7601                                    Location location)
7602 {
7603   if (this->local_methods_ == NULL)
7604     this->local_methods_ = new Bindings(NULL);
7605   return this->local_methods_->add_function_declaration(name, package, type,
7606                                                         location);
7607 }
7608
7609 // Add an existing method to this type.
7610
7611 void
7612 Named_type::add_existing_method(Named_object* no)
7613 {
7614   if (this->local_methods_ == NULL)
7615     this->local_methods_ = new Bindings(NULL);
7616   this->local_methods_->add_named_object(no);
7617 }
7618
7619 // Look for a local method NAME, and returns its named object, or NULL
7620 // if not there.
7621
7622 Named_object*
7623 Named_type::find_local_method(const std::string& name) const
7624 {
7625   if (this->local_methods_ == NULL)
7626     return NULL;
7627   return this->local_methods_->lookup(name);
7628 }
7629
7630 // Return whether NAME is an unexported field or method, for better
7631 // error reporting.
7632
7633 bool
7634 Named_type::is_unexported_local_method(Gogo* gogo,
7635                                        const std::string& name) const
7636 {
7637   Bindings* methods = this->local_methods_;
7638   if (methods != NULL)
7639     {
7640       for (Bindings::const_declarations_iterator p =
7641              methods->begin_declarations();
7642            p != methods->end_declarations();
7643            ++p)
7644         {
7645           if (Gogo::is_hidden_name(p->first)
7646               && name == Gogo::unpack_hidden_name(p->first)
7647               && gogo->pack_hidden_name(name, false) != p->first)
7648             return true;
7649         }
7650     }
7651   return false;
7652 }
7653
7654 // Build the complete list of methods for this type, which means
7655 // recursively including all methods for anonymous fields.  Create all
7656 // stub methods.
7657
7658 void
7659 Named_type::finalize_methods(Gogo* gogo)
7660 {
7661   if (this->all_methods_ != NULL)
7662     return;
7663
7664   if (this->local_methods_ != NULL
7665       && (this->points_to() != NULL || this->interface_type() != NULL))
7666     {
7667       const Bindings* lm = this->local_methods_;
7668       for (Bindings::const_declarations_iterator p = lm->begin_declarations();
7669            p != lm->end_declarations();
7670            ++p)
7671         error_at(p->second->location(),
7672                  "invalid pointer or interface receiver type");
7673       delete this->local_methods_;
7674       this->local_methods_ = NULL;
7675       return;
7676     }
7677
7678   Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
7679 }
7680
7681 // Return the method NAME, or NULL if there isn't one or if it is
7682 // ambiguous.  Set *IS_AMBIGUOUS if the method exists but is
7683 // ambiguous.
7684
7685 Method*
7686 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
7687 {
7688   return Type::method_function(this->all_methods_, name, is_ambiguous);
7689 }
7690
7691 // Return a pointer to the interface method table for this type for
7692 // the interface INTERFACE.  IS_POINTER is true if this is for a
7693 // pointer to THIS.
7694
7695 tree
7696 Named_type::interface_method_table(Gogo* gogo, const Interface_type* interface,
7697                                    bool is_pointer)
7698 {
7699   go_assert(!interface->is_empty());
7700
7701   Interface_method_tables** pimt = (is_pointer
7702                                     ? &this->interface_method_tables_
7703                                     : &this->pointer_interface_method_tables_);
7704
7705   if (*pimt == NULL)
7706     *pimt = new Interface_method_tables(5);
7707
7708   std::pair<const Interface_type*, tree> val(interface, NULL_TREE);
7709   std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
7710
7711   if (ins.second)
7712     {
7713       // This is a new entry in the hash table.
7714       go_assert(ins.first->second == NULL_TREE);
7715       ins.first->second = gogo->interface_method_table_for_type(interface,
7716                                                                 this,
7717                                                                 is_pointer);
7718     }
7719
7720   tree decl = ins.first->second;
7721   if (decl == error_mark_node)
7722     return error_mark_node;
7723   go_assert(decl != NULL_TREE && TREE_CODE(decl) == VAR_DECL);
7724   return build_fold_addr_expr(decl);
7725 }
7726
7727 // Return whether a named type has any hidden fields.
7728
7729 bool
7730 Named_type::named_type_has_hidden_fields(std::string* reason) const
7731 {
7732   if (this->seen_)
7733     return false;
7734   this->seen_ = true;
7735   bool ret = this->type_->has_hidden_fields(this, reason);
7736   this->seen_ = false;
7737   return ret;
7738 }
7739
7740 // Look for a use of a complete type within another type.  This is
7741 // used to check that we don't try to use a type within itself.
7742
7743 class Find_type_use : public Traverse
7744 {
7745  public:
7746   Find_type_use(Named_type* find_type)
7747     : Traverse(traverse_types),
7748       find_type_(find_type), found_(false)
7749   { }
7750
7751   // Whether we found the type.
7752   bool
7753   found() const
7754   { return this->found_; }
7755
7756  protected:
7757   int
7758   type(Type*);
7759
7760  private:
7761   // The type we are looking for.
7762   Named_type* find_type_;
7763   // Whether we found the type.
7764   bool found_;
7765 };
7766
7767 // Check for FIND_TYPE in TYPE.
7768
7769 int
7770 Find_type_use::type(Type* type)
7771 {
7772   if (type->named_type() != NULL && this->find_type_ == type->named_type())
7773     {
7774       this->found_ = true;
7775       return TRAVERSE_EXIT;
7776     }
7777
7778   // It's OK if we see a reference to the type in any type which is
7779   // essentially a pointer: a pointer, a slice, a function, a map, or
7780   // a channel.
7781   if (type->points_to() != NULL
7782       || type->is_slice_type()
7783       || type->function_type() != NULL
7784       || type->map_type() != NULL
7785       || type->channel_type() != NULL)
7786     return TRAVERSE_SKIP_COMPONENTS;
7787
7788   // For an interface, a reference to the type in a method type should
7789   // be ignored, but we have to consider direct inheritance.  When
7790   // this is called, there may be cases of direct inheritance
7791   // represented as a method with no name.
7792   if (type->interface_type() != NULL)
7793     {
7794       const Typed_identifier_list* methods = type->interface_type()->methods();
7795       if (methods != NULL)
7796         {
7797           for (Typed_identifier_list::const_iterator p = methods->begin();
7798                p != methods->end();
7799                ++p)
7800             {
7801               if (p->name().empty())
7802                 {
7803                   if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
7804                     return TRAVERSE_EXIT;
7805                 }
7806             }
7807         }
7808       return TRAVERSE_SKIP_COMPONENTS;
7809     }
7810
7811   // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
7812   // to convert TYPE to the backend representation before we convert
7813   // FIND_TYPE_.
7814   if (type->named_type() != NULL)
7815     {
7816       switch (type->base()->classification())
7817         {
7818         case Type::TYPE_ERROR:
7819         case Type::TYPE_BOOLEAN:
7820         case Type::TYPE_INTEGER:
7821         case Type::TYPE_FLOAT:
7822         case Type::TYPE_COMPLEX:
7823         case Type::TYPE_STRING:
7824         case Type::TYPE_NIL:
7825           break;
7826
7827         case Type::TYPE_ARRAY:
7828         case Type::TYPE_STRUCT:
7829           this->find_type_->add_dependency(type->named_type());
7830           break;
7831
7832         case Type::TYPE_NAMED:
7833         case Type::TYPE_FORWARD:
7834           go_assert(saw_errors());
7835           break;
7836
7837         case Type::TYPE_VOID:
7838         case Type::TYPE_SINK:
7839         case Type::TYPE_FUNCTION:
7840         case Type::TYPE_POINTER:
7841         case Type::TYPE_CALL_MULTIPLE_RESULT:
7842         case Type::TYPE_MAP:
7843         case Type::TYPE_CHANNEL:
7844         case Type::TYPE_INTERFACE:
7845         default:
7846           go_unreachable();
7847         }
7848     }
7849
7850   return TRAVERSE_CONTINUE;
7851 }
7852
7853 // Verify that a named type does not refer to itself.
7854
7855 bool
7856 Named_type::do_verify()
7857 {
7858   Find_type_use find(this);
7859   Type::traverse(this->type_, &find);
7860   if (find.found())
7861     {
7862       error_at(this->location_, "invalid recursive type %qs",
7863                this->message_name().c_str());
7864       this->is_error_ = true;
7865       return false;
7866     }
7867
7868   // Check whether any of the local methods overloads an existing
7869   // struct field or interface method.  We don't need to check the
7870   // list of methods against itself: that is handled by the Bindings
7871   // code.
7872   if (this->local_methods_ != NULL)
7873     {
7874       Struct_type* st = this->type_->struct_type();
7875       if (st != NULL)
7876         {
7877           for (Bindings::const_declarations_iterator p =
7878                  this->local_methods_->begin_declarations();
7879                p != this->local_methods_->end_declarations();
7880                ++p)
7881             {
7882               const std::string& name(p->first);
7883               if (st != NULL && st->find_local_field(name, NULL) != NULL)
7884                 {
7885                   error_at(p->second->location(),
7886                            "method %qs redeclares struct field name",
7887                            Gogo::message_name(name).c_str());
7888                 }
7889             }
7890         }
7891     }
7892
7893   return true;
7894 }
7895
7896 // Return whether this type is or contains a pointer.
7897
7898 bool
7899 Named_type::do_has_pointer() const
7900 {
7901   if (this->seen_)
7902     return false;
7903   this->seen_ = true;
7904   bool ret = this->type_->has_pointer();
7905   this->seen_ = false;
7906   return ret;
7907 }
7908
7909 // Return whether comparisons for this type can use the identity
7910 // function.
7911
7912 bool
7913 Named_type::do_compare_is_identity(Gogo* gogo) const
7914 {
7915   // We don't use this->seen_ here because compare_is_identity may
7916   // call base() later, and that will mess up if seen_ is set here.
7917   if (this->seen_in_compare_is_identity_)
7918     return false;
7919   this->seen_in_compare_is_identity_ = true;
7920   bool ret = this->type_->compare_is_identity(gogo);
7921   this->seen_in_compare_is_identity_ = false;
7922   return ret;
7923 }
7924
7925 // Return a hash code.  This is used for method lookup.  We simply
7926 // hash on the name itself.
7927
7928 unsigned int
7929 Named_type::do_hash_for_method(Gogo* gogo) const
7930 {
7931   if (this->is_alias())
7932     return this->type_->named_type()->do_hash_for_method(gogo);
7933
7934   const std::string& name(this->named_object()->name());
7935   unsigned int ret = Type::hash_string(name, 0);
7936
7937   // GOGO will be NULL here when called from Type_hash_identical.
7938   // That is OK because that is only used for internal hash tables
7939   // where we are going to be comparing named types for equality.  In
7940   // other cases, which are cases where the runtime is going to
7941   // compare hash codes to see if the types are the same, we need to
7942   // include the package prefix and name in the hash.
7943   if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
7944     {
7945       const Package* package = this->named_object()->package();
7946       if (package == NULL)
7947         {
7948           ret = Type::hash_string(gogo->unique_prefix(), ret);
7949           ret = Type::hash_string(gogo->package_name(), ret);
7950         }
7951       else
7952         {
7953           ret = Type::hash_string(package->unique_prefix(), ret);
7954           ret = Type::hash_string(package->name(), ret);
7955         }
7956     }
7957
7958   return ret;
7959 }
7960
7961 // Convert a named type to the backend representation.  In order to
7962 // get dependencies right, we fill in a dummy structure for this type,
7963 // then convert all the dependencies, then complete this type.  When
7964 // this function is complete, the size of the type is known.
7965
7966 void
7967 Named_type::convert(Gogo* gogo)
7968 {
7969   if (this->is_error_ || this->is_converted_)
7970     return;
7971
7972   this->create_placeholder(gogo);
7973
7974   // Convert all the dependencies.  If they refer indirectly back to
7975   // this type, they will pick up the intermediate tree we just
7976   // created.
7977   for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
7978        p != this->dependencies_.end();
7979        ++p)
7980     (*p)->convert(gogo);
7981
7982   // Complete this type.
7983   Btype* bt = this->named_btype_;
7984   Type* base = this->type_->base();
7985   switch (base->classification())
7986     {
7987     case TYPE_VOID:
7988     case TYPE_BOOLEAN:
7989     case TYPE_INTEGER:
7990     case TYPE_FLOAT:
7991     case TYPE_COMPLEX:
7992     case TYPE_STRING:
7993     case TYPE_NIL:
7994       break;
7995
7996     case TYPE_MAP:
7997     case TYPE_CHANNEL:
7998       break;
7999
8000     case TYPE_FUNCTION:
8001     case TYPE_POINTER:
8002       // The size of these types is already correct.  We don't worry
8003       // about filling them in until later, when we also track
8004       // circular references.
8005       break;
8006
8007     case TYPE_STRUCT:
8008       {
8009         std::vector<Backend::Btyped_identifier> bfields;
8010         get_backend_struct_fields(gogo, base->struct_type()->fields(),
8011                                   true, &bfields);
8012         if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8013           bt = gogo->backend()->error_type();
8014       }
8015       break;
8016
8017     case TYPE_ARRAY:
8018       // Slice types were completed in create_placeholder.
8019       if (!base->is_slice_type())
8020         {
8021           Btype* bet = base->array_type()->get_backend_element(gogo, true);
8022           Bexpression* blen = base->array_type()->get_backend_length(gogo);
8023           if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
8024             bt = gogo->backend()->error_type();
8025         }
8026       break;
8027
8028     case TYPE_INTERFACE:
8029       // Interface types were completed in create_placeholder.
8030       break;
8031
8032     case TYPE_ERROR:
8033       return;
8034
8035     default:
8036     case TYPE_SINK:
8037     case TYPE_CALL_MULTIPLE_RESULT:
8038     case TYPE_NAMED:
8039     case TYPE_FORWARD:
8040       go_unreachable();
8041     }
8042
8043   this->named_btype_ = bt;
8044   this->is_converted_ = true;
8045   this->is_placeholder_ = false;
8046 }
8047
8048 // Create the placeholder for a named type.  This is the first step in
8049 // converting to the backend representation.
8050
8051 void
8052 Named_type::create_placeholder(Gogo* gogo)
8053 {
8054   if (this->is_error_)
8055     this->named_btype_ = gogo->backend()->error_type();
8056
8057   if (this->named_btype_ != NULL)
8058     return;
8059
8060   // Create the structure for this type.  Note that because we call
8061   // base() here, we don't attempt to represent a named type defined
8062   // as another named type.  Instead both named types will point to
8063   // different base representations.
8064   Type* base = this->type_->base();
8065   Btype* bt;
8066   bool set_name = true;
8067   switch (base->classification())
8068     {
8069     case TYPE_ERROR:
8070       this->is_error_ = true;
8071       this->named_btype_ = gogo->backend()->error_type();
8072       return;
8073
8074     case TYPE_VOID:
8075     case TYPE_BOOLEAN:
8076     case TYPE_INTEGER:
8077     case TYPE_FLOAT:
8078     case TYPE_COMPLEX:
8079     case TYPE_STRING:
8080     case TYPE_NIL:
8081       // These are simple basic types, we can just create them
8082       // directly.
8083       bt = Type::get_named_base_btype(gogo, base);
8084       break;
8085
8086     case TYPE_MAP:
8087     case TYPE_CHANNEL:
8088       // All maps and channels have the same backend representation.
8089       bt = Type::get_named_base_btype(gogo, base);
8090       break;
8091
8092     case TYPE_FUNCTION:
8093     case TYPE_POINTER:
8094       {
8095         bool for_function = base->classification() == TYPE_FUNCTION;
8096         bt = gogo->backend()->placeholder_pointer_type(this->name(),
8097                                                        this->location_,
8098                                                        for_function);
8099         set_name = false;
8100       }
8101       break;
8102
8103     case TYPE_STRUCT:
8104       bt = gogo->backend()->placeholder_struct_type(this->name(),
8105                                                     this->location_);
8106       this->is_placeholder_ = true;
8107       set_name = false;
8108       break;
8109
8110     case TYPE_ARRAY:
8111       if (base->is_slice_type())
8112         bt = gogo->backend()->placeholder_struct_type(this->name(),
8113                                                       this->location_);
8114       else
8115         {
8116           bt = gogo->backend()->placeholder_array_type(this->name(),
8117                                                        this->location_);
8118           this->is_placeholder_ = true;
8119         }
8120       set_name = false;
8121       break;
8122
8123     case TYPE_INTERFACE:
8124       if (base->interface_type()->is_empty())
8125         bt = Interface_type::get_backend_empty_interface_type(gogo);
8126       else
8127         {
8128           bt = gogo->backend()->placeholder_struct_type(this->name(),
8129                                                         this->location_);
8130           set_name = false;
8131         }
8132       break;
8133
8134     default:
8135     case TYPE_SINK:
8136     case TYPE_CALL_MULTIPLE_RESULT:
8137     case TYPE_NAMED:
8138     case TYPE_FORWARD:
8139       go_unreachable();
8140     }
8141
8142   if (set_name)
8143     bt = gogo->backend()->named_type(this->name(), bt, this->location_);
8144
8145   this->named_btype_ = bt;
8146
8147   if (base->is_slice_type())
8148     {
8149       // We do not record slices as dependencies of other types,
8150       // because we can fill them in completely here with the final
8151       // size.
8152       std::vector<Backend::Btyped_identifier> bfields;
8153       get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
8154       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8155         this->named_btype_ = gogo->backend()->error_type();
8156     }
8157   else if (base->interface_type() != NULL
8158            && !base->interface_type()->is_empty())
8159     {
8160       // We do not record interfaces as dependencies of other types,
8161       // because we can fill them in completely here with the final
8162       // size.
8163       std::vector<Backend::Btyped_identifier> bfields;
8164       get_backend_interface_fields(gogo, base->interface_type(), true,
8165                                    &bfields);
8166       if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
8167         this->named_btype_ = gogo->backend()->error_type();
8168     }
8169 }
8170
8171 // Get a tree for a named type.
8172
8173 Btype*
8174 Named_type::do_get_backend(Gogo* gogo)
8175 {
8176   if (this->is_error_)
8177     return gogo->backend()->error_type();
8178
8179   Btype* bt = this->named_btype_;
8180
8181   if (!gogo->named_types_are_converted())
8182     {
8183       // We have not completed converting named types.  NAMED_BTYPE_
8184       // is a placeholder and we shouldn't do anything further.
8185       if (bt != NULL)
8186         return bt;
8187
8188       // We don't build dependencies for types whose sizes do not
8189       // change or are not relevant, so we may see them here while
8190       // converting types.
8191       this->create_placeholder(gogo);
8192       bt = this->named_btype_;
8193       go_assert(bt != NULL);
8194       return bt;
8195     }
8196
8197   // We are not converting types.  This should only be called if the
8198   // type has already been converted.
8199   if (!this->is_converted_)
8200     {
8201       go_assert(saw_errors());
8202       return gogo->backend()->error_type();
8203     }
8204
8205   go_assert(bt != NULL);
8206
8207   // Complete the tree.
8208   Type* base = this->type_->base();
8209   Btype* bt1;
8210   switch (base->classification())
8211     {
8212     case TYPE_ERROR:
8213       return gogo->backend()->error_type();
8214
8215     case TYPE_VOID:
8216     case TYPE_BOOLEAN:
8217     case TYPE_INTEGER:
8218     case TYPE_FLOAT:
8219     case TYPE_COMPLEX:
8220     case TYPE_STRING:
8221     case TYPE_NIL:
8222     case TYPE_MAP:
8223     case TYPE_CHANNEL:
8224       return bt;
8225
8226     case TYPE_STRUCT:
8227       if (!this->seen_in_get_backend_)
8228         {
8229           this->seen_in_get_backend_ = true;
8230           base->struct_type()->finish_backend_fields(gogo);
8231           this->seen_in_get_backend_ = false;
8232         }
8233       return bt;
8234
8235     case TYPE_ARRAY:
8236       if (!this->seen_in_get_backend_)
8237         {
8238           this->seen_in_get_backend_ = true;
8239           base->array_type()->finish_backend_element(gogo);
8240           this->seen_in_get_backend_ = false;
8241         }
8242       return bt;
8243
8244     case TYPE_INTERFACE:
8245       if (!this->seen_in_get_backend_)
8246         {
8247           this->seen_in_get_backend_ = true;
8248           base->interface_type()->finish_backend_methods(gogo);
8249           this->seen_in_get_backend_ = false;
8250         }
8251       return bt;
8252
8253     case TYPE_FUNCTION:
8254       // Don't build a circular data structure.  GENERIC can't handle
8255       // it.
8256       if (this->seen_in_get_backend_)
8257         {
8258           this->is_circular_ = true;
8259           return gogo->backend()->circular_pointer_type(bt, true);
8260         }
8261       this->seen_in_get_backend_ = true;
8262       bt1 = Type::get_named_base_btype(gogo, base);
8263       this->seen_in_get_backend_ = false;
8264       if (this->is_circular_)
8265         bt1 = gogo->backend()->circular_pointer_type(bt, true);
8266       if (!gogo->backend()->set_placeholder_function_type(bt, bt1))
8267         bt = gogo->backend()->error_type();
8268       return bt;
8269
8270     case TYPE_POINTER:
8271       // Don't build a circular data structure. GENERIC can't handle
8272       // it.
8273       if (this->seen_in_get_backend_)
8274         {
8275           this->is_circular_ = true;
8276           return gogo->backend()->circular_pointer_type(bt, false);
8277         }
8278       this->seen_in_get_backend_ = true;
8279       bt1 = Type::get_named_base_btype(gogo, base);
8280       this->seen_in_get_backend_ = false;
8281       if (this->is_circular_)
8282         bt1 = gogo->backend()->circular_pointer_type(bt, false);
8283       if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
8284         bt = gogo->backend()->error_type();
8285       return bt;
8286
8287     default:
8288     case TYPE_SINK:
8289     case TYPE_CALL_MULTIPLE_RESULT:
8290     case TYPE_NAMED:
8291     case TYPE_FORWARD:
8292       go_unreachable();
8293     }
8294
8295   go_unreachable();
8296 }
8297
8298 // Build a type descriptor for a named type.
8299
8300 Expression*
8301 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8302 {
8303   if (name == NULL && this->is_alias())
8304     return this->type_->type_descriptor(gogo, this->type_);
8305
8306   // If NAME is not NULL, then we don't really want the type
8307   // descriptor for this type; we want the descriptor for the
8308   // underlying type, giving it the name NAME.
8309   return this->named_type_descriptor(gogo, this->type_,
8310                                      name == NULL ? this : name);
8311 }
8312
8313 // Add to the reflection string.  This is used mostly for the name of
8314 // the type used in a type descriptor, not for actual reflection
8315 // strings.
8316
8317 void
8318 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
8319 {
8320   if (this->is_alias())
8321     {
8322       this->append_reflection(this->type_, gogo, ret);
8323       return;
8324     }
8325   if (!this->is_builtin())
8326     {
8327       const Package* package = this->named_object_->package();
8328       if (package != NULL)
8329         ret->append(package->name());
8330       else
8331         ret->append(gogo->package_name());
8332       ret->push_back('.');
8333     }
8334   if (this->in_function_ != NULL)
8335     {
8336       ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
8337       ret->push_back('$');
8338     }
8339   ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
8340 }
8341
8342 // Get the mangled name.
8343
8344 void
8345 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8346 {
8347   if (this->is_alias())
8348     {
8349       this->append_mangled_name(this->type_, gogo, ret);
8350       return;
8351     }
8352   Named_object* no = this->named_object_;
8353   std::string name;
8354   if (this->is_builtin())
8355     go_assert(this->in_function_ == NULL);
8356   else
8357     {
8358       const std::string& unique_prefix(no->package() == NULL
8359                                        ? gogo->unique_prefix()
8360                                        : no->package()->unique_prefix());
8361       const std::string& package_name(no->package() == NULL
8362                                       ? gogo->package_name()
8363                                       : no->package()->name());
8364       name = unique_prefix;
8365       name.append(1, '.');
8366       name.append(package_name);
8367       name.append(1, '.');
8368       if (this->in_function_ != NULL)
8369         {
8370           name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
8371           name.append(1, '$');
8372         }
8373     }
8374   name.append(Gogo::unpack_hidden_name(no->name()));
8375   char buf[20];
8376   snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
8377   ret->append(buf);
8378   ret->append(name);
8379 }
8380
8381 // Export the type.  This is called to export a global type.
8382
8383 void
8384 Named_type::export_named_type(Export* exp, const std::string&) const
8385 {
8386   // We don't need to write the name of the type here, because it will
8387   // be written by Export::write_type anyhow.
8388   exp->write_c_string("type ");
8389   exp->write_type(this);
8390   exp->write_c_string(";\n");
8391 }
8392
8393 // Import a named type.
8394
8395 void
8396 Named_type::import_named_type(Import* imp, Named_type** ptype)
8397 {
8398   imp->require_c_string("type ");
8399   Type *type = imp->read_type();
8400   *ptype = type->named_type();
8401   go_assert(*ptype != NULL);
8402   imp->require_c_string(";\n");
8403 }
8404
8405 // Export the type when it is referenced by another type.  In this
8406 // case Export::export_type will already have issued the name.
8407
8408 void
8409 Named_type::do_export(Export* exp) const
8410 {
8411   exp->write_type(this->type_);
8412
8413   // To save space, we only export the methods directly attached to
8414   // this type.
8415   Bindings* methods = this->local_methods_;
8416   if (methods == NULL)
8417     return;
8418
8419   exp->write_c_string("\n");
8420   for (Bindings::const_definitions_iterator p = methods->begin_definitions();
8421        p != methods->end_definitions();
8422        ++p)
8423     {
8424       exp->write_c_string(" ");
8425       (*p)->export_named_object(exp);
8426     }
8427
8428   for (Bindings::const_declarations_iterator p = methods->begin_declarations();
8429        p != methods->end_declarations();
8430        ++p)
8431     {
8432       if (p->second->is_function_declaration())
8433         {
8434           exp->write_c_string(" ");
8435           p->second->export_named_object(exp);
8436         }
8437     }
8438 }
8439
8440 // Make a named type.
8441
8442 Named_type*
8443 Type::make_named_type(Named_object* named_object, Type* type,
8444                       Location location)
8445 {
8446   return new Named_type(named_object, type, location);
8447 }
8448
8449 // Finalize the methods for TYPE.  It will be a named type or a struct
8450 // type.  This sets *ALL_METHODS to the list of methods, and builds
8451 // all required stubs.
8452
8453 void
8454 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
8455                        Methods** all_methods)
8456 {
8457   *all_methods = NULL;
8458   Types_seen types_seen;
8459   Type::add_methods_for_type(type, NULL, 0, false, false, &types_seen,
8460                              all_methods);
8461   Type::build_stub_methods(gogo, type, *all_methods, location);
8462 }
8463
8464 // Add the methods for TYPE to *METHODS.  FIELD_INDEXES is used to
8465 // build up the struct field indexes as we go.  DEPTH is the depth of
8466 // the field within TYPE.  IS_EMBEDDED_POINTER is true if we are
8467 // adding these methods for an anonymous field with pointer type.
8468 // NEEDS_STUB_METHOD is true if we need to use a stub method which
8469 // calls the real method.  TYPES_SEEN is used to avoid infinite
8470 // recursion.
8471
8472 void
8473 Type::add_methods_for_type(const Type* type,
8474                            const Method::Field_indexes* field_indexes,
8475                            unsigned int depth,
8476                            bool is_embedded_pointer,
8477                            bool needs_stub_method,
8478                            Types_seen* types_seen,
8479                            Methods** methods)
8480 {
8481   // Pointer types may not have methods.
8482   if (type->points_to() != NULL)
8483     return;
8484
8485   const Named_type* nt = type->named_type();
8486   if (nt != NULL)
8487     {
8488       std::pair<Types_seen::iterator, bool> ins = types_seen->insert(nt);
8489       if (!ins.second)
8490         return;
8491     }
8492
8493   if (nt != NULL)
8494     Type::add_local_methods_for_type(nt, field_indexes, depth,
8495                                      is_embedded_pointer, needs_stub_method,
8496                                      methods);
8497
8498   Type::add_embedded_methods_for_type(type, field_indexes, depth,
8499                                       is_embedded_pointer, needs_stub_method,
8500                                       types_seen, methods);
8501
8502   // If we are called with depth > 0, then we are looking at an
8503   // anonymous field of a struct.  If such a field has interface type,
8504   // then we need to add the interface methods.  We don't want to add
8505   // them when depth == 0, because we will already handle them
8506   // following the usual rules for an interface type.
8507   if (depth > 0)
8508     Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
8509 }
8510
8511 // Add the local methods for the named type NT to *METHODS.  The
8512 // parameters are as for add_methods_to_type.
8513
8514 void
8515 Type::add_local_methods_for_type(const Named_type* nt,
8516                                  const Method::Field_indexes* field_indexes,
8517                                  unsigned int depth,
8518                                  bool is_embedded_pointer,
8519                                  bool needs_stub_method,
8520                                  Methods** methods)
8521 {
8522   const Bindings* local_methods = nt->local_methods();
8523   if (local_methods == NULL)
8524     return;
8525
8526   if (*methods == NULL)
8527     *methods = new Methods();
8528
8529   for (Bindings::const_declarations_iterator p =
8530          local_methods->begin_declarations();
8531        p != local_methods->end_declarations();
8532        ++p)
8533     {
8534       Named_object* no = p->second;
8535       bool is_value_method = (is_embedded_pointer
8536                               || !Type::method_expects_pointer(no));
8537       Method* m = new Named_method(no, field_indexes, depth, is_value_method,
8538                                    (needs_stub_method
8539                                     || (depth > 0 && is_value_method)));
8540       if (!(*methods)->insert(no->name(), m))
8541         delete m;
8542     }
8543 }
8544
8545 // Add the embedded methods for TYPE to *METHODS.  These are the
8546 // methods attached to anonymous fields.  The parameters are as for
8547 // add_methods_to_type.
8548
8549 void
8550 Type::add_embedded_methods_for_type(const Type* type,
8551                                     const Method::Field_indexes* field_indexes,
8552                                     unsigned int depth,
8553                                     bool is_embedded_pointer,
8554                                     bool needs_stub_method,
8555                                     Types_seen* types_seen,
8556                                     Methods** methods)
8557 {
8558   // Look for anonymous fields in TYPE.  TYPE has fields if it is a
8559   // struct.
8560   const Struct_type* st = type->struct_type();
8561   if (st == NULL)
8562     return;
8563
8564   const Struct_field_list* fields = st->fields();
8565   if (fields == NULL)
8566     return;
8567
8568   unsigned int i = 0;
8569   for (Struct_field_list::const_iterator pf = fields->begin();
8570        pf != fields->end();
8571        ++pf, ++i)
8572     {
8573       if (!pf->is_anonymous())
8574         continue;
8575
8576       Type* ftype = pf->type();
8577       bool is_pointer = false;
8578       if (ftype->points_to() != NULL)
8579         {
8580           ftype = ftype->points_to();
8581           is_pointer = true;
8582         }
8583       Named_type* fnt = ftype->named_type();
8584       if (fnt == NULL)
8585         {
8586           // This is an error, but it will be diagnosed elsewhere.
8587           continue;
8588         }
8589
8590       Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
8591       sub_field_indexes->next = field_indexes;
8592       sub_field_indexes->field_index = i;
8593
8594       Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
8595                                  (is_embedded_pointer || is_pointer),
8596                                  (needs_stub_method
8597                                   || is_pointer
8598                                   || i > 0),
8599                                  types_seen,
8600                                  methods);
8601     }
8602 }
8603
8604 // If TYPE is an interface type, then add its method to *METHODS.
8605 // This is for interface methods attached to an anonymous field.  The
8606 // parameters are as for add_methods_for_type.
8607
8608 void
8609 Type::add_interface_methods_for_type(const Type* type,
8610                                      const Method::Field_indexes* field_indexes,
8611                                      unsigned int depth,
8612                                      Methods** methods)
8613 {
8614   const Interface_type* it = type->interface_type();
8615   if (it == NULL)
8616     return;
8617
8618   const Typed_identifier_list* imethods = it->methods();
8619   if (imethods == NULL)
8620     return;
8621
8622   if (*methods == NULL)
8623     *methods = new Methods();
8624
8625   for (Typed_identifier_list::const_iterator pm = imethods->begin();
8626        pm != imethods->end();
8627        ++pm)
8628     {
8629       Function_type* fntype = pm->type()->function_type();
8630       if (fntype == NULL)
8631         {
8632           // This is an error, but it should be reported elsewhere
8633           // when we look at the methods for IT.
8634           continue;
8635         }
8636       go_assert(!fntype->is_method());
8637       fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
8638       Method* m = new Interface_method(pm->name(), pm->location(), fntype,
8639                                        field_indexes, depth);
8640       if (!(*methods)->insert(pm->name(), m))
8641         delete m;
8642     }
8643 }
8644
8645 // Build stub methods for TYPE as needed.  METHODS is the set of
8646 // methods for the type.  A stub method may be needed when a type
8647 // inherits a method from an anonymous field.  When we need the
8648 // address of the method, as in a type descriptor, we need to build a
8649 // little stub which does the required field dereferences and jumps to
8650 // the real method.  LOCATION is the location of the type definition.
8651
8652 void
8653 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
8654                          Location location)
8655 {
8656   if (methods == NULL)
8657     return;
8658   for (Methods::const_iterator p = methods->begin();
8659        p != methods->end();
8660        ++p)
8661     {
8662       Method* m = p->second;
8663       if (m->is_ambiguous() || !m->needs_stub_method())
8664         continue;
8665
8666       const std::string& name(p->first);
8667
8668       // Build a stub method.
8669
8670       const Function_type* fntype = m->type();
8671
8672       static unsigned int counter;
8673       char buf[100];
8674       snprintf(buf, sizeof buf, "$this%u", counter);
8675       ++counter;
8676
8677       Type* receiver_type = const_cast<Type*>(type);
8678       if (!m->is_value_method())
8679         receiver_type = Type::make_pointer_type(receiver_type);
8680       Location receiver_location = m->receiver_location();
8681       Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
8682                                                         receiver_location);
8683
8684       const Typed_identifier_list* fnparams = fntype->parameters();
8685       Typed_identifier_list* stub_params;
8686       if (fnparams == NULL || fnparams->empty())
8687         stub_params = NULL;
8688       else
8689         {
8690           // We give each stub parameter a unique name.
8691           stub_params = new Typed_identifier_list();
8692           for (Typed_identifier_list::const_iterator pp = fnparams->begin();
8693                pp != fnparams->end();
8694                ++pp)
8695             {
8696               char pbuf[100];
8697               snprintf(pbuf, sizeof pbuf, "$p%u", counter);
8698               stub_params->push_back(Typed_identifier(pbuf, pp->type(),
8699                                                       pp->location()));
8700               ++counter;
8701             }
8702         }
8703
8704       const Typed_identifier_list* fnresults = fntype->results();
8705       Typed_identifier_list* stub_results;
8706       if (fnresults == NULL || fnresults->empty())
8707         stub_results = NULL;
8708       else
8709         {
8710           // We create the result parameters without any names, since
8711           // we won't refer to them.
8712           stub_results = new Typed_identifier_list();
8713           for (Typed_identifier_list::const_iterator pr = fnresults->begin();
8714                pr != fnresults->end();
8715                ++pr)
8716             stub_results->push_back(Typed_identifier("", pr->type(),
8717                                                      pr->location()));
8718         }
8719
8720       Function_type* stub_type = Type::make_function_type(receiver,
8721                                                           stub_params,
8722                                                           stub_results,
8723                                                           fntype->location());
8724       if (fntype->is_varargs())
8725         stub_type->set_is_varargs();
8726
8727       // We only create the function in the package which creates the
8728       // type.
8729       const Package* package;
8730       if (type->named_type() == NULL)
8731         package = NULL;
8732       else
8733         package = type->named_type()->named_object()->package();
8734       Named_object* stub;
8735       if (package != NULL)
8736         stub = Named_object::make_function_declaration(name, package,
8737                                                        stub_type, location);
8738       else
8739         {
8740           stub = gogo->start_function(name, stub_type, false,
8741                                       fntype->location());
8742           Type::build_one_stub_method(gogo, m, buf, stub_params,
8743                                       fntype->is_varargs(), location);
8744           gogo->finish_function(fntype->location());
8745         }
8746
8747       m->set_stub_object(stub);
8748     }
8749 }
8750
8751 // Build a stub method which adjusts the receiver as required to call
8752 // METHOD.  RECEIVER_NAME is the name we used for the receiver.
8753 // PARAMS is the list of function parameters.
8754
8755 void
8756 Type::build_one_stub_method(Gogo* gogo, Method* method,
8757                             const char* receiver_name,
8758                             const Typed_identifier_list* params,
8759                             bool is_varargs,
8760                             Location location)
8761 {
8762   Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
8763   go_assert(receiver_object != NULL);
8764
8765   Expression* expr = Expression::make_var_reference(receiver_object, location);
8766   expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
8767   if (expr->type()->points_to() == NULL)
8768     expr = Expression::make_unary(OPERATOR_AND, expr, location);
8769
8770   Expression_list* arguments;
8771   if (params == NULL || params->empty())
8772     arguments = NULL;
8773   else
8774     {
8775       arguments = new Expression_list();
8776       for (Typed_identifier_list::const_iterator p = params->begin();
8777            p != params->end();
8778            ++p)
8779         {
8780           Named_object* param = gogo->lookup(p->name(), NULL);
8781           go_assert(param != NULL);
8782           Expression* param_ref = Expression::make_var_reference(param,
8783                                                                  location);
8784           arguments->push_back(param_ref);
8785         }
8786     }
8787
8788   Expression* func = method->bind_method(expr, location);
8789   go_assert(func != NULL);
8790   Call_expression* call = Expression::make_call(func, arguments, is_varargs,
8791                                                 location);
8792   call->set_hidden_fields_are_ok();
8793   size_t count = call->result_count();
8794   if (count == 0)
8795     gogo->add_statement(Statement::make_statement(call, true));
8796   else
8797     {
8798       Expression_list* retvals = new Expression_list();
8799       if (count <= 1)
8800         retvals->push_back(call);
8801       else
8802         {
8803           for (size_t i = 0; i < count; ++i)
8804             retvals->push_back(Expression::make_call_result(call, i));
8805         }
8806       Return_statement* retstat = Statement::make_return_statement(retvals,
8807                                                                    location);
8808
8809       // We can return values with hidden fields from a stub.  This is
8810       // necessary if the method is itself hidden.
8811       retstat->set_hidden_fields_are_ok();
8812
8813       gogo->add_statement(retstat);
8814     }
8815 }
8816
8817 // Apply FIELD_INDEXES to EXPR.  The field indexes have to be applied
8818 // in reverse order.
8819
8820 Expression*
8821 Type::apply_field_indexes(Expression* expr,
8822                           const Method::Field_indexes* field_indexes,
8823                           Location location)
8824 {
8825   if (field_indexes == NULL)
8826     return expr;
8827   expr = Type::apply_field_indexes(expr, field_indexes->next, location);
8828   Struct_type* stype = expr->type()->deref()->struct_type();
8829   go_assert(stype != NULL
8830              && field_indexes->field_index < stype->field_count());
8831   if (expr->type()->struct_type() == NULL)
8832     {
8833       go_assert(expr->type()->points_to() != NULL);
8834       expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8835       go_assert(expr->type()->struct_type() == stype);
8836     }
8837   return Expression::make_field_reference(expr, field_indexes->field_index,
8838                                           location);
8839 }
8840
8841 // Return whether NO is a method for which the receiver is a pointer.
8842
8843 bool
8844 Type::method_expects_pointer(const Named_object* no)
8845 {
8846   const Function_type *fntype;
8847   if (no->is_function())
8848     fntype = no->func_value()->type();
8849   else if (no->is_function_declaration())
8850     fntype = no->func_declaration_value()->type();
8851   else
8852     go_unreachable();
8853   return fntype->receiver()->type()->points_to() != NULL;
8854 }
8855
8856 // Given a set of methods for a type, METHODS, return the method NAME,
8857 // or NULL if there isn't one or if it is ambiguous.  If IS_AMBIGUOUS
8858 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
8859 // but is ambiguous (and return NULL).
8860
8861 Method*
8862 Type::method_function(const Methods* methods, const std::string& name,
8863                       bool* is_ambiguous)
8864 {
8865   if (is_ambiguous != NULL)
8866     *is_ambiguous = false;
8867   if (methods == NULL)
8868     return NULL;
8869   Methods::const_iterator p = methods->find(name);
8870   if (p == methods->end())
8871     return NULL;
8872   Method* m = p->second;
8873   if (m->is_ambiguous())
8874     {
8875       if (is_ambiguous != NULL)
8876         *is_ambiguous = true;
8877       return NULL;
8878     }
8879   return m;
8880 }
8881
8882 // Look for field or method NAME for TYPE.  Return an Expression for
8883 // the field or method bound to EXPR.  If there is no such field or
8884 // method, give an appropriate error and return an error expression.
8885
8886 Expression*
8887 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
8888                            const std::string& name,
8889                            Location location)
8890 {
8891   if (type->deref()->is_error_type())
8892     return Expression::make_error(location);
8893
8894   const Named_type* nt = type->deref()->named_type();
8895   const Struct_type* st = type->deref()->struct_type();
8896   const Interface_type* it = type->interface_type();
8897
8898   // If this is a pointer to a pointer, then it is possible that the
8899   // pointed-to type has methods.
8900   bool dereferenced = false;
8901   if (nt == NULL
8902       && st == NULL
8903       && it == NULL
8904       && type->points_to() != NULL
8905       && type->points_to()->points_to() != NULL)
8906     {
8907       expr = Expression::make_unary(OPERATOR_MULT, expr, location);
8908       type = type->points_to();
8909       if (type->deref()->is_error_type())
8910         return Expression::make_error(location);
8911       nt = type->points_to()->named_type();
8912       st = type->points_to()->struct_type();
8913       dereferenced = true;
8914     }
8915
8916   bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
8917                                   || expr->is_addressable());
8918   std::vector<const Named_type*> seen;
8919   bool is_method = false;
8920   bool found_pointer_method = false;
8921   std::string ambig1;
8922   std::string ambig2;
8923   if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
8924                                  &seen, NULL, &is_method,
8925                                  &found_pointer_method, &ambig1, &ambig2))
8926     {
8927       Expression* ret;
8928       if (!is_method)
8929         {
8930           go_assert(st != NULL);
8931           if (type->struct_type() == NULL)
8932             {
8933               go_assert(type->points_to() != NULL);
8934               expr = Expression::make_unary(OPERATOR_MULT, expr,
8935                                             location);
8936               go_assert(expr->type()->struct_type() == st);
8937             }
8938           ret = st->field_reference(expr, name, location);
8939         }
8940       else if (it != NULL && it->find_method(name) != NULL)
8941         ret = Expression::make_interface_field_reference(expr, name,
8942                                                          location);
8943       else
8944         {
8945           Method* m;
8946           if (nt != NULL)
8947             m = nt->method_function(name, NULL);
8948           else if (st != NULL)
8949             m = st->method_function(name, NULL);
8950           else
8951             go_unreachable();
8952           go_assert(m != NULL);
8953           if (dereferenced && m->is_value_method())
8954             {
8955               error_at(location,
8956                        "calling value method requires explicit dereference");
8957               return Expression::make_error(location);
8958             }
8959           if (!m->is_value_method() && expr->type()->points_to() == NULL)
8960             expr = Expression::make_unary(OPERATOR_AND, expr, location);
8961           ret = m->bind_method(expr, location);
8962         }
8963       go_assert(ret != NULL);
8964       return ret;
8965     }
8966   else
8967     {
8968       if (!ambig1.empty())
8969         error_at(location, "%qs is ambiguous via %qs and %qs",
8970                  Gogo::message_name(name).c_str(), ambig1.c_str(),
8971                  ambig2.c_str());
8972       else if (found_pointer_method)
8973         error_at(location, "method requires a pointer");
8974       else if (nt == NULL && st == NULL && it == NULL)
8975         error_at(location,
8976                  ("reference to field %qs in object which "
8977                   "has no fields or methods"),
8978                  Gogo::message_name(name).c_str());
8979       else
8980         {
8981           bool is_unexported;
8982           if (!Gogo::is_hidden_name(name))
8983             is_unexported = false;
8984           else
8985             {
8986               std::string unpacked = Gogo::unpack_hidden_name(name);
8987               seen.clear();
8988               is_unexported = Type::is_unexported_field_or_method(gogo, type,
8989                                                                   unpacked,
8990                                                                   &seen);
8991             }
8992           if (is_unexported)
8993             error_at(location, "reference to unexported field or method %qs",
8994                      Gogo::message_name(name).c_str());
8995           else
8996             error_at(location, "reference to undefined field or method %qs",
8997                      Gogo::message_name(name).c_str());
8998         }
8999       return Expression::make_error(location);
9000     }
9001 }
9002
9003 // Look in TYPE for a field or method named NAME, return true if one
9004 // is found.  This looks through embedded anonymous fields and handles
9005 // ambiguity.  If a method is found, sets *IS_METHOD to true;
9006 // otherwise, if a field is found, set it to false.  If
9007 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
9008 // whose address can not be taken.  SEEN is used to avoid infinite
9009 // recursion on invalid types.
9010
9011 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
9012 // method we couldn't use because it requires a pointer.  LEVEL is
9013 // used for recursive calls, and can be NULL for a non-recursive call.
9014 // When this function returns false because it finds that the name is
9015 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
9016 // and *AMBIG2.  If the name is not found at all, *AMBIG1 and *AMBIG2
9017 // will be unchanged.
9018
9019 // This function just returns whether or not there is a field or
9020 // method, and whether it is a field or method.  It doesn't build an
9021 // expression to refer to it.  If it is a method, we then look in the
9022 // list of all methods for the type.  If it is a field, the search has
9023 // to be done again, looking only for fields, and building up the
9024 // expression as we go.
9025
9026 bool
9027 Type::find_field_or_method(const Type* type,
9028                            const std::string& name,
9029                            bool receiver_can_be_pointer,
9030                            std::vector<const Named_type*>* seen,
9031                            int* level,
9032                            bool* is_method,
9033                            bool* found_pointer_method,
9034                            std::string* ambig1,
9035                            std::string* ambig2)
9036 {
9037   // Named types can have locally defined methods.
9038   const Named_type* nt = type->named_type();
9039   if (nt == NULL && type->points_to() != NULL)
9040     nt = type->points_to()->named_type();
9041   if (nt != NULL)
9042     {
9043       Named_object* no = nt->find_local_method(name);
9044       if (no != NULL)
9045         {
9046           if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
9047             {
9048               *is_method = true;
9049               return true;
9050             }
9051
9052           // Record that we have found a pointer method in order to
9053           // give a better error message if we don't find anything
9054           // else.
9055           *found_pointer_method = true;
9056         }
9057
9058       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9059            p != seen->end();
9060            ++p)
9061         {
9062           if (*p == nt)
9063             {
9064               // We've already seen this type when searching for methods.
9065               return false;
9066             }
9067         }
9068     }
9069
9070   // Interface types can have methods.
9071   const Interface_type* it = type->interface_type();
9072   if (it != NULL && it->find_method(name) != NULL)
9073     {
9074       *is_method = true;
9075       return true;
9076     }
9077
9078   // Struct types can have fields.  They can also inherit fields and
9079   // methods from anonymous fields.
9080   const Struct_type* st = type->deref()->struct_type();
9081   if (st == NULL)
9082     return false;
9083   const Struct_field_list* fields = st->fields();
9084   if (fields == NULL)
9085     return false;
9086
9087   if (nt != NULL)
9088     seen->push_back(nt);
9089
9090   int found_level = 0;
9091   bool found_is_method = false;
9092   std::string found_ambig1;
9093   std::string found_ambig2;
9094   const Struct_field* found_parent = NULL;
9095   for (Struct_field_list::const_iterator pf = fields->begin();
9096        pf != fields->end();
9097        ++pf)
9098     {
9099       if (pf->is_field_name(name))
9100         {
9101           *is_method = false;
9102           if (nt != NULL)
9103             seen->pop_back();
9104           return true;
9105         }
9106
9107       if (!pf->is_anonymous())
9108         continue;
9109
9110       if (pf->type()->deref()->is_error_type()
9111           || pf->type()->deref()->is_undefined())
9112         continue;
9113
9114       Named_type* fnt = pf->type()->named_type();
9115       if (fnt == NULL)
9116         fnt = pf->type()->deref()->named_type();
9117       go_assert(fnt != NULL);
9118
9119       int sublevel = level == NULL ? 1 : *level + 1;
9120       bool sub_is_method;
9121       std::string subambig1;
9122       std::string subambig2;
9123       bool subfound = Type::find_field_or_method(fnt,
9124                                                  name,
9125                                                  receiver_can_be_pointer,
9126                                                  seen,
9127                                                  &sublevel,
9128                                                  &sub_is_method,
9129                                                  found_pointer_method,
9130                                                  &subambig1,
9131                                                  &subambig2);
9132       if (!subfound)
9133         {
9134           if (!subambig1.empty())
9135             {
9136               // The name was found via this field, but is ambiguous.
9137               // if the ambiguity is lower or at the same level as
9138               // anything else we have already found, then we want to
9139               // pass the ambiguity back to the caller.
9140               if (found_level == 0 || sublevel <= found_level)
9141                 {
9142                   found_ambig1 = (Gogo::message_name(pf->field_name())
9143                                   + '.' + subambig1);
9144                   found_ambig2 = (Gogo::message_name(pf->field_name())
9145                                   + '.' + subambig2);
9146                   found_level = sublevel;
9147                 }
9148             }
9149         }
9150       else
9151         {
9152           // The name was found via this field.  Use the level to see
9153           // if we want to use this one, or whether it introduces an
9154           // ambiguity.
9155           if (found_level == 0 || sublevel < found_level)
9156             {
9157               found_level = sublevel;
9158               found_is_method = sub_is_method;
9159               found_ambig1.clear();
9160               found_ambig2.clear();
9161               found_parent = &*pf;
9162             }
9163           else if (sublevel > found_level)
9164             ;
9165           else if (found_ambig1.empty())
9166             {
9167               // We found an ambiguity.
9168               go_assert(found_parent != NULL);
9169               found_ambig1 = Gogo::message_name(found_parent->field_name());
9170               found_ambig2 = Gogo::message_name(pf->field_name());
9171             }
9172           else
9173             {
9174               // We found an ambiguity, but we already know of one.
9175               // Just report the earlier one.
9176             }
9177         }
9178     }
9179
9180   // Here if we didn't find anything FOUND_LEVEL is 0.  If we found
9181   // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
9182   // FOUND_AMBIG2 are not empty.  If we found the field, FOUND_LEVEL
9183   // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
9184
9185   if (nt != NULL)
9186     seen->pop_back();
9187
9188   if (found_level == 0)
9189     return false;
9190   else if (!found_ambig1.empty())
9191     {
9192       go_assert(!found_ambig1.empty());
9193       ambig1->assign(found_ambig1);
9194       ambig2->assign(found_ambig2);
9195       if (level != NULL)
9196         *level = found_level;
9197       return false;
9198     }
9199   else
9200     {
9201       if (level != NULL)
9202         *level = found_level;
9203       *is_method = found_is_method;
9204       return true;
9205     }
9206 }
9207
9208 // Return whether NAME is an unexported field or method for TYPE.
9209
9210 bool
9211 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
9212                                     const std::string& name,
9213                                     std::vector<const Named_type*>* seen)
9214 {
9215   const Named_type* nt = type->named_type();
9216   if (nt == NULL)
9217     nt = type->deref()->named_type();
9218   if (nt != NULL)
9219     {
9220       if (nt->is_unexported_local_method(gogo, name))
9221         return true;
9222
9223       for (std::vector<const Named_type*>::const_iterator p = seen->begin();
9224            p != seen->end();
9225            ++p)
9226         {
9227           if (*p == nt)
9228             {
9229               // We've already seen this type.
9230               return false;
9231             }
9232         }
9233     }
9234
9235   const Interface_type* it = type->interface_type();
9236   if (it != NULL && it->is_unexported_method(gogo, name))
9237     return true;
9238
9239   type = type->deref();
9240
9241   const Struct_type* st = type->struct_type();
9242   if (st != NULL && st->is_unexported_local_field(gogo, name))
9243     return true;
9244
9245   if (st == NULL)
9246     return false;
9247
9248   const Struct_field_list* fields = st->fields();
9249   if (fields == NULL)
9250     return false;
9251
9252   if (nt != NULL)
9253     seen->push_back(nt);
9254
9255   for (Struct_field_list::const_iterator pf = fields->begin();
9256        pf != fields->end();
9257        ++pf)
9258     {
9259       if (pf->is_anonymous()
9260           && !pf->type()->deref()->is_error_type()
9261           && !pf->type()->deref()->is_undefined())
9262         {
9263           Named_type* subtype = pf->type()->named_type();
9264           if (subtype == NULL)
9265             subtype = pf->type()->deref()->named_type();
9266           if (subtype == NULL)
9267             {
9268               // This is an error, but it will be diagnosed elsewhere.
9269               continue;
9270             }
9271           if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
9272             {
9273               if (nt != NULL)
9274                 seen->pop_back();
9275               return true;
9276             }
9277         }
9278     }
9279
9280   if (nt != NULL)
9281     seen->pop_back();
9282
9283   return false;
9284 }
9285
9286 // Class Forward_declaration.
9287
9288 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
9289   : Type(TYPE_FORWARD),
9290     named_object_(named_object->resolve()), warned_(false)
9291 {
9292   go_assert(this->named_object_->is_unknown()
9293              || this->named_object_->is_type_declaration());
9294 }
9295
9296 // Return the named object.
9297
9298 Named_object*
9299 Forward_declaration_type::named_object()
9300 {
9301   return this->named_object_->resolve();
9302 }
9303
9304 const Named_object*
9305 Forward_declaration_type::named_object() const
9306 {
9307   return this->named_object_->resolve();
9308 }
9309
9310 // Return the name of the forward declared type.
9311
9312 const std::string&
9313 Forward_declaration_type::name() const
9314 {
9315   return this->named_object()->name();
9316 }
9317
9318 // Warn about a use of a type which has been declared but not defined.
9319
9320 void
9321 Forward_declaration_type::warn() const
9322 {
9323   Named_object* no = this->named_object_->resolve();
9324   if (no->is_unknown())
9325     {
9326       // The name was not defined anywhere.
9327       if (!this->warned_)
9328         {
9329           error_at(this->named_object_->location(),
9330                    "use of undefined type %qs",
9331                    no->message_name().c_str());
9332           this->warned_ = true;
9333         }
9334     }
9335   else if (no->is_type_declaration())
9336     {
9337       // The name was seen as a type, but the type was never defined.
9338       if (no->type_declaration_value()->using_type())
9339         {
9340           error_at(this->named_object_->location(),
9341                    "use of undefined type %qs",
9342                    no->message_name().c_str());
9343           this->warned_ = true;
9344         }
9345     }
9346   else
9347     {
9348       // The name was defined, but not as a type.
9349       if (!this->warned_)
9350         {
9351           error_at(this->named_object_->location(), "expected type");
9352           this->warned_ = true;
9353         }
9354     }
9355 }
9356
9357 // Get the base type of a declaration.  This gives an error if the
9358 // type has not yet been defined.
9359
9360 Type*
9361 Forward_declaration_type::real_type()
9362 {
9363   if (this->is_defined())
9364     return this->named_object()->type_value();
9365   else
9366     {
9367       this->warn();
9368       return Type::make_error_type();
9369     }
9370 }
9371
9372 const Type*
9373 Forward_declaration_type::real_type() const
9374 {
9375   if (this->is_defined())
9376     return this->named_object()->type_value();
9377   else
9378     {
9379       this->warn();
9380       return Type::make_error_type();
9381     }
9382 }
9383
9384 // Return whether the base type is defined.
9385
9386 bool
9387 Forward_declaration_type::is_defined() const
9388 {
9389   return this->named_object()->is_type();
9390 }
9391
9392 // Add a method.  This is used when methods are defined before the
9393 // type.
9394
9395 Named_object*
9396 Forward_declaration_type::add_method(const std::string& name,
9397                                      Function* function)
9398 {
9399   Named_object* no = this->named_object();
9400   if (no->is_unknown())
9401     no->declare_as_type();
9402   return no->type_declaration_value()->add_method(name, function);
9403 }
9404
9405 // Add a method declaration.  This is used when methods are declared
9406 // before the type.
9407
9408 Named_object*
9409 Forward_declaration_type::add_method_declaration(const std::string& name,
9410                                                  Package* package,
9411                                                  Function_type* type,
9412                                                  Location location)
9413 {
9414   Named_object* no = this->named_object();
9415   if (no->is_unknown())
9416     no->declare_as_type();
9417   Type_declaration* td = no->type_declaration_value();
9418   return td->add_method_declaration(name, package, type, location);
9419 }
9420
9421 // Traversal.
9422
9423 int
9424 Forward_declaration_type::do_traverse(Traverse* traverse)
9425 {
9426   if (this->is_defined()
9427       && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
9428     return TRAVERSE_EXIT;
9429   return TRAVERSE_CONTINUE;
9430 }
9431
9432 // Get the backend representation for the type.
9433
9434 Btype*
9435 Forward_declaration_type::do_get_backend(Gogo* gogo)
9436 {
9437   if (this->is_defined())
9438     return Type::get_named_base_btype(gogo, this->real_type());
9439
9440   if (this->warned_)
9441     return gogo->backend()->error_type();
9442
9443   // We represent an undefined type as a struct with no fields.  That
9444   // should work fine for the backend, since the same case can arise
9445   // in C.
9446   std::vector<Backend::Btyped_identifier> fields;
9447   Btype* bt = gogo->backend()->struct_type(fields);
9448   return gogo->backend()->named_type(this->name(), bt,
9449                                      this->named_object()->location());
9450 }
9451
9452 // Build a type descriptor for a forwarded type.
9453
9454 Expression*
9455 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9456 {
9457   Location ploc = Linemap::predeclared_location();
9458   if (!this->is_defined())
9459     return Expression::make_error(ploc);
9460   else
9461     {
9462       Type* t = this->real_type();
9463       if (name != NULL)
9464         return this->named_type_descriptor(gogo, t, name);
9465       else
9466         return Expression::make_type_descriptor(t, ploc);
9467     }
9468 }
9469
9470 // The reflection string.
9471
9472 void
9473 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
9474 {
9475   this->append_reflection(this->real_type(), gogo, ret);
9476 }
9477
9478 // The mangled name.
9479
9480 void
9481 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9482 {
9483   if (this->is_defined())
9484     this->append_mangled_name(this->real_type(), gogo, ret);
9485   else
9486     {
9487       const Named_object* no = this->named_object();
9488       std::string name;
9489       if (no->package() == NULL)
9490         name = gogo->package_name();
9491       else
9492         name = no->package()->name();
9493       name += '.';
9494       name += Gogo::unpack_hidden_name(no->name());
9495       char buf[20];
9496       snprintf(buf, sizeof buf, "N%u_",
9497                static_cast<unsigned int>(name.length()));
9498       ret->append(buf);
9499       ret->append(name);
9500     }
9501 }
9502
9503 // Export a forward declaration.  This can happen when a defined type
9504 // refers to a type which is only declared (and is presumably defined
9505 // in some other file in the same package).
9506
9507 void
9508 Forward_declaration_type::do_export(Export*) const
9509 {
9510   // If there is a base type, that should be exported instead of this.
9511   go_assert(!this->is_defined());
9512
9513   // We don't output anything.
9514 }
9515
9516 // Make a forward declaration.
9517
9518 Type*
9519 Type::make_forward_declaration(Named_object* named_object)
9520 {
9521   return new Forward_declaration_type(named_object);
9522 }
9523
9524 // Class Typed_identifier_list.
9525
9526 // Sort the entries by name.
9527
9528 struct Typed_identifier_list_sort
9529 {
9530  public:
9531   bool
9532   operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
9533   { return t1.name() < t2.name(); }
9534 };
9535
9536 void
9537 Typed_identifier_list::sort_by_name()
9538 {
9539   std::sort(this->entries_.begin(), this->entries_.end(),
9540             Typed_identifier_list_sort());
9541 }
9542
9543 // Traverse types.
9544
9545 int
9546 Typed_identifier_list::traverse(Traverse* traverse)
9547 {
9548   for (Typed_identifier_list::const_iterator p = this->begin();
9549        p != this->end();
9550        ++p)
9551     {
9552       if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
9553         return TRAVERSE_EXIT;
9554     }
9555   return TRAVERSE_CONTINUE;
9556 }
9557
9558 // Copy the list.
9559
9560 Typed_identifier_list*
9561 Typed_identifier_list::copy() const
9562 {
9563   Typed_identifier_list* ret = new Typed_identifier_list();
9564   for (Typed_identifier_list::const_iterator p = this->begin();
9565        p != this->end();
9566        ++p)
9567     ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
9568   return ret;
9569 }