OSDN Git Service

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