OSDN Git Service

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