github.com/ronhuafeng/gofrontend@v0.0.0-20220715151246-ff23266b8bc5/go/types.cc (about)

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