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

     1  // expressions.cc -- Go frontend expression handling.
     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 <algorithm>
    10  
    11  #include "go-c.h"
    12  #include "gogo.h"
    13  #include "go-diagnostics.h"
    14  #include "go-encode-id.h"
    15  #include "types.h"
    16  #include "export.h"
    17  #include "import.h"
    18  #include "statements.h"
    19  #include "lex.h"
    20  #include "runtime.h"
    21  #include "backend.h"
    22  #include "expressions.h"
    23  #include "ast-dump.h"
    24  
    25  // Class Expression.
    26  
    27  Expression::Expression(Expression_classification classification,
    28  		       Location location)
    29    : classification_(classification), location_(location)
    30  {
    31  }
    32  
    33  Expression::~Expression()
    34  {
    35  }
    36  
    37  // Traverse the expressions.
    38  
    39  int
    40  Expression::traverse(Expression** pexpr, Traverse* traverse)
    41  {
    42    Expression* expr = *pexpr;
    43    if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
    44      {
    45        int t = traverse->expression(pexpr);
    46        if (t == TRAVERSE_EXIT)
    47  	return TRAVERSE_EXIT;
    48        else if (t == TRAVERSE_SKIP_COMPONENTS)
    49  	return TRAVERSE_CONTINUE;
    50      }
    51    return expr->do_traverse(traverse);
    52  }
    53  
    54  // Traverse subexpressions of this expression.
    55  
    56  int
    57  Expression::traverse_subexpressions(Traverse* traverse)
    58  {
    59    return this->do_traverse(traverse);
    60  }
    61  
    62  // A traversal used to set the location of subexpressions.
    63  
    64  class Set_location : public Traverse
    65  {
    66   public:
    67    Set_location(Location loc)
    68      : Traverse(traverse_expressions),
    69        loc_(loc)
    70    { }
    71  
    72    int
    73    expression(Expression** pexpr);
    74  
    75   private:
    76    Location loc_;
    77  };
    78  
    79  // Set the location of an expression.
    80  
    81  int
    82  Set_location::expression(Expression** pexpr)
    83  {
    84    // Some expressions are shared or don't have an independent
    85    // location, so we shouldn't change their location.  This is the set
    86    // of expressions for which do_copy is just "return this" or
    87    // otherwise does not pass down the location.
    88    switch ((*pexpr)->classification())
    89      {
    90      case Expression::EXPRESSION_ERROR:
    91      case Expression::EXPRESSION_VAR_REFERENCE:
    92      case Expression::EXPRESSION_ENCLOSED_VAR_REFERENCE:
    93      case Expression::EXPRESSION_STRING:
    94      case Expression::EXPRESSION_FUNC_DESCRIPTOR:
    95      case Expression::EXPRESSION_TYPE:
    96      case Expression::EXPRESSION_BOOLEAN:
    97      case Expression::EXPRESSION_CONST_REFERENCE:
    98      case Expression::EXPRESSION_NIL:
    99      case Expression::EXPRESSION_TYPE_DESCRIPTOR:
   100      case Expression::EXPRESSION_GC_SYMBOL:
   101      case Expression::EXPRESSION_PTRMASK_SYMBOL:
   102      case Expression::EXPRESSION_TYPE_INFO:
   103      case Expression::EXPRESSION_STRUCT_FIELD_OFFSET:
   104        return TRAVERSE_CONTINUE;
   105      default:
   106        break;
   107      }
   108  
   109    (*pexpr)->location_ = this->loc_;
   110    return TRAVERSE_CONTINUE;
   111  }
   112  
   113  // Set the location of an expression and its subexpressions.
   114  
   115  void
   116  Expression::set_location(Location loc)
   117  {
   118    this->location_ = loc;
   119    Set_location sl(loc);
   120    this->traverse_subexpressions(&sl);
   121  }
   122  
   123  // Default implementation for do_traverse for child classes.
   124  
   125  int
   126  Expression::do_traverse(Traverse*)
   127  {
   128    return TRAVERSE_CONTINUE;
   129  }
   130  
   131  // This virtual function is called by the parser if the value of this
   132  // expression is being discarded.  By default, we give an error.
   133  // Expressions with side effects override.
   134  
   135  bool
   136  Expression::do_discarding_value()
   137  {
   138    this->unused_value_error();
   139    return false;
   140  }
   141  
   142  // This virtual function is called to export expressions.  This will
   143  // only be used by expressions which may be constant.
   144  
   145  void
   146  Expression::do_export(Export_function_body*) const
   147  {
   148    go_unreachable();
   149  }
   150  
   151  // Write a name to the export data.
   152  
   153  void
   154  Expression::export_name(Export_function_body* efb, const Named_object* no)
   155  {
   156    if (no->package() != NULL)
   157      {
   158        char buf[50];
   159        snprintf(buf, sizeof buf, "<p%d>", efb->package_index(no->package()));
   160        efb->write_c_string(buf);
   161      }
   162  
   163    if (!Gogo::is_hidden_name(no->name()))
   164      efb->write_string(no->name());
   165    else
   166      {
   167        efb->write_c_string(".");
   168        efb->write_string(Gogo::unpack_hidden_name(no->name()));
   169      }
   170  }
   171  
   172  // Give an error saying that the value of the expression is not used.
   173  
   174  void
   175  Expression::unused_value_error()
   176  {
   177    if (this->type()->is_error())
   178      {
   179        go_assert(saw_errors());
   180        this->set_is_error();
   181      }
   182    else
   183      this->report_error(_("value computed is not used"));
   184  }
   185  
   186  // Note that this expression is an error.  This is called by children
   187  // when they discover an error.
   188  
   189  void
   190  Expression::set_is_error()
   191  {
   192    this->classification_ = EXPRESSION_ERROR;
   193  }
   194  
   195  // For children to call to report an error conveniently.
   196  
   197  void
   198  Expression::report_error(const char* msg)
   199  {
   200    go_error_at(this->location_, "%s", msg);
   201    this->set_is_error();
   202  }
   203  
   204  // Set types of variables and constants.  This is implemented by the
   205  // child class.
   206  
   207  void
   208  Expression::determine_type(const Type_context* context)
   209  {
   210    this->do_determine_type(context);
   211  }
   212  
   213  // Set types when there is no context.
   214  
   215  void
   216  Expression::determine_type_no_context()
   217  {
   218    Type_context context;
   219    this->do_determine_type(&context);
   220  }
   221  
   222  // Return true if two expressions refer to the same variable or struct
   223  // field.  This can only be true when there are no side effects.
   224  
   225  bool
   226  Expression::is_same_variable(Expression* a, Expression* b)
   227  {
   228    if (a->classification() != b->classification())
   229      return false;
   230  
   231    Var_expression* av = a->var_expression();
   232    if (av != NULL)
   233      return av->named_object() == b->var_expression()->named_object();
   234  
   235    Field_reference_expression* af = a->field_reference_expression();
   236    if (af != NULL)
   237      {
   238        Field_reference_expression* bf = b->field_reference_expression();
   239        return (af->field_index() == bf->field_index()
   240  	      && Expression::is_same_variable(af->expr(), bf->expr()));
   241      }
   242  
   243    Unary_expression* au = a->unary_expression();
   244    if (au != NULL)
   245      {
   246        Unary_expression* bu = b->unary_expression();
   247        return (au->op() == OPERATOR_MULT
   248  	      && bu->op() == OPERATOR_MULT
   249  	      && Expression::is_same_variable(au->operand(),
   250  					      bu->operand()));
   251      }
   252  
   253    Array_index_expression* aie = a->array_index_expression();
   254    if (aie != NULL)
   255      {
   256        Array_index_expression* bie = b->array_index_expression();
   257        return (aie->end() == NULL
   258  	      && bie->end() == NULL
   259  	      && Expression::is_same_variable(aie->array(), bie->array())
   260  	      && Expression::is_same_variable(aie->start(), bie->start()));
   261      }
   262  
   263    Numeric_constant aval;
   264    if (a->numeric_constant_value(&aval))
   265      {
   266        Numeric_constant bval;
   267        if (b->numeric_constant_value(&bval))
   268  	return aval.equals(bval);
   269      }
   270  
   271    return false;
   272  }
   273  
   274  // Return an expression handling any conversions which must be done during
   275  // assignment.
   276  
   277  Expression*
   278  Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
   279  				   Expression* rhs, Location location)
   280  {
   281    Type* rhs_type = rhs->type();
   282    if (lhs_type->is_error()
   283        || rhs_type->is_error()
   284        || rhs->is_error_expression())
   285      return Expression::make_error(location);
   286  
   287    bool are_identical = Type::are_identical(lhs_type, rhs_type,
   288  					   (Type::COMPARE_ERRORS
   289  					    | Type::COMPARE_TAGS),
   290  					   NULL);
   291    if (!are_identical && lhs_type->interface_type() != NULL)
   292      {
   293        // Type to interface conversions have been made explicit early.
   294        go_assert(rhs_type->interface_type() != NULL);
   295        return Expression::convert_interface_to_interface(lhs_type, rhs, false,
   296                                                          location);
   297      }
   298    else if (!are_identical && rhs_type->interface_type() != NULL)
   299      return Expression::convert_interface_to_type(gogo, lhs_type, rhs, location);
   300    else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
   301      {
   302        // Assigning nil to a slice.
   303        Expression* nil = Expression::make_nil(location);
   304        Expression* zero = Expression::make_integer_ul(0, NULL, location);
   305        return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
   306      }
   307    else if (rhs_type->is_nil_type())
   308      return Expression::make_nil(location);
   309    else if (are_identical)
   310      {
   311        if (lhs_type->forwarded() != rhs_type->forwarded())
   312  	{
   313  	  // Different but identical types require an explicit
   314  	  // conversion.  This happens with type aliases.
   315  	  return Expression::make_cast(lhs_type, rhs, location);
   316  	}
   317  
   318        // No conversion is needed.
   319        return rhs;
   320      }
   321    else if (lhs_type->points_to() != NULL)
   322      return Expression::make_unsafe_cast(lhs_type, rhs, location);
   323    else if (lhs_type->is_numeric_type())
   324      return Expression::make_cast(lhs_type, rhs, location);
   325    else if ((lhs_type->struct_type() != NULL
   326              && rhs_type->struct_type() != NULL)
   327             || (lhs_type->array_type() != NULL
   328                 && rhs_type->array_type() != NULL))
   329      {
   330        // This conversion must be permitted by Go, or we wouldn't have
   331        // gotten here.
   332        return Expression::make_unsafe_cast(lhs_type, rhs, location);
   333      }
   334    else
   335      return rhs;
   336  }
   337  
   338  // Return an expression for a conversion from a non-interface type to an
   339  // interface type.  If ON_STACK is true, it can allocate the storage on
   340  // stack.
   341  
   342  Expression*
   343  Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
   344                                        bool on_stack, Location location)
   345  {
   346    Interface_type* lhs_interface_type = lhs_type->interface_type();
   347    bool lhs_is_empty = lhs_interface_type->is_empty();
   348  
   349    // Since RHS_TYPE is a static type, we can create the interface
   350    // method table at compile time.
   351  
   352    // When setting an interface to nil, we just set both fields to
   353    // NULL.
   354    Type* rhs_type = rhs->type();
   355    if (rhs_type->is_nil_type())
   356      {
   357        Expression* nil = Expression::make_nil(location);
   358        return Expression::make_interface_value(lhs_type, nil, nil, location);
   359      }
   360  
   361    // This should have been checked already.
   362    if (!lhs_interface_type->implements_interface(rhs_type, NULL))
   363      {
   364        go_assert(saw_errors());
   365        return Expression::make_error(location);
   366      }
   367  
   368    // An interface is a tuple.  If LHS_TYPE is an empty interface type,
   369    // then the first field is the type descriptor for RHS_TYPE.
   370    // Otherwise it is the interface method table for RHS_TYPE.
   371    Expression* first_field;
   372    if (lhs_is_empty)
   373      first_field = Expression::make_type_descriptor(rhs_type, location);
   374    else
   375      {
   376        // Build the interface method table for this interface and this
   377        // object type: a list of function pointers for each interface
   378        // method.
   379        Named_type* rhs_named_type = rhs_type->named_type();
   380        Struct_type* rhs_struct_type = rhs_type->struct_type();
   381        bool is_pointer = false;
   382        if (rhs_named_type == NULL && rhs_struct_type == NULL)
   383  	{
   384  	  rhs_named_type = rhs_type->deref()->named_type();
   385  	  rhs_struct_type = rhs_type->deref()->struct_type();
   386  	  is_pointer = true;
   387  	}
   388        if (rhs_named_type != NULL)
   389  	first_field =
   390  	  rhs_named_type->interface_method_table(lhs_interface_type,
   391                                                   is_pointer);
   392        else if (rhs_struct_type != NULL)
   393  	first_field =
   394  	  rhs_struct_type->interface_method_table(lhs_interface_type,
   395                                                    is_pointer);
   396        else
   397  	first_field = Expression::make_nil(location);
   398      }
   399  
   400    Expression* obj;
   401    if (rhs_type->is_direct_iface_type())
   402      {
   403        // We are assigning a pointer to the interface; the interface
   404        // holds the pointer itself.
   405        obj = unpack_direct_iface(rhs, location);
   406      }
   407    else
   408      {
   409        // We are assigning a non-pointer value to the interface; the
   410        // interface gets a copy of the value in the heap if it escapes.
   411  
   412        // An exception is &global if global is notinheap, which is a
   413        // pointer value but not a direct-iface type and we can't simply
   414        // take its address.
   415        bool is_address = (rhs->unary_expression() != NULL
   416                           && rhs->unary_expression()->op() == OPERATOR_AND);
   417  
   418        if (rhs->is_constant() && !is_address)
   419          obj = Expression::make_unary(OPERATOR_AND, rhs, location);
   420        else
   421          {
   422            obj = Expression::make_heap_expression(rhs, location);
   423            if (on_stack)
   424              obj->heap_expression()->set_allocate_on_stack();
   425          }
   426      }
   427  
   428    return Expression::make_interface_value(lhs_type, first_field, obj, location);
   429  }
   430  
   431  // Return an expression for the pointer-typed value of a direct interface
   432  // type.  Specifically, for single field struct or array, get the single
   433  // field, and do this recursively.  The reason for this is that we don't
   434  // want to assign a struct or an array to a pointer-typed field.  The
   435  // backend may not like that.
   436  
   437  Expression*
   438  Expression::unpack_direct_iface(Expression* rhs, Location loc)
   439  {
   440    Struct_type* st = rhs->type()->struct_type();
   441    if (st != NULL)
   442      {
   443        go_assert(st->field_count() == 1);
   444        Expression* field = Expression::make_field_reference(rhs, 0, loc);
   445        return unpack_direct_iface(field, loc);
   446      }
   447    Array_type* at = rhs->type()->array_type();
   448    if (at != NULL)
   449      {
   450        int64_t len;
   451        bool ok = at->int_length(&len);
   452        go_assert(ok && len == 1);
   453        Type* int_type = Type::lookup_integer_type("int");
   454        Expression* index = Expression::make_integer_ul(0, int_type, loc);
   455        Expression* elem = Expression::make_array_index(rhs, index, NULL, NULL, loc);
   456        return unpack_direct_iface(elem, loc);
   457      }
   458    return rhs;
   459  }
   460  
   461  // The opposite of unpack_direct_iface.
   462  
   463  Expression*
   464  Expression::pack_direct_iface(Type* t, Expression* rhs, Location loc)
   465  {
   466    if (rhs->type() == t)
   467      return rhs;
   468    Struct_type* st = t->struct_type();
   469    if (st != NULL)
   470      {
   471        Expression_list* vals = new Expression_list();
   472        vals->push_back(pack_direct_iface(st->field(0)->type(), rhs, loc));
   473        return Expression::make_struct_composite_literal(t, vals, loc);
   474      }
   475    Array_type* at = t->array_type();
   476    if (at != NULL)
   477      {
   478        Expression_list* vals = new Expression_list();
   479        vals->push_back(pack_direct_iface(at->element_type(), rhs, loc));
   480        return Expression::make_array_composite_literal(t, vals, loc);
   481      }
   482    return Expression::make_unsafe_cast(t, rhs, loc);
   483  }
   484  
   485  // Return an expression for the type descriptor of RHS.
   486  
   487  Expression*
   488  Expression::get_interface_type_descriptor(Expression* rhs)
   489  {
   490    go_assert(rhs->type()->interface_type() != NULL);
   491    Location location = rhs->location();
   492  
   493    // The type descriptor is the first field of an empty interface.
   494    if (rhs->type()->interface_type()->is_empty())
   495      return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
   496                                             location);
   497  
   498    Expression* mtable =
   499        Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
   500  
   501    Expression* descriptor =
   502        Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
   503    descriptor = Expression::make_field_reference(descriptor, 0, location);
   504    Expression* nil = Expression::make_nil(location);
   505  
   506    Expression* eq =
   507        Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
   508    return Expression::make_conditional(eq, nil, descriptor, location);
   509  }
   510  
   511  // Return an expression for the conversion of an interface type to an
   512  // interface type.
   513  
   514  Expression*
   515  Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
   516                                             bool for_type_guard,
   517                                             Location location)
   518  {
   519    if (Type::are_identical(lhs_type, rhs->type(),
   520  			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
   521  			  NULL))
   522      return rhs;
   523  
   524    Interface_type* lhs_interface_type = lhs_type->interface_type();
   525    bool lhs_is_empty = lhs_interface_type->is_empty();
   526  
   527    // In the general case this requires runtime examination of the type
   528    // method table to match it up with the interface methods.
   529  
   530    // FIXME: If all of the methods in the right hand side interface
   531    // also appear in the left hand side interface, then we don't need
   532    // to do a runtime check, although we still need to build a new
   533    // method table.
   534  
   535    // We are going to evaluate RHS multiple times.
   536    go_assert(rhs->is_multi_eval_safe());
   537  
   538    // Get the type descriptor for the right hand side.  This will be
   539    // NULL for a nil interface.
   540    Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
   541    Expression* lhs_type_expr =
   542        Expression::make_type_descriptor(lhs_type, location);
   543  
   544    Expression* first_field;
   545    if (for_type_guard)
   546      {
   547        // A type assertion fails when converting a nil interface.
   548        first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
   549  				       lhs_type_expr, rhs_type_expr);
   550      }
   551    else if (lhs_is_empty)
   552      {
   553        // A conversion to an empty interface always succeeds, and the
   554        // first field is just the type descriptor of the object.
   555        first_field = rhs_type_expr;
   556      }
   557    else
   558      {
   559        // A conversion to a non-empty interface may fail, but unlike a
   560        // type assertion converting nil will always succeed.
   561        first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
   562  				       lhs_type_expr, rhs_type_expr);
   563      }
   564  
   565    // The second field is simply the object pointer.
   566    Expression* obj =
   567        Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
   568    return Expression::make_interface_value(lhs_type, first_field, obj, location);
   569  }
   570  
   571  // Return an expression for the conversion of an interface type to a
   572  // non-interface type.
   573  
   574  Expression*
   575  Expression::convert_interface_to_type(Gogo* gogo, Type *lhs_type, Expression* rhs,
   576                                        Location location)
   577  {
   578    // We are going to evaluate RHS multiple times.
   579    go_assert(rhs->is_multi_eval_safe());
   580  
   581    // Build an expression to check that the type is valid.  It will
   582    // panic with an appropriate runtime type error if the type is not
   583    // valid.
   584    // (lhs_type == rhs_type ? nil /*dummy*/ :
   585    //    panicdottype(lhs_type, rhs_type, inter_type))
   586    // For some Oses, we need to call runtime.eqtype instead of
   587    // lhs_type == rhs_type, as we may have unmerged type descriptors
   588    // from shared libraries.
   589    Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
   590                                                                  location);
   591    Expression* rhs_descriptor =
   592        Expression::get_interface_type_descriptor(rhs);
   593  
   594    Type* rhs_type = rhs->type();
   595    Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
   596                                                                  location);
   597  
   598    Expression* cond;
   599    if (gogo->need_eqtype()) {
   600      cond = Runtime::make_call(Runtime::EQTYPE, location,
   601                                2, lhs_type_expr,
   602                                rhs_descriptor);
   603    } else {
   604      cond = Expression::make_binary(OPERATOR_EQEQ, lhs_type_expr,
   605                                     rhs_descriptor, location);
   606    }
   607  
   608    rhs_descriptor = Expression::get_interface_type_descriptor(rhs);
   609    Expression* panic = Runtime::make_call(Runtime::PANICDOTTYPE, location,
   610                                           3, lhs_type_expr->copy(),
   611                                           rhs_descriptor,
   612                                           rhs_inter_expr);
   613    Expression* nil = Expression::make_nil(location);
   614    Expression* check = Expression::make_conditional(cond, nil, panic,
   615                                                     location);
   616  
   617    // If the conversion succeeds, pull out the value.
   618    Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
   619                                                      location);
   620  
   621    // If the value is a direct interface, then it is the value we want.
   622    // Otherwise it points to the value.
   623    if (lhs_type->is_direct_iface_type())
   624      obj = Expression::pack_direct_iface(lhs_type, obj, location);
   625    else
   626      {
   627        obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
   628                                           location);
   629        obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
   630                                           location);
   631      }
   632    return Expression::make_compound(check, obj, location);
   633  }
   634  
   635  // Convert an expression to its backend representation.  This is implemented by
   636  // the child class.  Not that it is not in general safe to call this multiple
   637  // times for a single expression, but that we don't catch such errors.
   638  
   639  Bexpression*
   640  Expression::get_backend(Translate_context* context)
   641  {
   642    // The child may have marked this expression as having an error.
   643    if (this->classification_ == EXPRESSION_ERROR)
   644      {
   645        go_assert(saw_errors());
   646        return context->backend()->error_expression();
   647      }
   648  
   649    return this->do_get_backend(context);
   650  }
   651  
   652  // Return a backend expression for VAL.
   653  Bexpression*
   654  Expression::backend_numeric_constant_expression(Translate_context* context,
   655                                                  Numeric_constant* val)
   656  {
   657    Gogo* gogo = context->gogo();
   658    Type* type = val->type();
   659    if (type == NULL)
   660      return gogo->backend()->error_expression();
   661  
   662    Btype* btype = type->get_backend(gogo);
   663    Bexpression* ret;
   664    if (type->integer_type() != NULL)
   665      {
   666        mpz_t ival;
   667        if (!val->to_int(&ival))
   668          {
   669            go_assert(saw_errors());
   670            return gogo->backend()->error_expression();
   671          }
   672        ret = gogo->backend()->integer_constant_expression(btype, ival);
   673        mpz_clear(ival);
   674      }
   675    else if (type->float_type() != NULL)
   676      {
   677        mpfr_t fval;
   678        if (!val->to_float(&fval))
   679          {
   680            go_assert(saw_errors());
   681            return gogo->backend()->error_expression();
   682          }
   683        ret = gogo->backend()->float_constant_expression(btype, fval);
   684        mpfr_clear(fval);
   685      }
   686    else if (type->complex_type() != NULL)
   687      {
   688        mpc_t cval;
   689        if (!val->to_complex(&cval))
   690          {
   691            go_assert(saw_errors());
   692            return gogo->backend()->error_expression();
   693          }
   694        ret = gogo->backend()->complex_constant_expression(btype, cval);
   695        mpc_clear(cval);
   696      }
   697    else
   698      go_unreachable();
   699  
   700    return ret;
   701  }
   702  
   703  // Insert bounds checks for an index expression.  Check that that VAL
   704  // >= 0 and that it fits in an int.  Then check that VAL OP BOUND is
   705  // true.  If any condition is false, call one of the CODE runtime
   706  // functions, which will panic.
   707  
   708  void
   709  Expression::check_bounds(Expression* val, Operator op, Expression* bound,
   710  			 Runtime::Function code,
   711  			 Runtime::Function code_u,
   712  			 Runtime::Function code_extend,
   713  			 Runtime::Function code_extend_u,
   714  			 Statement_inserter* inserter,
   715  			 Location loc)
   716  {
   717    go_assert(val->is_multi_eval_safe());
   718    go_assert(bound->is_multi_eval_safe());
   719  
   720    Type* int_type = Type::lookup_integer_type("int");
   721    int int_type_size = int_type->integer_type()->bits();
   722  
   723    Type* val_type = val->type();
   724    if (val_type->integer_type() == NULL)
   725      {
   726        go_assert(saw_errors());
   727        return;
   728      }
   729    int val_type_size = val_type->integer_type()->bits();
   730    bool val_is_unsigned = val_type->integer_type()->is_unsigned();
   731  
   732    // Check that VAL >= 0.
   733    Expression* check = NULL;
   734    if (!val_is_unsigned)
   735      {
   736        Expression* zero = Expression::make_integer_ul(0, val_type, loc);
   737        check = Expression::make_binary(OPERATOR_GE, val->copy(), zero, loc);
   738      }
   739  
   740    // If VAL's type is larger than int, check that VAL fits in an int.
   741    if (val_type_size > int_type_size
   742        || (val_type_size == int_type_size
   743  	  && val_is_unsigned))
   744      {
   745        mpz_t one;
   746        mpz_init_set_ui(one, 1UL);
   747  
   748        // maxval = 2^(int_type_size - 1) - 1
   749        mpz_t maxval;
   750        mpz_init(maxval);
   751        mpz_mul_2exp(maxval, one, int_type_size - 1);
   752        mpz_sub_ui(maxval, maxval, 1);
   753        Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
   754        mpz_clear(one);
   755        mpz_clear(maxval);
   756  
   757        Expression* cmp = Expression::make_binary(OPERATOR_LE, val->copy(),
   758  						max, loc);
   759        if (check == NULL)
   760  	check = cmp;
   761        else
   762  	check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
   763      }
   764  
   765    // For the final check we can assume that VAL fits in an int.
   766    Expression* ival;
   767    if (val_type == int_type)
   768      ival = val->copy();
   769    else
   770      ival = Expression::make_cast(int_type, val->copy(), loc);
   771  
   772    // BOUND is assumed to fit in an int.  Either it comes from len or
   773    // cap, or it was checked by an earlier call.
   774    Expression* ibound;
   775    if (bound->type() == int_type)
   776      ibound = bound->copy();
   777    else
   778      ibound = Expression::make_cast(int_type, bound->copy(), loc);
   779  
   780    Expression* cmp = Expression::make_binary(op, ival, ibound, loc);
   781    if (check == NULL)
   782      check = cmp;
   783    else
   784      check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
   785  
   786    Runtime::Function c;
   787    if (val_type_size > int_type_size)
   788      {
   789        if (val_is_unsigned)
   790  	c = code_extend_u;
   791        else
   792  	c = code_extend;
   793      }
   794    else
   795      {
   796        if (val_is_unsigned)
   797  	c = code_u;
   798        else
   799  	c = code;
   800      }
   801  
   802    Expression* ignore = Expression::make_boolean(true, loc);
   803    Expression* crash = Runtime::make_call(c, loc, 2,
   804  					 val->copy(), bound->copy());
   805    Expression* cond = Expression::make_conditional(check, ignore, crash, loc);
   806    inserter->insert(Statement::make_statement(cond, true));
   807  }
   808  
   809  void
   810  Expression::dump_expression(Ast_dump_context* ast_dump_context) const
   811  {
   812    this->do_dump_expression(ast_dump_context);
   813  }
   814  
   815  // Error expressions.  This are used to avoid cascading errors.
   816  
   817  class Error_expression : public Expression
   818  {
   819   public:
   820    Error_expression(Location location)
   821      : Expression(EXPRESSION_ERROR, location)
   822    { }
   823  
   824   protected:
   825    bool
   826    do_is_constant() const
   827    { return true; }
   828  
   829    bool
   830    do_numeric_constant_value(Numeric_constant* nc) const
   831    {
   832      nc->set_unsigned_long(NULL, 0);
   833      return true;
   834    }
   835  
   836    bool
   837    do_discarding_value()
   838    { return true; }
   839  
   840    Type*
   841    do_type()
   842    { return Type::make_error_type(); }
   843  
   844    void
   845    do_determine_type(const Type_context*)
   846    { }
   847  
   848    Expression*
   849    do_copy()
   850    { return this; }
   851  
   852    bool
   853    do_is_addressable() const
   854    { return true; }
   855  
   856    Bexpression*
   857    do_get_backend(Translate_context* context)
   858    { return context->backend()->error_expression(); }
   859  
   860    void
   861    do_dump_expression(Ast_dump_context*) const;
   862  };
   863  
   864  // Dump the ast representation for an error expression to a dump context.
   865  
   866  void
   867  Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
   868  {
   869    ast_dump_context->ostream() << "_Error_" ;
   870  }
   871  
   872  Expression*
   873  Expression::make_error(Location location)
   874  {
   875    return new Error_expression(location);
   876  }
   877  
   878  // An expression which is really a type.  This is used during parsing.
   879  // It is an error if these survive after lowering.
   880  
   881  class
   882  Type_expression : public Expression
   883  {
   884   public:
   885    Type_expression(Type* type, Location location)
   886      : Expression(EXPRESSION_TYPE, location),
   887        type_(type)
   888    { }
   889  
   890   protected:
   891    int
   892    do_traverse(Traverse* traverse)
   893    { return Type::traverse(this->type_, traverse); }
   894  
   895    Type*
   896    do_type()
   897    { return this->type_; }
   898  
   899    void
   900    do_determine_type(const Type_context*)
   901    { }
   902  
   903    void
   904    do_check_types(Gogo*);
   905  
   906    Expression*
   907    do_copy()
   908    { return this; }
   909  
   910    Bexpression*
   911    do_get_backend(Translate_context*)
   912    { go_unreachable(); }
   913  
   914    void do_dump_expression(Ast_dump_context*) const;
   915  
   916   private:
   917    // The type which we are representing as an expression.
   918    Type* type_;
   919  };
   920  
   921  void
   922  Type_expression::do_check_types(Gogo*)
   923  {
   924    if (this->type_->is_error())
   925      {
   926        go_assert(saw_errors());
   927        this->set_is_error();
   928      }
   929    else
   930      this->report_error(_("invalid use of type"));
   931  }
   932  
   933  void
   934  Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
   935  {
   936    ast_dump_context->dump_type(this->type_);
   937  }
   938  
   939  Expression*
   940  Expression::make_type(Type* type, Location location)
   941  {
   942    return new Type_expression(type, location);
   943  }
   944  
   945  // Class Parser_expression.
   946  
   947  Type*
   948  Parser_expression::do_type()
   949  {
   950    // We should never really ask for the type of a Parser_expression.
   951    // However, it can happen, at least when we have an invalid const
   952    // whose initializer refers to the const itself.  In that case we
   953    // may ask for the type when lowering the const itself.
   954    go_assert(saw_errors());
   955    return Type::make_error_type();
   956  }
   957  
   958  // Class Var_expression.
   959  
   960  // Lower a variable expression.  Here we just make sure that the
   961  // initialization expression of the variable has been lowered.  This
   962  // ensures that we will be able to determine the type of the variable
   963  // if necessary.
   964  
   965  Expression*
   966  Var_expression::do_lower(Gogo* gogo, Named_object* function,
   967  			 Statement_inserter* inserter, int)
   968  {
   969    if (this->variable_->is_variable())
   970      {
   971        Variable* var = this->variable_->var_value();
   972        // This is either a local variable or a global variable.  A
   973        // reference to a variable which is local to an enclosing
   974        // function will be a reference to a field in a closure.
   975        if (var->is_global())
   976  	{
   977  	  function = NULL;
   978  	  inserter = NULL;
   979  	}
   980        var->lower_init_expression(gogo, function, inserter);
   981      }
   982    return this;
   983  }
   984  
   985  // Return the type of a reference to a variable.
   986  
   987  Type*
   988  Var_expression::do_type()
   989  {
   990    if (this->variable_->is_variable())
   991      return this->variable_->var_value()->type();
   992    else if (this->variable_->is_result_variable())
   993      return this->variable_->result_var_value()->type();
   994    else
   995      go_unreachable();
   996  }
   997  
   998  // Determine the type of a reference to a variable.
   999  
  1000  void
  1001  Var_expression::do_determine_type(const Type_context*)
  1002  {
  1003    if (this->variable_->is_variable())
  1004      this->variable_->var_value()->determine_type();
  1005  }
  1006  
  1007  // Something takes the address of this variable.  This means that we
  1008  // may want to move the variable onto the heap.
  1009  
  1010  void
  1011  Var_expression::do_address_taken(bool escapes)
  1012  {
  1013    if (!escapes)
  1014      {
  1015        if (this->variable_->is_variable())
  1016  	this->variable_->var_value()->set_non_escaping_address_taken();
  1017        else if (this->variable_->is_result_variable())
  1018  	this->variable_->result_var_value()->set_non_escaping_address_taken();
  1019        else
  1020  	go_unreachable();
  1021      }
  1022    else
  1023      {
  1024        if (this->variable_->is_variable())
  1025  	this->variable_->var_value()->set_address_taken();
  1026        else if (this->variable_->is_result_variable())
  1027  	this->variable_->result_var_value()->set_address_taken();
  1028        else
  1029  	go_unreachable();
  1030      }
  1031  
  1032    if (this->variable_->is_variable()
  1033        && this->variable_->var_value()->is_in_heap())
  1034      {
  1035        Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
  1036        Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
  1037      }
  1038  }
  1039  
  1040  // Export a reference to a variable.
  1041  
  1042  void
  1043  Var_expression::do_export(Export_function_body* efb) const
  1044  {
  1045    Named_object* no = this->variable_;
  1046    if (no->is_result_variable() || !no->var_value()->is_global())
  1047      efb->write_string(Gogo::unpack_hidden_name(no->name()));
  1048    else
  1049      Expression::export_name(efb, no);
  1050  }
  1051  
  1052  // Get the backend representation for a reference to a variable.
  1053  
  1054  Bexpression*
  1055  Var_expression::do_get_backend(Translate_context* context)
  1056  {
  1057    Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
  1058  							  context->function());
  1059    bool is_in_heap;
  1060    Location loc = this->location();
  1061    Btype* btype;
  1062    Gogo* gogo = context->gogo();
  1063    if (this->variable_->is_variable())
  1064      {
  1065        is_in_heap = this->variable_->var_value()->is_in_heap();
  1066        btype = this->variable_->var_value()->type()->get_backend(gogo);
  1067      }
  1068    else if (this->variable_->is_result_variable())
  1069      {
  1070        is_in_heap = this->variable_->result_var_value()->is_in_heap();
  1071        btype = this->variable_->result_var_value()->type()->get_backend(gogo);
  1072      }
  1073    else
  1074      go_unreachable();
  1075  
  1076    Bexpression* ret =
  1077        context->backend()->var_expression(bvar, loc);
  1078    if (is_in_heap)
  1079      ret = context->backend()->indirect_expression(btype, ret, true, loc);
  1080    return ret;
  1081  }
  1082  
  1083  // Ast dump for variable expression.
  1084  
  1085  void
  1086  Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  1087  {
  1088    ast_dump_context->ostream() << this->variable_->message_name() ;
  1089  }
  1090  
  1091  // Make a reference to a variable in an expression.
  1092  
  1093  Expression*
  1094  Expression::make_var_reference(Named_object* var, Location location)
  1095  {
  1096    if (var->is_sink())
  1097      return Expression::make_sink(location);
  1098  
  1099    // FIXME: Creating a new object for each reference to a variable is
  1100    // wasteful.
  1101    return new Var_expression(var, location);
  1102  }
  1103  
  1104  // Class Enclosed_var_expression.
  1105  
  1106  int
  1107  Enclosed_var_expression::do_traverse(Traverse*)
  1108  {
  1109    return TRAVERSE_CONTINUE;
  1110  }
  1111  
  1112  // Lower the reference to the enclosed variable.
  1113  
  1114  Expression*
  1115  Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
  1116  				  Statement_inserter* inserter, int)
  1117  {
  1118    gogo->lower_expression(function, inserter, &this->reference_);
  1119    return this;
  1120  }
  1121  
  1122  // Flatten the reference to the enclosed variable.
  1123  
  1124  Expression*
  1125  Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
  1126  				    Statement_inserter* inserter)
  1127  {
  1128    gogo->flatten_expression(function, inserter, &this->reference_);
  1129    return this;
  1130  }
  1131  
  1132  void
  1133  Enclosed_var_expression::do_address_taken(bool escapes)
  1134  {
  1135    if (!escapes)
  1136      {
  1137        if (this->variable_->is_variable())
  1138  	this->variable_->var_value()->set_non_escaping_address_taken();
  1139        else if (this->variable_->is_result_variable())
  1140  	this->variable_->result_var_value()->set_non_escaping_address_taken();
  1141        else
  1142  	go_unreachable();
  1143      }
  1144    else
  1145      {
  1146        if (this->variable_->is_variable())
  1147  	this->variable_->var_value()->set_address_taken();
  1148        else if (this->variable_->is_result_variable())
  1149  	this->variable_->result_var_value()->set_address_taken();
  1150        else
  1151  	go_unreachable();
  1152      }
  1153  
  1154    if (this->variable_->is_variable()
  1155        && this->variable_->var_value()->is_in_heap())
  1156      Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
  1157  }
  1158  
  1159  // Ast dump for enclosed variable expression.
  1160  
  1161  void
  1162  Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
  1163  {
  1164    adc->ostream() << this->variable_->message_name();
  1165  }
  1166  
  1167  // Make a reference to a variable within an enclosing function.
  1168  
  1169  Expression*
  1170  Expression::make_enclosing_var_reference(Expression* reference,
  1171  					 Named_object* var, Location location)
  1172  {
  1173    return new Enclosed_var_expression(reference, var, location);
  1174  }
  1175  
  1176  // Class Temporary_reference_expression.
  1177  
  1178  // The type.
  1179  
  1180  Type*
  1181  Temporary_reference_expression::do_type()
  1182  {
  1183    return this->statement_->type();
  1184  }
  1185  
  1186  // Called if something takes the address of this temporary variable.
  1187  // We never have to move temporary variables to the heap, but we do
  1188  // need to know that they must live in the stack rather than in a
  1189  // register.
  1190  
  1191  void
  1192  Temporary_reference_expression::do_address_taken(bool)
  1193  {
  1194    this->statement_->set_is_address_taken();
  1195  }
  1196  
  1197  // Export a reference to a temporary.
  1198  
  1199  void
  1200  Temporary_reference_expression::do_export(Export_function_body* efb) const
  1201  {
  1202    unsigned int idx = efb->temporary_index(this->statement_);
  1203    char buf[50];
  1204    snprintf(buf, sizeof buf, "$t%u", idx);
  1205    efb->write_c_string(buf);
  1206  }
  1207  
  1208  // Import a reference to a temporary.
  1209  
  1210  Expression*
  1211  Temporary_reference_expression::do_import(Import_function_body* ifb,
  1212  					  Location loc)
  1213  {
  1214    std::string id = ifb->read_identifier();
  1215    go_assert(id[0] == '$' && id[1] == 't');
  1216    const char *p = id.c_str();
  1217    char *end;
  1218    long idx = strtol(p + 2, &end, 10);
  1219    if (*end != '\0' || idx > 0x7fffffff)
  1220      {
  1221        if (!ifb->saw_error())
  1222  	go_error_at(loc,
  1223  		    ("invalid export data for %qs: "
  1224  		     "invalid temporary reference index at %lu"),
  1225  		    ifb->name().c_str(),
  1226  		    static_cast<unsigned long>(ifb->off()));
  1227        ifb->set_saw_error();
  1228        return Expression::make_error(loc);
  1229      }
  1230  
  1231    Temporary_statement* temp =
  1232      ifb->temporary_statement(static_cast<unsigned int>(idx));
  1233    if (temp == NULL)
  1234      {
  1235        if (!ifb->saw_error())
  1236  	go_error_at(loc,
  1237  		    ("invalid export data for %qs: "
  1238  		     "undefined temporary reference index at %lu"),
  1239  		    ifb->name().c_str(),
  1240  		    static_cast<unsigned long>(ifb->off()));
  1241        ifb->set_saw_error();
  1242        return Expression::make_error(loc);
  1243      }
  1244  
  1245    return Expression::make_temporary_reference(temp, loc);
  1246  }
  1247  
  1248  // Get a backend expression referring to the variable.
  1249  
  1250  Bexpression*
  1251  Temporary_reference_expression::do_get_backend(Translate_context* context)
  1252  {
  1253    Gogo* gogo = context->gogo();
  1254    Bvariable* bvar = this->statement_->get_backend_variable(context);
  1255    Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
  1256  
  1257    // The backend can't always represent the same set of recursive types
  1258    // that the Go frontend can.  In some cases this means that a
  1259    // temporary variable won't have the right backend type.  Correct
  1260    // that here by adding a type cast.  We need to use base() to push
  1261    // the circularity down one level.
  1262    Type* stype = this->statement_->type();
  1263    if (!this->is_lvalue_
  1264        && stype->points_to() != NULL
  1265        && stype->points_to()->is_void_type())
  1266      {
  1267        Btype* btype = this->type()->base()->get_backend(gogo);
  1268        ret = gogo->backend()->convert_expression(btype, ret, this->location());
  1269      }
  1270    return ret;
  1271  }
  1272  
  1273  // Ast dump for temporary reference.
  1274  
  1275  void
  1276  Temporary_reference_expression::do_dump_expression(
  1277                                  Ast_dump_context* ast_dump_context) const
  1278  {
  1279    ast_dump_context->dump_temp_variable_name(this->statement_);
  1280  }
  1281  
  1282  // Make a reference to a temporary variable.
  1283  
  1284  Temporary_reference_expression*
  1285  Expression::make_temporary_reference(Temporary_statement* statement,
  1286  				     Location location)
  1287  {
  1288    statement->add_use();
  1289    return new Temporary_reference_expression(statement, location);
  1290  }
  1291  
  1292  // Class Set_and_use_temporary_expression.
  1293  
  1294  // Return the type.
  1295  
  1296  Type*
  1297  Set_and_use_temporary_expression::do_type()
  1298  {
  1299    return this->statement_->type();
  1300  }
  1301  
  1302  // Determine the type of the expression.
  1303  
  1304  void
  1305  Set_and_use_temporary_expression::do_determine_type(
  1306      const Type_context* context)
  1307  {
  1308    this->expr_->determine_type(context);
  1309  }
  1310  
  1311  // Take the address.
  1312  
  1313  void
  1314  Set_and_use_temporary_expression::do_address_taken(bool)
  1315  {
  1316    this->statement_->set_is_address_taken();
  1317  }
  1318  
  1319  // Return the backend representation.
  1320  
  1321  Bexpression*
  1322  Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
  1323  {
  1324    Location loc = this->location();
  1325    Gogo* gogo = context->gogo();
  1326    Bvariable* bvar = this->statement_->get_backend_variable(context);
  1327    Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
  1328  
  1329    Named_object* fn = context->function();
  1330    go_assert(fn != NULL);
  1331    Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
  1332    Bexpression* bexpr = this->expr_->get_backend(context);
  1333    Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
  1334                                                            bexpr, loc);
  1335    Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
  1336    Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
  1337    return ret;
  1338  }
  1339  
  1340  // Dump.
  1341  
  1342  void
  1343  Set_and_use_temporary_expression::do_dump_expression(
  1344      Ast_dump_context* ast_dump_context) const
  1345  {
  1346    ast_dump_context->ostream() << '(';
  1347    ast_dump_context->dump_temp_variable_name(this->statement_);
  1348    ast_dump_context->ostream() << " = ";
  1349    this->expr_->dump_expression(ast_dump_context);
  1350    ast_dump_context->ostream() << ')';
  1351  }
  1352  
  1353  // Make a set-and-use temporary.
  1354  
  1355  Set_and_use_temporary_expression*
  1356  Expression::make_set_and_use_temporary(Temporary_statement* statement,
  1357  				       Expression* expr, Location location)
  1358  {
  1359    return new Set_and_use_temporary_expression(statement, expr, location);
  1360  }
  1361  
  1362  // A sink expression--a use of the blank identifier _.
  1363  
  1364  class Sink_expression : public Expression
  1365  {
  1366   public:
  1367    Sink_expression(Location location)
  1368      : Expression(EXPRESSION_SINK, location),
  1369        type_(NULL), bvar_(NULL)
  1370    { }
  1371  
  1372   protected:
  1373    bool
  1374    do_discarding_value()
  1375    { return true; }
  1376  
  1377    Type*
  1378    do_type();
  1379  
  1380    void
  1381    do_determine_type(const Type_context*);
  1382  
  1383    Expression*
  1384    do_copy()
  1385    { return new Sink_expression(this->location()); }
  1386  
  1387    Bexpression*
  1388    do_get_backend(Translate_context*);
  1389  
  1390    void
  1391    do_dump_expression(Ast_dump_context*) const;
  1392  
  1393   private:
  1394    // The type of this sink variable.
  1395    Type* type_;
  1396    // The temporary variable we generate.
  1397    Bvariable* bvar_;
  1398  };
  1399  
  1400  // Return the type of a sink expression.
  1401  
  1402  Type*
  1403  Sink_expression::do_type()
  1404  {
  1405    if (this->type_ == NULL)
  1406      return Type::make_sink_type();
  1407    return this->type_;
  1408  }
  1409  
  1410  // Determine the type of a sink expression.
  1411  
  1412  void
  1413  Sink_expression::do_determine_type(const Type_context* context)
  1414  {
  1415    if (context->type != NULL)
  1416      this->type_ = context->type;
  1417  }
  1418  
  1419  // Return a temporary variable for a sink expression.  This will
  1420  // presumably be a write-only variable which the middle-end will drop.
  1421  
  1422  Bexpression*
  1423  Sink_expression::do_get_backend(Translate_context* context)
  1424  {
  1425    Location loc = this->location();
  1426    Gogo* gogo = context->gogo();
  1427    if (this->bvar_ == NULL)
  1428      {
  1429        if (this->type_ == NULL || this->type_->is_sink_type())
  1430  	{
  1431  	  go_assert(saw_errors());
  1432  	  return gogo->backend()->error_expression();
  1433  	}
  1434  
  1435        Named_object* fn = context->function();
  1436        go_assert(fn != NULL);
  1437        Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
  1438        Btype* bt = this->type_->get_backend(context->gogo());
  1439        Bstatement* decl;
  1440        this->bvar_ =
  1441  	gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
  1442  					    0, loc, &decl);
  1443        Bexpression* var_ref =
  1444            gogo->backend()->var_expression(this->bvar_, loc);
  1445        var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
  1446        return var_ref;
  1447      }
  1448    return gogo->backend()->var_expression(this->bvar_, loc);
  1449  }
  1450  
  1451  // Ast dump for sink expression.
  1452  
  1453  void
  1454  Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  1455  {
  1456    ast_dump_context->ostream() << "_" ;
  1457  }
  1458  
  1459  // Make a sink expression.
  1460  
  1461  Expression*
  1462  Expression::make_sink(Location location)
  1463  {
  1464    return new Sink_expression(location);
  1465  }
  1466  
  1467  // Class Func_expression.
  1468  
  1469  // FIXME: Can a function expression appear in a constant expression?
  1470  // The value is unchanging.  Initializing a constant to the address of
  1471  // a function seems like it could work, though there might be little
  1472  // point to it.
  1473  
  1474  // Traversal.
  1475  
  1476  int
  1477  Func_expression::do_traverse(Traverse* traverse)
  1478  {
  1479    return (this->closure_ == NULL
  1480  	  ? TRAVERSE_CONTINUE
  1481  	  : Expression::traverse(&this->closure_, traverse));
  1482  }
  1483  
  1484  // Return the type of a function expression.
  1485  
  1486  Type*
  1487  Func_expression::do_type()
  1488  {
  1489    if (this->function_->is_function())
  1490      return this->function_->func_value()->type();
  1491    else if (this->function_->is_function_declaration())
  1492      return this->function_->func_declaration_value()->type();
  1493    else
  1494      go_unreachable();
  1495  }
  1496  
  1497  // Get the backend representation for the code of a function expression.
  1498  
  1499  Bexpression*
  1500  Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
  1501  {
  1502    Function_type* fntype;
  1503    if (no->is_function())
  1504      fntype = no->func_value()->type();
  1505    else if (no->is_function_declaration())
  1506      fntype = no->func_declaration_value()->type();
  1507    else
  1508      go_unreachable();
  1509  
  1510    // Builtin functions are handled specially by Call_expression.  We
  1511    // can't take their address.
  1512    if (fntype->is_builtin())
  1513      {
  1514        go_error_at(loc,
  1515  		  ("invalid use of special built-in function %qs; "
  1516  		   "must be called"),
  1517  		  no->message_name().c_str());
  1518        return gogo->backend()->error_expression();
  1519      }
  1520  
  1521    Bfunction* fndecl;
  1522    if (no->is_function())
  1523      fndecl = no->func_value()->get_or_make_decl(gogo, no);
  1524    else if (no->is_function_declaration())
  1525      fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
  1526    else
  1527      go_unreachable();
  1528  
  1529    return gogo->backend()->function_code_expression(fndecl, loc);
  1530  }
  1531  
  1532  // Get the backend representation for a function expression.  This is used when
  1533  // we take the address of a function rather than simply calling it.  A func
  1534  // value is represented as a pointer to a block of memory.  The first
  1535  // word of that memory is a pointer to the function code.  The
  1536  // remaining parts of that memory are the addresses of variables that
  1537  // the function closes over.
  1538  
  1539  Bexpression*
  1540  Func_expression::do_get_backend(Translate_context* context)
  1541  {
  1542    // If there is no closure, just use the function descriptor.
  1543    if (this->closure_ == NULL)
  1544      {
  1545        Gogo* gogo = context->gogo();
  1546        Named_object* no = this->function_;
  1547        Expression* descriptor;
  1548        if (no->is_function())
  1549  	descriptor = no->func_value()->descriptor(gogo, no);
  1550        else if (no->is_function_declaration())
  1551  	{
  1552  	  if (no->func_declaration_value()->type()->is_builtin())
  1553  	    {
  1554  	      go_error_at(this->location(),
  1555  			  ("invalid use of special built-in function %qs; "
  1556  			   "must be called"),
  1557  			  no->message_name().c_str());
  1558  	      return gogo->backend()->error_expression();
  1559  	    }
  1560  	  descriptor = no->func_declaration_value()->descriptor(gogo, no);
  1561  	}
  1562        else
  1563  	go_unreachable();
  1564  
  1565        Bexpression* bdesc = descriptor->get_backend(context);
  1566        return gogo->backend()->address_expression(bdesc, this->location());
  1567      }
  1568  
  1569    go_assert(this->function_->func_value()->enclosing() != NULL);
  1570  
  1571    // If there is a closure, then the closure is itself the function
  1572    // expression.  It is a pointer to a struct whose first field points
  1573    // to the function code and whose remaining fields are the addresses
  1574    // of the closed-over variables.
  1575    Bexpression *bexpr = this->closure_->get_backend(context);
  1576  
  1577    // Introduce a backend type conversion, to account for any differences
  1578    // between the argument type (function descriptor, struct with a
  1579    // single field) and the closure (struct with multiple fields).
  1580    Gogo* gogo = context->gogo();
  1581    Btype *btype = this->type()->get_backend(gogo);
  1582    return gogo->backend()->convert_expression(btype, bexpr, this->location());
  1583  }
  1584  
  1585  // The cost of inlining a function reference.
  1586  
  1587  int
  1588  Func_expression::do_inlining_cost() const
  1589  {
  1590    // FIXME: We don't inline references to nested functions.
  1591    if (this->closure_ != NULL)
  1592      return 0x100000;
  1593    if (this->function_->is_function()
  1594        && this->function_->func_value()->enclosing() != NULL)
  1595      return 0x100000;
  1596  
  1597    return 1;
  1598  }
  1599  
  1600  // Export a reference to a function.
  1601  
  1602  void
  1603  Func_expression::do_export(Export_function_body* efb) const
  1604  {
  1605    Expression::export_name(efb, this->function_);
  1606  }
  1607  
  1608  // Ast dump for function.
  1609  
  1610  void
  1611  Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  1612  {
  1613    ast_dump_context->ostream() << this->function_->name();
  1614    if (this->closure_ != NULL)
  1615      {
  1616        ast_dump_context->ostream() << " {closure =  ";
  1617        this->closure_->dump_expression(ast_dump_context);
  1618        ast_dump_context->ostream() << "}";
  1619      }
  1620  }
  1621  
  1622  // Make a reference to a function in an expression.
  1623  
  1624  Expression*
  1625  Expression::make_func_reference(Named_object* function, Expression* closure,
  1626  				Location location)
  1627  {
  1628    Func_expression* fe = new Func_expression(function, closure, location);
  1629  
  1630    // Detect references to builtin functions and set the runtime code if
  1631    // appropriate.
  1632    if (function->is_function_declaration())
  1633      fe->set_runtime_code(Runtime::name_to_code(function->name()));
  1634    return fe;
  1635  }
  1636  
  1637  // Class Func_descriptor_expression.
  1638  
  1639  // Constructor.
  1640  
  1641  Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
  1642    : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
  1643      fn_(fn), dvar_(NULL)
  1644  {
  1645    go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
  1646  }
  1647  
  1648  // Traversal.
  1649  
  1650  int
  1651  Func_descriptor_expression::do_traverse(Traverse*)
  1652  {
  1653    return TRAVERSE_CONTINUE;
  1654  }
  1655  
  1656  // All function descriptors have the same type.
  1657  
  1658  Type* Func_descriptor_expression::descriptor_type;
  1659  
  1660  void
  1661  Func_descriptor_expression::make_func_descriptor_type()
  1662  {
  1663    if (Func_descriptor_expression::descriptor_type != NULL)
  1664      return;
  1665    Type* uintptr_type = Type::lookup_integer_type("uintptr");
  1666    Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
  1667    Func_descriptor_expression::descriptor_type =
  1668      Type::make_builtin_named_type("functionDescriptor", struct_type);
  1669  }
  1670  
  1671  Type*
  1672  Func_descriptor_expression::do_type()
  1673  {
  1674    Func_descriptor_expression::make_func_descriptor_type();
  1675    return Func_descriptor_expression::descriptor_type;
  1676  }
  1677  
  1678  // The backend representation for a function descriptor.
  1679  
  1680  Bexpression*
  1681  Func_descriptor_expression::do_get_backend(Translate_context* context)
  1682  {
  1683    Named_object* no = this->fn_;
  1684    Location loc = no->location();
  1685    if (this->dvar_ != NULL)
  1686      return context->backend()->var_expression(this->dvar_, loc);
  1687  
  1688    Gogo* gogo = context->gogo();
  1689    Backend_name bname;
  1690    gogo->function_descriptor_backend_name(no, &bname);
  1691    bool is_descriptor = false;
  1692    if (no->is_function_declaration()
  1693        && !no->func_declaration_value()->asm_name().empty()
  1694        && Linemap::is_predeclared_location(no->location()))
  1695      is_descriptor = true;
  1696  
  1697    // The runtime package implements some functions defined in the
  1698    // syscall package.  Let the syscall package define the descriptor
  1699    // in this case.
  1700    if (gogo->compiling_runtime()
  1701        && gogo->package_name() == "runtime"
  1702        && no->is_function()
  1703        && !no->func_value()->asm_name().empty()
  1704        && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
  1705      is_descriptor = true;
  1706  
  1707    Btype* btype = this->type()->get_backend(gogo);
  1708  
  1709    Bvariable* bvar;
  1710    if (no->package() != NULL || is_descriptor)
  1711      bvar =
  1712        context->backend()->immutable_struct_reference(bname.name(),
  1713  						     bname.optional_asm_name(),
  1714  						     btype, loc);
  1715    else
  1716      {
  1717        Location bloc = Linemap::predeclared_location();
  1718  
  1719        // The runtime package has hash/equality functions that are
  1720        // referenced by type descriptors outside of the runtime, so the
  1721        // function descriptors must be visible even though they are not
  1722        // exported.
  1723        bool is_exported_runtime = false;
  1724        if (gogo->compiling_runtime()
  1725  	  && gogo->package_name() == "runtime"
  1726  	  && (no->name().find("hash") != std::string::npos
  1727  	      || no->name().find("equal") != std::string::npos))
  1728  	is_exported_runtime = true;
  1729  
  1730        bool is_hidden = ((no->is_function()
  1731  			 && no->func_value()->enclosing() != NULL)
  1732  			|| (Gogo::is_hidden_name(no->name())
  1733  			    && !is_exported_runtime)
  1734  			|| Gogo::is_thunk(no));
  1735  
  1736        if (no->is_function() && no->func_value()->is_referenced_by_inline())
  1737  	is_hidden = false;
  1738  
  1739        unsigned int flags = 0;
  1740        if (is_hidden)
  1741  	flags |= Backend::variable_is_hidden;
  1742        bvar = context->backend()->immutable_struct(bname.name(),
  1743  						  bname.optional_asm_name(),
  1744  						  flags, btype, bloc);
  1745        Expression_list* vals = new Expression_list();
  1746        vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
  1747        Expression* init =
  1748  	Expression::make_struct_composite_literal(this->type(), vals, bloc);
  1749        Translate_context bcontext(gogo, NULL, NULL, NULL);
  1750        bcontext.set_is_const();
  1751        Bexpression* binit = init->get_backend(&bcontext);
  1752        context->backend()->immutable_struct_set_init(bvar, bname.name(),
  1753  						    flags, btype, bloc, binit);
  1754      }
  1755  
  1756    this->dvar_ = bvar;
  1757    return gogo->backend()->var_expression(bvar, loc);
  1758  }
  1759  
  1760  // Print a function descriptor expression.
  1761  
  1762  void
  1763  Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
  1764  {
  1765    context->ostream() << "[descriptor " << this->fn_->name() << "]";
  1766  }
  1767  
  1768  // Make a function descriptor expression.
  1769  
  1770  Func_descriptor_expression*
  1771  Expression::make_func_descriptor(Named_object* fn)
  1772  {
  1773    return new Func_descriptor_expression(fn);
  1774  }
  1775  
  1776  // Make the function descriptor type, so that it can be converted.
  1777  
  1778  void
  1779  Expression::make_func_descriptor_type()
  1780  {
  1781    Func_descriptor_expression::make_func_descriptor_type();
  1782  }
  1783  
  1784  // A reference to just the code of a function.
  1785  
  1786  class Func_code_reference_expression : public Expression
  1787  {
  1788   public:
  1789    Func_code_reference_expression(Named_object* function, Location location)
  1790      : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
  1791        function_(function)
  1792    { }
  1793  
  1794   protected:
  1795    int
  1796    do_traverse(Traverse*)
  1797    { return TRAVERSE_CONTINUE; }
  1798  
  1799    bool
  1800    do_is_static_initializer() const
  1801    { return true; }
  1802  
  1803    Type*
  1804    do_type()
  1805    { return Type::make_pointer_type(Type::make_void_type()); }
  1806  
  1807    void
  1808    do_determine_type(const Type_context*)
  1809    { }
  1810  
  1811    Expression*
  1812    do_copy()
  1813    {
  1814      return Expression::make_func_code_reference(this->function_,
  1815  						this->location());
  1816    }
  1817  
  1818    Bexpression*
  1819    do_get_backend(Translate_context*);
  1820  
  1821    void
  1822    do_dump_expression(Ast_dump_context* context) const
  1823    { context->ostream() << "[raw " << this->function_->name() << "]" ; }
  1824  
  1825   private:
  1826    // The function.
  1827    Named_object* function_;
  1828  };
  1829  
  1830  // Get the backend representation for a reference to function code.
  1831  
  1832  Bexpression*
  1833  Func_code_reference_expression::do_get_backend(Translate_context* context)
  1834  {
  1835    return Func_expression::get_code_pointer(context->gogo(), this->function_,
  1836  					   this->location());
  1837  }
  1838  
  1839  // Make a reference to the code of a function.
  1840  
  1841  Expression*
  1842  Expression::make_func_code_reference(Named_object* function, Location location)
  1843  {
  1844    return new Func_code_reference_expression(function, location);
  1845  }
  1846  
  1847  // Class Unknown_expression.
  1848  
  1849  // Return the name of an unknown expression.
  1850  
  1851  const std::string&
  1852  Unknown_expression::name() const
  1853  {
  1854    return this->named_object_->name();
  1855  }
  1856  
  1857  // Lower a reference to an unknown name.
  1858  
  1859  Expression*
  1860  Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
  1861  {
  1862    Location location = this->location();
  1863    Named_object* no = this->named_object_;
  1864    Named_object* real;
  1865    if (!no->is_unknown())
  1866      real = no;
  1867    else
  1868      {
  1869        real = no->unknown_value()->real_named_object();
  1870        if (real == NULL)
  1871  	{
  1872  	  if (!this->no_error_message_)
  1873  	    go_error_at(location, "reference to undefined name %qs",
  1874  			this->named_object_->message_name().c_str());
  1875  	  return Expression::make_error(location);
  1876  	}
  1877      }
  1878    switch (real->classification())
  1879      {
  1880      case Named_object::NAMED_OBJECT_CONST:
  1881        return Expression::make_const_reference(real, location);
  1882      case Named_object::NAMED_OBJECT_TYPE:
  1883        return Expression::make_type(real->type_value(), location);
  1884      case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
  1885        if (!this->no_error_message_)
  1886  	go_error_at(location, "reference to undefined type %qs",
  1887  		    real->message_name().c_str());
  1888        return Expression::make_error(location);
  1889      case Named_object::NAMED_OBJECT_VAR:
  1890        real->var_value()->set_is_used();
  1891        return Expression::make_var_reference(real, location);
  1892      case Named_object::NAMED_OBJECT_FUNC:
  1893      case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
  1894        return Expression::make_func_reference(real, NULL, location);
  1895      case Named_object::NAMED_OBJECT_PACKAGE:
  1896        if (!this->no_error_message_)
  1897  	go_error_at(location, "unexpected reference to package");
  1898        return Expression::make_error(location);
  1899      default:
  1900        go_unreachable();
  1901      }
  1902  }
  1903  
  1904  // Dump the ast representation for an unknown expression to a dump context.
  1905  
  1906  void
  1907  Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  1908  {
  1909    ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
  1910  			      << ")";
  1911  }
  1912  
  1913  // Make a reference to an unknown name.
  1914  
  1915  Unknown_expression*
  1916  Expression::make_unknown_reference(Named_object* no, Location location)
  1917  {
  1918    return new Unknown_expression(no, location);
  1919  }
  1920  
  1921  // Start exporting a type conversion for a constant, if needed.  This
  1922  // returns whether we need to export a closing parenthesis.
  1923  
  1924  bool
  1925  Expression::export_constant_type(Export_function_body* efb, Type* type)
  1926  {
  1927    if (type == NULL
  1928        || type->is_abstract()
  1929        || type == efb->type_context())
  1930      return false;
  1931    efb->write_c_string("$convert(");
  1932    efb->write_type(type);
  1933    efb->write_c_string(", ");
  1934    return true;
  1935  }
  1936  
  1937  // Finish a type conversion for a constant.
  1938  
  1939  void
  1940  Expression::finish_export_constant_type(Export_function_body* efb, bool needed)
  1941  {
  1942    if (needed)
  1943      efb->write_c_string(")");
  1944  }
  1945  
  1946  // A boolean expression.
  1947  
  1948  class Boolean_expression : public Expression
  1949  {
  1950   public:
  1951    Boolean_expression(bool val, Location location)
  1952      : Expression(EXPRESSION_BOOLEAN, location),
  1953        val_(val), type_(NULL)
  1954    { }
  1955  
  1956    static Expression*
  1957    do_import(Import_expression*, Location);
  1958  
  1959   protected:
  1960    int
  1961    do_traverse(Traverse*);
  1962  
  1963    bool
  1964    do_is_constant() const
  1965    { return true; }
  1966  
  1967    bool
  1968    do_is_zero_value() const
  1969    { return this->val_ == false; }
  1970  
  1971    bool
  1972    do_boolean_constant_value(bool* val) const
  1973    {
  1974      *val = this->val_;
  1975      return true;
  1976    }
  1977  
  1978    bool
  1979    do_is_static_initializer() const
  1980    { return true; }
  1981  
  1982    Type*
  1983    do_type();
  1984  
  1985    void
  1986    do_determine_type(const Type_context*);
  1987  
  1988    Expression*
  1989    do_copy()
  1990    { return this; }
  1991  
  1992    Bexpression*
  1993    do_get_backend(Translate_context* context)
  1994    { return context->backend()->boolean_constant_expression(this->val_); }
  1995  
  1996    int
  1997    do_inlining_cost() const
  1998    { return 1; }
  1999  
  2000    void
  2001    do_export(Export_function_body* efb) const;
  2002  
  2003    void
  2004    do_dump_expression(Ast_dump_context* ast_dump_context) const
  2005    { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
  2006  
  2007   private:
  2008    // The constant.
  2009    bool val_;
  2010    // The type as determined by context.
  2011    Type* type_;
  2012  };
  2013  
  2014  // Traverse a boolean expression.  We just need to traverse the type
  2015  // if there is one.
  2016  
  2017  int
  2018  Boolean_expression::do_traverse(Traverse* traverse)
  2019  {
  2020    if (this->type_ != NULL)
  2021      return Type::traverse(this->type_, traverse);
  2022    return TRAVERSE_CONTINUE;
  2023  }
  2024  
  2025  // Get the type.
  2026  
  2027  Type*
  2028  Boolean_expression::do_type()
  2029  {
  2030    if (this->type_ == NULL)
  2031      this->type_ = Type::make_boolean_type();
  2032    return this->type_;
  2033  }
  2034  
  2035  // Set the type from the context.
  2036  
  2037  void
  2038  Boolean_expression::do_determine_type(const Type_context* context)
  2039  {
  2040    if (this->type_ != NULL && !this->type_->is_abstract())
  2041      ;
  2042    else if (context->type != NULL && context->type->is_boolean_type())
  2043      this->type_ = context->type;
  2044    else if (!context->may_be_abstract)
  2045      this->type_ = Type::lookup_bool_type();
  2046  }
  2047  
  2048  // Export a boolean constant.
  2049  
  2050  void
  2051  Boolean_expression::do_export(Export_function_body* efb) const
  2052  {
  2053    bool exported_type = Expression::export_constant_type(efb, this->type_);
  2054    efb->write_c_string(this->val_ ? "$true" : "$false");
  2055    Expression::finish_export_constant_type(efb, exported_type);
  2056  }
  2057  
  2058  // Import a boolean constant.
  2059  
  2060  Expression*
  2061  Boolean_expression::do_import(Import_expression* imp, Location loc)
  2062  {
  2063    if (imp->version() >= EXPORT_FORMAT_V3)
  2064      imp->require_c_string("$");
  2065    if (imp->peek_char() == 't')
  2066      {
  2067        imp->require_c_string("true");
  2068        return Expression::make_boolean(true, loc);
  2069      }
  2070    else
  2071      {
  2072        imp->require_c_string("false");
  2073        return Expression::make_boolean(false, loc);
  2074      }
  2075  }
  2076  
  2077  // Make a boolean expression.
  2078  
  2079  Expression*
  2080  Expression::make_boolean(bool val, Location location)
  2081  {
  2082    return new Boolean_expression(val, location);
  2083  }
  2084  
  2085  // Class String_expression.
  2086  
  2087  // Traverse a string expression.  We just need to traverse the type
  2088  // if there is one.
  2089  
  2090  int
  2091  String_expression::do_traverse(Traverse* traverse)
  2092  {
  2093    if (this->type_ != NULL)
  2094      return Type::traverse(this->type_, traverse);
  2095    return TRAVERSE_CONTINUE;
  2096  }
  2097  
  2098  // Get the type.
  2099  
  2100  Type*
  2101  String_expression::do_type()
  2102  {
  2103    if (this->type_ == NULL)
  2104      this->type_ = Type::make_string_type();
  2105    return this->type_;
  2106  }
  2107  
  2108  // Set the type from the context.
  2109  
  2110  void
  2111  String_expression::do_determine_type(const Type_context* context)
  2112  {
  2113    if (this->type_ != NULL && !this->type_->is_abstract())
  2114      ;
  2115    else if (context->type != NULL && context->type->is_string_type())
  2116      this->type_ = context->type;
  2117    else if (!context->may_be_abstract)
  2118      this->type_ = Type::lookup_string_type();
  2119  }
  2120  
  2121  // Build a string constant.
  2122  
  2123  Bexpression*
  2124  String_expression::do_get_backend(Translate_context* context)
  2125  {
  2126    Gogo* gogo = context->gogo();
  2127    Btype* btype = Type::make_string_type()->get_backend(gogo);
  2128  
  2129    Location loc = this->location();
  2130    std::vector<Bexpression*> init(2);
  2131  
  2132    if (this->val_.size() == 0)
  2133      init[0] = gogo->backend()->nil_pointer_expression();
  2134    else
  2135      {
  2136        Bexpression* str_cst =
  2137  	gogo->backend()->string_constant_expression(this->val_);
  2138        init[0] = gogo->backend()->address_expression(str_cst, loc);
  2139      }
  2140  
  2141    Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
  2142    mpz_t lenval;
  2143    mpz_init_set_ui(lenval, this->val_.length());
  2144    init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
  2145    mpz_clear(lenval);
  2146  
  2147    return gogo->backend()->constructor_expression(btype, init, loc);
  2148  }
  2149  
  2150   // Write string literal to string dump.
  2151  
  2152  void
  2153  String_expression::export_string(String_dump* exp,
  2154  				 const String_expression* str)
  2155  {
  2156    std::string s;
  2157    s.reserve(str->val_.length() * 4 + 2);
  2158    s += '"';
  2159    for (std::string::const_iterator p = str->val_.begin();
  2160         p != str->val_.end();
  2161         ++p)
  2162      {
  2163        if (*p == '\\' || *p == '"')
  2164  	{
  2165  	  s += '\\';
  2166  	  s += *p;
  2167  	}
  2168        else if (*p >= 0x20 && *p < 0x7f)
  2169  	s += *p;
  2170        else if (*p == '\n')
  2171  	s += "\\n";
  2172        else if (*p == '\t')
  2173  	s += "\\t";
  2174        else
  2175  	{
  2176  	  s += "\\x";
  2177  	  unsigned char c = *p;
  2178  	  unsigned int dig = c >> 4;
  2179  	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
  2180  	  dig = c & 0xf;
  2181  	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
  2182  	}
  2183      }
  2184    s += '"';
  2185    exp->write_string(s);
  2186  }
  2187  
  2188  // Export a string expression.
  2189  
  2190  void
  2191  String_expression::do_export(Export_function_body* efb) const
  2192  {
  2193    bool exported_type = Expression::export_constant_type(efb, this->type_);
  2194    String_expression::export_string(efb, this);
  2195    Expression::finish_export_constant_type(efb, exported_type);
  2196  }
  2197  
  2198  // Import a string expression.
  2199  
  2200  Expression*
  2201  String_expression::do_import(Import_expression* imp, Location loc)
  2202  {
  2203    imp->require_c_string("\"");
  2204    std::string val;
  2205    while (true)
  2206      {
  2207        int c = imp->get_char();
  2208        if (c == '"' || c == -1)
  2209  	break;
  2210        if (c != '\\')
  2211  	val += static_cast<char>(c);
  2212        else
  2213  	{
  2214  	  c = imp->get_char();
  2215  	  if (c == '\\' || c == '"')
  2216  	    val += static_cast<char>(c);
  2217  	  else if (c == 'n')
  2218  	    val += '\n';
  2219  	  else if (c == 't')
  2220  	    val += '\t';
  2221  	  else if (c == 'x')
  2222  	    {
  2223  	      c = imp->get_char();
  2224  	      unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
  2225  	      c = imp->get_char();
  2226  	      unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
  2227  	      char v = (vh << 4) | vl;
  2228  	      val += v;
  2229  	    }
  2230  	  else
  2231  	    {
  2232  	      go_error_at(imp->location(), "bad string constant");
  2233  	      return Expression::make_error(loc);
  2234  	    }
  2235  	}
  2236      }
  2237    return Expression::make_string(val, loc);
  2238  }
  2239  
  2240  // Ast dump for string expression.
  2241  
  2242  void
  2243  String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  2244  {
  2245    String_expression::export_string(ast_dump_context, this);
  2246  }
  2247  
  2248  // Make a string expression with abstract string type (common case).
  2249  
  2250  Expression*
  2251  Expression::make_string(const std::string& val, Location location)
  2252  {
  2253    return new String_expression(val, NULL, location);
  2254  }
  2255  
  2256  // Make a string expression with a specific string type.
  2257  
  2258  Expression*
  2259  Expression::make_string_typed(const std::string& val, Type* type, Location location)
  2260  {
  2261    return new String_expression(val, type, location);
  2262  }
  2263  
  2264  // An expression that evaluates to some characteristic of a string.
  2265  // This is used when indexing, bound-checking, or nil checking a string.
  2266  
  2267  class String_info_expression : public Expression
  2268  {
  2269   public:
  2270    String_info_expression(Expression* string, String_info string_info,
  2271                          Location location)
  2272      : Expression(EXPRESSION_STRING_INFO, location),
  2273        string_(string), string_info_(string_info)
  2274    { }
  2275  
  2276   protected:
  2277    Type*
  2278    do_type();
  2279  
  2280    void
  2281    do_determine_type(const Type_context*)
  2282    { go_unreachable(); }
  2283  
  2284    Expression*
  2285    do_copy()
  2286    {
  2287      return new String_info_expression(this->string_->copy(), this->string_info_,
  2288  				      this->location());
  2289    }
  2290  
  2291    Bexpression*
  2292    do_get_backend(Translate_context* context);
  2293  
  2294    void
  2295    do_dump_expression(Ast_dump_context*) const;
  2296  
  2297    void
  2298    do_issue_nil_check()
  2299    { this->string_->issue_nil_check(); }
  2300  
  2301   private:
  2302    // The string for which we are getting information.
  2303    Expression* string_;
  2304    // What information we want.
  2305    String_info string_info_;
  2306  };
  2307  
  2308  // Return the type of the string info.
  2309  
  2310  Type*
  2311  String_info_expression::do_type()
  2312  {
  2313    switch (this->string_info_)
  2314      {
  2315      case STRING_INFO_DATA:
  2316        {
  2317  	Type* byte_type = Type::lookup_integer_type("uint8");
  2318  	return Type::make_pointer_type(byte_type);
  2319        }
  2320      case STRING_INFO_LENGTH:
  2321          return Type::lookup_integer_type("int");
  2322      default:
  2323        go_unreachable();
  2324      }
  2325  }
  2326  
  2327  // Return string information in GENERIC.
  2328  
  2329  Bexpression*
  2330  String_info_expression::do_get_backend(Translate_context* context)
  2331  {
  2332    Gogo* gogo = context->gogo();
  2333  
  2334    Bexpression* bstring = this->string_->get_backend(context);
  2335    switch (this->string_info_)
  2336      {
  2337      case STRING_INFO_DATA:
  2338      case STRING_INFO_LENGTH:
  2339        return gogo->backend()->struct_field_expression(bstring,
  2340  						      this->string_info_,
  2341  						      this->location());
  2342        break;
  2343      default:
  2344        go_unreachable();
  2345      }
  2346  }
  2347  
  2348  // Dump ast representation for a type info expression.
  2349  
  2350  void
  2351  String_info_expression::do_dump_expression(
  2352      Ast_dump_context* ast_dump_context) const
  2353  {
  2354    ast_dump_context->ostream() << "stringinfo(";
  2355    this->string_->dump_expression(ast_dump_context);
  2356    ast_dump_context->ostream() << ",";
  2357    ast_dump_context->ostream() <<
  2358        (this->string_info_ == STRING_INFO_DATA ? "data"
  2359      : this->string_info_ == STRING_INFO_LENGTH ? "length"
  2360      : "unknown");
  2361    ast_dump_context->ostream() << ")";
  2362  }
  2363  
  2364  // Make a string info expression.
  2365  
  2366  Expression*
  2367  Expression::make_string_info(Expression* string, String_info string_info,
  2368                              Location location)
  2369  {
  2370    return new String_info_expression(string, string_info, location);
  2371  }
  2372  
  2373  // An expression that represents an string value: a struct with value pointer
  2374  // and length fields.
  2375  
  2376  class String_value_expression : public Expression
  2377  {
  2378   public:
  2379    String_value_expression(Expression* valptr, Expression* len, Location location)
  2380        : Expression(EXPRESSION_STRING_VALUE, location),
  2381          valptr_(valptr), len_(len)
  2382    { }
  2383  
  2384   protected:
  2385    int
  2386    do_traverse(Traverse*);
  2387  
  2388    Type*
  2389    do_type()
  2390    { return Type::make_string_type(); }
  2391  
  2392    void
  2393    do_determine_type(const Type_context*)
  2394    { go_unreachable(); }
  2395  
  2396    Expression*
  2397    do_copy()
  2398    {
  2399      return new String_value_expression(this->valptr_->copy(),
  2400                                         this->len_->copy(),
  2401                                         this->location());
  2402    }
  2403  
  2404    Bexpression*
  2405    do_get_backend(Translate_context* context);
  2406  
  2407    void
  2408    do_dump_expression(Ast_dump_context*) const;
  2409  
  2410   private:
  2411    // The value pointer.
  2412    Expression* valptr_;
  2413    // The length.
  2414    Expression* len_;
  2415  };
  2416  
  2417  int
  2418  String_value_expression::do_traverse(Traverse* traverse)
  2419  {
  2420    if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
  2421        || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
  2422      return TRAVERSE_EXIT;
  2423    return TRAVERSE_CONTINUE;
  2424  }
  2425  
  2426  Bexpression*
  2427  String_value_expression::do_get_backend(Translate_context* context)
  2428  {
  2429    std::vector<Bexpression*> vals(2);
  2430    vals[0] = this->valptr_->get_backend(context);
  2431    vals[1] = this->len_->get_backend(context);
  2432  
  2433    Gogo* gogo = context->gogo();
  2434    Btype* btype = Type::make_string_type()->get_backend(gogo);
  2435    return gogo->backend()->constructor_expression(btype, vals, this->location());
  2436  }
  2437  
  2438  void
  2439  String_value_expression::do_dump_expression(
  2440      Ast_dump_context* ast_dump_context) const
  2441  {
  2442    ast_dump_context->ostream() << "stringvalue(";
  2443    ast_dump_context->ostream() << "value: ";
  2444    this->valptr_->dump_expression(ast_dump_context);
  2445    ast_dump_context->ostream() << ", length: ";
  2446    this->len_->dump_expression(ast_dump_context);
  2447    ast_dump_context->ostream() << ")";
  2448  }
  2449  
  2450  Expression*
  2451  Expression::make_string_value(Expression* valptr, Expression* len,
  2452                                Location location)
  2453  {
  2454    return new String_value_expression(valptr, len, location);
  2455  }
  2456  
  2457  // Make an integer expression.
  2458  
  2459  class Integer_expression : public Expression
  2460  {
  2461   public:
  2462    Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
  2463  		     Location location)
  2464      : Expression(EXPRESSION_INTEGER, location),
  2465        type_(type), is_character_constant_(is_character_constant)
  2466    { mpz_init_set(this->val_, *val); }
  2467  
  2468    static Expression*
  2469    do_import(Import_expression*, Location);
  2470  
  2471    // Write VAL to string dump.
  2472    static void
  2473    export_integer(String_dump* exp, const mpz_t val);
  2474  
  2475    // Write VAL to dump context.
  2476    static void
  2477    dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
  2478  
  2479   protected:
  2480    int
  2481    do_traverse(Traverse*);
  2482  
  2483    bool
  2484    do_is_constant() const
  2485    { return true; }
  2486  
  2487    bool
  2488    do_is_zero_value() const
  2489    { return mpz_sgn(this->val_) == 0; }
  2490  
  2491    bool
  2492    do_is_static_initializer() const
  2493    { return true; }
  2494  
  2495    bool
  2496    do_numeric_constant_value(Numeric_constant* nc) const;
  2497  
  2498    Type*
  2499    do_type();
  2500  
  2501    void
  2502    do_determine_type(const Type_context* context);
  2503  
  2504    void
  2505    do_check_types(Gogo*);
  2506  
  2507    Bexpression*
  2508    do_get_backend(Translate_context*);
  2509  
  2510    Expression*
  2511    do_copy()
  2512    {
  2513      if (this->is_character_constant_)
  2514        return Expression::make_character(&this->val_,
  2515  					(this->type_ == NULL
  2516  					 ? NULL
  2517  					 : this->type_->copy_expressions()),
  2518  					this->location());
  2519      else
  2520        return Expression::make_integer_z(&this->val_,
  2521  					(this->type_ == NULL
  2522  					 ? NULL
  2523  					 : this->type_->copy_expressions()),
  2524  					this->location());
  2525    }
  2526  
  2527    int
  2528    do_inlining_cost() const
  2529    { return 1; }
  2530  
  2531    void
  2532    do_export(Export_function_body*) const;
  2533  
  2534    void
  2535    do_dump_expression(Ast_dump_context*) const;
  2536  
  2537   private:
  2538    // The integer value.
  2539    mpz_t val_;
  2540    // The type so far.
  2541    Type* type_;
  2542    // Whether this is a character constant.
  2543    bool is_character_constant_;
  2544  };
  2545  
  2546  // Traverse an integer expression.  We just need to traverse the type
  2547  // if there is one.
  2548  
  2549  int
  2550  Integer_expression::do_traverse(Traverse* traverse)
  2551  {
  2552    if (this->type_ != NULL)
  2553      return Type::traverse(this->type_, traverse);
  2554    return TRAVERSE_CONTINUE;
  2555  }
  2556  
  2557  // Return a numeric constant for this expression.  We have to mark
  2558  // this as a character when appropriate.
  2559  
  2560  bool
  2561  Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
  2562  {
  2563    if (this->is_character_constant_)
  2564      nc->set_rune(this->type_, this->val_);
  2565    else
  2566      nc->set_int(this->type_, this->val_);
  2567    return true;
  2568  }
  2569  
  2570  // Return the current type.  If we haven't set the type yet, we return
  2571  // an abstract integer type.
  2572  
  2573  Type*
  2574  Integer_expression::do_type()
  2575  {
  2576    if (this->type_ == NULL)
  2577      {
  2578        if (this->is_character_constant_)
  2579  	this->type_ = Type::make_abstract_character_type();
  2580        else
  2581  	this->type_ = Type::make_abstract_integer_type();
  2582      }
  2583    return this->type_;
  2584  }
  2585  
  2586  // Set the type of the integer value.  Here we may switch from an
  2587  // abstract type to a real type.
  2588  
  2589  void
  2590  Integer_expression::do_determine_type(const Type_context* context)
  2591  {
  2592    if (this->type_ != NULL && !this->type_->is_abstract())
  2593      ;
  2594    else if (context->type != NULL && context->type->is_numeric_type())
  2595      this->type_ = context->type;
  2596    else if (!context->may_be_abstract)
  2597      {
  2598        if (this->is_character_constant_)
  2599  	this->type_ = Type::lookup_integer_type("int32");
  2600        else
  2601  	this->type_ = Type::lookup_integer_type("int");
  2602      }
  2603  }
  2604  
  2605  // Check the type of an integer constant.
  2606  
  2607  void
  2608  Integer_expression::do_check_types(Gogo*)
  2609  {
  2610    Type* type = this->type_;
  2611    if (type == NULL)
  2612      return;
  2613    Numeric_constant nc;
  2614    if (this->is_character_constant_)
  2615      nc.set_rune(NULL, this->val_);
  2616    else
  2617      nc.set_int(NULL, this->val_);
  2618    if (!nc.set_type(type, true, this->location()))
  2619      this->set_is_error();
  2620  }
  2621  
  2622  // Get the backend representation for an integer constant.
  2623  
  2624  Bexpression*
  2625  Integer_expression::do_get_backend(Translate_context* context)
  2626  {
  2627    if (this->is_error_expression()
  2628        || (this->type_ != NULL && this->type_->is_error_type()))
  2629      {
  2630        go_assert(saw_errors());
  2631        return context->gogo()->backend()->error_expression();
  2632      }
  2633  
  2634    Type* resolved_type = NULL;
  2635    if (this->type_ != NULL && !this->type_->is_abstract())
  2636      resolved_type = this->type_;
  2637    else if (this->type_ != NULL && this->type_->float_type() != NULL)
  2638      {
  2639        // We are converting to an abstract floating point type.
  2640        resolved_type = Type::lookup_float_type("float64");
  2641      }
  2642    else if (this->type_ != NULL && this->type_->complex_type() != NULL)
  2643      {
  2644        // We are converting to an abstract complex type.
  2645        resolved_type = Type::lookup_complex_type("complex128");
  2646      }
  2647    else
  2648      {
  2649        // If we still have an abstract type here, then this is being
  2650        // used in a constant expression which didn't get reduced for
  2651        // some reason.  Use a type which will fit the value.  We use <,
  2652        // not <=, because we need an extra bit for the sign bit.
  2653        int bits = mpz_sizeinbase(this->val_, 2);
  2654        Type* int_type = Type::lookup_integer_type("int");
  2655        if (bits < int_type->integer_type()->bits())
  2656  	resolved_type = int_type;
  2657        else if (bits < 64)
  2658          resolved_type = Type::lookup_integer_type("int64");
  2659        else
  2660          {
  2661            if (!saw_errors())
  2662              go_error_at(this->location(),
  2663                          "unknown type for large integer constant");
  2664            return context->gogo()->backend()->error_expression();
  2665          }
  2666      }
  2667    Numeric_constant nc;
  2668    nc.set_int(resolved_type, this->val_);
  2669    return Expression::backend_numeric_constant_expression(context, &nc);
  2670  }
  2671  
  2672  // Write VAL to export data.
  2673  
  2674  void
  2675  Integer_expression::export_integer(String_dump* exp, const mpz_t val)
  2676  {
  2677    char* s = mpz_get_str(NULL, 10, val);
  2678    exp->write_c_string(s);
  2679    free(s);
  2680  }
  2681  
  2682  // Export an integer in a constant expression.
  2683  
  2684  void
  2685  Integer_expression::do_export(Export_function_body* efb) const
  2686  {
  2687    bool exported_type = Expression::export_constant_type(efb, this->type_);
  2688  
  2689    Integer_expression::export_integer(efb, this->val_);
  2690    if (this->is_character_constant_)
  2691      efb->write_c_string("'");
  2692    // A trailing space lets us reliably identify the end of the number.
  2693    efb->write_c_string(" ");
  2694  
  2695    Expression::finish_export_constant_type(efb, exported_type);
  2696  }
  2697  
  2698  // Import an integer, floating point, or complex value.  This handles
  2699  // all these types because they all start with digits.
  2700  
  2701  Expression*
  2702  Integer_expression::do_import(Import_expression* imp, Location loc)
  2703  {
  2704    std::string num = imp->read_identifier();
  2705    imp->require_c_string(" ");
  2706    if (!num.empty() && num[num.length() - 1] == 'i')
  2707      {
  2708        mpfr_t real;
  2709        size_t plus_pos = num.find('+', 1);
  2710        size_t minus_pos = num.find('-', 1);
  2711        size_t pos;
  2712        if (plus_pos == std::string::npos)
  2713  	pos = minus_pos;
  2714        else if (minus_pos == std::string::npos)
  2715  	pos = plus_pos;
  2716        else
  2717  	{
  2718  	  go_error_at(imp->location(), "bad number in import data: %qs",
  2719  		      num.c_str());
  2720  	  return Expression::make_error(loc);
  2721  	}
  2722        if (pos == std::string::npos)
  2723  	mpfr_init_set_ui(real, 0, MPFR_RNDN);
  2724        else
  2725  	{
  2726  	  std::string real_str = num.substr(0, pos);
  2727  	  if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
  2728  	    {
  2729  	      go_error_at(imp->location(), "bad number in import data: %qs",
  2730  			  real_str.c_str());
  2731  	      return Expression::make_error(loc);
  2732  	    }
  2733  	}
  2734  
  2735        std::string imag_str;
  2736        if (pos == std::string::npos)
  2737  	imag_str = num;
  2738        else
  2739  	imag_str = num.substr(pos);
  2740        imag_str = imag_str.substr(0, imag_str.size() - 1);
  2741        mpfr_t imag;
  2742        if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
  2743  	{
  2744  	  go_error_at(imp->location(), "bad number in import data: %qs",
  2745  		      imag_str.c_str());
  2746  	  return Expression::make_error(loc);
  2747  	}
  2748        mpc_t cval;
  2749        mpc_init2(cval, mpc_precision);
  2750        mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
  2751        mpfr_clear(real);
  2752        mpfr_clear(imag);
  2753        Expression* ret = Expression::make_complex(&cval, NULL, loc);
  2754        mpc_clear(cval);
  2755        return ret;
  2756      }
  2757    else if (num.find('.') == std::string::npos
  2758  	   && num.find('E') == std::string::npos)
  2759      {
  2760        bool is_character_constant = (!num.empty()
  2761  				    && num[num.length() - 1] == '\'');
  2762        if (is_character_constant)
  2763  	num = num.substr(0, num.length() - 1);
  2764        mpz_t val;
  2765        if (mpz_init_set_str(val, num.c_str(), 10) != 0)
  2766  	{
  2767  	  go_error_at(imp->location(), "bad number in import data: %qs",
  2768  		      num.c_str());
  2769  	  return Expression::make_error(loc);
  2770  	}
  2771        Expression* ret;
  2772        if (is_character_constant)
  2773  	ret = Expression::make_character(&val, NULL, loc);
  2774        else
  2775  	ret = Expression::make_integer_z(&val, NULL, loc);
  2776        mpz_clear(val);
  2777        return ret;
  2778      }
  2779    else
  2780      {
  2781        mpfr_t val;
  2782        if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
  2783  	{
  2784  	  go_error_at(imp->location(), "bad number in import data: %qs",
  2785  		      num.c_str());
  2786  	  return Expression::make_error(loc);
  2787  	}
  2788        Expression* ret = Expression::make_float(&val, NULL, loc);
  2789        mpfr_clear(val);
  2790        return ret;
  2791      }
  2792  }
  2793  // Ast dump for integer expression.
  2794  
  2795  void
  2796  Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  2797  {
  2798    if (this->is_character_constant_)
  2799      ast_dump_context->ostream() << '\'';
  2800    Integer_expression::export_integer(ast_dump_context, this->val_);
  2801    if (this->is_character_constant_)
  2802      ast_dump_context->ostream() << '\'';
  2803  }
  2804  
  2805  // Build a new integer value from a multi-precision integer.
  2806  
  2807  Expression*
  2808  Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
  2809  {
  2810    return new Integer_expression(val, type, false, location);
  2811  }
  2812  
  2813  // Build a new integer value from an unsigned long.
  2814  
  2815  Expression*
  2816  Expression::make_integer_ul(unsigned long val, Type *type, Location location)
  2817  {
  2818    mpz_t zval;
  2819    mpz_init_set_ui(zval, val);
  2820    Expression* ret = Expression::make_integer_z(&zval, type, location);
  2821    mpz_clear(zval);
  2822    return ret;
  2823  }
  2824  
  2825  // Build a new integer value from a signed long.
  2826  
  2827  Expression*
  2828  Expression::make_integer_sl(long val, Type *type, Location location)
  2829  {
  2830    mpz_t zval;
  2831    mpz_init_set_si(zval, val);
  2832    Expression* ret = Expression::make_integer_z(&zval, type, location);
  2833    mpz_clear(zval);
  2834    return ret;
  2835  }
  2836  
  2837  // Store an int64_t in an uninitialized mpz_t.
  2838  
  2839  static void
  2840  set_mpz_from_int64(mpz_t* zval, int64_t val)
  2841  {
  2842    if (val >= 0)
  2843      {
  2844        unsigned long ul = static_cast<unsigned long>(val);
  2845        if (static_cast<int64_t>(ul) == val)
  2846  	{
  2847  	  mpz_init_set_ui(*zval, ul);
  2848  	  return;
  2849  	}
  2850      }
  2851    uint64_t uv;
  2852    if (val >= 0)
  2853      uv = static_cast<uint64_t>(val);
  2854    else
  2855      uv = static_cast<uint64_t>(- val);
  2856    unsigned long ul = uv & 0xffffffffUL;
  2857    mpz_init_set_ui(*zval, ul);
  2858    mpz_t hval;
  2859    mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
  2860    mpz_mul_2exp(hval, hval, 32);
  2861    mpz_add(*zval, *zval, hval);
  2862    mpz_clear(hval);
  2863    if (val < 0)
  2864      mpz_neg(*zval, *zval);
  2865  }
  2866  
  2867  // Build a new integer value from an int64_t.
  2868  
  2869  Expression*
  2870  Expression::make_integer_int64(int64_t val, Type* type, Location location)
  2871  {
  2872    mpz_t zval;
  2873    set_mpz_from_int64(&zval, val);
  2874    Expression* ret = Expression::make_integer_z(&zval, type, location);
  2875    mpz_clear(zval);
  2876    return ret;
  2877  }
  2878  
  2879  // Build a new character constant value.
  2880  
  2881  Expression*
  2882  Expression::make_character(const mpz_t* val, Type* type, Location location)
  2883  {
  2884    return new Integer_expression(val, type, true, location);
  2885  }
  2886  
  2887  // Floats.
  2888  
  2889  class Float_expression : public Expression
  2890  {
  2891   public:
  2892    Float_expression(const mpfr_t* val, Type* type, Location location)
  2893      : Expression(EXPRESSION_FLOAT, location),
  2894        type_(type)
  2895    {
  2896      mpfr_init_set(this->val_, *val, MPFR_RNDN);
  2897    }
  2898  
  2899    // Write VAL to export data.
  2900    static void
  2901    export_float(String_dump* exp, const mpfr_t val);
  2902  
  2903    // Write VAL to dump file.
  2904    static void
  2905    dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
  2906  
  2907   protected:
  2908    int
  2909    do_traverse(Traverse*);
  2910  
  2911    bool
  2912    do_is_constant() const
  2913    { return true; }
  2914  
  2915    bool
  2916    do_is_zero_value() const
  2917    {
  2918      return mpfr_zero_p(this->val_) != 0
  2919             && mpfr_signbit(this->val_) == 0;
  2920    }
  2921  
  2922    bool
  2923    do_is_static_initializer() const
  2924    { return true; }
  2925  
  2926    bool
  2927    do_numeric_constant_value(Numeric_constant* nc) const
  2928    {
  2929      nc->set_float(this->type_, this->val_);
  2930      return true;
  2931    }
  2932  
  2933    Type*
  2934    do_type();
  2935  
  2936    void
  2937    do_determine_type(const Type_context*);
  2938  
  2939    void
  2940    do_check_types(Gogo*);
  2941  
  2942    Expression*
  2943    do_copy()
  2944    { return Expression::make_float(&this->val_,
  2945  				  (this->type_ == NULL
  2946  				   ? NULL
  2947  				   : this->type_->copy_expressions()),
  2948  				  this->location()); }
  2949  
  2950    Bexpression*
  2951    do_get_backend(Translate_context*);
  2952  
  2953    int
  2954    do_inlining_cost() const
  2955    { return 1; }
  2956  
  2957    void
  2958    do_export(Export_function_body*) const;
  2959  
  2960    void
  2961    do_dump_expression(Ast_dump_context*) const;
  2962  
  2963   private:
  2964    // The floating point value.
  2965    mpfr_t val_;
  2966    // The type so far.
  2967    Type* type_;
  2968  };
  2969  
  2970  // Traverse a float expression.  We just need to traverse the type if
  2971  // there is one.
  2972  
  2973  int
  2974  Float_expression::do_traverse(Traverse* traverse)
  2975  {
  2976    if (this->type_ != NULL)
  2977      return Type::traverse(this->type_, traverse);
  2978    return TRAVERSE_CONTINUE;
  2979  }
  2980  
  2981  // Return the current type.  If we haven't set the type yet, we return
  2982  // an abstract float type.
  2983  
  2984  Type*
  2985  Float_expression::do_type()
  2986  {
  2987    if (this->type_ == NULL)
  2988      this->type_ = Type::make_abstract_float_type();
  2989    return this->type_;
  2990  }
  2991  
  2992  // Set the type of the float value.  Here we may switch from an
  2993  // abstract type to a real type.
  2994  
  2995  void
  2996  Float_expression::do_determine_type(const Type_context* context)
  2997  {
  2998    if (this->type_ != NULL && !this->type_->is_abstract())
  2999      ;
  3000    else if (context->type != NULL
  3001  	   && (context->type->integer_type() != NULL
  3002  	       || context->type->float_type() != NULL
  3003  	       || context->type->complex_type() != NULL))
  3004      this->type_ = context->type;
  3005    else if (!context->may_be_abstract)
  3006      this->type_ = Type::lookup_float_type("float64");
  3007  }
  3008  
  3009  // Check the type of a float value.
  3010  
  3011  void
  3012  Float_expression::do_check_types(Gogo*)
  3013  {
  3014    Type* type = this->type_;
  3015    if (type == NULL)
  3016      return;
  3017    Numeric_constant nc;
  3018    nc.set_float(NULL, this->val_);
  3019    if (!nc.set_type(this->type_, true, this->location()))
  3020      this->set_is_error();
  3021  }
  3022  
  3023  // Get the backend representation for a float constant.
  3024  
  3025  Bexpression*
  3026  Float_expression::do_get_backend(Translate_context* context)
  3027  {
  3028    if (this->is_error_expression()
  3029        || (this->type_ != NULL && this->type_->is_error_type()))
  3030      {
  3031        go_assert(saw_errors());
  3032        return context->gogo()->backend()->error_expression();
  3033      }
  3034  
  3035    Type* resolved_type;
  3036    if (this->type_ != NULL && !this->type_->is_abstract())
  3037      resolved_type = this->type_;
  3038    else if (this->type_ != NULL && this->type_->integer_type() != NULL)
  3039      {
  3040        // We have an abstract integer type.  We just hope for the best.
  3041        resolved_type = Type::lookup_integer_type("int");
  3042      }
  3043    else if (this->type_ != NULL && this->type_->complex_type() != NULL)
  3044      {
  3045        // We are converting to an abstract complex type.
  3046        resolved_type = Type::lookup_complex_type("complex128");
  3047      }
  3048    else
  3049      {
  3050        // If we still have an abstract type here, then this is being
  3051        // used in a constant expression which didn't get reduced.  We
  3052        // just use float64 and hope for the best.
  3053        resolved_type = Type::lookup_float_type("float64");
  3054      }
  3055  
  3056    Numeric_constant nc;
  3057    nc.set_float(resolved_type, this->val_);
  3058    return Expression::backend_numeric_constant_expression(context, &nc);
  3059  }
  3060  
  3061  // Write a floating point number to a string dump.
  3062  
  3063  void
  3064  Float_expression::export_float(String_dump *exp, const mpfr_t val)
  3065  {
  3066    mpfr_exp_t exponent;
  3067    char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
  3068    if (*s == '-')
  3069      exp->write_c_string("-");
  3070    exp->write_c_string("0.");
  3071    exp->write_c_string(*s == '-' ? s + 1 : s);
  3072    mpfr_free_str(s);
  3073    char buf[30];
  3074    snprintf(buf, sizeof buf, "E%ld", exponent);
  3075    exp->write_c_string(buf);
  3076  }
  3077  
  3078  // Export a floating point number in a constant expression.
  3079  
  3080  void
  3081  Float_expression::do_export(Export_function_body* efb) const
  3082  {
  3083    bool exported_type = Expression::export_constant_type(efb, this->type_);
  3084  
  3085    Float_expression::export_float(efb, this->val_);
  3086    // A trailing space lets us reliably identify the end of the number.
  3087    efb->write_c_string(" ");
  3088  
  3089    Expression::finish_export_constant_type(efb, exported_type);
  3090  }
  3091  
  3092  // Dump a floating point number to the dump file.
  3093  
  3094  void
  3095  Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  3096  {
  3097    Float_expression::export_float(ast_dump_context, this->val_);
  3098  }
  3099  
  3100  // Make a float expression.
  3101  
  3102  Expression*
  3103  Expression::make_float(const mpfr_t* val, Type* type, Location location)
  3104  {
  3105    return new Float_expression(val, type, location);
  3106  }
  3107  
  3108  // Complex numbers.
  3109  
  3110  class Complex_expression : public Expression
  3111  {
  3112   public:
  3113    Complex_expression(const mpc_t* val, Type* type, Location location)
  3114      : Expression(EXPRESSION_COMPLEX, location),
  3115        type_(type)
  3116    {
  3117      mpc_init2(this->val_, mpc_precision);
  3118      mpc_set(this->val_, *val, MPC_RNDNN);
  3119    }
  3120  
  3121    // Write VAL to string dump.
  3122    static void
  3123    export_complex(String_dump* exp, const mpc_t val);
  3124  
  3125    // Write REAL/IMAG to dump context.
  3126    static void
  3127    dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
  3128  
  3129   protected:
  3130    int
  3131    do_traverse(Traverse*);
  3132  
  3133    bool
  3134    do_is_constant() const
  3135    { return true; }
  3136  
  3137    bool
  3138    do_is_zero_value() const
  3139    {
  3140      return mpfr_zero_p(mpc_realref(this->val_)) != 0
  3141             && mpfr_signbit(mpc_realref(this->val_)) == 0
  3142             && mpfr_zero_p(mpc_imagref(this->val_)) != 0
  3143             && mpfr_signbit(mpc_imagref(this->val_)) == 0;
  3144    }
  3145  
  3146    bool
  3147    do_is_static_initializer() const
  3148    { return true; }
  3149  
  3150    bool
  3151    do_numeric_constant_value(Numeric_constant* nc) const
  3152    {
  3153      nc->set_complex(this->type_, this->val_);
  3154      return true;
  3155    }
  3156  
  3157    Type*
  3158    do_type();
  3159  
  3160    void
  3161    do_determine_type(const Type_context*);
  3162  
  3163    void
  3164    do_check_types(Gogo*);
  3165  
  3166    Expression*
  3167    do_copy()
  3168    {
  3169      return Expression::make_complex(&this->val_,
  3170  				    (this->type_ == NULL
  3171  				     ? NULL
  3172  				     : this->type_->copy_expressions()),
  3173  				    this->location());
  3174    }
  3175  
  3176    Bexpression*
  3177    do_get_backend(Translate_context*);
  3178  
  3179    int
  3180    do_inlining_cost() const
  3181    { return 2; }
  3182  
  3183    void
  3184    do_export(Export_function_body*) const;
  3185  
  3186    void
  3187    do_dump_expression(Ast_dump_context*) const;
  3188  
  3189   private:
  3190    // The complex value.
  3191    mpc_t val_;
  3192    // The type if known.
  3193    Type* type_;
  3194  };
  3195  
  3196  // Traverse a complex expression.  We just need to traverse the type
  3197  // if there is one.
  3198  
  3199  int
  3200  Complex_expression::do_traverse(Traverse* traverse)
  3201  {
  3202    if (this->type_ != NULL)
  3203      return Type::traverse(this->type_, traverse);
  3204    return TRAVERSE_CONTINUE;
  3205  }
  3206  
  3207  // Return the current type.  If we haven't set the type yet, we return
  3208  // an abstract complex type.
  3209  
  3210  Type*
  3211  Complex_expression::do_type()
  3212  {
  3213    if (this->type_ == NULL)
  3214      this->type_ = Type::make_abstract_complex_type();
  3215    return this->type_;
  3216  }
  3217  
  3218  // Set the type of the complex value.  Here we may switch from an
  3219  // abstract type to a real type.
  3220  
  3221  void
  3222  Complex_expression::do_determine_type(const Type_context* context)
  3223  {
  3224    if (this->type_ != NULL && !this->type_->is_abstract())
  3225      ;
  3226    else if (context->type != NULL && context->type->is_numeric_type())
  3227      this->type_ = context->type;
  3228    else if (!context->may_be_abstract)
  3229      this->type_ = Type::lookup_complex_type("complex128");
  3230  }
  3231  
  3232  // Check the type of a complex value.
  3233  
  3234  void
  3235  Complex_expression::do_check_types(Gogo*)
  3236  {
  3237    Type* type = this->type_;
  3238    if (type == NULL)
  3239      return;
  3240    Numeric_constant nc;
  3241    nc.set_complex(NULL, this->val_);
  3242    if (!nc.set_type(this->type_, true, this->location()))
  3243      this->set_is_error();
  3244  }
  3245  
  3246  // Get the backend representation for a complex constant.
  3247  
  3248  Bexpression*
  3249  Complex_expression::do_get_backend(Translate_context* context)
  3250  {
  3251    if (this->is_error_expression()
  3252        || (this->type_ != NULL && this->type_->is_error_type()))
  3253      {
  3254        go_assert(saw_errors());
  3255        return context->gogo()->backend()->error_expression();
  3256      }
  3257  
  3258    Type* resolved_type;
  3259    if (this->type_ != NULL && !this->type_->is_abstract())
  3260      resolved_type = this->type_;
  3261    else if (this->type_ != NULL && this->type_->integer_type() != NULL)
  3262      {
  3263        // We are converting to an abstract integer type.
  3264        resolved_type = Type::lookup_integer_type("int");
  3265      }
  3266    else if (this->type_ != NULL && this->type_->float_type() != NULL)
  3267      {
  3268        // We are converting to an abstract float type.
  3269        resolved_type = Type::lookup_float_type("float64");
  3270      }
  3271    else
  3272      {
  3273        // If we still have an abstract type here, this is being
  3274        // used in a constant expression which didn't get reduced.  We
  3275        // just use complex128 and hope for the best.
  3276        resolved_type = Type::lookup_complex_type("complex128");
  3277      }
  3278  
  3279    Numeric_constant nc;
  3280    nc.set_complex(resolved_type, this->val_);
  3281    return Expression::backend_numeric_constant_expression(context, &nc);
  3282  }
  3283  
  3284  // Write REAL/IMAG to export data.
  3285  
  3286  void
  3287  Complex_expression::export_complex(String_dump* exp, const mpc_t val)
  3288  {
  3289    if (!mpfr_zero_p(mpc_realref(val)))
  3290      {
  3291        Float_expression::export_float(exp, mpc_realref(val));
  3292        if (mpfr_sgn(mpc_imagref(val)) >= 0)
  3293  	exp->write_c_string("+");
  3294      }
  3295    Float_expression::export_float(exp, mpc_imagref(val));
  3296    exp->write_c_string("i");
  3297  }
  3298  
  3299  // Export a complex number in a constant expression.
  3300  
  3301  void
  3302  Complex_expression::do_export(Export_function_body* efb) const
  3303  {
  3304    bool exported_type = Expression::export_constant_type(efb, this->type_);
  3305  
  3306    Complex_expression::export_complex(efb, this->val_);
  3307    // A trailing space lets us reliably identify the end of the number.
  3308    efb->write_c_string(" ");
  3309  
  3310    Expression::finish_export_constant_type(efb, exported_type);
  3311  }
  3312  
  3313  // Dump a complex expression to the dump file.
  3314  
  3315  void
  3316  Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  3317  {
  3318    Complex_expression::export_complex(ast_dump_context, this->val_);
  3319  }
  3320  
  3321  // Make a complex expression.
  3322  
  3323  Expression*
  3324  Expression::make_complex(const mpc_t* val, Type* type, Location location)
  3325  {
  3326    return new Complex_expression(val, type, location);
  3327  }
  3328  
  3329  // Find a named object in an expression.
  3330  
  3331  class Find_named_object : public Traverse
  3332  {
  3333   public:
  3334    Find_named_object(Named_object* no)
  3335      : Traverse(traverse_expressions),
  3336        no_(no), found_(false)
  3337    { }
  3338  
  3339    // Whether we found the object.
  3340    bool
  3341    found() const
  3342    { return this->found_; }
  3343  
  3344   protected:
  3345    int
  3346    expression(Expression**);
  3347  
  3348   private:
  3349    // The object we are looking for.
  3350    Named_object* no_;
  3351    // Whether we found it.
  3352    bool found_;
  3353  };
  3354  
  3355  // Class Const_expression.
  3356  
  3357  // Traversal.
  3358  
  3359  int
  3360  Const_expression::do_traverse(Traverse* traverse)
  3361  {
  3362    if (this->type_ != NULL)
  3363      return Type::traverse(this->type_, traverse);
  3364    return TRAVERSE_CONTINUE;
  3365  }
  3366  
  3367  // Whether this is the zero value.
  3368  
  3369  bool
  3370  Const_expression::do_is_zero_value() const
  3371  {
  3372    return this->constant_->const_value()->expr()->is_zero_value();
  3373  }
  3374  
  3375  // Lower a constant expression.  This is where we convert the
  3376  // predeclared constant iota into an integer value.
  3377  
  3378  Expression*
  3379  Const_expression::do_lower(Gogo* gogo, Named_object*,
  3380  			   Statement_inserter*, int iota_value)
  3381  {
  3382    if (this->constant_->const_value()->expr()->classification()
  3383        == EXPRESSION_IOTA)
  3384      {
  3385        if (iota_value == -1)
  3386  	{
  3387  	  go_error_at(this->location(),
  3388  		      "iota is only defined in const declarations");
  3389  	  iota_value = 0;
  3390  	}
  3391        return Expression::make_integer_ul(iota_value, NULL, this->location());
  3392      }
  3393  
  3394    // Make sure that the constant itself has been lowered.
  3395    gogo->lower_constant(this->constant_);
  3396  
  3397    return this;
  3398  }
  3399  
  3400  // Return a numeric constant value.
  3401  
  3402  bool
  3403  Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
  3404  {
  3405    if (this->seen_)
  3406      return false;
  3407  
  3408    Expression* e = this->constant_->const_value()->expr();
  3409  
  3410    this->seen_ = true;
  3411  
  3412    bool r = e->numeric_constant_value(nc);
  3413  
  3414    this->seen_ = false;
  3415  
  3416    Type* ctype;
  3417    if (this->type_ != NULL)
  3418      ctype = this->type_;
  3419    else
  3420      ctype = this->constant_->const_value()->type();
  3421    if (r && ctype != NULL)
  3422      {
  3423        if (!nc->set_type(ctype, false, this->location()))
  3424  	return false;
  3425      }
  3426  
  3427    return r;
  3428  }
  3429  
  3430  bool
  3431  Const_expression::do_string_constant_value(std::string* val) const
  3432  {
  3433    if (this->seen_)
  3434      return false;
  3435  
  3436    Expression* e = this->constant_->const_value()->expr();
  3437  
  3438    this->seen_ = true;
  3439    bool ok = e->string_constant_value(val);
  3440    this->seen_ = false;
  3441  
  3442    return ok;
  3443  }
  3444  
  3445  bool
  3446  Const_expression::do_boolean_constant_value(bool* val) const
  3447  {
  3448    if (this->seen_)
  3449      return false;
  3450  
  3451    Expression* e = this->constant_->const_value()->expr();
  3452  
  3453    this->seen_ = true;
  3454    bool ok = e->boolean_constant_value(val);
  3455    this->seen_ = false;
  3456  
  3457    return ok;
  3458  }
  3459  
  3460  // Return the type of the const reference.
  3461  
  3462  Type*
  3463  Const_expression::do_type()
  3464  {
  3465    if (this->type_ != NULL)
  3466      return this->type_;
  3467  
  3468    Named_constant* nc = this->constant_->const_value();
  3469  
  3470    if (this->seen_ || nc->lowering())
  3471      {
  3472        if (nc->type() == NULL || !nc->type()->is_error_type())
  3473  	{
  3474  	  Location loc = this->location();
  3475  	  if (!this->seen_)
  3476  	    loc = nc->location();
  3477  	  go_error_at(loc, "constant refers to itself");
  3478  	}
  3479        this->set_is_error();
  3480        this->type_ = Type::make_error_type();
  3481        nc->set_type(this->type_);
  3482        return this->type_;
  3483      }
  3484  
  3485    this->seen_ = true;
  3486  
  3487    Type* ret = nc->type();
  3488  
  3489    if (ret != NULL)
  3490      {
  3491        this->seen_ = false;
  3492        return ret;
  3493      }
  3494  
  3495    // During parsing, a named constant may have a NULL type, but we
  3496    // must not return a NULL type here.
  3497    ret = nc->expr()->type();
  3498  
  3499    this->seen_ = false;
  3500  
  3501    if (ret->is_error_type())
  3502      nc->set_type(ret);
  3503  
  3504    return ret;
  3505  }
  3506  
  3507  // Set the type of the const reference.
  3508  
  3509  void
  3510  Const_expression::do_determine_type(const Type_context* context)
  3511  {
  3512    Type* ctype = this->constant_->const_value()->type();
  3513    Type* cetype = (ctype != NULL
  3514  		  ? ctype
  3515  		  : this->constant_->const_value()->expr()->type());
  3516    if (ctype != NULL && !ctype->is_abstract())
  3517      ;
  3518    else if (context->type != NULL
  3519  	   && context->type->is_numeric_type()
  3520  	   && cetype->is_numeric_type())
  3521      this->type_ = context->type;
  3522    else if (context->type != NULL
  3523  	   && context->type->is_string_type()
  3524  	   && cetype->is_string_type())
  3525      this->type_ = context->type;
  3526    else if (context->type != NULL
  3527  	   && context->type->is_boolean_type()
  3528  	   && cetype->is_boolean_type())
  3529      this->type_ = context->type;
  3530    else if (!context->may_be_abstract)
  3531      {
  3532        if (cetype->is_abstract())
  3533  	cetype = cetype->make_non_abstract_type();
  3534        this->type_ = cetype;
  3535      }
  3536  }
  3537  
  3538  // Check for a loop in which the initializer of a constant refers to
  3539  // the constant itself.
  3540  
  3541  void
  3542  Const_expression::check_for_init_loop()
  3543  {
  3544    if (this->type_ != NULL && this->type_->is_error())
  3545      return;
  3546  
  3547    if (this->seen_)
  3548      {
  3549        this->report_error(_("constant refers to itself"));
  3550        this->type_ = Type::make_error_type();
  3551        return;
  3552      }
  3553  
  3554    Expression* init = this->constant_->const_value()->expr();
  3555    Find_named_object find_named_object(this->constant_);
  3556  
  3557    this->seen_ = true;
  3558    Expression::traverse(&init, &find_named_object);
  3559    this->seen_ = false;
  3560  
  3561    if (find_named_object.found())
  3562      {
  3563        if (this->type_ == NULL || !this->type_->is_error())
  3564  	{
  3565  	  this->report_error(_("constant refers to itself"));
  3566  	  this->type_ = Type::make_error_type();
  3567  	}
  3568        return;
  3569      }
  3570  }
  3571  
  3572  // Check types of a const reference.
  3573  
  3574  void
  3575  Const_expression::do_check_types(Gogo*)
  3576  {
  3577    if (this->type_ != NULL && this->type_->is_error())
  3578      return;
  3579  
  3580    this->check_for_init_loop();
  3581  
  3582    // Check that numeric constant fits in type.
  3583    if (this->type_ != NULL && this->type_->is_numeric_type())
  3584      {
  3585        Numeric_constant nc;
  3586        if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
  3587  	{
  3588  	  if (!nc.set_type(this->type_, true, this->location()))
  3589  	    this->set_is_error();
  3590  	}
  3591      }
  3592  }
  3593  
  3594  // Return the backend representation for a const reference.
  3595  
  3596  Bexpression*
  3597  Const_expression::do_get_backend(Translate_context* context)
  3598  {
  3599    if (this->is_error_expression()
  3600        || (this->type_ != NULL && this->type_->is_error()))
  3601      {
  3602        go_assert(saw_errors());
  3603        return context->backend()->error_expression();
  3604      }
  3605  
  3606    // If the type has been set for this expression, but the underlying
  3607    // object is an abstract int or float, we try to get the abstract
  3608    // value.  Otherwise we may lose something in the conversion.
  3609    Expression* expr = this->constant_->const_value()->expr();
  3610    if (this->type_ != NULL
  3611        && this->type_->is_numeric_type()
  3612        && (this->constant_->const_value()->type() == NULL
  3613  	  || this->constant_->const_value()->type()->is_abstract()))
  3614      {
  3615        Numeric_constant nc;
  3616        if (expr->numeric_constant_value(&nc)
  3617  	  && nc.set_type(this->type_, false, this->location()))
  3618  	{
  3619  	  Expression* e = nc.expression(this->location());
  3620  	  return e->get_backend(context);
  3621  	}
  3622      }
  3623  
  3624    if (this->type_ != NULL)
  3625      expr = Expression::make_cast(this->type_, expr, this->location());
  3626    return expr->get_backend(context);
  3627  }
  3628  
  3629  // When exporting a reference to a const as part of a const
  3630  // expression, we export the value.  We ignore the fact that it has
  3631  // a name.
  3632  
  3633  void
  3634  Const_expression::do_export(Export_function_body* efb) const
  3635  {
  3636    this->constant_->const_value()->expr()->export_expression(efb);
  3637  }
  3638  
  3639  // Dump ast representation for constant expression.
  3640  
  3641  void
  3642  Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  3643  {
  3644    ast_dump_context->ostream() << this->constant_->name();
  3645  }
  3646  
  3647  // Make a reference to a constant in an expression.
  3648  
  3649  Expression*
  3650  Expression::make_const_reference(Named_object* constant,
  3651  				 Location location)
  3652  {
  3653    return new Const_expression(constant, location);
  3654  }
  3655  
  3656  // Find a named object in an expression.
  3657  
  3658  int
  3659  Find_named_object::expression(Expression** pexpr)
  3660  {
  3661    switch ((*pexpr)->classification())
  3662      {
  3663      case Expression::EXPRESSION_CONST_REFERENCE:
  3664        {
  3665  	Const_expression* ce = static_cast<Const_expression*>(*pexpr);
  3666  	if (ce->named_object() == this->no_)
  3667  	  break;
  3668  
  3669  	// We need to check a constant initializer explicitly, as
  3670  	// loops here will not be caught by the loop checking for
  3671  	// variable initializers.
  3672  	ce->check_for_init_loop();
  3673  
  3674  	return TRAVERSE_CONTINUE;
  3675        }
  3676  
  3677      case Expression::EXPRESSION_VAR_REFERENCE:
  3678        if ((*pexpr)->var_expression()->named_object() == this->no_)
  3679  	break;
  3680        return TRAVERSE_CONTINUE;
  3681      case Expression::EXPRESSION_FUNC_REFERENCE:
  3682        if ((*pexpr)->func_expression()->named_object() == this->no_)
  3683  	break;
  3684        return TRAVERSE_CONTINUE;
  3685      default:
  3686        return TRAVERSE_CONTINUE;
  3687      }
  3688    this->found_ = true;
  3689    return TRAVERSE_EXIT;
  3690  }
  3691  
  3692  // The nil value.
  3693  
  3694  class Nil_expression : public Expression
  3695  {
  3696   public:
  3697    Nil_expression(Location location)
  3698      : Expression(EXPRESSION_NIL, location)
  3699    { }
  3700  
  3701    static Expression*
  3702    do_import(Import_expression*, Location);
  3703  
  3704   protected:
  3705    bool
  3706    do_is_constant() const
  3707    { return true; }
  3708  
  3709    bool
  3710    do_is_zero_value() const
  3711    { return true; }
  3712  
  3713    bool
  3714    do_is_static_initializer() const
  3715    { return true; }
  3716  
  3717    Type*
  3718    do_type()
  3719    { return Type::make_nil_type(); }
  3720  
  3721    void
  3722    do_determine_type(const Type_context*)
  3723    { }
  3724  
  3725    Expression*
  3726    do_copy()
  3727    { return this; }
  3728  
  3729    Bexpression*
  3730    do_get_backend(Translate_context* context)
  3731    { return context->backend()->nil_pointer_expression(); }
  3732  
  3733    int
  3734    do_inlining_cost() const
  3735    { return 1; }
  3736  
  3737    void
  3738    do_export(Export_function_body* efb) const
  3739    { efb->write_c_string("$nil"); }
  3740  
  3741    void
  3742    do_dump_expression(Ast_dump_context* ast_dump_context) const
  3743    { ast_dump_context->ostream() << "nil"; }
  3744  };
  3745  
  3746  // Import a nil expression.
  3747  
  3748  Expression*
  3749  Nil_expression::do_import(Import_expression* imp, Location loc)
  3750  {
  3751    if (imp->version() >= EXPORT_FORMAT_V3)
  3752      imp->require_c_string("$");
  3753    imp->require_c_string("nil");
  3754    return Expression::make_nil(loc);
  3755  }
  3756  
  3757  // Make a nil expression.
  3758  
  3759  Expression*
  3760  Expression::make_nil(Location location)
  3761  {
  3762    return new Nil_expression(location);
  3763  }
  3764  
  3765  // The value of the predeclared constant iota.  This is little more
  3766  // than a marker.  This will be lowered to an integer in
  3767  // Const_expression::do_lower, which is where we know the value that
  3768  // it should have.
  3769  
  3770  class Iota_expression : public Parser_expression
  3771  {
  3772   public:
  3773    Iota_expression(Location location)
  3774      : Parser_expression(EXPRESSION_IOTA, location)
  3775    { }
  3776  
  3777   protected:
  3778    Expression*
  3779    do_lower(Gogo*, Named_object*, Statement_inserter*, int)
  3780    { go_unreachable(); }
  3781  
  3782    // There should only ever be one of these.
  3783    Expression*
  3784    do_copy()
  3785    { go_unreachable(); }
  3786  
  3787    void
  3788    do_dump_expression(Ast_dump_context* ast_dump_context) const
  3789    { ast_dump_context->ostream() << "iota"; }
  3790  };
  3791  
  3792  // Make an iota expression.  This is only called for one case: the
  3793  // value of the predeclared constant iota.
  3794  
  3795  Expression*
  3796  Expression::make_iota()
  3797  {
  3798    static Iota_expression iota_expression(Linemap::unknown_location());
  3799    return &iota_expression;
  3800  }
  3801  
  3802  // Class Type_conversion_expression.
  3803  
  3804  // Traversal.
  3805  
  3806  int
  3807  Type_conversion_expression::do_traverse(Traverse* traverse)
  3808  {
  3809    if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
  3810        || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
  3811      return TRAVERSE_EXIT;
  3812    return TRAVERSE_CONTINUE;
  3813  }
  3814  
  3815  // Convert to a constant at lowering time.  Also lower conversions
  3816  // from slice to pointer-to-array, as they can panic.
  3817  
  3818  Expression*
  3819  Type_conversion_expression::do_lower(Gogo*, Named_object*,
  3820  				     Statement_inserter* inserter, int)
  3821  {
  3822    Type* type = this->type_;
  3823    Expression* val = this->expr_;
  3824    Location location = this->location();
  3825  
  3826    if (type->is_numeric_type())
  3827      {
  3828        Numeric_constant nc;
  3829        if (val->numeric_constant_value(&nc))
  3830  	{
  3831  	  if (!nc.set_type(type, true, location))
  3832  	    return Expression::make_error(location);
  3833  	  return nc.expression(location);
  3834  	}
  3835      }
  3836  
  3837    // According to the language specification on string conversions
  3838    // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
  3839    // When converting an integer into a string, the string will be a UTF-8
  3840    // representation of the integer and integers "outside the range of valid
  3841    // Unicode code points are converted to '\uFFFD'."
  3842    if (type->is_string_type())
  3843      {
  3844        Numeric_constant nc;
  3845        if (val->numeric_constant_value(&nc) && nc.is_int())
  3846          {
  3847            // An integer value doesn't fit in the Unicode code point range if it
  3848            // overflows the Go "int" type or is negative.
  3849            unsigned long ul;
  3850            if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
  3851                || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
  3852              return Expression::make_string("\ufffd", location);
  3853          }
  3854      }
  3855  
  3856    if (type->is_slice_type())
  3857      {
  3858        Type* element_type = type->array_type()->element_type()->forwarded();
  3859        bool is_byte = (element_type->integer_type() != NULL
  3860  		      && element_type->integer_type()->is_byte());
  3861        bool is_rune = (element_type->integer_type() != NULL
  3862  		      && element_type->integer_type()->is_rune());
  3863        if (is_byte || is_rune)
  3864  	{
  3865  	  std::string s;
  3866  	  if (val->string_constant_value(&s))
  3867  	    {
  3868  	      Expression_list* vals = new Expression_list();
  3869  	      if (is_byte)
  3870  		{
  3871  		  for (std::string::const_iterator p = s.begin();
  3872  		       p != s.end();
  3873  		       p++)
  3874  		    {
  3875  		      unsigned char c = static_cast<unsigned char>(*p);
  3876  		      vals->push_back(Expression::make_integer_ul(c,
  3877  								  element_type,
  3878  								  location));
  3879  		    }
  3880  		}
  3881  	      else
  3882  		{
  3883  		  const char *p = s.data();
  3884  		  const char *pend = s.data() + s.length();
  3885  		  while (p < pend)
  3886  		    {
  3887  		      unsigned int c;
  3888  		      int adv = Lex::fetch_char(p, &c);
  3889  		      if (adv == 0)
  3890  			{
  3891  			  go_warning_at(this->location(), 0,
  3892  				     "invalid UTF-8 encoding");
  3893  			  adv = 1;
  3894  			}
  3895  		      p += adv;
  3896  		      vals->push_back(Expression::make_integer_ul(c,
  3897  								  element_type,
  3898  								  location));
  3899  		    }
  3900  		}
  3901  
  3902  	      return Expression::make_slice_composite_literal(type, vals,
  3903  							      location);
  3904  	    }
  3905  	}
  3906      }
  3907  
  3908    if (type->points_to() != NULL
  3909        && type->points_to()->array_type() != NULL
  3910        && !type->points_to()->is_slice_type()
  3911        && val->type()->is_slice_type()
  3912        && Type::are_identical(type->points_to()->array_type()->element_type(),
  3913  			     val->type()->array_type()->element_type(),
  3914  			     0, NULL))
  3915      {
  3916        Temporary_statement* val_temp = NULL;
  3917        if (!val->is_multi_eval_safe())
  3918  	{
  3919  	  val_temp = Statement::make_temporary(val->type(), NULL, location);
  3920  	  inserter->insert(val_temp);
  3921  	  val = Expression::make_set_and_use_temporary(val_temp, val,
  3922  						       location);
  3923  	}
  3924  
  3925        Type* int_type = Type::lookup_integer_type("int");
  3926        Temporary_statement* vallen_temp =
  3927  	Statement::make_temporary(int_type, NULL, location);
  3928        inserter->insert(vallen_temp);
  3929  
  3930        Expression* arrlen = type->points_to()->array_type()->length();
  3931        Expression* vallen =
  3932  	Expression::make_slice_info(val, Expression::SLICE_INFO_LENGTH,
  3933  				    location);
  3934        vallen = Expression::make_set_and_use_temporary(vallen_temp, vallen,
  3935  						      location);
  3936        Expression* cond = Expression::make_binary(OPERATOR_GT, arrlen, vallen,
  3937  						 location);
  3938  
  3939        vallen = Expression::make_temporary_reference(vallen_temp, location);
  3940        Expression* panic = Runtime::make_call(Runtime::PANIC_SLICE_CONVERT,
  3941  					     location, 2, arrlen, vallen);
  3942  
  3943        Expression* nil = Expression::make_nil(location);
  3944        Expression* check = Expression::make_conditional(cond, panic, nil,
  3945  						       location);
  3946  
  3947        if (val_temp == NULL)
  3948  	val = val->copy();
  3949        else
  3950  	val = Expression::make_temporary_reference(val_temp, location);
  3951        Expression* ptr =
  3952  	Expression::make_slice_info(val, Expression::SLICE_INFO_VALUE_POINTER,
  3953  				    location);
  3954        ptr = Expression::make_unsafe_cast(type, ptr, location);
  3955  
  3956        return Expression::make_compound(check, ptr, location);
  3957      }
  3958  
  3959    return this;
  3960  }
  3961  
  3962  // Flatten a type conversion by using a temporary variable for the slice
  3963  // in slice to string conversions.
  3964  
  3965  Expression*
  3966  Type_conversion_expression::do_flatten(Gogo*, Named_object*,
  3967                                         Statement_inserter* inserter)
  3968  {
  3969    if (this->type()->is_error_type() || this->expr_->is_error_expression())
  3970      {
  3971        go_assert(saw_errors());
  3972        return Expression::make_error(this->location());
  3973      }
  3974  
  3975    if (((this->type()->is_string_type()
  3976          && this->expr_->type()->is_slice_type())
  3977         || this->expr_->type()->interface_type() != NULL)
  3978        && !this->expr_->is_multi_eval_safe())
  3979      {
  3980        Temporary_statement* temp =
  3981            Statement::make_temporary(NULL, this->expr_, this->location());
  3982        inserter->insert(temp);
  3983        this->expr_ = Expression::make_temporary_reference(temp, this->location());
  3984      }
  3985  
  3986    // For interface conversion and string to/from slice conversions,
  3987    // decide if we can allocate on stack.
  3988    if (this->type()->interface_type() != NULL
  3989        || this->type()->is_string_type()
  3990        || this->expr_->type()->is_string_type())
  3991      {
  3992        Node* n = Node::make_node(this);
  3993        if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
  3994          this->no_escape_ = true;
  3995      }
  3996    return this;
  3997  }
  3998  
  3999  // Return whether a type conversion is a constant.
  4000  
  4001  bool
  4002  Type_conversion_expression::do_is_constant() const
  4003  {
  4004    if (!this->expr_->is_constant())
  4005      return false;
  4006  
  4007    // A conversion to a type that may not be used as a constant is not
  4008    // a constant.  For example, []byte(nil).
  4009    Type* type = this->type_;
  4010    if (type->integer_type() == NULL
  4011        && type->float_type() == NULL
  4012        && type->complex_type() == NULL
  4013        && !type->is_boolean_type()
  4014        && !type->is_string_type())
  4015      return false;
  4016  
  4017    return true;
  4018  }
  4019  
  4020  // Return whether a type conversion is a zero value.
  4021  
  4022  bool
  4023  Type_conversion_expression::do_is_zero_value() const
  4024  {
  4025    if (!this->expr_->is_zero_value())
  4026      return false;
  4027  
  4028    // Some type conversion from zero value is still not zero value.
  4029    // For example, []byte("") or interface{}(0).
  4030    // Conservatively, only report true if the RHS is nil.
  4031    Type* type = this->type_;
  4032    if (type->integer_type() == NULL
  4033        && type->float_type() == NULL
  4034        && type->complex_type() == NULL
  4035        && !type->is_boolean_type()
  4036        && !type->is_string_type())
  4037      return this->expr_->is_nil_expression();
  4038  
  4039    return true;
  4040  }
  4041  
  4042  // Return whether a type conversion can be used in a constant
  4043  // initializer.
  4044  
  4045  bool
  4046  Type_conversion_expression::do_is_static_initializer() const
  4047  {
  4048    Type* type = this->type_;
  4049    Type* expr_type = this->expr_->type();
  4050  
  4051    if (type->interface_type() != NULL
  4052        || expr_type->interface_type() != NULL)
  4053      return false;
  4054  
  4055    if (!this->expr_->is_static_initializer())
  4056      return false;
  4057  
  4058    if (Type::are_identical(type, expr_type,
  4059  			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
  4060  			  NULL))
  4061      return true;
  4062  
  4063    if (type->is_string_type() && expr_type->is_string_type())
  4064      return true;
  4065  
  4066    if ((type->is_numeric_type()
  4067         || type->is_boolean_type()
  4068         || type->points_to() != NULL)
  4069        && (expr_type->is_numeric_type()
  4070  	  || expr_type->is_boolean_type()
  4071  	  || expr_type->points_to() != NULL))
  4072      return true;
  4073  
  4074    return false;
  4075  }
  4076  
  4077  // Return the constant numeric value if there is one.
  4078  
  4079  bool
  4080  Type_conversion_expression::do_numeric_constant_value(
  4081      Numeric_constant* nc) const
  4082  {
  4083    if (!this->type_->is_numeric_type())
  4084      return false;
  4085    if (!this->expr_->numeric_constant_value(nc))
  4086      return false;
  4087    return nc->set_type(this->type_, false, this->location());
  4088  }
  4089  
  4090  // Return the constant string value if there is one.
  4091  
  4092  bool
  4093  Type_conversion_expression::do_string_constant_value(std::string* val) const
  4094  {
  4095    if (this->type_->is_string_type()
  4096        && this->expr_->type()->integer_type() != NULL)
  4097      {
  4098        Numeric_constant nc;
  4099        if (this->expr_->numeric_constant_value(&nc))
  4100  	{
  4101  	  unsigned long ival;
  4102  	  if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
  4103  	    {
  4104  	      unsigned int cval = static_cast<unsigned int>(ival);
  4105  	      if (static_cast<unsigned long>(cval) != ival)
  4106  		{
  4107  		  go_warning_at(this->location(), 0,
  4108  				"unicode code point 0x%lx out of range",
  4109  				ival);
  4110  		  cval = 0xfffd; // Unicode "replacement character."
  4111  		}
  4112  	      val->clear();
  4113  	      Lex::append_char(cval, true, val, this->location());
  4114  	      return true;
  4115  	    }
  4116  	}
  4117      }
  4118  
  4119    // FIXME: Could handle conversion from const []int here.
  4120  
  4121    return false;
  4122  }
  4123  
  4124  // Return the constant boolean value if there is one.
  4125  
  4126  bool
  4127  Type_conversion_expression::do_boolean_constant_value(bool* val) const
  4128  {
  4129    if (!this->type_->is_boolean_type())
  4130      return false;
  4131    return this->expr_->boolean_constant_value(val);
  4132  }
  4133  
  4134  // Determine the resulting type of the conversion.
  4135  
  4136  void
  4137  Type_conversion_expression::do_determine_type(const Type_context*)
  4138  {
  4139    Type_context subcontext(this->type_, false);
  4140    this->expr_->determine_type(&subcontext);
  4141  }
  4142  
  4143  // Check that types are convertible.
  4144  
  4145  void
  4146  Type_conversion_expression::do_check_types(Gogo*)
  4147  {
  4148    Type* type = this->type_;
  4149    Type* expr_type = this->expr_->type();
  4150    std::string reason;
  4151  
  4152    if (type->is_error() || expr_type->is_error())
  4153      {
  4154        this->set_is_error();
  4155        return;
  4156      }
  4157  
  4158    if (this->may_convert_function_types_
  4159        && type->function_type() != NULL
  4160        && expr_type->function_type() != NULL)
  4161      return;
  4162  
  4163    if (Type::are_convertible(type, expr_type, &reason))
  4164      return;
  4165  
  4166    go_error_at(this->location(), "%s", reason.c_str());
  4167    this->set_is_error();
  4168  }
  4169  
  4170  // Copy.
  4171  
  4172  Expression*
  4173  Type_conversion_expression::do_copy()
  4174  {
  4175    Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
  4176                                                     this->expr_->copy(),
  4177                                                     this->location());
  4178    ret->conversion_expression()->set_no_copy(this->no_copy_);
  4179    return ret;
  4180  }
  4181  
  4182  // Get the backend representation for a type conversion.
  4183  
  4184  Bexpression*
  4185  Type_conversion_expression::do_get_backend(Translate_context* context)
  4186  {
  4187    Type* type = this->type_;
  4188    Type* expr_type = this->expr_->type();
  4189  
  4190    Gogo* gogo = context->gogo();
  4191    Btype* btype = type->get_backend(gogo);
  4192    Location loc = this->location();
  4193  
  4194    if (Type::are_identical(type, expr_type,
  4195  			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
  4196  			  NULL))
  4197      {
  4198        Bexpression* bexpr = this->expr_->get_backend(context);
  4199        return gogo->backend()->convert_expression(btype, bexpr, loc);
  4200      }
  4201    else if (type->interface_type() != NULL
  4202             && expr_type->interface_type() == NULL)
  4203      {
  4204        Expression* conversion =
  4205            Expression::convert_type_to_interface(type, this->expr_,
  4206                                                  this->no_escape_, loc);
  4207        return conversion->get_backend(context);
  4208      }
  4209    else if (type->interface_type() != NULL
  4210  	   || expr_type->interface_type() != NULL)
  4211      {
  4212        Expression* conversion =
  4213            Expression::convert_for_assignment(gogo, type, this->expr_,
  4214                                               loc);
  4215        return conversion->get_backend(context);
  4216      }
  4217    else if (type->is_string_type()
  4218  	   && expr_type->integer_type() != NULL)
  4219      {
  4220        mpz_t intval;
  4221        Numeric_constant nc;
  4222        if (this->expr_->numeric_constant_value(&nc)
  4223  	  && nc.to_int(&intval))
  4224  	{
  4225  	  std::string s;
  4226            unsigned int x;
  4227            if (mpz_fits_uint_p(intval))
  4228              x = mpz_get_ui(intval);
  4229            else
  4230              {
  4231                char* ms = mpz_get_str(NULL, 16, intval);
  4232                go_warning_at(loc, 0,
  4233                              "unicode code point 0x%s out of range in string",
  4234                              ms);
  4235                free(ms);
  4236                x = 0xfffd;
  4237              }
  4238  	  Lex::append_char(x, true, &s, loc);
  4239  	  mpz_clear(intval);
  4240  	  Expression* se = Expression::make_string(s, loc);
  4241  	  return se->get_backend(context);
  4242  	}
  4243  
  4244        Expression* buf;
  4245        if (this->no_escape_)
  4246          {
  4247            Type* byte_type = Type::lookup_integer_type("uint8");
  4248            Expression* buflen =
  4249              Expression::make_integer_ul(4, NULL, loc);
  4250            Type* array_type = Type::make_array_type(byte_type, buflen);
  4251            buf = Expression::make_allocation(array_type, loc);
  4252            buf->allocation_expression()->set_allocate_on_stack();
  4253            buf->allocation_expression()->set_no_zero();
  4254          }
  4255        else
  4256          buf = Expression::make_nil(loc);
  4257        Expression* i2s_expr =
  4258          Runtime::make_call(Runtime::INTSTRING, loc, 2, buf, this->expr_);
  4259        return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
  4260      }
  4261    else if (type->is_string_type() && expr_type->is_slice_type())
  4262      {
  4263        Array_type* a = expr_type->array_type();
  4264        Type* e = a->element_type()->forwarded();
  4265        go_assert(e->integer_type() != NULL);
  4266        go_assert(this->expr_->is_multi_eval_safe());
  4267  
  4268        Expression* buf;
  4269        if (this->no_escape_ && !this->no_copy_)
  4270          {
  4271            Type* byte_type = Type::lookup_integer_type("uint8");
  4272            Expression* buflen =
  4273              Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
  4274            Type* array_type = Type::make_array_type(byte_type, buflen);
  4275            buf = Expression::make_allocation(array_type, loc);
  4276            buf->allocation_expression()->set_allocate_on_stack();
  4277            buf->allocation_expression()->set_no_zero();
  4278          }
  4279        else
  4280          buf = Expression::make_nil(loc);
  4281  
  4282        if (e->integer_type()->is_byte())
  4283          {
  4284  	  Expression* ptr =
  4285  	    Expression::make_slice_info(this->expr_, SLICE_INFO_VALUE_POINTER,
  4286  					loc);
  4287  	  Expression* len =
  4288  	    Expression::make_slice_info(this->expr_, SLICE_INFO_LENGTH, loc);
  4289            if (this->no_copy_)
  4290              {
  4291                if (gogo->debug_optimization())
  4292                  go_debug(loc, "no copy string([]byte)");
  4293                Expression* str = Expression::make_string_value(ptr, len, loc);
  4294                return str->get_backend(context);
  4295              }
  4296  	  return Runtime::make_call(Runtime::SLICEBYTETOSTRING, loc, 3, buf,
  4297  				    ptr, len)->get_backend(context);
  4298          }
  4299        else
  4300          {
  4301            go_assert(e->integer_type()->is_rune());
  4302  	  return Runtime::make_call(Runtime::SLICERUNETOSTRING, loc, 2, buf,
  4303  				    this->expr_)->get_backend(context);
  4304  	}
  4305      }
  4306    else if (type->is_slice_type() && expr_type->is_string_type())
  4307      {
  4308        Type* e = type->array_type()->element_type()->forwarded();
  4309        go_assert(e->integer_type() != NULL);
  4310  
  4311        Runtime::Function code;
  4312        if (e->integer_type()->is_byte())
  4313  	code = Runtime::STRINGTOSLICEBYTE;
  4314        else
  4315  	{
  4316  	  go_assert(e->integer_type()->is_rune());
  4317  	  code = Runtime::STRINGTOSLICERUNE;
  4318  	}
  4319  
  4320        Expression* buf;
  4321        if (this->no_escape_)
  4322          {
  4323            Expression* buflen =
  4324              Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
  4325            Type* array_type = Type::make_array_type(e, buflen);
  4326            buf = Expression::make_allocation(array_type, loc);
  4327            buf->allocation_expression()->set_allocate_on_stack();
  4328            buf->allocation_expression()->set_no_zero();
  4329          }
  4330        else
  4331          buf = Expression::make_nil(loc);
  4332        Expression* s2a = Runtime::make_call(code, loc, 2, buf, this->expr_);
  4333        return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
  4334      }
  4335    else if (type->is_numeric_type())
  4336      {
  4337        go_assert(Type::are_convertible(type, expr_type, NULL));
  4338        Bexpression* bexpr = this->expr_->get_backend(context);
  4339        return gogo->backend()->convert_expression(btype, bexpr, loc);
  4340      }
  4341    else if ((type->is_unsafe_pointer_type()
  4342  	    && (expr_type->points_to() != NULL
  4343                  || expr_type->integer_type()))
  4344             || (expr_type->is_unsafe_pointer_type()
  4345  	       && type->points_to() != NULL)
  4346             || (this->may_convert_function_types_
  4347                 && type->function_type() != NULL
  4348                 && expr_type->function_type() != NULL))
  4349      {
  4350        Bexpression* bexpr = this->expr_->get_backend(context);
  4351        return gogo->backend()->convert_expression(btype, bexpr, loc);
  4352      }
  4353    else
  4354      {
  4355        Expression* conversion =
  4356            Expression::convert_for_assignment(gogo, type, this->expr_, loc);
  4357        return conversion->get_backend(context);
  4358      }
  4359  }
  4360  
  4361  // Cost of inlining a type conversion.
  4362  
  4363  int
  4364  Type_conversion_expression::do_inlining_cost() const
  4365  {
  4366    Type* type = this->type_;
  4367    Type* expr_type = this->expr_->type();
  4368    if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
  4369      return 10;
  4370    else if (type->is_string_type() && expr_type->integer_type() != NULL)
  4371      return 10;
  4372    else if (type->is_string_type() && expr_type->is_slice_type())
  4373      return 10;
  4374    else if (type->is_slice_type() && expr_type->is_string_type())
  4375      return 10;
  4376    else
  4377      return 1;
  4378  }
  4379  
  4380  // Output a type conversion in a constant expression.
  4381  
  4382  void
  4383  Type_conversion_expression::do_export(Export_function_body* efb) const
  4384  {
  4385    efb->write_c_string("$convert(");
  4386    efb->write_type(this->type_);
  4387    efb->write_c_string(", ");
  4388  
  4389    Type* old_context = efb->type_context();
  4390    efb->set_type_context(this->type_);
  4391  
  4392    this->expr_->export_expression(efb);
  4393  
  4394    efb->set_type_context(old_context);
  4395  
  4396    efb->write_c_string(")");
  4397  }
  4398  
  4399  // Import a type conversion or a struct construction.
  4400  
  4401  Expression*
  4402  Type_conversion_expression::do_import(Import_expression* imp, Location loc)
  4403  {
  4404    imp->require_c_string("$convert(");
  4405    Type* type = imp->read_type();
  4406    imp->require_c_string(", ");
  4407    Expression* val = Expression::import_expression(imp, loc);
  4408    imp->require_c_string(")");
  4409    return Expression::make_cast(type, val, loc);
  4410  }
  4411  
  4412  // Dump ast representation for a type conversion expression.
  4413  
  4414  void
  4415  Type_conversion_expression::do_dump_expression(
  4416      Ast_dump_context* ast_dump_context) const
  4417  {
  4418    ast_dump_context->dump_type(this->type_);
  4419    ast_dump_context->ostream() << "(";
  4420    ast_dump_context->dump_expression(this->expr_);
  4421    ast_dump_context->ostream() << ") ";
  4422  }
  4423  
  4424  // Make a type cast expression.
  4425  
  4426  Expression*
  4427  Expression::make_cast(Type* type, Expression* val, Location location)
  4428  {
  4429    if (type->is_error_type() || val->is_error_expression())
  4430      return Expression::make_error(location);
  4431    return new Type_conversion_expression(type, val, location);
  4432  }
  4433  
  4434  // Class Unsafe_type_conversion_expression.
  4435  
  4436  // Traversal.
  4437  
  4438  int
  4439  Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
  4440  {
  4441    if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
  4442        || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
  4443      return TRAVERSE_EXIT;
  4444    return TRAVERSE_CONTINUE;
  4445  }
  4446  
  4447  // Return whether an unsafe type conversion can be used as a constant
  4448  // initializer.
  4449  
  4450  bool
  4451  Unsafe_type_conversion_expression::do_is_static_initializer() const
  4452  {
  4453    Type* type = this->type_;
  4454    Type* expr_type = this->expr_->type();
  4455  
  4456    if (type->interface_type() != NULL
  4457        || expr_type->interface_type() != NULL)
  4458      return false;
  4459  
  4460    if (!this->expr_->is_static_initializer())
  4461      return false;
  4462  
  4463    if (Type::are_convertible(type, expr_type, NULL))
  4464      return true;
  4465  
  4466    if (type->is_string_type() && expr_type->is_string_type())
  4467      return true;
  4468  
  4469    if ((type->is_numeric_type()
  4470         || type->is_boolean_type()
  4471         || type->points_to() != NULL)
  4472        && (expr_type->is_numeric_type()
  4473  	  || expr_type->is_boolean_type()
  4474  	  || expr_type->points_to() != NULL))
  4475      return true;
  4476  
  4477    return false;
  4478  }
  4479  
  4480  // Copy.
  4481  
  4482  Expression*
  4483  Unsafe_type_conversion_expression::do_copy()
  4484  {
  4485    return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
  4486  					       this->expr_->copy(),
  4487  					       this->location());
  4488  }
  4489  
  4490  // Convert to backend representation.
  4491  
  4492  Bexpression*
  4493  Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
  4494  {
  4495    // We are only called for a limited number of cases.
  4496  
  4497    Type* t = this->type_;
  4498    Type* et = this->expr_->type();
  4499  
  4500    if (t->is_error_type()
  4501        || this->expr_->is_error_expression()
  4502        || et->is_error_type())
  4503      {
  4504        go_assert(saw_errors());
  4505        return context->backend()->error_expression();
  4506      }
  4507  
  4508    if (t->array_type() != NULL)
  4509      go_assert(et->array_type() != NULL
  4510                && t->is_slice_type() == et->is_slice_type());
  4511    else if (t->struct_type() != NULL)
  4512      {
  4513        if (t->named_type() != NULL
  4514            && et->named_type() != NULL
  4515            && !Type::are_convertible(t, et, NULL))
  4516  	{
  4517  	  go_assert(saw_errors());
  4518  	  return context->backend()->error_expression();
  4519  	}
  4520  
  4521        go_assert(et->struct_type() != NULL
  4522                  && Type::are_convertible(t, et, NULL));
  4523      }
  4524    else if (t->map_type() != NULL)
  4525      go_assert(et->map_type() != NULL || et->points_to() != NULL);
  4526    else if (t->channel_type() != NULL)
  4527      go_assert(et->channel_type() != NULL || et->points_to() != NULL);
  4528    else if (t->points_to() != NULL)
  4529      go_assert(et->points_to() != NULL
  4530                || et->channel_type() != NULL
  4531                || et->map_type() != NULL
  4532                || et->function_type() != NULL
  4533  	      || et->integer_type() != NULL
  4534                || et->is_nil_type());
  4535    else if (t->function_type() != NULL)
  4536      go_assert(et->points_to() != NULL);
  4537    else if (et->is_unsafe_pointer_type())
  4538      go_assert(t->points_to() != NULL
  4539  	      || (t->integer_type() != NULL
  4540  		  && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
  4541    else if (t->interface_type() != NULL)
  4542      {
  4543        bool empty_iface = t->interface_type()->is_empty();
  4544        go_assert(et->interface_type() != NULL
  4545                  && et->interface_type()->is_empty() == empty_iface);
  4546      }
  4547    else if (t->integer_type() != NULL)
  4548      go_assert(et->is_boolean_type()
  4549                || et->integer_type() != NULL
  4550                || et->function_type() != NULL
  4551                || et->points_to() != NULL
  4552                || et->map_type() != NULL
  4553                || et->channel_type() != NULL
  4554  	      || et->is_nil_type());
  4555    else
  4556      go_unreachable();
  4557  
  4558    Gogo* gogo = context->gogo();
  4559    Btype* btype = t->get_backend(gogo);
  4560    Bexpression* bexpr = this->expr_->get_backend(context);
  4561    Location loc = this->location();
  4562    return gogo->backend()->convert_expression(btype, bexpr, loc);
  4563  }
  4564  
  4565  // Dump ast representation for an unsafe type conversion expression.
  4566  
  4567  void
  4568  Unsafe_type_conversion_expression::do_dump_expression(
  4569      Ast_dump_context* ast_dump_context) const
  4570  {
  4571    ast_dump_context->dump_type(this->type_);
  4572    ast_dump_context->ostream() << "(";
  4573    ast_dump_context->dump_expression(this->expr_);
  4574    ast_dump_context->ostream() << ") ";
  4575  }
  4576  
  4577  // Make an unsafe type conversion expression.
  4578  
  4579  Expression*
  4580  Expression::make_unsafe_cast(Type* type, Expression* expr,
  4581  			     Location location)
  4582  {
  4583    return new Unsafe_type_conversion_expression(type, expr, location);
  4584  }
  4585  
  4586  // Class Unary_expression.
  4587  
  4588  // Call the address_taken method of the operand if needed.  This is
  4589  // called after escape analysis but before inserting write barriers.
  4590  
  4591  void
  4592  Unary_expression::check_operand_address_taken(Gogo*)
  4593  {
  4594    if (this->op_ != OPERATOR_AND)
  4595      return;
  4596  
  4597    // If this->escapes_ is false at this point, then it was set to
  4598    // false by an explicit call to set_does_not_escape, and the value
  4599    // does not escape.  If this->escapes_ is true, we may be able to
  4600    // set it to false based on the escape analysis pass.
  4601    if (this->escapes_)
  4602      {
  4603        Node* n = Node::make_node(this);
  4604        if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
  4605  	this->escapes_ = false;
  4606      }
  4607  
  4608    this->expr_->address_taken(this->escapes_);
  4609  }
  4610  
  4611  // If we are taking the address of a composite literal, and the
  4612  // contents are not constant, then we want to make a heap expression
  4613  // instead.
  4614  
  4615  Expression*
  4616  Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
  4617  {
  4618    Location loc = this->location();
  4619    Operator op = this->op_;
  4620    Expression* expr = this->expr_;
  4621  
  4622    if (op == OPERATOR_MULT && expr->is_type_expression())
  4623      return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
  4624  
  4625    // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
  4626    // moving x to the heap.  FIXME: Is it worth doing a real escape
  4627    // analysis here?  This case is found in math/unsafe.go and is
  4628    // therefore worth special casing.
  4629    if (op == OPERATOR_MULT)
  4630      {
  4631        Expression* e = expr;
  4632        while (e->classification() == EXPRESSION_CONVERSION)
  4633  	{
  4634  	  Type_conversion_expression* te
  4635  	    = static_cast<Type_conversion_expression*>(e);
  4636  	  e = te->expr();
  4637  	}
  4638  
  4639        if (e->classification() == EXPRESSION_UNARY)
  4640  	{
  4641  	  Unary_expression* ue = static_cast<Unary_expression*>(e);
  4642  	  if (ue->op_ == OPERATOR_AND)
  4643  	    {
  4644  	      if (e == expr)
  4645  		{
  4646  		  // *&x == x.
  4647  		  if (!ue->expr_->is_addressable() && !ue->create_temp_)
  4648  		    {
  4649  		      go_error_at(ue->location(),
  4650  				  "invalid operand for unary %<&%>");
  4651  		      this->set_is_error();
  4652  		    }
  4653  		  return ue->expr_;
  4654  		}
  4655  	      ue->set_does_not_escape();
  4656  	    }
  4657  	}
  4658      }
  4659  
  4660    // Catching an invalid indirection of unsafe.Pointer here avoid
  4661    // having to deal with TYPE_VOID in other places.
  4662    if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
  4663      {
  4664        go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
  4665        return Expression::make_error(this->location());
  4666      }
  4667  
  4668    // Check for an invalid pointer dereference.  We need to do this
  4669    // here because Unary_expression::do_type will return an error type
  4670    // in this case.  That can cause code to appear erroneous, and
  4671    // therefore disappear at lowering time, without any error message.
  4672    if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
  4673      {
  4674        this->report_error(_("expected pointer"));
  4675        return Expression::make_error(this->location());
  4676      }
  4677  
  4678    if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
  4679      {
  4680        Numeric_constant nc;
  4681        if (expr->numeric_constant_value(&nc))
  4682  	{
  4683  	  Numeric_constant result;
  4684  	  bool issued_error;
  4685  	  if (Unary_expression::eval_constant(op, &nc, loc, &result,
  4686  					      &issued_error))
  4687  	    return result.expression(loc);
  4688  	  else if (issued_error)
  4689  	    return Expression::make_error(this->location());
  4690  	}
  4691      }
  4692  
  4693    return this;
  4694  }
  4695  
  4696  // Flatten expression if a nil check must be performed and create temporary
  4697  // variables if necessary.
  4698  
  4699  Expression*
  4700  Unary_expression::do_flatten(Gogo* gogo, Named_object*,
  4701                               Statement_inserter* inserter)
  4702  {
  4703    if (this->is_error_expression()
  4704        || this->expr_->is_error_expression()
  4705        || this->expr_->type()->is_error_type())
  4706      {
  4707        go_assert(saw_errors());
  4708        return Expression::make_error(this->location());
  4709      }
  4710  
  4711    Location location = this->location();
  4712    if (this->op_ == OPERATOR_MULT
  4713        && !this->expr_->is_multi_eval_safe())
  4714      {
  4715        go_assert(this->expr_->type()->points_to() != NULL);
  4716        switch (this->requires_nil_check(gogo))
  4717          {
  4718            case NIL_CHECK_ERROR_ENCOUNTERED:
  4719              {
  4720                go_assert(saw_errors());
  4721                return Expression::make_error(this->location());
  4722              }
  4723            case NIL_CHECK_NOT_NEEDED:
  4724              break;
  4725            case NIL_CHECK_NEEDED:
  4726              this->create_temp_ = true;
  4727              break;
  4728            case NIL_CHECK_DEFAULT:
  4729              go_unreachable();
  4730          }
  4731      }
  4732  
  4733    if (this->create_temp_ && !this->expr_->is_multi_eval_safe())
  4734      {
  4735        Temporary_statement* temp =
  4736            Statement::make_temporary(NULL, this->expr_, location);
  4737        inserter->insert(temp);
  4738        this->expr_ = Expression::make_temporary_reference(temp, location);
  4739      }
  4740  
  4741    return this;
  4742  }
  4743  
  4744  // Return whether a unary expression is a constant.
  4745  
  4746  bool
  4747  Unary_expression::do_is_constant() const
  4748  {
  4749    if (this->op_ == OPERATOR_MULT)
  4750      {
  4751        // Indirecting through a pointer is only constant if the object
  4752        // to which the expression points is constant, but we currently
  4753        // have no way to determine that.
  4754        return false;
  4755      }
  4756    else if (this->op_ == OPERATOR_AND)
  4757      {
  4758        // Taking the address of a variable is constant if it is a
  4759        // global variable, not constant otherwise.  In other cases taking the
  4760        // address is probably not a constant.
  4761        Var_expression* ve = this->expr_->var_expression();
  4762        if (ve != NULL)
  4763  	{
  4764  	  Named_object* no = ve->named_object();
  4765  	  return no->is_variable() && no->var_value()->is_global();
  4766  	}
  4767        return false;
  4768      }
  4769    else
  4770      return this->expr_->is_constant();
  4771  }
  4772  
  4773  // Return whether a unary expression can be used as a constant
  4774  // initializer.
  4775  
  4776  bool
  4777  Unary_expression::do_is_static_initializer() const
  4778  {
  4779    if (this->op_ == OPERATOR_MULT)
  4780      return false;
  4781    else if (this->op_ == OPERATOR_AND)
  4782      return Unary_expression::base_is_static_initializer(this->expr_);
  4783    else
  4784      return this->expr_->is_static_initializer();
  4785  }
  4786  
  4787  // Return whether the address of EXPR can be used as a static
  4788  // initializer.
  4789  
  4790  bool
  4791  Unary_expression::base_is_static_initializer(Expression* expr)
  4792  {
  4793    // The address of a field reference can be a static initializer if
  4794    // the base can be a static initializer.
  4795    Field_reference_expression* fre = expr->field_reference_expression();
  4796    if (fre != NULL)
  4797      return Unary_expression::base_is_static_initializer(fre->expr());
  4798  
  4799    // The address of an index expression can be a static initializer if
  4800    // the base can be a static initializer and the index is constant.
  4801    Array_index_expression* aind = expr->array_index_expression();
  4802    if (aind != NULL)
  4803      return (aind->end() == NULL
  4804  	    && aind->start()->is_constant()
  4805  	    && Unary_expression::base_is_static_initializer(aind->array()));
  4806  
  4807    // The address of a global variable can be a static initializer.
  4808    Var_expression* ve = expr->var_expression();
  4809    if (ve != NULL)
  4810      {
  4811        Named_object* no = ve->named_object();
  4812        return no->is_variable() && no->var_value()->is_global();
  4813      }
  4814  
  4815    // The address of a composite literal can be used as a static
  4816    // initializer if the composite literal is itself usable as a
  4817    // static initializer.
  4818    if (expr->is_composite_literal() && expr->is_static_initializer())
  4819      return true;
  4820  
  4821    // The address of a string constant can be used as a static
  4822    // initializer.  This can not be written in Go itself but this is
  4823    // used when building a type descriptor.
  4824    if (expr->string_expression() != NULL)
  4825      return true;
  4826  
  4827    return false;
  4828  }
  4829  
  4830  // Return whether this dereference expression requires an explicit nil
  4831  // check. If we are dereferencing the pointer to a large struct
  4832  // (greater than the specified size threshold), we need to check for
  4833  // nil. We don't bother to check for small structs because we expect
  4834  // the system to crash on a nil pointer dereference. However, if we
  4835  // know the address of this expression is being taken, we must always
  4836  // check for nil.
  4837  Unary_expression::Nil_check_classification
  4838  Unary_expression::requires_nil_check(Gogo* gogo)
  4839  {
  4840    go_assert(this->op_ == OPERATOR_MULT);
  4841    go_assert(this->expr_->type()->points_to() != NULL);
  4842  
  4843    if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
  4844      return NIL_CHECK_NEEDED;
  4845    else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
  4846      return NIL_CHECK_NOT_NEEDED;
  4847  
  4848    Type* ptype = this->expr_->type()->points_to();
  4849    int64_t type_size = -1;
  4850    if (!ptype->is_void_type())
  4851      {
  4852        bool ok = ptype->backend_type_size(gogo, &type_size);
  4853        if (!ok)
  4854          return NIL_CHECK_ERROR_ENCOUNTERED;
  4855      }
  4856  
  4857    int64_t size_cutoff = gogo->nil_check_size_threshold();
  4858    if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
  4859      this->issue_nil_check_ = NIL_CHECK_NEEDED;
  4860    else
  4861      this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
  4862    return this->issue_nil_check_;
  4863  }
  4864  
  4865  // Apply unary opcode OP to UNC, setting NC.  Return true if this
  4866  // could be done, false if not.  On overflow, issues an error and sets
  4867  // *ISSUED_ERROR.
  4868  
  4869  bool
  4870  Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
  4871  				Location location, Numeric_constant* nc,
  4872  				bool* issued_error)
  4873  {
  4874    *issued_error = false;
  4875    switch (op)
  4876      {
  4877      case OPERATOR_PLUS:
  4878        *nc = *unc;
  4879        return true;
  4880  
  4881      case OPERATOR_MINUS:
  4882        if (unc->is_int() || unc->is_rune())
  4883  	break;
  4884        else if (unc->is_float())
  4885  	{
  4886  	  mpfr_t uval;
  4887  	  unc->get_float(&uval);
  4888  	  mpfr_t val;
  4889  	  mpfr_init(val);
  4890  	  mpfr_neg(val, uval, MPFR_RNDN);
  4891  	  nc->set_float(unc->type(), val);
  4892  	  mpfr_clear(uval);
  4893  	  mpfr_clear(val);
  4894  	  return true;
  4895  	}
  4896        else if (unc->is_complex())
  4897  	{
  4898  	  mpc_t uval;
  4899  	  unc->get_complex(&uval);
  4900  	  mpc_t val;
  4901  	  mpc_init2(val, mpc_precision);
  4902  	  mpc_neg(val, uval, MPC_RNDNN);
  4903  	  nc->set_complex(unc->type(), val);
  4904  	  mpc_clear(uval);
  4905  	  mpc_clear(val);
  4906  	  return true;
  4907  	}
  4908        else
  4909  	go_unreachable();
  4910  
  4911      case OPERATOR_XOR:
  4912        break;
  4913  
  4914      case OPERATOR_NOT:
  4915      case OPERATOR_AND:
  4916      case OPERATOR_MULT:
  4917        return false;
  4918  
  4919      default:
  4920        go_unreachable();
  4921      }
  4922  
  4923    if (!unc->is_int() && !unc->is_rune())
  4924      return false;
  4925  
  4926    mpz_t uval;
  4927    if (unc->is_rune())
  4928      unc->get_rune(&uval);
  4929    else
  4930      unc->get_int(&uval);
  4931    mpz_t val;
  4932    mpz_init(val);
  4933  
  4934    switch (op)
  4935      {
  4936      case OPERATOR_MINUS:
  4937        mpz_neg(val, uval);
  4938        break;
  4939  
  4940      case OPERATOR_NOT:
  4941        mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
  4942        break;
  4943  
  4944      case OPERATOR_XOR:
  4945        {
  4946  	Type* utype = unc->type();
  4947  	if (utype->integer_type() == NULL
  4948  	    || utype->integer_type()->is_abstract())
  4949  	  mpz_com(val, uval);
  4950  	else
  4951  	  {
  4952  	    // The number of HOST_WIDE_INTs that it takes to represent
  4953  	    // UVAL.
  4954  	    size_t count = ((mpz_sizeinbase(uval, 2)
  4955  			     + HOST_BITS_PER_WIDE_INT
  4956  			     - 1)
  4957  			    / HOST_BITS_PER_WIDE_INT);
  4958  
  4959  	    unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
  4960  	    memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
  4961  
  4962  	    size_t obits = utype->integer_type()->bits();
  4963  
  4964  	    if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
  4965  	      {
  4966  		mpz_t adj;
  4967  		mpz_init_set_ui(adj, 1);
  4968  		mpz_mul_2exp(adj, adj, obits);
  4969  		mpz_add(uval, uval, adj);
  4970  		mpz_clear(adj);
  4971  	      }
  4972  
  4973  	    size_t ecount;
  4974  	    mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
  4975  	    go_assert(ecount <= count);
  4976  
  4977  	    // Trim down to the number of words required by the type.
  4978  	    size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
  4979  			     / HOST_BITS_PER_WIDE_INT);
  4980  	    go_assert(ocount <= count);
  4981  
  4982  	    for (size_t i = 0; i < ocount; ++i)
  4983  	      phwi[i] = ~phwi[i];
  4984  
  4985  	    size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
  4986  	    if (clearbits != 0)
  4987  	      phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
  4988  				   >> clearbits);
  4989  
  4990  	    mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
  4991  
  4992  	    if (!utype->integer_type()->is_unsigned()
  4993  		&& mpz_tstbit(val, obits - 1))
  4994  	      {
  4995  		mpz_t adj;
  4996  		mpz_init_set_ui(adj, 1);
  4997  		mpz_mul_2exp(adj, adj, obits);
  4998  		mpz_sub(val, val, adj);
  4999  		mpz_clear(adj);
  5000  	      }
  5001  
  5002  	    delete[] phwi;
  5003  	  }
  5004        }
  5005        break;
  5006  
  5007      default:
  5008        go_unreachable();
  5009      }
  5010  
  5011    if (unc->is_rune())
  5012      nc->set_rune(NULL, val);
  5013    else
  5014      nc->set_int(NULL, val);
  5015  
  5016    mpz_clear(uval);
  5017    mpz_clear(val);
  5018  
  5019    if (!nc->set_type(unc->type(), true, location))
  5020      {
  5021        *issued_error = true;
  5022        return false;
  5023      }
  5024    return true;
  5025  }
  5026  
  5027  // Return the integral constant value of a unary expression, if it has one.
  5028  
  5029  bool
  5030  Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
  5031  {
  5032    Numeric_constant unc;
  5033    if (!this->expr_->numeric_constant_value(&unc))
  5034      return false;
  5035    bool issued_error;
  5036    return Unary_expression::eval_constant(this->op_, &unc, this->location(),
  5037  					 nc, &issued_error);
  5038  }
  5039  
  5040  // Return the boolean constant value of a unary expression, if it has one.
  5041  
  5042  bool
  5043  Unary_expression::do_boolean_constant_value(bool* val) const
  5044  {
  5045    if (this->op_ == OPERATOR_NOT
  5046        && this->expr_->boolean_constant_value(val))
  5047      {
  5048        *val = !*val;
  5049        return true;
  5050      }
  5051    return false;
  5052  }
  5053  
  5054  // Return the type of a unary expression.
  5055  
  5056  Type*
  5057  Unary_expression::do_type()
  5058  {
  5059    switch (this->op_)
  5060      {
  5061      case OPERATOR_PLUS:
  5062      case OPERATOR_MINUS:
  5063      case OPERATOR_NOT:
  5064      case OPERATOR_XOR:
  5065        return this->expr_->type();
  5066  
  5067      case OPERATOR_AND:
  5068        return Type::make_pointer_type(this->expr_->type());
  5069  
  5070      case OPERATOR_MULT:
  5071        {
  5072  	Type* subtype = this->expr_->type();
  5073  	Type* points_to = subtype->points_to();
  5074  	if (points_to == NULL)
  5075  	  return Type::make_error_type();
  5076  	return points_to;
  5077        }
  5078  
  5079      default:
  5080        go_unreachable();
  5081      }
  5082  }
  5083  
  5084  // Determine abstract types for a unary expression.
  5085  
  5086  void
  5087  Unary_expression::do_determine_type(const Type_context* context)
  5088  {
  5089    switch (this->op_)
  5090      {
  5091      case OPERATOR_PLUS:
  5092      case OPERATOR_MINUS:
  5093      case OPERATOR_NOT:
  5094      case OPERATOR_XOR:
  5095        this->expr_->determine_type(context);
  5096        break;
  5097  
  5098      case OPERATOR_AND:
  5099        // Taking the address of something.
  5100        {
  5101  	Type* subtype = (context->type == NULL
  5102  			 ? NULL
  5103  			 : context->type->points_to());
  5104  	Type_context subcontext(subtype, false);
  5105  	this->expr_->determine_type(&subcontext);
  5106        }
  5107        break;
  5108  
  5109      case OPERATOR_MULT:
  5110        // Indirecting through a pointer.
  5111        {
  5112  	Type* subtype = (context->type == NULL
  5113  			 ? NULL
  5114  			 : Type::make_pointer_type(context->type));
  5115  	Type_context subcontext(subtype, false);
  5116  	this->expr_->determine_type(&subcontext);
  5117        }
  5118        break;
  5119  
  5120      default:
  5121        go_unreachable();
  5122      }
  5123  }
  5124  
  5125  // Check types for a unary expression.
  5126  
  5127  void
  5128  Unary_expression::do_check_types(Gogo*)
  5129  {
  5130    Type* type = this->expr_->type();
  5131    if (type->is_error())
  5132      {
  5133        this->set_is_error();
  5134        return;
  5135      }
  5136  
  5137    switch (this->op_)
  5138      {
  5139      case OPERATOR_PLUS:
  5140      case OPERATOR_MINUS:
  5141        if (type->integer_type() == NULL
  5142  	  && type->float_type() == NULL
  5143  	  && type->complex_type() == NULL)
  5144  	this->report_error(_("expected numeric type"));
  5145        break;
  5146  
  5147      case OPERATOR_NOT:
  5148        if (!type->is_boolean_type())
  5149  	this->report_error(_("expected boolean type"));
  5150        break;
  5151  
  5152      case OPERATOR_XOR:
  5153        if (type->integer_type() == NULL)
  5154  	this->report_error(_("expected integer"));
  5155        break;
  5156  
  5157      case OPERATOR_AND:
  5158        if (!this->expr_->is_addressable())
  5159  	{
  5160  	  if (!this->create_temp_)
  5161  	    {
  5162  	      go_error_at(this->location(), "invalid operand for unary %<&%>");
  5163  	      this->set_is_error();
  5164  	    }
  5165  	}
  5166        else
  5167  	this->expr_->issue_nil_check();
  5168        break;
  5169  
  5170      case OPERATOR_MULT:
  5171        // Indirecting through a pointer.
  5172        if (type->points_to() == NULL)
  5173  	this->report_error(_("expected pointer"));
  5174        if (type->points_to()->is_error())
  5175  	this->set_is_error();
  5176        break;
  5177  
  5178      default:
  5179        go_unreachable();
  5180      }
  5181  }
  5182  
  5183  // Get the backend representation for a unary expression.
  5184  
  5185  Bexpression*
  5186  Unary_expression::do_get_backend(Translate_context* context)
  5187  {
  5188    Gogo* gogo = context->gogo();
  5189    Location loc = this->location();
  5190  
  5191    // Taking the address of a set-and-use-temporary expression requires
  5192    // setting the temporary and then taking the address.
  5193    if (this->op_ == OPERATOR_AND)
  5194      {
  5195        Set_and_use_temporary_expression* sut =
  5196  	this->expr_->set_and_use_temporary_expression();
  5197        if (sut != NULL)
  5198  	{
  5199  	  Temporary_statement* temp = sut->temporary();
  5200  	  Bvariable* bvar = temp->get_backend_variable(context);
  5201            Bexpression* bvar_expr =
  5202                gogo->backend()->var_expression(bvar, loc);
  5203            Bexpression* bval = sut->expression()->get_backend(context);
  5204  
  5205            Named_object* fn = context->function();
  5206            go_assert(fn != NULL);
  5207            Bfunction* bfn =
  5208                fn->func_value()->get_or_make_decl(gogo, fn);
  5209            Bstatement* bassign =
  5210                gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
  5211            Bexpression* bvar_addr =
  5212                gogo->backend()->address_expression(bvar_expr, loc);
  5213  	  return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
  5214  	}
  5215      }
  5216  
  5217    Bexpression* ret;
  5218    Bexpression* bexpr = this->expr_->get_backend(context);
  5219    Btype* btype = this->expr_->type()->get_backend(gogo);
  5220    switch (this->op_)
  5221      {
  5222      case OPERATOR_PLUS:
  5223        ret = bexpr;
  5224        break;
  5225  
  5226      case OPERATOR_MINUS:
  5227        ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
  5228        ret = gogo->backend()->convert_expression(btype, ret, loc);
  5229        break;
  5230  
  5231      case OPERATOR_NOT:
  5232      case OPERATOR_XOR:
  5233        ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
  5234        break;
  5235  
  5236      case OPERATOR_AND:
  5237        if (!this->create_temp_)
  5238  	{
  5239  	  // We should not see a non-constant constructor here; cases
  5240  	  // where we would see one should have been moved onto the
  5241  	  // heap at parse time.  Taking the address of a nonconstant
  5242  	  // constructor will not do what the programmer expects.
  5243  
  5244            go_assert(!this->expr_->is_composite_literal()
  5245                      || this->expr_->is_static_initializer());
  5246  	  if (this->expr_->classification() == EXPRESSION_UNARY)
  5247  	    {
  5248  	      Unary_expression* ue =
  5249  		static_cast<Unary_expression*>(this->expr_);
  5250  	      go_assert(ue->op() != OPERATOR_AND);
  5251  	    }
  5252  	}
  5253  
  5254        if (this->is_gc_root_ || this->is_slice_init_)
  5255  	{
  5256  	  std::string var_name;
  5257  	  bool copy_to_heap = false;
  5258  	  if (this->is_gc_root_)
  5259  	    {
  5260  	      // Build a decl for a GC root variable.  GC roots are mutable, so
  5261  	      // they cannot be represented as an immutable_struct in the
  5262  	      // backend.
  5263  	      var_name = gogo->gc_root_name();
  5264  	    }
  5265  	  else
  5266  	    {
  5267  	      // Build a decl for a slice value initializer.  An immutable slice
  5268  	      // value initializer may have to be copied to the heap if it
  5269  	      // contains pointers in a non-constant context.
  5270  	      var_name = gogo->initializer_name();
  5271  
  5272  	      Array_type* at = this->expr_->type()->array_type();
  5273  	      go_assert(at != NULL);
  5274  
  5275  	      // If we are not copying the value to the heap, we will only
  5276  	      // initialize the value once, so we can use this directly
  5277  	      // rather than copying it.  In that case we can't make it
  5278  	      // read-only, because the program is permitted to change it.
  5279  	      copy_to_heap = (context->function() != NULL
  5280                                || context->is_const());
  5281  	    }
  5282  	  unsigned int flags = (Backend::variable_is_hidden
  5283  				| Backend::variable_address_is_taken);
  5284  	  if (copy_to_heap)
  5285  	    flags |= Backend::variable_is_constant;
  5286  	  Bvariable* implicit =
  5287  	    gogo->backend()->implicit_variable(var_name, "", btype, flags, 0);
  5288  	  gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
  5289  						      flags, bexpr);
  5290  	  bexpr = gogo->backend()->var_expression(implicit, loc);
  5291  
  5292  	  // If we are not copying a slice initializer to the heap,
  5293  	  // then it can be changed by the program, so if it can
  5294  	  // contain pointers we must register it as a GC root.
  5295  	  if (this->is_slice_init_
  5296  	      && !copy_to_heap
  5297  	      && this->expr_->type()->has_pointer())
  5298  	    {
  5299  	      Bexpression* root =
  5300                    gogo->backend()->var_expression(implicit, loc);
  5301  	      root = gogo->backend()->address_expression(root, loc);
  5302  	      Type* type = Type::make_pointer_type(this->expr_->type());
  5303  	      gogo->add_gc_root(Expression::make_backend(root, type, loc));
  5304  	    }
  5305  	}
  5306        else if ((this->expr_->is_composite_literal()
  5307  		|| this->expr_->string_expression() != NULL)
  5308  	       && this->expr_->is_static_initializer())
  5309          {
  5310  	  std::string var_name(gogo->initializer_name());
  5311  	  unsigned int flags = (Backend::variable_is_hidden
  5312  				| Backend::variable_address_is_taken);
  5313            Bvariable* decl =
  5314  	    gogo->backend()->immutable_struct(var_name, "", flags, btype, loc);
  5315            gogo->backend()->immutable_struct_set_init(decl, var_name, flags,
  5316  						     btype, loc, bexpr);
  5317            bexpr = gogo->backend()->var_expression(decl, loc);
  5318          }
  5319        else if (this->expr_->is_constant())
  5320          {
  5321            std::string var_name(gogo->initializer_name());
  5322  	  unsigned int flags = (Backend::variable_is_hidden
  5323  				| Backend::variable_is_constant
  5324  				| Backend::variable_address_is_taken);
  5325            Bvariable* decl =
  5326  	    gogo->backend()->implicit_variable(var_name, "", btype, flags, 0);
  5327            gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
  5328  						      flags, bexpr);
  5329            bexpr = gogo->backend()->var_expression(decl, loc);
  5330          }
  5331  
  5332        go_assert(!this->create_temp_ || this->expr_->is_multi_eval_safe());
  5333        ret = gogo->backend()->address_expression(bexpr, loc);
  5334        break;
  5335  
  5336      case OPERATOR_MULT:
  5337        {
  5338          go_assert(this->expr_->type()->points_to() != NULL);
  5339  
  5340          Type* ptype = this->expr_->type()->points_to();
  5341          Btype* pbtype = ptype->get_backend(gogo);
  5342          switch (this->requires_nil_check(gogo))
  5343            {
  5344              case NIL_CHECK_NOT_NEEDED:
  5345                break;
  5346              case NIL_CHECK_ERROR_ENCOUNTERED:
  5347                {
  5348                  go_assert(saw_errors());
  5349                  return gogo->backend()->error_expression();
  5350                }
  5351              case NIL_CHECK_NEEDED:
  5352                {
  5353                  go_assert(this->expr_->is_multi_eval_safe());
  5354  
  5355                  // If we're nil-checking the result of a set-and-use-temporary
  5356                  // expression, then pick out the target temp and use that
  5357                  // for the final result of the conditional.
  5358                  Bexpression* tbexpr = bexpr;
  5359                  Bexpression* ubexpr = bexpr;
  5360                  Set_and_use_temporary_expression* sut =
  5361                      this->expr_->set_and_use_temporary_expression();
  5362                  if (sut != NULL) {
  5363                    Temporary_statement* temp = sut->temporary();
  5364                    Bvariable* bvar = temp->get_backend_variable(context);
  5365                    ubexpr = gogo->backend()->var_expression(bvar, loc);
  5366                  }
  5367                  Bexpression* nil =
  5368                      Expression::make_nil(loc)->get_backend(context);
  5369                  Bexpression* compare =
  5370                      gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
  5371                                                         nil, loc);
  5372  		Expression* crash = Runtime::make_call(Runtime::PANIC_MEM,
  5373  						       loc, 0);
  5374  		Bexpression* bcrash = crash->get_backend(context);
  5375                  Bfunction* bfn = context->function()->func_value()->get_decl();
  5376                  bexpr = gogo->backend()->conditional_expression(bfn, btype,
  5377                                                                  compare,
  5378                                                                  bcrash, ubexpr,
  5379                                                                  loc);
  5380                  break;
  5381                }
  5382              case NIL_CHECK_DEFAULT:
  5383                go_unreachable();
  5384            }
  5385          ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
  5386        }
  5387        break;
  5388  
  5389      default:
  5390        go_unreachable();
  5391      }
  5392  
  5393    return ret;
  5394  }
  5395  
  5396  // Export a unary expression.
  5397  
  5398  void
  5399  Unary_expression::do_export(Export_function_body* efb) const
  5400  {
  5401    switch (this->op_)
  5402      {
  5403      case OPERATOR_PLUS:
  5404        efb->write_c_string("+");
  5405        break;
  5406      case OPERATOR_MINUS:
  5407        efb->write_c_string("-");
  5408        break;
  5409      case OPERATOR_NOT:
  5410        efb->write_c_string("!");
  5411        break;
  5412      case OPERATOR_XOR:
  5413        efb->write_c_string("^");
  5414        break;
  5415      case OPERATOR_AND:
  5416        efb->write_c_string("&");
  5417        break;
  5418      case OPERATOR_MULT:
  5419        efb->write_c_string("*");
  5420        break;
  5421      default:
  5422        go_unreachable();
  5423      }
  5424    this->expr_->export_expression(efb);
  5425  }
  5426  
  5427  // Import a unary expression.
  5428  
  5429  Expression*
  5430  Unary_expression::do_import(Import_expression* imp, Location loc)
  5431  {
  5432    Operator op;
  5433    switch (imp->get_char())
  5434      {
  5435      case '+':
  5436        op = OPERATOR_PLUS;
  5437        break;
  5438      case '-':
  5439        op = OPERATOR_MINUS;
  5440        break;
  5441      case '!':
  5442        op = OPERATOR_NOT;
  5443        break;
  5444      case '^':
  5445        op = OPERATOR_XOR;
  5446        break;
  5447      case '&':
  5448        op = OPERATOR_AND;
  5449        break;
  5450      case '*':
  5451        op = OPERATOR_MULT;
  5452        break;
  5453      default:
  5454        go_unreachable();
  5455      }
  5456    if (imp->version() < EXPORT_FORMAT_V3)
  5457      imp->require_c_string(" ");
  5458    Expression* expr = Expression::import_expression(imp, loc);
  5459    return Expression::make_unary(op, expr, loc);
  5460  }
  5461  
  5462  // Dump ast representation of an unary expression.
  5463  
  5464  void
  5465  Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  5466  {
  5467    ast_dump_context->dump_operator(this->op_);
  5468    ast_dump_context->ostream() << "(";
  5469    ast_dump_context->dump_expression(this->expr_);
  5470    ast_dump_context->ostream() << ") ";
  5471  }
  5472  
  5473  // Make a unary expression.
  5474  
  5475  Expression*
  5476  Expression::make_unary(Operator op, Expression* expr, Location location)
  5477  {
  5478    return new Unary_expression(op, expr, location);
  5479  }
  5480  
  5481  Expression*
  5482  Expression::make_dereference(Expression* ptr,
  5483                               Nil_check_classification docheck,
  5484                               Location location)
  5485  {
  5486    Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
  5487    if (docheck == NIL_CHECK_NEEDED)
  5488      deref->unary_expression()->set_requires_nil_check(true);
  5489    else if (docheck == NIL_CHECK_NOT_NEEDED)
  5490      deref->unary_expression()->set_requires_nil_check(false);
  5491    return deref;
  5492  }
  5493  
  5494  // If this is an indirection through a pointer, return the expression
  5495  // being pointed through.  Otherwise return this.
  5496  
  5497  Expression*
  5498  Expression::deref()
  5499  {
  5500    if (this->classification_ == EXPRESSION_UNARY)
  5501      {
  5502        Unary_expression* ue = static_cast<Unary_expression*>(this);
  5503        if (ue->op() == OPERATOR_MULT)
  5504  	return ue->operand();
  5505      }
  5506    return this;
  5507  }
  5508  
  5509  // Class Binary_expression.
  5510  
  5511  // Traversal.
  5512  
  5513  int
  5514  Binary_expression::do_traverse(Traverse* traverse)
  5515  {
  5516    int t = Expression::traverse(&this->left_, traverse);
  5517    if (t == TRAVERSE_EXIT)
  5518      return TRAVERSE_EXIT;
  5519    return Expression::traverse(&this->right_, traverse);
  5520  }
  5521  
  5522  // Return whether this expression may be used as a static initializer.
  5523  
  5524  bool
  5525  Binary_expression::do_is_static_initializer() const
  5526  {
  5527    if (!this->left_->is_static_initializer()
  5528        || !this->right_->is_static_initializer())
  5529      return false;
  5530  
  5531    // Addresses can be static initializers, but we can't implement
  5532    // arbitray binary expressions of them.
  5533    Unary_expression* lu = this->left_->unary_expression();
  5534    Unary_expression* ru = this->right_->unary_expression();
  5535    if (lu != NULL && lu->op() == OPERATOR_AND)
  5536      {
  5537        if (ru != NULL && ru->op() == OPERATOR_AND)
  5538  	return this->op_ == OPERATOR_MINUS;
  5539        else
  5540  	return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
  5541      }
  5542    else if (ru != NULL && ru->op() == OPERATOR_AND)
  5543      return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
  5544  
  5545    // Other cases should resolve in the backend.
  5546    return true;
  5547  }
  5548  
  5549  // Return the type to use for a binary operation on operands of
  5550  // LEFT_TYPE and RIGHT_TYPE.  These are the types of constants and as
  5551  // such may be NULL or abstract.
  5552  
  5553  bool
  5554  Binary_expression::operation_type(Operator op, Type* left_type,
  5555  				  Type* right_type, Type** result_type)
  5556  {
  5557    if (left_type != right_type
  5558        && !left_type->is_abstract()
  5559        && !right_type->is_abstract()
  5560        && left_type->base() != right_type->base()
  5561        && op != OPERATOR_LSHIFT
  5562        && op != OPERATOR_RSHIFT)
  5563      {
  5564        // May be a type error--let it be diagnosed elsewhere.
  5565        return false;
  5566      }
  5567  
  5568    if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
  5569      {
  5570        if (left_type->integer_type() != NULL)
  5571  	*result_type = left_type;
  5572        else
  5573  	*result_type = Type::make_abstract_integer_type();
  5574      }
  5575    else if (!left_type->is_abstract() && left_type->named_type() != NULL)
  5576      *result_type = left_type;
  5577    else if (!right_type->is_abstract() && right_type->named_type() != NULL)
  5578      *result_type = right_type;
  5579    else if (!left_type->is_abstract())
  5580      *result_type = left_type;
  5581    else if (!right_type->is_abstract())
  5582      *result_type = right_type;
  5583    else if (left_type->complex_type() != NULL)
  5584      *result_type = left_type;
  5585    else if (right_type->complex_type() != NULL)
  5586      *result_type = right_type;
  5587    else if (left_type->float_type() != NULL)
  5588      *result_type = left_type;
  5589    else if (right_type->float_type() != NULL)
  5590      *result_type = right_type;
  5591    else if (left_type->integer_type() != NULL
  5592  	   && left_type->integer_type()->is_rune())
  5593      *result_type = left_type;
  5594    else if (right_type->integer_type() != NULL
  5595  	   && right_type->integer_type()->is_rune())
  5596      *result_type = right_type;
  5597    else
  5598      *result_type = left_type;
  5599  
  5600    return true;
  5601  }
  5602  
  5603  // Convert an integer comparison code and an operator to a boolean
  5604  // value.
  5605  
  5606  bool
  5607  Binary_expression::cmp_to_bool(Operator op, int cmp)
  5608  {
  5609    switch (op)
  5610      {
  5611      case OPERATOR_EQEQ:
  5612        return cmp == 0;
  5613        break;
  5614      case OPERATOR_NOTEQ:
  5615        return cmp != 0;
  5616        break;
  5617      case OPERATOR_LT:
  5618        return cmp < 0;
  5619        break;
  5620      case OPERATOR_LE:
  5621        return cmp <= 0;
  5622      case OPERATOR_GT:
  5623        return cmp > 0;
  5624      case OPERATOR_GE:
  5625        return cmp >= 0;
  5626      default:
  5627        go_unreachable();
  5628      }
  5629  }
  5630  
  5631  // Compare constants according to OP.
  5632  
  5633  bool
  5634  Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
  5635  				    Numeric_constant* right_nc,
  5636  				    Location location, bool* result)
  5637  {
  5638    Type* left_type = left_nc->type();
  5639    Type* right_type = right_nc->type();
  5640  
  5641    Type* type;
  5642    if (!Binary_expression::operation_type(op, left_type, right_type, &type))
  5643      return false;
  5644  
  5645    // When comparing an untyped operand to a typed operand, we are
  5646    // effectively coercing the untyped operand to the other operand's
  5647    // type, so make sure that is valid.
  5648    if (!left_nc->set_type(type, true, location)
  5649        || !right_nc->set_type(type, true, location))
  5650      return false;
  5651  
  5652    bool ret;
  5653    int cmp;
  5654    if (type->complex_type() != NULL)
  5655      {
  5656        if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
  5657  	return false;
  5658        ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
  5659      }
  5660    else if (type->float_type() != NULL)
  5661      ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
  5662    else
  5663      ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
  5664  
  5665    if (ret)
  5666      *result = Binary_expression::cmp_to_bool(op, cmp);
  5667  
  5668    return ret;
  5669  }
  5670  
  5671  // Compare integer constants.
  5672  
  5673  bool
  5674  Binary_expression::compare_integer(const Numeric_constant* left_nc,
  5675  				   const Numeric_constant* right_nc,
  5676  				   int* cmp)
  5677  {
  5678    mpz_t left_val;
  5679    if (!left_nc->to_int(&left_val))
  5680      return false;
  5681    mpz_t right_val;
  5682    if (!right_nc->to_int(&right_val))
  5683      {
  5684        mpz_clear(left_val);
  5685        return false;
  5686      }
  5687  
  5688    *cmp = mpz_cmp(left_val, right_val);
  5689  
  5690    mpz_clear(left_val);
  5691    mpz_clear(right_val);
  5692  
  5693    return true;
  5694  }
  5695  
  5696  // Compare floating point constants.
  5697  
  5698  bool
  5699  Binary_expression::compare_float(const Numeric_constant* left_nc,
  5700  				 const Numeric_constant* right_nc,
  5701  				 int* cmp)
  5702  {
  5703    mpfr_t left_val;
  5704    if (!left_nc->to_float(&left_val))
  5705      return false;
  5706    mpfr_t right_val;
  5707    if (!right_nc->to_float(&right_val))
  5708      {
  5709        mpfr_clear(left_val);
  5710        return false;
  5711      }
  5712  
  5713    // We already coerced both operands to the same type.  If that type
  5714    // is not an abstract type, we need to round the values accordingly.
  5715    Type* type = left_nc->type();
  5716    if (!type->is_abstract() && type->float_type() != NULL)
  5717      {
  5718        int bits = type->float_type()->bits();
  5719        mpfr_prec_round(left_val, bits, MPFR_RNDN);
  5720        mpfr_prec_round(right_val, bits, MPFR_RNDN);
  5721      }
  5722  
  5723    *cmp = mpfr_cmp(left_val, right_val);
  5724  
  5725    mpfr_clear(left_val);
  5726    mpfr_clear(right_val);
  5727  
  5728    return true;
  5729  }
  5730  
  5731  // Compare complex constants.  Complex numbers may only be compared
  5732  // for equality.
  5733  
  5734  bool
  5735  Binary_expression::compare_complex(const Numeric_constant* left_nc,
  5736  				   const Numeric_constant* right_nc,
  5737  				   int* cmp)
  5738  {
  5739    mpc_t left_val;
  5740    if (!left_nc->to_complex(&left_val))
  5741      return false;
  5742    mpc_t right_val;
  5743    if (!right_nc->to_complex(&right_val))
  5744      {
  5745        mpc_clear(left_val);
  5746        return false;
  5747      }
  5748  
  5749    // We already coerced both operands to the same type.  If that type
  5750    // is not an abstract type, we need to round the values accordingly.
  5751    Type* type = left_nc->type();
  5752    if (!type->is_abstract() && type->complex_type() != NULL)
  5753      {
  5754        int bits = type->complex_type()->bits();
  5755        mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
  5756        mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
  5757        mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
  5758        mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
  5759      }
  5760  
  5761    *cmp = mpc_cmp(left_val, right_val) != 0;
  5762  
  5763    mpc_clear(left_val);
  5764    mpc_clear(right_val);
  5765  
  5766    return true;
  5767  }
  5768  
  5769  // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC.  Return
  5770  // true if this could be done, false if not.  Issue errors at LOCATION
  5771  // as appropriate, and sets *ISSUED_ERROR if it did.
  5772  
  5773  bool
  5774  Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
  5775  				 Numeric_constant* right_nc,
  5776  				 Location location, Numeric_constant* nc,
  5777  				 bool* issued_error)
  5778  {
  5779    *issued_error = false;
  5780    switch (op)
  5781      {
  5782      case OPERATOR_OROR:
  5783      case OPERATOR_ANDAND:
  5784      case OPERATOR_EQEQ:
  5785      case OPERATOR_NOTEQ:
  5786      case OPERATOR_LT:
  5787      case OPERATOR_LE:
  5788      case OPERATOR_GT:
  5789      case OPERATOR_GE:
  5790        // These return boolean values, not numeric.
  5791        return false;
  5792      default:
  5793        break;
  5794      }
  5795  
  5796    Type* left_type = left_nc->type();
  5797    Type* right_type = right_nc->type();
  5798  
  5799    Type* type;
  5800    if (!Binary_expression::operation_type(op, left_type, right_type, &type))
  5801      return false;
  5802  
  5803    bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
  5804  
  5805    // When combining an untyped operand with a typed operand, we are
  5806    // effectively coercing the untyped operand to the other operand's
  5807    // type, so make sure that is valid.
  5808    if (!left_nc->set_type(type, true, location))
  5809      return false;
  5810    if (!is_shift && !right_nc->set_type(type, true, location))
  5811      return false;
  5812    if (is_shift
  5813        && ((left_type->integer_type() == NULL
  5814             && !left_type->is_abstract())
  5815            || (right_type->integer_type() == NULL
  5816                && !right_type->is_abstract())))
  5817      return false;
  5818  
  5819    bool r;
  5820    if (type->complex_type() != NULL)
  5821      r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
  5822    else if (type->float_type() != NULL)
  5823      r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
  5824    else
  5825      r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
  5826  
  5827    if (r)
  5828      {
  5829        r = nc->set_type(type, true, location);
  5830        if (!r)
  5831  	*issued_error = true;
  5832      }
  5833  
  5834    return r;
  5835  }
  5836  
  5837  // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
  5838  // integer operations.  Return true if this could be done, false if
  5839  // not.
  5840  
  5841  bool
  5842  Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
  5843  				const Numeric_constant* right_nc,
  5844  				Location location, Numeric_constant* nc)
  5845  {
  5846    mpz_t left_val;
  5847    if (!left_nc->to_int(&left_val))
  5848      return false;
  5849    mpz_t right_val;
  5850    if (!right_nc->to_int(&right_val))
  5851      {
  5852        mpz_clear(left_val);
  5853        return false;
  5854      }
  5855  
  5856    mpz_t val;
  5857    mpz_init(val);
  5858  
  5859    switch (op)
  5860      {
  5861      case OPERATOR_PLUS:
  5862        mpz_add(val, left_val, right_val);
  5863        if (mpz_sizeinbase(val, 2) > 0x100000)
  5864  	{
  5865  	  go_error_at(location, "constant addition overflow");
  5866            nc->set_invalid();
  5867  	  mpz_set_ui(val, 1);
  5868  	}
  5869        break;
  5870      case OPERATOR_MINUS:
  5871        mpz_sub(val, left_val, right_val);
  5872        if (mpz_sizeinbase(val, 2) > 0x100000)
  5873  	{
  5874  	  go_error_at(location, "constant subtraction overflow");
  5875            nc->set_invalid();
  5876  	  mpz_set_ui(val, 1);
  5877  	}
  5878        break;
  5879      case OPERATOR_OR:
  5880        mpz_ior(val, left_val, right_val);
  5881        break;
  5882      case OPERATOR_XOR:
  5883        mpz_xor(val, left_val, right_val);
  5884        break;
  5885      case OPERATOR_MULT:
  5886        mpz_mul(val, left_val, right_val);
  5887        if (mpz_sizeinbase(val, 2) > 0x100000)
  5888  	{
  5889  	  go_error_at(location, "constant multiplication overflow");
  5890            nc->set_invalid();
  5891  	  mpz_set_ui(val, 1);
  5892  	}
  5893        break;
  5894      case OPERATOR_DIV:
  5895        if (mpz_sgn(right_val) != 0)
  5896  	mpz_tdiv_q(val, left_val, right_val);
  5897        else
  5898  	{
  5899  	  go_error_at(location, "division by zero");
  5900            nc->set_invalid();
  5901  	  mpz_set_ui(val, 0);
  5902  	}
  5903        break;
  5904      case OPERATOR_MOD:
  5905        if (mpz_sgn(right_val) != 0)
  5906  	mpz_tdiv_r(val, left_val, right_val);
  5907        else
  5908  	{
  5909  	  go_error_at(location, "division by zero");
  5910            nc->set_invalid();
  5911  	  mpz_set_ui(val, 0);
  5912  	}
  5913        break;
  5914      case OPERATOR_LSHIFT:
  5915        {
  5916  	unsigned long shift = mpz_get_ui(right_val);
  5917  	if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
  5918  	  mpz_mul_2exp(val, left_val, shift);
  5919  	else
  5920  	  {
  5921  	    go_error_at(location, "shift count overflow");
  5922              nc->set_invalid();
  5923  	    mpz_set_ui(val, 1);
  5924  	  }
  5925  	break;
  5926        }
  5927        break;
  5928      case OPERATOR_RSHIFT:
  5929        {
  5930  	unsigned long shift = mpz_get_ui(right_val);
  5931  	if (mpz_cmp_ui(right_val, shift) != 0)
  5932  	  {
  5933  	    go_error_at(location, "shift count overflow");
  5934              nc->set_invalid();
  5935  	    mpz_set_ui(val, 1);
  5936  	  }
  5937  	else
  5938  	  {
  5939  	    if (mpz_cmp_ui(left_val, 0) >= 0)
  5940  	      mpz_tdiv_q_2exp(val, left_val, shift);
  5941  	    else
  5942  	      mpz_fdiv_q_2exp(val, left_val, shift);
  5943  	  }
  5944  	break;
  5945        }
  5946        break;
  5947      case OPERATOR_AND:
  5948        mpz_and(val, left_val, right_val);
  5949        break;
  5950      case OPERATOR_BITCLEAR:
  5951        {
  5952  	mpz_t tval;
  5953  	mpz_init(tval);
  5954  	mpz_com(tval, right_val);
  5955  	mpz_and(val, left_val, tval);
  5956  	mpz_clear(tval);
  5957        }
  5958        break;
  5959      default:
  5960        go_unreachable();
  5961      }
  5962  
  5963    mpz_clear(left_val);
  5964    mpz_clear(right_val);
  5965  
  5966    if (left_nc->is_rune()
  5967        || (op != OPERATOR_LSHIFT
  5968  	  && op != OPERATOR_RSHIFT
  5969  	  && right_nc->is_rune()))
  5970      nc->set_rune(NULL, val);
  5971    else
  5972      nc->set_int(NULL, val);
  5973  
  5974    mpz_clear(val);
  5975  
  5976    return true;
  5977  }
  5978  
  5979  // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
  5980  // floating point operations.  Return true if this could be done,
  5981  // false if not.
  5982  
  5983  bool
  5984  Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
  5985  			      const Numeric_constant* right_nc,
  5986  			      Location location, Numeric_constant* nc)
  5987  {
  5988    mpfr_t left_val;
  5989    if (!left_nc->to_float(&left_val))
  5990      return false;
  5991    mpfr_t right_val;
  5992    if (!right_nc->to_float(&right_val))
  5993      {
  5994        mpfr_clear(left_val);
  5995        return false;
  5996      }
  5997  
  5998    mpfr_t val;
  5999    mpfr_init(val);
  6000  
  6001    bool ret = true;
  6002    switch (op)
  6003      {
  6004      case OPERATOR_PLUS:
  6005        mpfr_add(val, left_val, right_val, MPFR_RNDN);
  6006        break;
  6007      case OPERATOR_MINUS:
  6008        mpfr_sub(val, left_val, right_val, MPFR_RNDN);
  6009        break;
  6010      case OPERATOR_OR:
  6011      case OPERATOR_XOR:
  6012      case OPERATOR_AND:
  6013      case OPERATOR_BITCLEAR:
  6014      case OPERATOR_MOD:
  6015      case OPERATOR_LSHIFT:
  6016      case OPERATOR_RSHIFT:
  6017        mpfr_set_ui(val, 0, MPFR_RNDN);
  6018        ret = false;
  6019        break;
  6020      case OPERATOR_MULT:
  6021        mpfr_mul(val, left_val, right_val, MPFR_RNDN);
  6022        break;
  6023      case OPERATOR_DIV:
  6024        if (!mpfr_zero_p(right_val))
  6025  	mpfr_div(val, left_val, right_val, MPFR_RNDN);
  6026        else
  6027  	{
  6028  	  go_error_at(location, "division by zero");
  6029            nc->set_invalid();
  6030  	  mpfr_set_ui(val, 0, MPFR_RNDN);
  6031  	}
  6032        break;
  6033      default:
  6034        go_unreachable();
  6035      }
  6036  
  6037    mpfr_clear(left_val);
  6038    mpfr_clear(right_val);
  6039  
  6040    nc->set_float(NULL, val);
  6041    mpfr_clear(val);
  6042  
  6043    return ret;
  6044  }
  6045  
  6046  // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
  6047  // complex operations.  Return true if this could be done, false if
  6048  // not.
  6049  
  6050  bool
  6051  Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
  6052  				const Numeric_constant* right_nc,
  6053  				Location location, Numeric_constant* nc)
  6054  {
  6055    mpc_t left_val;
  6056    if (!left_nc->to_complex(&left_val))
  6057      return false;
  6058    mpc_t right_val;
  6059    if (!right_nc->to_complex(&right_val))
  6060      {
  6061        mpc_clear(left_val);
  6062        return false;
  6063      }
  6064  
  6065    mpc_t val;
  6066    mpc_init2(val, mpc_precision);
  6067  
  6068    bool ret = true;
  6069    switch (op)
  6070      {
  6071      case OPERATOR_PLUS:
  6072        mpc_add(val, left_val, right_val, MPC_RNDNN);
  6073        break;
  6074      case OPERATOR_MINUS:
  6075        mpc_sub(val, left_val, right_val, MPC_RNDNN);
  6076        break;
  6077      case OPERATOR_OR:
  6078      case OPERATOR_XOR:
  6079      case OPERATOR_AND:
  6080      case OPERATOR_BITCLEAR:
  6081      case OPERATOR_MOD:
  6082      case OPERATOR_LSHIFT:
  6083      case OPERATOR_RSHIFT:
  6084        mpc_set_ui(val, 0, MPC_RNDNN);
  6085        ret = false;
  6086        break;
  6087      case OPERATOR_MULT:
  6088        mpc_mul(val, left_val, right_val, MPC_RNDNN);
  6089        break;
  6090      case OPERATOR_DIV:
  6091        if (mpc_cmp_si(right_val, 0) == 0)
  6092  	{
  6093  	  go_error_at(location, "division by zero");
  6094            nc->set_invalid();
  6095  	  mpc_set_ui(val, 0, MPC_RNDNN);
  6096  	  break;
  6097  	}
  6098        mpc_div(val, left_val, right_val, MPC_RNDNN);
  6099        break;
  6100      default:
  6101        go_unreachable();
  6102      }
  6103  
  6104    mpc_clear(left_val);
  6105    mpc_clear(right_val);
  6106  
  6107    nc->set_complex(NULL, val);
  6108    mpc_clear(val);
  6109  
  6110    return ret;
  6111  }
  6112  
  6113  // Lower a binary expression.  We have to evaluate constant
  6114  // expressions now, in order to implement Go's unlimited precision
  6115  // constants.
  6116  
  6117  Expression*
  6118  Binary_expression::do_lower(Gogo* gogo, Named_object*,
  6119  			    Statement_inserter* inserter, int)
  6120  {
  6121    Location location = this->location();
  6122    Operator op = this->op_;
  6123    Expression* left = this->left_;
  6124    Expression* right = this->right_;
  6125  
  6126    const bool is_comparison = (op == OPERATOR_EQEQ
  6127  			      || op == OPERATOR_NOTEQ
  6128  			      || op == OPERATOR_LT
  6129  			      || op == OPERATOR_LE
  6130  			      || op == OPERATOR_GT
  6131  			      || op == OPERATOR_GE);
  6132  
  6133    // Numeric constant expressions.
  6134    {
  6135      Numeric_constant left_nc;
  6136      Numeric_constant right_nc;
  6137      if (left->numeric_constant_value(&left_nc)
  6138  	&& right->numeric_constant_value(&right_nc))
  6139        {
  6140  	if (is_comparison)
  6141  	  {
  6142  	    bool result;
  6143  	    if (!Binary_expression::compare_constant(op, &left_nc,
  6144  						     &right_nc, location,
  6145  						     &result))
  6146  	      return this;
  6147  	    return Expression::make_boolean(result, location);
  6148  	  }
  6149  	else
  6150  	  {
  6151  	    Numeric_constant nc;
  6152  	    bool issued_error;
  6153  	    if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
  6154  						  location, &nc,
  6155  						  &issued_error))
  6156  	      {
  6157  		if (issued_error)
  6158  		  return Expression::make_error(location);
  6159                  return this;
  6160  	      }
  6161  	    return nc.expression(location);
  6162  	  }
  6163        }
  6164    }
  6165  
  6166    // String constant expressions.
  6167    //
  6168    // Avoid constant folding here if the left and right types are incompatible
  6169    // (leave the operation intact so that the type checker can complain about it
  6170    // later on). If concatenating an abstract string with a named string type,
  6171    // result type needs to be of the named type (see issue 31412).
  6172    if (left->type()->is_string_type()
  6173        && right->type()->is_string_type()
  6174        && (left->type()->named_type() == NULL
  6175            || right->type()->named_type() == NULL
  6176            || left->type()->named_type() == right->type()->named_type()))
  6177      {
  6178        std::string left_string;
  6179        std::string right_string;
  6180        if (left->string_constant_value(&left_string)
  6181  	  && right->string_constant_value(&right_string))
  6182  	{
  6183  	  if (op == OPERATOR_PLUS)
  6184              {
  6185                Type* result_type = (left->type()->named_type() != NULL
  6186                                     ? left->type()
  6187                                     : right->type());
  6188  	      delete left;
  6189  	      delete right;
  6190                return Expression::make_string_typed(left_string + right_string,
  6191                                                     result_type, location);
  6192              }
  6193  	  else if (is_comparison)
  6194  	    {
  6195  	      int cmp = left_string.compare(right_string);
  6196  	      bool r = Binary_expression::cmp_to_bool(op, cmp);
  6197  	      delete left;
  6198  	      delete right;
  6199  	      return Expression::make_boolean(r, location);
  6200  	    }
  6201  	}
  6202      }
  6203  
  6204    // Lower struct, array, and some interface comparisons.
  6205    if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
  6206      {
  6207        if (left->type()->struct_type() != NULL
  6208  	  && right->type()->struct_type() != NULL)
  6209  	return this->lower_struct_comparison(gogo, inserter);
  6210        else if (left->type()->array_type() != NULL
  6211  	       && !left->type()->is_slice_type()
  6212  	       && right->type()->array_type() != NULL
  6213  	       && !right->type()->is_slice_type())
  6214  	return this->lower_array_comparison(gogo, inserter);
  6215        else if ((left->type()->interface_type() != NULL
  6216                  && right->type()->interface_type() == NULL)
  6217                 || (left->type()->interface_type() == NULL
  6218                     && right->type()->interface_type() != NULL))
  6219  	return this->lower_interface_value_comparison(gogo, inserter);
  6220      }
  6221  
  6222    // Lower string concatenation to String_concat_expression, so that
  6223    // we can group sequences of string additions.
  6224    if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
  6225      {
  6226        Expression_list* exprs;
  6227        String_concat_expression* left_sce =
  6228  	this->left_->string_concat_expression();
  6229        if (left_sce != NULL)
  6230  	exprs = left_sce->exprs();
  6231        else
  6232  	{
  6233  	  exprs = new Expression_list();
  6234  	  exprs->push_back(this->left_);
  6235  	}
  6236  
  6237        String_concat_expression* right_sce =
  6238  	this->right_->string_concat_expression();
  6239        if (right_sce != NULL)
  6240  	exprs->append(right_sce->exprs());
  6241        else
  6242  	exprs->push_back(this->right_);
  6243  
  6244        return Expression::make_string_concat(exprs);
  6245      }
  6246  
  6247    return this;
  6248  }
  6249  
  6250  // Lower a struct comparison.
  6251  
  6252  Expression*
  6253  Binary_expression::lower_struct_comparison(Gogo* gogo,
  6254  					   Statement_inserter* inserter)
  6255  {
  6256    Struct_type* st = this->left_->type()->struct_type();
  6257    Struct_type* st2 = this->right_->type()->struct_type();
  6258    if (st2 == NULL)
  6259      return this;
  6260    if (st != st2
  6261        && !Type::are_identical(st, st2,
  6262  			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
  6263  			      NULL))
  6264      return this;
  6265    if (!Type::are_compatible_for_comparison(true, this->left_->type(),
  6266  					   this->right_->type(), NULL))
  6267      return this;
  6268  
  6269    // See if we can compare using memcmp.  As a heuristic, we use
  6270    // memcmp rather than field references and comparisons if there are
  6271    // more than two fields.
  6272    if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
  6273      return this->lower_compare_to_memcmp(gogo, inserter);
  6274  
  6275    Location loc = this->location();
  6276  
  6277    Expression* left = this->left_;
  6278    Temporary_statement* left_temp = NULL;
  6279    if (left->var_expression() == NULL
  6280        && left->temporary_reference_expression() == NULL)
  6281      {
  6282        left_temp = Statement::make_temporary(left->type(), NULL, loc);
  6283        inserter->insert(left_temp);
  6284        left = Expression::make_set_and_use_temporary(left_temp, left, loc);
  6285      }
  6286  
  6287    Expression* right = this->right_;
  6288    Temporary_statement* right_temp = NULL;
  6289    if (right->var_expression() == NULL
  6290        && right->temporary_reference_expression() == NULL)
  6291      {
  6292        right_temp = Statement::make_temporary(right->type(), NULL, loc);
  6293        inserter->insert(right_temp);
  6294        right = Expression::make_set_and_use_temporary(right_temp, right, loc);
  6295      }
  6296  
  6297    Expression* ret = Expression::make_boolean(true, loc);
  6298    const Struct_field_list* fields = st->fields();
  6299    unsigned int field_index = 0;
  6300    for (Struct_field_list::const_iterator pf = fields->begin();
  6301         pf != fields->end();
  6302         ++pf, ++field_index)
  6303      {
  6304        if (Gogo::is_sink_name(pf->field_name()))
  6305  	continue;
  6306  
  6307        if (field_index > 0)
  6308  	{
  6309  	  if (left_temp == NULL)
  6310  	    left = left->copy();
  6311  	  else
  6312  	    left = Expression::make_temporary_reference(left_temp, loc);
  6313  	  if (right_temp == NULL)
  6314  	    right = right->copy();
  6315  	  else
  6316  	    right = Expression::make_temporary_reference(right_temp, loc);
  6317  	}
  6318        Expression* f1 = Expression::make_field_reference(left, field_index,
  6319  							loc);
  6320        Expression* f2 = Expression::make_field_reference(right, field_index,
  6321  							loc);
  6322        Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
  6323        ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
  6324      }
  6325  
  6326    if (this->op_ == OPERATOR_NOTEQ)
  6327      ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
  6328  
  6329    return ret;
  6330  }
  6331  
  6332  // Lower an array comparison.
  6333  
  6334  Expression*
  6335  Binary_expression::lower_array_comparison(Gogo* gogo,
  6336  					  Statement_inserter* inserter)
  6337  {
  6338    Array_type* at = this->left_->type()->array_type();
  6339    Array_type* at2 = this->right_->type()->array_type();
  6340    if (at2 == NULL)
  6341      return this;
  6342    if (at != at2
  6343        && !Type::are_identical(at, at2,
  6344  			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
  6345  			      NULL))
  6346      return this;
  6347    if (!Type::are_compatible_for_comparison(true, this->left_->type(),
  6348  					   this->right_->type(), NULL))
  6349      return this;
  6350  
  6351    // Call memcmp directly if possible.  This may let the middle-end
  6352    // optimize the call.
  6353    if (at->compare_is_identity(gogo))
  6354      return this->lower_compare_to_memcmp(gogo, inserter);
  6355  
  6356    // Call the array comparison function.
  6357    Named_object* equal_fn =
  6358      at->equal_function(gogo, this->left_->type()->named_type(), NULL);
  6359  
  6360    Location loc = this->location();
  6361  
  6362    Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
  6363  
  6364    Expression_list* args = new Expression_list();
  6365    args->push_back(this->operand_address(inserter, this->left_));
  6366    args->push_back(this->operand_address(inserter, this->right_));
  6367  
  6368    Call_expression* ce = Expression::make_call(func, args, false, loc);
  6369  
  6370    // Record that this is a call to a generated equality function.  We
  6371    // need to do this because a comparison returns an abstract boolean
  6372    // type, but the function necessarily returns "bool".  The
  6373    // difference shows up in code like
  6374    //     type mybool bool
  6375    //     var b mybool = [10]string{} == [10]string{}
  6376    // The comparison function returns "bool", but since a comparison
  6377    // has an abstract boolean type we need an implicit conversion to
  6378    // "mybool".  The implicit conversion is inserted in
  6379    // Call_expression::do_flatten.
  6380    ce->set_is_equal_function();
  6381  
  6382    Expression* ret = ce;
  6383    if (this->op_ == OPERATOR_NOTEQ)
  6384      ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
  6385  
  6386    return ret;
  6387  }
  6388  
  6389  // Lower an interface to value comparison.
  6390  
  6391  Expression*
  6392  Binary_expression::lower_interface_value_comparison(Gogo*,
  6393                                                      Statement_inserter* inserter)
  6394  {
  6395    Type* left_type = this->left_->type();
  6396    Type* right_type = this->right_->type();
  6397    Interface_type* ift;
  6398    if (left_type->interface_type() != NULL)
  6399      {
  6400        ift = left_type->interface_type();
  6401        if (!ift->implements_interface(right_type, NULL))
  6402          return this;
  6403      }
  6404    else
  6405      {
  6406        ift = right_type->interface_type();
  6407        if (!ift->implements_interface(left_type, NULL))
  6408          return this;
  6409      }
  6410    if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
  6411      return this;
  6412  
  6413    Location loc = this->location();
  6414  
  6415    if (left_type->interface_type() == NULL
  6416        && left_type->points_to() == NULL
  6417        && !this->left_->is_addressable())
  6418      {
  6419        Temporary_statement* temp =
  6420            Statement::make_temporary(left_type, NULL, loc);
  6421        inserter->insert(temp);
  6422        this->left_ =
  6423            Expression::make_set_and_use_temporary(temp, this->left_, loc);
  6424      }
  6425  
  6426    if (right_type->interface_type() == NULL
  6427        && right_type->points_to() == NULL
  6428        && !this->right_->is_addressable())
  6429      {
  6430        Temporary_statement* temp =
  6431            Statement::make_temporary(right_type, NULL, loc);
  6432        inserter->insert(temp);
  6433        this->right_ =
  6434            Expression::make_set_and_use_temporary(temp, this->right_, loc);
  6435      }
  6436  
  6437    return this;
  6438  }
  6439  
  6440  // Lower a struct or array comparison to a call to memcmp.
  6441  
  6442  Expression*
  6443  Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
  6444  {
  6445    Location loc = this->location();
  6446  
  6447    Expression* a1 = this->operand_address(inserter, this->left_);
  6448    Expression* a2 = this->operand_address(inserter, this->right_);
  6449    Expression* len = Expression::make_type_info(this->left_->type(),
  6450  					       TYPE_INFO_SIZE);
  6451  
  6452    Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
  6453    Type* int32_type = Type::lookup_integer_type("int32");
  6454    Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
  6455    return Expression::make_binary(this->op_, call, zero, loc);
  6456  }
  6457  
  6458  Expression*
  6459  Binary_expression::do_flatten(Gogo* gogo, Named_object*,
  6460                                Statement_inserter* inserter)
  6461  {
  6462    Location loc = this->location();
  6463    if (this->left_->type()->is_error_type()
  6464        || this->right_->type()->is_error_type()
  6465        || this->left_->is_error_expression()
  6466        || this->right_->is_error_expression())
  6467      {
  6468        go_assert(saw_errors());
  6469        return Expression::make_error(loc);
  6470      }
  6471  
  6472    Temporary_statement* temp;
  6473  
  6474    Type* left_type = this->left_->type();
  6475    bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
  6476                        || this->op_ == OPERATOR_RSHIFT);
  6477    bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
  6478                        left_type->integer_type() != NULL)
  6479                       || this->op_ == OPERATOR_MOD);
  6480    bool is_string_op = (left_type->is_string_type()
  6481                         && this->right_->type()->is_string_type());
  6482  
  6483    if (is_string_op)
  6484      {
  6485        // Mark string([]byte) operands to reuse the backing store.
  6486        // String comparison does not keep the reference, so it is safe.
  6487        Type_conversion_expression* lce =
  6488          this->left_->conversion_expression();
  6489        if (lce != NULL && lce->expr()->type()->is_slice_type())
  6490          lce->set_no_copy(true);
  6491        Type_conversion_expression* rce =
  6492          this->right_->conversion_expression();
  6493        if (rce != NULL && rce->expr()->type()->is_slice_type())
  6494          rce->set_no_copy(true);
  6495      }
  6496  
  6497    if (is_shift_op
  6498        || (is_idiv_op
  6499  	  && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
  6500        || is_string_op)
  6501      {
  6502        if (!this->left_->is_multi_eval_safe())
  6503          {
  6504            temp = Statement::make_temporary(NULL, this->left_, loc);
  6505            inserter->insert(temp);
  6506            this->left_ = Expression::make_temporary_reference(temp, loc);
  6507          }
  6508        if (!this->right_->is_multi_eval_safe())
  6509          {
  6510            temp =
  6511                Statement::make_temporary(NULL, this->right_, loc);
  6512            this->right_ = Expression::make_temporary_reference(temp, loc);
  6513            inserter->insert(temp);
  6514          }
  6515      }
  6516    return this;
  6517  }
  6518  
  6519  
  6520  // Return the address of EXPR, cast to unsafe.Pointer.
  6521  
  6522  Expression*
  6523  Binary_expression::operand_address(Statement_inserter* inserter,
  6524  				   Expression* expr)
  6525  {
  6526    Location loc = this->location();
  6527  
  6528    if (!expr->is_addressable())
  6529      {
  6530        Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
  6531  							    loc);
  6532        inserter->insert(temp);
  6533        expr = Expression::make_set_and_use_temporary(temp, expr, loc);
  6534      }
  6535    expr = Expression::make_unary(OPERATOR_AND, expr, loc);
  6536    static_cast<Unary_expression*>(expr)->set_does_not_escape();
  6537    Type* void_type = Type::make_void_type();
  6538    Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
  6539    return Expression::make_cast(unsafe_pointer_type, expr, loc);
  6540  }
  6541  
  6542  // Return the numeric constant value, if it has one.
  6543  
  6544  bool
  6545  Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
  6546  {
  6547    Numeric_constant left_nc;
  6548    if (!this->left_->numeric_constant_value(&left_nc))
  6549      return false;
  6550    Numeric_constant right_nc;
  6551    if (!this->right_->numeric_constant_value(&right_nc))
  6552      return false;
  6553    bool issued_error;
  6554    return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
  6555  					  this->location(), nc, &issued_error);
  6556  }
  6557  
  6558  // Return the boolean constant value, if it has one.
  6559  
  6560  bool
  6561  Binary_expression::do_boolean_constant_value(bool* val) const
  6562  {
  6563    bool is_comparison = false;
  6564    switch (this->op_)
  6565      {
  6566      case OPERATOR_EQEQ:
  6567      case OPERATOR_NOTEQ:
  6568      case OPERATOR_LT:
  6569      case OPERATOR_LE:
  6570      case OPERATOR_GT:
  6571      case OPERATOR_GE:
  6572        is_comparison = true;
  6573        break;
  6574      case OPERATOR_ANDAND:
  6575      case OPERATOR_OROR:
  6576        break;
  6577      default:
  6578        return false;
  6579      }
  6580  
  6581    Numeric_constant left_nc, right_nc;
  6582    if (is_comparison
  6583        && this->left_->numeric_constant_value(&left_nc)
  6584        && this->right_->numeric_constant_value(&right_nc))
  6585      return Binary_expression::compare_constant(this->op_, &left_nc,
  6586                                                 &right_nc,
  6587                                                 this->location(),
  6588                                                 val);
  6589  
  6590    std::string left_str, right_str;
  6591    if (is_comparison
  6592        && this->left_->string_constant_value(&left_str)
  6593        && this->right_->string_constant_value(&right_str))
  6594      {
  6595        *val = Binary_expression::cmp_to_bool(this->op_,
  6596                                              left_str.compare(right_str));
  6597        return true;
  6598      }
  6599  
  6600    bool left_bval;
  6601    if (this->left_->boolean_constant_value(&left_bval))
  6602      {
  6603        if (this->op_ == OPERATOR_ANDAND && !left_bval)
  6604          {
  6605            *val = false;
  6606            return true;
  6607          }
  6608        else if (this->op_ == OPERATOR_OROR && left_bval)
  6609          {
  6610            *val = true;
  6611            return true;
  6612          }
  6613  
  6614        bool right_bval;
  6615        if (this->right_->boolean_constant_value(&right_bval))
  6616          {
  6617            switch (this->op_)
  6618              {
  6619              case OPERATOR_EQEQ:
  6620                *val = (left_bval == right_bval);
  6621                return true;
  6622              case OPERATOR_NOTEQ:
  6623                *val = (left_bval != right_bval);
  6624                return true;
  6625              case OPERATOR_ANDAND:
  6626              case OPERATOR_OROR:
  6627                *val = right_bval;
  6628                return true;
  6629              default:
  6630                go_unreachable();
  6631              }
  6632          }
  6633      }
  6634  
  6635    return false;
  6636  }
  6637  
  6638  // Note that the value is being discarded.
  6639  
  6640  bool
  6641  Binary_expression::do_discarding_value()
  6642  {
  6643    if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
  6644      return this->right_->discarding_value();
  6645    else
  6646      {
  6647        this->unused_value_error();
  6648        return false;
  6649      }
  6650  }
  6651  
  6652  // Get type.
  6653  
  6654  Type*
  6655  Binary_expression::do_type()
  6656  {
  6657    if (this->classification() == EXPRESSION_ERROR)
  6658      return Type::make_error_type();
  6659  
  6660    switch (this->op_)
  6661      {
  6662      case OPERATOR_EQEQ:
  6663      case OPERATOR_NOTEQ:
  6664      case OPERATOR_LT:
  6665      case OPERATOR_LE:
  6666      case OPERATOR_GT:
  6667      case OPERATOR_GE:
  6668        if (this->type_ == NULL)
  6669  	this->type_ = Type::make_boolean_type();
  6670        return this->type_;
  6671  
  6672      case OPERATOR_PLUS:
  6673      case OPERATOR_MINUS:
  6674      case OPERATOR_OR:
  6675      case OPERATOR_XOR:
  6676      case OPERATOR_MULT:
  6677      case OPERATOR_DIV:
  6678      case OPERATOR_MOD:
  6679      case OPERATOR_AND:
  6680      case OPERATOR_BITCLEAR:
  6681      case OPERATOR_OROR:
  6682      case OPERATOR_ANDAND:
  6683        {
  6684  	Type* type;
  6685  	if (!Binary_expression::operation_type(this->op_,
  6686  					       this->left_->type(),
  6687  					       this->right_->type(),
  6688  					       &type))
  6689  	  return Type::make_error_type();
  6690  	return type;
  6691        }
  6692  
  6693      case OPERATOR_LSHIFT:
  6694      case OPERATOR_RSHIFT:
  6695        return this->left_->type();
  6696  
  6697      default:
  6698        go_unreachable();
  6699      }
  6700  }
  6701  
  6702  // Set type for a binary expression.
  6703  
  6704  void
  6705  Binary_expression::do_determine_type(const Type_context* context)
  6706  {
  6707    Type* tleft = this->left_->type();
  6708    Type* tright = this->right_->type();
  6709  
  6710    // Both sides should have the same type, except for the shift
  6711    // operations.  For a comparison, we should ignore the incoming
  6712    // type.
  6713  
  6714    bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
  6715  		      || this->op_ == OPERATOR_RSHIFT);
  6716  
  6717    bool is_comparison = (this->op_ == OPERATOR_EQEQ
  6718  			|| this->op_ == OPERATOR_NOTEQ
  6719  			|| this->op_ == OPERATOR_LT
  6720  			|| this->op_ == OPERATOR_LE
  6721  			|| this->op_ == OPERATOR_GT
  6722  			|| this->op_ == OPERATOR_GE);
  6723  
  6724    // For constant expressions, the context of the result is not useful in
  6725    // determining the types of the operands.  It is only legal to use abstract
  6726    // boolean, numeric, and string constants as operands where it is legal to
  6727    // use non-abstract boolean, numeric, and string constants, respectively.
  6728    // Any issues with the operation will be resolved in the check_types pass.
  6729    bool is_constant_expr = (this->left_->is_constant()
  6730                             && this->right_->is_constant());
  6731  
  6732    Type_context subcontext(*context);
  6733  
  6734    if (is_constant_expr && !is_shift_op)
  6735      {
  6736        subcontext.type = NULL;
  6737        subcontext.may_be_abstract = true;
  6738      }
  6739    else if (is_comparison)
  6740      {
  6741        // In a comparison, the context does not determine the types of
  6742        // the operands.
  6743        subcontext.type = NULL;
  6744      }
  6745  
  6746    // Set the context for the left hand operand.
  6747    if (is_shift_op)
  6748      {
  6749        // The right hand operand of a shift plays no role in
  6750        // determining the type of the left hand operand.
  6751      }
  6752    else if (!tleft->is_abstract())
  6753      subcontext.type = tleft;
  6754    else if (!tright->is_abstract())
  6755      subcontext.type = tright;
  6756    else if (subcontext.type == NULL)
  6757      {
  6758        if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
  6759  	  || (tleft->float_type() != NULL && tright->float_type() != NULL)
  6760  	  || (tleft->complex_type() != NULL && tright->complex_type() != NULL)
  6761  	  || (tleft->is_boolean_type() && tright->is_boolean_type()))
  6762  	{
  6763  	  // Both sides have an abstract integer, abstract float,
  6764  	  // abstract complex, or abstract boolean type.  Just let
  6765  	  // CONTEXT determine whether they may remain abstract or not.
  6766  	}
  6767        else if (tleft->complex_type() != NULL)
  6768  	subcontext.type = tleft;
  6769        else if (tright->complex_type() != NULL)
  6770  	subcontext.type = tright;
  6771        else if (tleft->float_type() != NULL)
  6772  	subcontext.type = tleft;
  6773        else if (tright->float_type() != NULL)
  6774  	subcontext.type = tright;
  6775        else
  6776  	subcontext.type = tleft;
  6777  
  6778        if (subcontext.type != NULL && !context->may_be_abstract)
  6779  	subcontext.type = subcontext.type->make_non_abstract_type();
  6780      }
  6781  
  6782    this->left_->determine_type(&subcontext);
  6783  
  6784    if (is_shift_op)
  6785      {
  6786        // We may have inherited an unusable type for the shift operand.
  6787        // Give a useful error if that happened.
  6788        if (tleft->is_abstract()
  6789  	  && subcontext.type != NULL
  6790  	  && !subcontext.may_be_abstract
  6791  	  && subcontext.type->interface_type() == NULL
  6792  	  && subcontext.type->integer_type() == NULL)
  6793  	this->report_error(("invalid context-determined non-integer type "
  6794  			    "for left operand of shift"));
  6795  
  6796        // The context for the right hand operand is the same as for the
  6797        // left hand operand, except for a shift operator.
  6798        subcontext.type = Type::lookup_integer_type("uint");
  6799        subcontext.may_be_abstract = false;
  6800      }
  6801  
  6802    this->right_->determine_type(&subcontext);
  6803  
  6804    if (is_comparison)
  6805      {
  6806        if (this->type_ != NULL && !this->type_->is_abstract())
  6807  	;
  6808        else if (context->type != NULL && context->type->is_boolean_type())
  6809  	this->type_ = context->type;
  6810        else if (!context->may_be_abstract)
  6811  	this->type_ = Type::lookup_bool_type();
  6812      }
  6813  }
  6814  
  6815  // Report an error if the binary operator OP does not support TYPE.
  6816  // OTYPE is the type of the other operand.  Return whether the
  6817  // operation is OK.  This should not be used for shift.
  6818  
  6819  bool
  6820  Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
  6821  				       Location location)
  6822  {
  6823    switch (op)
  6824      {
  6825      case OPERATOR_OROR:
  6826      case OPERATOR_ANDAND:
  6827        if (!type->is_boolean_type()
  6828            || !otype->is_boolean_type())
  6829  	{
  6830  	  go_error_at(location, "expected boolean type");
  6831  	  return false;
  6832  	}
  6833        break;
  6834  
  6835      case OPERATOR_EQEQ:
  6836      case OPERATOR_NOTEQ:
  6837        {
  6838  	std::string reason;
  6839  	if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
  6840  	  {
  6841  	    go_error_at(location, "%s", reason.c_str());
  6842  	    return false;
  6843  	  }
  6844        }
  6845        break;
  6846  
  6847      case OPERATOR_LT:
  6848      case OPERATOR_LE:
  6849      case OPERATOR_GT:
  6850      case OPERATOR_GE:
  6851        {
  6852  	std::string reason;
  6853  	if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
  6854  	  {
  6855  	    go_error_at(location, "%s", reason.c_str());
  6856  	    return false;
  6857  	  }
  6858        }
  6859        break;
  6860  
  6861      case OPERATOR_PLUS:
  6862      case OPERATOR_PLUSEQ:
  6863        if ((!type->is_numeric_type() && !type->is_string_type())
  6864            || (!otype->is_numeric_type() && !otype->is_string_type()))
  6865  	{
  6866  	  go_error_at(location,
  6867  		   "expected integer, floating, complex, or string type");
  6868  	  return false;
  6869  	}
  6870        break;
  6871  
  6872      case OPERATOR_MINUS:
  6873      case OPERATOR_MINUSEQ:
  6874      case OPERATOR_MULT:
  6875      case OPERATOR_MULTEQ:
  6876      case OPERATOR_DIV:
  6877      case OPERATOR_DIVEQ:
  6878        if (!type->is_numeric_type() || !otype->is_numeric_type())
  6879  	{
  6880  	  go_error_at(location, "expected integer, floating, or complex type");
  6881  	  return false;
  6882  	}
  6883        break;
  6884  
  6885      case OPERATOR_MOD:
  6886      case OPERATOR_MODEQ:
  6887      case OPERATOR_OR:
  6888      case OPERATOR_OREQ:
  6889      case OPERATOR_AND:
  6890      case OPERATOR_ANDEQ:
  6891      case OPERATOR_XOR:
  6892      case OPERATOR_XOREQ:
  6893      case OPERATOR_BITCLEAR:
  6894      case OPERATOR_BITCLEAREQ:
  6895        if (type->integer_type() == NULL || otype->integer_type() == NULL)
  6896  	{
  6897  	  go_error_at(location, "expected integer type");
  6898  	  return false;
  6899  	}
  6900        break;
  6901  
  6902      default:
  6903        go_unreachable();
  6904      }
  6905  
  6906    return true;
  6907  }
  6908  
  6909  // Check types.
  6910  
  6911  void
  6912  Binary_expression::do_check_types(Gogo*)
  6913  {
  6914    if (this->classification() == EXPRESSION_ERROR)
  6915      return;
  6916  
  6917    Type* left_type = this->left_->type();
  6918    Type* right_type = this->right_->type();
  6919    if (left_type->is_error() || right_type->is_error())
  6920      {
  6921        this->set_is_error();
  6922        return;
  6923      }
  6924  
  6925    if (this->op_ == OPERATOR_EQEQ
  6926        || this->op_ == OPERATOR_NOTEQ
  6927        || this->op_ == OPERATOR_LT
  6928        || this->op_ == OPERATOR_LE
  6929        || this->op_ == OPERATOR_GT
  6930        || this->op_ == OPERATOR_GE)
  6931      {
  6932        if (left_type->is_nil_type() && right_type->is_nil_type())
  6933  	{
  6934  	  this->report_error(_("invalid comparison of nil with nil"));
  6935  	  return;
  6936  	}
  6937        if (!Type::are_assignable(left_type, right_type, NULL)
  6938  	  && !Type::are_assignable(right_type, left_type, NULL))
  6939  	{
  6940  	  this->report_error(_("incompatible types in binary expression"));
  6941  	  return;
  6942  	}
  6943        if (!Binary_expression::check_operator_type(this->op_, left_type,
  6944  						  right_type,
  6945  						  this->location())
  6946  	  || !Binary_expression::check_operator_type(this->op_, right_type,
  6947  						     left_type,
  6948  						     this->location()))
  6949  	{
  6950  	  this->set_is_error();
  6951  	  return;
  6952  	}
  6953      }
  6954    else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
  6955      {
  6956        if (!Type::are_compatible_for_binop(left_type, right_type))
  6957  	{
  6958  	  this->report_error(_("incompatible types in binary expression"));
  6959  	  return;
  6960  	}
  6961        if (!Binary_expression::check_operator_type(this->op_, left_type,
  6962  						  right_type,
  6963  						  this->location()))
  6964  	{
  6965  	  this->set_is_error();
  6966  	  return;
  6967  	}
  6968        if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
  6969  	{
  6970  	  // Division by a zero integer constant is an error.
  6971  	  Numeric_constant rconst;
  6972  	  unsigned long rval;
  6973  	  if (left_type->integer_type() != NULL
  6974  	      && this->right_->numeric_constant_value(&rconst)
  6975  	      && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
  6976  	      && rval == 0)
  6977  	    {
  6978  	      this->report_error(_("integer division by zero"));
  6979  	      return;
  6980  	    }
  6981  	}
  6982      }
  6983    else
  6984      {
  6985        if (left_type->integer_type() == NULL)
  6986  	this->report_error(_("shift of non-integer operand"));
  6987  
  6988        if (right_type->is_string_type())
  6989          this->report_error(_("shift count not integer"));
  6990        else if (!right_type->is_abstract()
  6991  	       && right_type->integer_type() == NULL)
  6992  	this->report_error(_("shift count not integer"));
  6993        else
  6994  	{
  6995  	  Numeric_constant nc;
  6996  	  if (this->right_->numeric_constant_value(&nc))
  6997  	    {
  6998  	      mpz_t val;
  6999  	      if (!nc.to_int(&val))
  7000  		this->report_error(_("shift count not integer"));
  7001  	      else
  7002  		{
  7003  		  if (mpz_sgn(val) < 0)
  7004  		    {
  7005  		      this->report_error(_("negative shift count"));
  7006  		      Location rloc = this->right_->location();
  7007  		      this->right_ = Expression::make_integer_ul(0, right_type,
  7008  								 rloc);
  7009  		    }
  7010  		  mpz_clear(val);
  7011  		}
  7012  	    }
  7013  	}
  7014      }
  7015  }
  7016  
  7017  // Get the backend representation for a binary expression.
  7018  
  7019  Bexpression*
  7020  Binary_expression::do_get_backend(Translate_context* context)
  7021  {
  7022    Gogo* gogo = context->gogo();
  7023    Location loc = this->location();
  7024    Type* left_type = this->left_->type();
  7025    Type* right_type = this->right_->type();
  7026  
  7027    bool use_left_type = true;
  7028    bool is_shift_op = false;
  7029    bool is_idiv_op = false;
  7030    switch (this->op_)
  7031      {
  7032      case OPERATOR_EQEQ:
  7033      case OPERATOR_NOTEQ:
  7034      case OPERATOR_LT:
  7035      case OPERATOR_LE:
  7036      case OPERATOR_GT:
  7037      case OPERATOR_GE:
  7038        return Expression::comparison(context, this->type_, this->op_,
  7039  				    this->left_, this->right_, loc);
  7040  
  7041      case OPERATOR_OROR:
  7042      case OPERATOR_ANDAND:
  7043        use_left_type = false;
  7044        break;
  7045      case OPERATOR_PLUS:
  7046      case OPERATOR_MINUS:
  7047      case OPERATOR_OR:
  7048      case OPERATOR_XOR:
  7049      case OPERATOR_MULT:
  7050        break;
  7051      case OPERATOR_DIV:
  7052        if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
  7053          break;
  7054        // Fall through.
  7055      case OPERATOR_MOD:
  7056        is_idiv_op = true;
  7057        break;
  7058      case OPERATOR_LSHIFT:
  7059      case OPERATOR_RSHIFT:
  7060        is_shift_op = true;
  7061        break;
  7062      case OPERATOR_BITCLEAR:
  7063        this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
  7064      case OPERATOR_AND:
  7065        break;
  7066      default:
  7067        go_unreachable();
  7068      }
  7069  
  7070    // The only binary operation for string is +, and that should have
  7071    // been converted to a String_concat_expression in do_lower.
  7072    go_assert(!left_type->is_string_type());
  7073  
  7074    Bexpression* left = this->left_->get_backend(context);
  7075    Bexpression* right = this->right_->get_backend(context);
  7076  
  7077    Type* type = use_left_type ? left_type : right_type;
  7078    Btype* btype = type->get_backend(gogo);
  7079  
  7080    Bexpression* ret =
  7081        gogo->backend()->binary_expression(this->op_, left, right, loc);
  7082    ret = gogo->backend()->convert_expression(btype, ret, loc);
  7083  
  7084    // Initialize overflow constants.
  7085    Bexpression* overflow;
  7086    mpz_t zero;
  7087    mpz_init_set_ui(zero, 0UL);
  7088    mpz_t one;
  7089    mpz_init_set_ui(one, 1UL);
  7090    mpz_t neg_one;
  7091    mpz_init_set_si(neg_one, -1);
  7092  
  7093    Btype* left_btype = left_type->get_backend(gogo);
  7094    Btype* right_btype = right_type->get_backend(gogo);
  7095  
  7096    // In Go, a shift larger than the size of the type is well-defined.
  7097    // This is not true in C, so we need to insert a conditional.
  7098    // We also need to check for a negative shift count.
  7099    if (is_shift_op)
  7100      {
  7101        go_assert(left_type->integer_type() != NULL);
  7102        go_assert(right_type->integer_type() != NULL);
  7103  
  7104        int bits = left_type->integer_type()->bits();
  7105  
  7106        Numeric_constant nc;
  7107        unsigned long ul;
  7108        if (!this->right_->numeric_constant_value(&nc)
  7109  	  || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
  7110  	  || ul >= static_cast<unsigned long>(bits))
  7111  	{
  7112  	  mpz_t bitsval;
  7113  	  mpz_init_set_ui(bitsval, bits);
  7114  	  Bexpression* bits_expr =
  7115  	    gogo->backend()->integer_constant_expression(right_btype, bitsval);
  7116  	  Bexpression* compare =
  7117  	    gogo->backend()->binary_expression(OPERATOR_LT,
  7118  					       right, bits_expr, loc);
  7119  
  7120  	  Bexpression* zero_expr =
  7121  	    gogo->backend()->integer_constant_expression(left_btype, zero);
  7122  	  overflow = zero_expr;
  7123  	  Bfunction* bfn = context->function()->func_value()->get_decl();
  7124  	  if (this->op_ == OPERATOR_RSHIFT
  7125  	      && !left_type->integer_type()->is_unsigned())
  7126  	    {
  7127  	      Bexpression* neg_expr =
  7128  		gogo->backend()->binary_expression(OPERATOR_LT, left,
  7129  						   zero_expr, loc);
  7130  	      Bexpression* neg_one_expr =
  7131  		gogo->backend()->integer_constant_expression(left_btype,
  7132  							     neg_one);
  7133  	      overflow = gogo->backend()->conditional_expression(bfn,
  7134  								 btype,
  7135  								 neg_expr,
  7136  								 neg_one_expr,
  7137  								 zero_expr,
  7138  								 loc);
  7139  	    }
  7140  	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
  7141  							ret, overflow, loc);
  7142  	  mpz_clear(bitsval);
  7143  	}
  7144  
  7145        if (!right_type->integer_type()->is_unsigned()
  7146  	  && (!this->right_->numeric_constant_value(&nc)
  7147  	      || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
  7148  	{
  7149  	  Bexpression* zero_expr =
  7150  	    gogo->backend()->integer_constant_expression(right_btype, zero);
  7151  	  Bexpression* compare =
  7152  	    gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
  7153  					       loc);
  7154  	  Expression* crash = Runtime::make_call(Runtime::PANIC_SHIFT,
  7155  						 loc, 0);
  7156  	  Bexpression* bcrash = crash->get_backend(context);
  7157  	  Bfunction* bfn = context->function()->func_value()->get_decl();
  7158  	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
  7159  							bcrash, ret, loc);
  7160  	}
  7161      }
  7162  
  7163    // Add checks for division by zero and division overflow as needed.
  7164    if (is_idiv_op)
  7165      {
  7166        if (gogo->check_divide_by_zero())
  7167  	{
  7168  	  // right == 0
  7169            Bexpression* zero_expr =
  7170                gogo->backend()->integer_constant_expression(right_btype, zero);
  7171            Bexpression* check =
  7172                gogo->backend()->binary_expression(OPERATOR_EQEQ,
  7173                                                   right, zero_expr, loc);
  7174  
  7175  	  Expression* crash = Runtime::make_call(Runtime::PANIC_DIVIDE,
  7176  						 loc, 0);
  7177  	  Bexpression* bcrash = crash->get_backend(context);
  7178  
  7179  	  // right == 0 ? (panicdivide(), 0) : ret
  7180            Bfunction* bfn = context->function()->func_value()->get_decl();
  7181            ret = gogo->backend()->conditional_expression(bfn, btype,
  7182                                                          check, bcrash,
  7183  							ret, loc);
  7184  	}
  7185  
  7186        if (gogo->check_divide_overflow())
  7187  	{
  7188  	  // right == -1
  7189  	  // FIXME: It would be nice to say that this test is expected
  7190  	  // to return false.
  7191  
  7192            Bexpression* neg_one_expr =
  7193                gogo->backend()->integer_constant_expression(right_btype, neg_one);
  7194            Bexpression* check =
  7195                gogo->backend()->binary_expression(OPERATOR_EQEQ,
  7196                                                   right, neg_one_expr, loc);
  7197  
  7198            Bexpression* zero_expr =
  7199                gogo->backend()->integer_constant_expression(btype, zero);
  7200            Bexpression* one_expr =
  7201                gogo->backend()->integer_constant_expression(btype, one);
  7202            Bfunction* bfn = context->function()->func_value()->get_decl();
  7203  
  7204  	  if (type->integer_type()->is_unsigned())
  7205  	    {
  7206  	      // An unsigned -1 is the largest possible number, so
  7207  	      // dividing is always 1 or 0.
  7208  
  7209                Bexpression* cmp =
  7210                    gogo->backend()->binary_expression(OPERATOR_EQEQ,
  7211                                                       left, right, loc);
  7212  	      if (this->op_ == OPERATOR_DIV)
  7213                  overflow =
  7214                      gogo->backend()->conditional_expression(bfn, btype, cmp,
  7215                                                              one_expr, zero_expr,
  7216                                                              loc);
  7217  	      else
  7218                  overflow =
  7219                      gogo->backend()->conditional_expression(bfn, btype, cmp,
  7220                                                              zero_expr, left,
  7221                                                              loc);
  7222  	    }
  7223  	  else
  7224  	    {
  7225  	      // Computing left / -1 is the same as computing - left,
  7226  	      // which does not overflow since Go sets -fwrapv.
  7227  	      if (this->op_ == OPERATOR_DIV)
  7228                  {
  7229                    Expression* negate_expr =
  7230                        Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
  7231                    overflow = negate_expr->get_backend(context);
  7232                  }
  7233  	      else
  7234                  overflow = zero_expr;
  7235  	    }
  7236            overflow = gogo->backend()->convert_expression(btype, overflow, loc);
  7237  
  7238  	  // right == -1 ? - left : ret
  7239            ret = gogo->backend()->conditional_expression(bfn, btype,
  7240                                                          check, overflow,
  7241                                                          ret, loc);
  7242  	}
  7243      }
  7244  
  7245    mpz_clear(zero);
  7246    mpz_clear(one);
  7247    mpz_clear(neg_one);
  7248    return ret;
  7249  }
  7250  
  7251  // Export a binary expression.
  7252  
  7253  void
  7254  Binary_expression::do_export(Export_function_body* efb) const
  7255  {
  7256    efb->write_c_string("(");
  7257    this->left_->export_expression(efb);
  7258    switch (this->op_)
  7259      {
  7260      case OPERATOR_OROR:
  7261        efb->write_c_string(" || ");
  7262        break;
  7263      case OPERATOR_ANDAND:
  7264        efb->write_c_string(" && ");
  7265        break;
  7266      case OPERATOR_EQEQ:
  7267        efb->write_c_string(" == ");
  7268        break;
  7269      case OPERATOR_NOTEQ:
  7270        efb->write_c_string(" != ");
  7271        break;
  7272      case OPERATOR_LT:
  7273        efb->write_c_string(" < ");
  7274        break;
  7275      case OPERATOR_LE:
  7276        efb->write_c_string(" <= ");
  7277        break;
  7278      case OPERATOR_GT:
  7279        efb->write_c_string(" > ");
  7280        break;
  7281      case OPERATOR_GE:
  7282        efb->write_c_string(" >= ");
  7283        break;
  7284      case OPERATOR_PLUS:
  7285        efb->write_c_string(" + ");
  7286        break;
  7287      case OPERATOR_MINUS:
  7288        efb->write_c_string(" - ");
  7289        break;
  7290      case OPERATOR_OR:
  7291        efb->write_c_string(" | ");
  7292        break;
  7293      case OPERATOR_XOR:
  7294        efb->write_c_string(" ^ ");
  7295        break;
  7296      case OPERATOR_MULT:
  7297        efb->write_c_string(" * ");
  7298        break;
  7299      case OPERATOR_DIV:
  7300        efb->write_c_string(" / ");
  7301        break;
  7302      case OPERATOR_MOD:
  7303        efb->write_c_string(" % ");
  7304        break;
  7305      case OPERATOR_LSHIFT:
  7306        efb->write_c_string(" << ");
  7307        break;
  7308      case OPERATOR_RSHIFT:
  7309        efb->write_c_string(" >> ");
  7310        break;
  7311      case OPERATOR_AND:
  7312        efb->write_c_string(" & ");
  7313        break;
  7314      case OPERATOR_BITCLEAR:
  7315        efb->write_c_string(" &^ ");
  7316        break;
  7317      default:
  7318        go_unreachable();
  7319      }
  7320    this->right_->export_expression(efb);
  7321    efb->write_c_string(")");
  7322  }
  7323  
  7324  // Import a binary expression.
  7325  
  7326  Expression*
  7327  Binary_expression::do_import(Import_expression* imp, Location loc)
  7328  {
  7329    imp->require_c_string("(");
  7330  
  7331    Expression* left = Expression::import_expression(imp, loc);
  7332  
  7333    Operator op;
  7334    if (imp->match_c_string(" || "))
  7335      {
  7336        op = OPERATOR_OROR;
  7337        imp->advance(4);
  7338      }
  7339    else if (imp->match_c_string(" && "))
  7340      {
  7341        op = OPERATOR_ANDAND;
  7342        imp->advance(4);
  7343      }
  7344    else if (imp->match_c_string(" == "))
  7345      {
  7346        op = OPERATOR_EQEQ;
  7347        imp->advance(4);
  7348      }
  7349    else if (imp->match_c_string(" != "))
  7350      {
  7351        op = OPERATOR_NOTEQ;
  7352        imp->advance(4);
  7353      }
  7354    else if (imp->match_c_string(" < "))
  7355      {
  7356        op = OPERATOR_LT;
  7357        imp->advance(3);
  7358      }
  7359    else if (imp->match_c_string(" <= "))
  7360      {
  7361        op = OPERATOR_LE;
  7362        imp->advance(4);
  7363      }
  7364    else if (imp->match_c_string(" > "))
  7365      {
  7366        op = OPERATOR_GT;
  7367        imp->advance(3);
  7368      }
  7369    else if (imp->match_c_string(" >= "))
  7370      {
  7371        op = OPERATOR_GE;
  7372        imp->advance(4);
  7373      }
  7374    else if (imp->match_c_string(" + "))
  7375      {
  7376        op = OPERATOR_PLUS;
  7377        imp->advance(3);
  7378      }
  7379    else if (imp->match_c_string(" - "))
  7380      {
  7381        op = OPERATOR_MINUS;
  7382        imp->advance(3);
  7383      }
  7384    else if (imp->match_c_string(" | "))
  7385      {
  7386        op = OPERATOR_OR;
  7387        imp->advance(3);
  7388      }
  7389    else if (imp->match_c_string(" ^ "))
  7390      {
  7391        op = OPERATOR_XOR;
  7392        imp->advance(3);
  7393      }
  7394    else if (imp->match_c_string(" * "))
  7395      {
  7396        op = OPERATOR_MULT;
  7397        imp->advance(3);
  7398      }
  7399    else if (imp->match_c_string(" / "))
  7400      {
  7401        op = OPERATOR_DIV;
  7402        imp->advance(3);
  7403      }
  7404    else if (imp->match_c_string(" % "))
  7405      {
  7406        op = OPERATOR_MOD;
  7407        imp->advance(3);
  7408      }
  7409    else if (imp->match_c_string(" << "))
  7410      {
  7411        op = OPERATOR_LSHIFT;
  7412        imp->advance(4);
  7413      }
  7414    else if (imp->match_c_string(" >> "))
  7415      {
  7416        op = OPERATOR_RSHIFT;
  7417        imp->advance(4);
  7418      }
  7419    else if (imp->match_c_string(" & "))
  7420      {
  7421        op = OPERATOR_AND;
  7422        imp->advance(3);
  7423      }
  7424    else if (imp->match_c_string(" &^ "))
  7425      {
  7426        op = OPERATOR_BITCLEAR;
  7427        imp->advance(4);
  7428      }
  7429    else if (imp->match_c_string(")"))
  7430      {
  7431        // Not a binary operator after all.
  7432        imp->advance(1);
  7433        return left;
  7434      }
  7435    else
  7436      {
  7437        go_error_at(imp->location(), "unrecognized binary operator");
  7438        return Expression::make_error(loc);
  7439      }
  7440  
  7441    Expression* right = Expression::import_expression(imp, loc);
  7442  
  7443    imp->require_c_string(")");
  7444  
  7445    return Expression::make_binary(op, left, right, loc);
  7446  }
  7447  
  7448  // Dump ast representation of a binary expression.
  7449  
  7450  void
  7451  Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
  7452  {
  7453    ast_dump_context->ostream() << "(";
  7454    ast_dump_context->dump_expression(this->left_);
  7455    ast_dump_context->ostream() << " ";
  7456    ast_dump_context->dump_operator(this->op_);
  7457    ast_dump_context->ostream() << " ";
  7458    ast_dump_context->dump_expression(this->right_);
  7459    ast_dump_context->ostream() << ") ";
  7460  }
  7461  
  7462  // Make a binary expression.
  7463  
  7464  Expression*
  7465  Expression::make_binary(Operator op, Expression* left, Expression* right,
  7466  			Location location)
  7467  {
  7468    return new Binary_expression(op, left, right, location);
  7469  }
  7470  
  7471  // Implement a comparison.
  7472  
  7473  Bexpression*
  7474  Expression::comparison(Translate_context* context, Type* result_type,
  7475  		       Operator op, Expression* left, Expression* right,
  7476  		       Location location)
  7477  {
  7478    Type* left_type = left->type();
  7479    Type* right_type = right->type();
  7480  
  7481    Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
  7482  
  7483    if (left_type->is_string_type() && right_type->is_string_type())
  7484      {
  7485        go_assert(left->is_multi_eval_safe());
  7486        go_assert(right->is_multi_eval_safe());
  7487  
  7488        if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
  7489  	{
  7490            // (l.len == r.len
  7491            //  ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
  7492            //  : false)
  7493            Expression* llen = Expression::make_string_info(left,
  7494                                                            STRING_INFO_LENGTH,
  7495                                                            location);
  7496            Expression* rlen = Expression::make_string_info(right,
  7497                                                            STRING_INFO_LENGTH,
  7498                                                            location);
  7499            Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
  7500                                                        location);
  7501            Expression* lptr = Expression::make_string_info(left->copy(),
  7502                                                            STRING_INFO_DATA,
  7503                                                            location);
  7504            Expression* rptr = Expression::make_string_info(right->copy(),
  7505                                                            STRING_INFO_DATA,
  7506                                                            location);
  7507            Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
  7508                                                        location);
  7509            Expression* btrue = Expression::make_boolean(true, location);
  7510            Expression* call = Runtime::make_call(Runtime::MEMCMP, location, 3,
  7511                                                  lptr->copy(), rptr->copy(),
  7512                                                  rlen->copy());
  7513            Type* int32_type = Type::lookup_integer_type("int32");
  7514            Expression* zero = Expression::make_integer_ul(0, int32_type, location);
  7515            Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
  7516                                                      location);
  7517            Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
  7518                                                            location);
  7519            Expression* bfalse = Expression::make_boolean(false, location);
  7520            left = Expression::make_conditional(leneq, cond, bfalse, location);
  7521  	  right = Expression::make_boolean(true, location);
  7522  	}
  7523        else
  7524  	{
  7525  	  left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
  7526  				    left, right);
  7527  	  right = zexpr;
  7528  	}
  7529      }
  7530    else if ((left_type->interface_type() != NULL
  7531  	    && right_type->interface_type() == NULL
  7532  	    && !right_type->is_nil_type())
  7533  	   || (left_type->interface_type() == NULL
  7534  	       && !left_type->is_nil_type()
  7535  	       && right_type->interface_type() != NULL))
  7536      {
  7537        // Comparing an interface value to a non-interface value.
  7538        if (left_type->interface_type() == NULL)
  7539  	{
  7540  	  std::swap(left_type, right_type);
  7541  	  std::swap(left, right);
  7542  	}
  7543  
  7544        // The right operand is not an interface.  We need to take its
  7545        // address if it is not a direct interface type.
  7546        Expression* pointer_arg = NULL;
  7547        if (right_type->is_direct_iface_type())
  7548          pointer_arg = Expression::unpack_direct_iface(right, location);
  7549        else
  7550  	{
  7551            go_assert(right->is_addressable());
  7552            pointer_arg = Expression::make_unary(OPERATOR_AND, right,
  7553                                                 location);
  7554  	}
  7555  
  7556        Expression* descriptor =
  7557            Expression::make_type_descriptor(right_type, location);
  7558        left =
  7559            Runtime::make_call((left_type->interface_type()->is_empty()
  7560                                ? Runtime::EFACEVALEQ
  7561                                : Runtime::IFACEVALEQ),
  7562                               location, 3, left, descriptor,
  7563                               pointer_arg);
  7564        go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
  7565        right = Expression::make_boolean(true, location);
  7566      }
  7567    else if (left_type->interface_type() != NULL
  7568  	   && right_type->interface_type() != NULL)
  7569      {
  7570        Runtime::Function compare_function;
  7571        if (left_type->interface_type()->is_empty()
  7572  	  && right_type->interface_type()->is_empty())
  7573  	compare_function = Runtime::EFACEEQ;
  7574        else if (!left_type->interface_type()->is_empty()
  7575  	       && !right_type->interface_type()->is_empty())
  7576  	compare_function = Runtime::IFACEEQ;
  7577        else
  7578  	{
  7579  	  if (left_type->interface_type()->is_empty())
  7580  	    {
  7581  	      std::swap(left_type, right_type);
  7582  	      std::swap(left, right);
  7583  	    }
  7584  	  go_assert(!left_type->interface_type()->is_empty());
  7585  	  go_assert(right_type->interface_type()->is_empty());
  7586  	  compare_function = Runtime::IFACEEFACEEQ;
  7587  	}
  7588  
  7589        left = Runtime::make_call(compare_function, location, 2, left, right);
  7590        go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
  7591        right = Expression::make_boolean(true, location);
  7592      }
  7593  
  7594    if (left_type->is_nil_type()
  7595        && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
  7596      {
  7597        std::swap(left_type, right_type);
  7598        std::swap(left, right);
  7599      }
  7600  
  7601    if (right_type->is_nil_type())
  7602      {
  7603        right = Expression::make_nil(location);
  7604        if (left_type->array_type() != NULL
  7605  	  && left_type->array_type()->length() == NULL)
  7606  	{
  7607  	  Array_type* at = left_type->array_type();
  7608            left = at->get_value_pointer(context->gogo(), left);
  7609  	}
  7610        else if (left_type->interface_type() != NULL)
  7611  	{
  7612  	  // An interface is nil if the first field is nil.
  7613            left = Expression::make_field_reference(left, 0, location);
  7614  	}
  7615      }
  7616  
  7617    Bexpression* left_bexpr = left->get_backend(context);
  7618    Bexpression* right_bexpr = right->get_backend(context);
  7619  
  7620    Gogo* gogo = context->gogo();
  7621    Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
  7622                                                          right_bexpr, location);
  7623    if (result_type != NULL)
  7624      ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
  7625                                                ret, location);
  7626    return ret;
  7627  }
  7628  
  7629  // Class String_concat_expression.
  7630  
  7631  bool
  7632  String_concat_expression::do_is_constant() const
  7633  {
  7634    for (Expression_list::const_iterator pe = this->exprs_->begin();
  7635         pe != this->exprs_->end();
  7636         ++pe)
  7637      {
  7638        if (!(*pe)->is_constant())
  7639  	return false;
  7640      }
  7641    return true;
  7642  }
  7643  
  7644  bool
  7645  String_concat_expression::do_is_zero_value() const
  7646  {
  7647    for (Expression_list::const_iterator pe = this->exprs_->begin();
  7648         pe != this->exprs_->end();
  7649         ++pe)
  7650      {
  7651        if (!(*pe)->is_zero_value())
  7652  	return false;
  7653      }
  7654    return true;
  7655  }
  7656  
  7657  bool
  7658  String_concat_expression::do_is_static_initializer() const
  7659  {
  7660    for (Expression_list::const_iterator pe = this->exprs_->begin();
  7661         pe != this->exprs_->end();
  7662         ++pe)
  7663      {
  7664        if (!(*pe)->is_static_initializer())
  7665  	return false;
  7666      }
  7667    return true;
  7668  }
  7669  
  7670  Type*
  7671  String_concat_expression::do_type()
  7672  {
  7673    Type* t = this->exprs_->front()->type();
  7674    Expression_list::iterator pe = this->exprs_->begin();
  7675    ++pe;
  7676    for (; pe != this->exprs_->end(); ++pe)
  7677      {
  7678        Type* t1;
  7679        if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
  7680  					     (*pe)->type(),
  7681  					     &t1))
  7682  	return Type::make_error_type();
  7683        t = t1;
  7684      }
  7685    return t;
  7686  }
  7687  
  7688  void
  7689  String_concat_expression::do_determine_type(const Type_context* context)
  7690  {
  7691    Type_context subcontext(*context);
  7692    for (Expression_list::iterator pe = this->exprs_->begin();
  7693         pe != this->exprs_->end();
  7694         ++pe)
  7695      {
  7696        Type* t = (*pe)->type();
  7697        if (!t->is_abstract())
  7698  	{
  7699  	  subcontext.type = t;
  7700  	  break;
  7701  	}
  7702      }
  7703    if (subcontext.type == NULL)
  7704      subcontext.type = this->exprs_->front()->type();
  7705    for (Expression_list::iterator pe = this->exprs_->begin();
  7706         pe != this->exprs_->end();
  7707         ++pe)
  7708      (*pe)->determine_type(&subcontext);
  7709  }
  7710  
  7711  void
  7712  String_concat_expression::do_check_types(Gogo*)
  7713  {
  7714    if (this->is_error_expression())
  7715      return;
  7716    Type* t = this->exprs_->front()->type();
  7717    if (t->is_error())
  7718      {
  7719        this->set_is_error();
  7720        return;
  7721      }
  7722    Expression_list::iterator pe = this->exprs_->begin();
  7723    ++pe;
  7724    for (; pe != this->exprs_->end(); ++pe)
  7725      {
  7726        Type* t1 = (*pe)->type();
  7727        if (!Type::are_compatible_for_binop(t, t1))
  7728  	{
  7729  	  this->report_error("incompatible types in binary expression");
  7730  	  return;
  7731  	}
  7732        if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
  7733  						  this->location()))
  7734  	{
  7735  	  this->set_is_error();
  7736  	  return;
  7737  	}
  7738      }
  7739  }
  7740  
  7741  Expression*
  7742  String_concat_expression::do_flatten(Gogo*, Named_object*,
  7743  				     Statement_inserter* inserter)
  7744  {
  7745    if (this->is_error_expression())
  7746      return this;
  7747    Location loc = this->location();
  7748    Type* type = this->type();
  7749  
  7750    // Mark string([]byte) operands to reuse the backing store.
  7751    // runtime.concatstrings does not keep the reference.
  7752    //
  7753    // Note: in the gc runtime, if all but one inputs are empty,
  7754    // concatstrings returns the only nonempty input without copy.
  7755    // So it is not safe to reuse the backing store if it is a
  7756    // string([]byte) conversion. So the gc compiler does the
  7757    // no-copy optimization only when there is at least one
  7758    // constant nonempty input. Currently the gccgo runtime
  7759    // doesn't do this, so we don't do the check.
  7760    for (Expression_list::iterator p = this->exprs_->begin();
  7761         p != this->exprs_->end();
  7762         ++p)
  7763      {
  7764        Type_conversion_expression* tce = (*p)->conversion_expression();
  7765        if (tce != NULL)
  7766          tce->set_no_copy(true);
  7767      }
  7768  
  7769    Expression* buf = NULL;
  7770    Node* n = Node::make_node(this);
  7771    if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
  7772      {
  7773        size_t size = 0;
  7774        for (Expression_list::iterator p = this->exprs_->begin();
  7775             p != this->exprs_->end();
  7776             ++p)
  7777          {
  7778            std::string s;
  7779            if ((*p)->string_constant_value(&s))
  7780              size += s.length();
  7781          }
  7782        // Make a buffer on stack if the result does not escape.
  7783        // But don't do this if we know it won't fit.
  7784        if (size < (size_t)tmp_string_buf_size)
  7785          {
  7786            Type* byte_type = Type::lookup_integer_type("uint8");
  7787            Expression* buflen =
  7788              Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
  7789            Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
  7790            Type* array_type = Type::make_array_type(byte_type, buflen);
  7791            buf = Expression::make_allocation(array_type, loc);
  7792            buf->allocation_expression()->set_allocate_on_stack();
  7793            buf->allocation_expression()->set_no_zero();
  7794          }
  7795      }
  7796    if (buf == NULL)
  7797      buf = Expression::make_nil(loc);
  7798    go_assert(this->exprs_->size() > 1);
  7799    Expression* len =
  7800      Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
  7801    Array_type* array_type = Type::make_array_type(type, len);
  7802    array_type->set_is_array_incomparable();
  7803    Expression* array =
  7804      Expression::make_array_composite_literal(array_type, this->exprs_,
  7805                                               loc);
  7806    Temporary_statement* ts =
  7807      Statement::make_temporary(array_type, array, loc);
  7808    inserter->insert(ts);
  7809    Expression* ref = Expression::make_temporary_reference(ts, loc);
  7810    ref = Expression::make_unary(OPERATOR_AND, ref, loc);
  7811  	Expression* call =
  7812      Runtime::make_call(Runtime::CONCATSTRINGS, loc, 3, buf,
  7813                         ref, len->copy());
  7814    return Expression::make_cast(type, call, loc);
  7815  }
  7816  
  7817  void
  7818  String_concat_expression::do_dump_expression(
  7819      Ast_dump_context* ast_dump_context) const
  7820  {
  7821    ast_dump_context->ostream() << "concat(";
  7822    ast_dump_context->dump_expression_list(this->exprs_, false);
  7823    ast_dump_context->ostream() << ")";
  7824  }
  7825  
  7826  Expression*
  7827  Expression::make_string_concat(Expression_list* exprs)
  7828  {
  7829    return new String_concat_expression(exprs);
  7830  }
  7831  
  7832  // Class Bound_method_expression.
  7833  
  7834  // Traversal.
  7835  
  7836  int
  7837  Bound_method_expression::do_traverse(Traverse* traverse)
  7838  {
  7839    return Expression::traverse(&this->expr_, traverse);
  7840  }
  7841  
  7842  // Return the type of a bound method expression.  The type of this
  7843  // object is simply the type of the method with no receiver.
  7844  
  7845  Type*
  7846  Bound_method_expression::do_type()
  7847  {
  7848    Named_object* fn = this->method_->named_object();
  7849    Function_type* fntype;
  7850    if (fn->is_function())
  7851      fntype = fn->func_value()->type();
  7852    else if (fn->is_function_declaration())
  7853      fntype = fn->func_declaration_value()->type();
  7854    else
  7855      return Type::make_error_type();
  7856    return fntype->copy_without_receiver();
  7857  }
  7858  
  7859  // Determine the types of a method expression.
  7860  
  7861  void
  7862  Bound_method_expression::do_determine_type(const Type_context*)
  7863  {
  7864    Named_object* fn = this->method_->named_object();
  7865    Function_type* fntype;
  7866    if (fn->is_function())
  7867      fntype = fn->func_value()->type();
  7868    else if (fn->is_function_declaration())
  7869      fntype = fn->func_declaration_value()->type();
  7870    else
  7871      fntype = NULL;
  7872    if (fntype == NULL || !fntype->is_method())
  7873      this->expr_->determine_type_no_context();
  7874    else
  7875      {
  7876        Type_context subcontext(fntype->receiver()->type(), false);
  7877        this->expr_->determine_type(&subcontext);
  7878      }
  7879  }
  7880  
  7881  // Check the types of a method expression.
  7882  
  7883  void
  7884  Bound_method_expression::do_check_types(Gogo*)
  7885  {
  7886    Named_object* fn = this->method_->named_object();
  7887    if (!fn->is_function() && !fn->is_function_declaration())
  7888      {
  7889        this->report_error(_("object is not a method"));
  7890        return;
  7891      }
  7892  
  7893    Function_type* fntype;
  7894    if (fn->is_function())
  7895      fntype = fn->func_value()->type();
  7896    else if (fn->is_function_declaration())
  7897      fntype = fn->func_declaration_value()->type();
  7898    else
  7899      go_unreachable();
  7900    Type* rtype = fntype->receiver()->type()->deref();
  7901    Type* etype = (this->expr_type_ != NULL
  7902  		 ? this->expr_type_
  7903  		 : this->expr_->type());
  7904    etype = etype->deref();
  7905    if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
  7906      this->report_error(_("method type does not match object type"));
  7907  }
  7908  
  7909  // If a bound method expression is not simply called, then it is
  7910  // represented as a closure.  The closure will hold a single variable,
  7911  // the receiver to pass to the method.  The function will be a simple
  7912  // thunk that pulls that value from the closure and calls the method
  7913  // with the remaining arguments.
  7914  //
  7915  // Because method values are not common, we don't build all thunks for
  7916  // every methods, but instead only build them as we need them.  In
  7917  // particular, we even build them on demand for methods defined in
  7918  // other packages.
  7919  
  7920  Bound_method_expression::Method_value_thunks
  7921    Bound_method_expression::method_value_thunks;
  7922  
  7923  // Find or create the thunk for FN.
  7924  
  7925  Named_object*
  7926  Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
  7927  				      Named_object* fn)
  7928  {
  7929    std::pair<Named_object*, Named_object*> val(fn, NULL);
  7930    std::pair<Method_value_thunks::iterator, bool> ins =
  7931      Bound_method_expression::method_value_thunks.insert(val);
  7932    if (!ins.second)
  7933      {
  7934        // We have seen this method before.
  7935        go_assert(ins.first->second != NULL);
  7936        return ins.first->second;
  7937      }
  7938  
  7939    Location loc = fn->location();
  7940  
  7941    Function_type* orig_fntype;
  7942    if (fn->is_function())
  7943      orig_fntype = fn->func_value()->type();
  7944    else if (fn->is_function_declaration())
  7945      orig_fntype = fn->func_declaration_value()->type();
  7946    else
  7947      orig_fntype = NULL;
  7948  
  7949    if (orig_fntype == NULL || !orig_fntype->is_method())
  7950      {
  7951        ins.first->second =
  7952  	Named_object::make_erroneous_name(gogo->thunk_name());
  7953        return ins.first->second;
  7954      }
  7955  
  7956    Struct_field_list* sfl = new Struct_field_list();
  7957    // The type here is wrong--it should be the C function type.  But it
  7958    // doesn't really matter.
  7959    Type* vt = Type::make_pointer_type(Type::make_void_type());
  7960    sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
  7961    sfl->push_back(Struct_field(Typed_identifier("val",
  7962  					       orig_fntype->receiver()->type(),
  7963  					       loc)));
  7964    Struct_type* st = Type::make_struct_type(sfl, loc);
  7965    st->set_is_struct_incomparable();
  7966    Type* closure_type = Type::make_pointer_type(st);
  7967  
  7968    Function_type* new_fntype = orig_fntype->copy_with_names();
  7969  
  7970    std::string thunk_name = gogo->thunk_name();
  7971    Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
  7972  					      false, loc);
  7973  
  7974    Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
  7975    cvar->set_is_used();
  7976    cvar->set_is_closure();
  7977    Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
  7978  						 NULL, cvar);
  7979    new_no->func_value()->set_closure_var(cp);
  7980  
  7981    gogo->start_block(loc);
  7982  
  7983    // Field 0 of the closure is the function code pointer, field 1 is
  7984    // the value on which to invoke the method.
  7985    Expression* arg = Expression::make_var_reference(cp, loc);
  7986    arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
  7987    arg = Expression::make_field_reference(arg, 1, loc);
  7988  
  7989    Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
  7990  
  7991    const Typed_identifier_list* orig_params = orig_fntype->parameters();
  7992    Expression_list* args;
  7993    if (orig_params == NULL || orig_params->empty())
  7994      args = NULL;
  7995    else
  7996      {
  7997        const Typed_identifier_list* new_params = new_fntype->parameters();
  7998        args = new Expression_list();
  7999        for (Typed_identifier_list::const_iterator p = new_params->begin();
  8000  	   p != new_params->end();
  8001  	   ++p)
  8002  	{
  8003  	  Named_object* p_no = gogo->lookup(p->name(), NULL);
  8004  	  go_assert(p_no != NULL
  8005  		    && p_no->is_variable()
  8006  		    && p_no->var_value()->is_parameter());
  8007  	  args->push_back(Expression::make_var_reference(p_no, loc));
  8008  	}
  8009      }
  8010  
  8011    Call_expression* call = Expression::make_call(bme, args,
  8012  						orig_fntype->is_varargs(),
  8013  						loc);
  8014    call->set_varargs_are_lowered();
  8015  
  8016    Statement* s = Statement::make_return_from_call(call, loc);
  8017    gogo->add_statement(s);
  8018    Block* b = gogo->finish_block(loc);
  8019    gogo->add_block(b, loc);
  8020  
  8021    // This is called after lowering but before determine_types.
  8022    gogo->lower_block(new_no, b);
  8023  
  8024    gogo->finish_function(loc);
  8025  
  8026    ins.first->second = new_no;
  8027    return new_no;
  8028  }
  8029  
  8030  // Look up a thunk for FN.
  8031  
  8032  Named_object*
  8033  Bound_method_expression::lookup_thunk(Named_object* fn)
  8034  {
  8035    Method_value_thunks::const_iterator p =
  8036      Bound_method_expression::method_value_thunks.find(fn);
  8037    if (p == Bound_method_expression::method_value_thunks.end())
  8038      return NULL;
  8039    return p->second;
  8040  }
  8041  
  8042  // Return an expression to check *REF for nil while dereferencing
  8043  // according to FIELD_INDEXES.  Update *REF to build up the field
  8044  // reference.  This is a static function so that we don't have to
  8045  // worry about declaring Field_indexes in expressions.h.
  8046  
  8047  static Expression*
  8048  bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
  8049  	      Expression** ref)
  8050  {
  8051    if (field_indexes == NULL)
  8052      return Expression::make_boolean(false, loc);
  8053    Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
  8054    Struct_type* stype = (*ref)->type()->deref()->struct_type();
  8055    go_assert(stype != NULL
  8056  	    && field_indexes->field_index < stype->field_count());
  8057    if ((*ref)->type()->struct_type() == NULL)
  8058      {
  8059        go_assert((*ref)->type()->points_to() != NULL);
  8060        Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
  8061  					      Expression::make_nil(loc),
  8062  					      loc);
  8063        cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
  8064        *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
  8065                                            loc);
  8066        go_assert((*ref)->type()->struct_type() == stype);
  8067      }
  8068    *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
  8069  					  loc);
  8070    return cond;
  8071  }
  8072  
  8073  // Flatten a method value into a struct with nil checks.  We can't do
  8074  // this in the lowering phase, because if the method value is called
  8075  // directly we don't need a thunk.  That case will have been handled
  8076  // by Call_expression::do_lower, so if we get here then we do need a
  8077  // thunk.
  8078  
  8079  Expression*
  8080  Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
  8081  				    Statement_inserter* inserter)
  8082  {
  8083    Location loc = this->location();
  8084  
  8085    Named_object* thunk = Bound_method_expression::lookup_thunk(this->function_);
  8086  
  8087    // The thunk should have been created during the
  8088    // create_function_descriptors pass.
  8089    if (thunk == NULL || thunk->is_erroneous())
  8090      {
  8091        go_assert(saw_errors());
  8092        return Expression::make_error(loc);
  8093      }
  8094  
  8095    // Force the expression into a variable.  This is only necessary if
  8096    // we are going to do nil checks below, but it's easy enough to
  8097    // always do it.
  8098    Expression* expr = this->expr_;
  8099    if (!expr->is_multi_eval_safe())
  8100      {
  8101        Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
  8102        inserter->insert(etemp);
  8103        expr = Expression::make_temporary_reference(etemp, loc);
  8104      }
  8105  
  8106    // If the method expects a value, and we have a pointer, we need to
  8107    // dereference the pointer.
  8108  
  8109    Named_object* fn = this->method_->named_object();
  8110    Function_type *fntype;
  8111    if (fn->is_function())
  8112      fntype = fn->func_value()->type();
  8113    else if (fn->is_function_declaration())
  8114      fntype = fn->func_declaration_value()->type();
  8115    else
  8116      go_unreachable();
  8117  
  8118    Expression* val = expr;
  8119    if (fntype->receiver()->type()->points_to() == NULL
  8120        && val->type()->points_to() != NULL)
  8121      val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
  8122  
  8123    // Note that we are ignoring this->expr_type_ here.  The thunk will
  8124    // expect a closure whose second field has type this->expr_type_ (if
  8125    // that is not NULL).  We are going to pass it a closure whose
  8126    // second field has type this->expr_->type().  Since
  8127    // this->expr_type_ is only not-NULL for pointer types, we can get
  8128    // away with this.
  8129  
  8130    Struct_field_list* fields = new Struct_field_list();
  8131    fields->push_back(Struct_field(Typed_identifier("fn",
  8132  						  thunk->func_value()->type(),
  8133  						  loc)));
  8134    fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
  8135    Struct_type* st = Type::make_struct_type(fields, loc);
  8136    st->set_is_struct_incomparable();
  8137  
  8138    Expression_list* vals = new Expression_list();
  8139    vals->push_back(Expression::make_func_code_reference(thunk, loc));
  8140    vals->push_back(val);
  8141  
  8142    Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
  8143    ret = Expression::make_heap_expression(ret, loc);
  8144  
  8145    Node* node = Node::make_node(this);
  8146    if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
  8147      ret->heap_expression()->set_allocate_on_stack();
  8148    else if (gogo->compiling_runtime()
  8149  	   && gogo->package_name() == "runtime"
  8150  	   && !saw_errors())
  8151      go_error_at(loc, "%s escapes to heap, not allowed in runtime",
  8152                  node->ast_format(gogo).c_str());
  8153  
  8154    // If necessary, check whether the expression or any embedded
  8155    // pointers are nil.
  8156  
  8157    Expression* nil_check = NULL;
  8158    if (this->method_->field_indexes() != NULL)
  8159      {
  8160        Expression* ref = expr;
  8161        nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
  8162        expr = ref;
  8163      }
  8164  
  8165    if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
  8166      {
  8167        Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
  8168  					      Expression::make_nil(loc),
  8169  					      loc);
  8170        if (nil_check == NULL)
  8171  	nil_check = n;
  8172        else
  8173  	nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
  8174      }
  8175  
  8176    if (nil_check != NULL)
  8177      {
  8178        Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
  8179        // Fix the type of the conditional expression by pretending to
  8180        // evaluate to RET either way through the conditional.
  8181        crash = Expression::make_compound(crash, ret, loc);
  8182        ret = Expression::make_conditional(nil_check, crash, ret, loc);
  8183      }
  8184  
  8185    // RET is a pointer to a struct, but we want a function type.
  8186    ret = Expression::make_unsafe_cast(this->type(), ret, loc);
  8187  
  8188    return ret;
  8189  }
  8190  
  8191  // Dump ast representation of a bound method expression.
  8192  
  8193  void
  8194  Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
  8195      const
  8196  {
  8197    if (this->expr_type_ != NULL)
  8198      ast_dump_context->ostream() << "(";
  8199    ast_dump_context->dump_expression(this->expr_);
  8200    if (this->expr_type_ != NULL)
  8201      {
  8202        ast_dump_context->ostream() << ":";
  8203        ast_dump_context->dump_type(this->expr_type_);
  8204        ast_dump_context->ostream() << ")";
  8205      }
  8206  
  8207    ast_dump_context->ostream() << "." << this->function_->name();
  8208  }
  8209  
  8210  // Make a method expression.
  8211  
  8212  Bound_method_expression*
  8213  Expression::make_bound_method(Expression* expr, const Method* method,
  8214  			      Named_object* function, Location location)
  8215  {
  8216    return new Bound_method_expression(expr, method, function, location);
  8217  }
  8218  
  8219  // Class Builtin_call_expression.  This is used for a call to a
  8220  // builtin function.
  8221  
  8222  Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
  8223  						 Expression* fn,
  8224  						 Expression_list* args,
  8225  						 bool is_varargs,
  8226  						 Location location)
  8227    : Call_expression(fn, args, is_varargs, location),
  8228      gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
  8229      recover_arg_is_set_(false)
  8230  {
  8231    Func_expression* fnexp = this->fn()->func_expression();
  8232    if (fnexp == NULL)
  8233      {
  8234        this->code_ = BUILTIN_INVALID;
  8235        return;
  8236      }
  8237    const std::string& name(fnexp->named_object()->name());
  8238    if (name == "append")
  8239      this->code_ = BUILTIN_APPEND;
  8240    else if (name == "cap")
  8241      this->code_ = BUILTIN_CAP;
  8242    else if (name == "close")
  8243      this->code_ = BUILTIN_CLOSE;
  8244    else if (name == "complex")
  8245      this->code_ = BUILTIN_COMPLEX;
  8246    else if (name == "copy")
  8247      this->code_ = BUILTIN_COPY;
  8248    else if (name == "delete")
  8249      this->code_ = BUILTIN_DELETE;
  8250    else if (name == "imag")
  8251      this->code_ = BUILTIN_IMAG;
  8252    else if (name == "len")
  8253      this->code_ = BUILTIN_LEN;
  8254    else if (name == "make")
  8255      this->code_ = BUILTIN_MAKE;
  8256    else if (name == "new")
  8257      this->code_ = BUILTIN_NEW;
  8258    else if (name == "panic")
  8259      this->code_ = BUILTIN_PANIC;
  8260    else if (name == "print")
  8261      this->code_ = BUILTIN_PRINT;
  8262    else if (name == "println")
  8263      this->code_ = BUILTIN_PRINTLN;
  8264    else if (name == "real")
  8265      this->code_ = BUILTIN_REAL;
  8266    else if (name == "recover")
  8267      this->code_ = BUILTIN_RECOVER;
  8268    else if (name == "Add")
  8269      this->code_ = BUILTIN_ADD;
  8270    else if (name == "Alignof")
  8271      this->code_ = BUILTIN_ALIGNOF;
  8272    else if (name == "Offsetof")
  8273      this->code_ = BUILTIN_OFFSETOF;
  8274    else if (name == "Sizeof")
  8275      this->code_ = BUILTIN_SIZEOF;
  8276    else if (name == "Slice")
  8277      this->code_ = BUILTIN_SLICE;
  8278    else
  8279      go_unreachable();
  8280  }
  8281  
  8282  // Return whether this is a call to recover.  This is a virtual
  8283  // function called from the parent class.
  8284  
  8285  bool
  8286  Builtin_call_expression::do_is_recover_call() const
  8287  {
  8288    if (this->classification() == EXPRESSION_ERROR)
  8289      return false;
  8290    return this->code_ == BUILTIN_RECOVER;
  8291  }
  8292  
  8293  // Set the argument for a call to recover.
  8294  
  8295  void
  8296  Builtin_call_expression::do_set_recover_arg(Expression* arg)
  8297  {
  8298    const Expression_list* args = this->args();
  8299    go_assert(args == NULL || args->empty());
  8300    Expression_list* new_args = new Expression_list();
  8301    new_args->push_back(arg);
  8302    this->set_args(new_args);
  8303    this->recover_arg_is_set_ = true;
  8304  }
  8305  
  8306  // Lower a builtin call expression.  This turns new and make into
  8307  // specific expressions.  We also convert to a constant if we can.
  8308  
  8309  Expression*
  8310  Builtin_call_expression::do_lower(Gogo*, Named_object* function,
  8311  				  Statement_inserter* inserter, int)
  8312  {
  8313    if (this->is_error_expression())
  8314      return this;
  8315  
  8316    Location loc = this->location();
  8317  
  8318    if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
  8319      {
  8320        this->report_error(_("invalid use of %<...%> with builtin function"));
  8321        return Expression::make_error(loc);
  8322      }
  8323  
  8324    if (this->code_ == BUILTIN_OFFSETOF)
  8325      {
  8326        Expression* arg = this->one_arg();
  8327  
  8328        if (arg->bound_method_expression() != NULL
  8329  	  || arg->interface_field_reference_expression() != NULL)
  8330  	{
  8331  	  this->report_error(_("invalid use of method value as argument "
  8332  			       "of Offsetof"));
  8333  	  return this;
  8334  	}
  8335  
  8336        Field_reference_expression* farg = arg->field_reference_expression();
  8337        while (farg != NULL)
  8338  	{
  8339  	  if (!farg->implicit())
  8340  	    break;
  8341  	  // When the selector refers to an embedded field,
  8342  	  // it must not be reached through pointer indirections.
  8343  	  if (farg->expr()->deref() != farg->expr())
  8344  	    {
  8345  	      this->report_error(_("argument of Offsetof implies "
  8346  				   "indirection of an embedded field"));
  8347  	      return this;
  8348  	    }
  8349  	  // Go up until we reach the original base.
  8350  	  farg = farg->expr()->field_reference_expression();
  8351  	}
  8352      }
  8353  
  8354    if (this->is_constant())
  8355      {
  8356        Numeric_constant nc;
  8357        if (this->numeric_constant_value(&nc))
  8358  	return nc.expression(loc);
  8359      }
  8360  
  8361    switch (this->code_)
  8362      {
  8363      default:
  8364        break;
  8365  
  8366      case BUILTIN_NEW:
  8367        {
  8368  	const Expression_list* args = this->args();
  8369  	if (args == NULL || args->size() < 1)
  8370  	  this->report_error(_("not enough arguments"));
  8371  	else if (args->size() > 1)
  8372  	  this->report_error(_("too many arguments"));
  8373  	else
  8374  	  {
  8375  	    Expression* arg = args->front();
  8376  	    if (!arg->is_type_expression())
  8377  	      {
  8378  		go_error_at(arg->location(), "expected type");
  8379  		this->set_is_error();
  8380  	      }
  8381  	    else
  8382  	      return Expression::make_allocation(arg->type(), loc);
  8383  	  }
  8384        }
  8385        break;
  8386  
  8387      case BUILTIN_MAKE:
  8388        return this->lower_make(inserter);
  8389  
  8390      case BUILTIN_RECOVER:
  8391        if (function != NULL)
  8392  	function->func_value()->set_calls_recover();
  8393        else
  8394  	{
  8395  	  // Calling recover outside of a function always returns the
  8396  	  // nil empty interface.
  8397  	  Type* eface = Type::make_empty_interface_type(loc);
  8398  	  return Expression::make_cast(eface, Expression::make_nil(loc), loc);
  8399  	}
  8400        break;
  8401  
  8402      case BUILTIN_DELETE:
  8403        {
  8404          const Expression_list* args = this->args();
  8405          if (args == NULL || args->size() < 2)
  8406            this->report_error(_("not enough arguments"));
  8407          else if (args->size() > 2)
  8408            this->report_error(_("too many arguments"));
  8409          else if (args->front()->type()->map_type() == NULL)
  8410            this->report_error(_("argument 1 must be a map"));
  8411          else
  8412            {
  8413              Type* key_type =
  8414                args->front()->type()->map_type()->key_type();
  8415              Expression_list::iterator pa = this->args()->begin();
  8416              pa++;
  8417              Type* arg_type = (*pa)->type();
  8418              std::string reason;
  8419              if (!Type::are_assignable(key_type, arg_type, &reason))
  8420                {
  8421                  if (reason.empty())
  8422                    go_error_at(loc, "argument 2 has incompatible type");
  8423                  else
  8424                    go_error_at(loc, "argument 2 has incompatible type (%s)",
  8425                                reason.c_str());
  8426                  this->set_is_error();
  8427                }
  8428              else if (!Type::are_identical(key_type, arg_type, 0, NULL))
  8429                *pa = Expression::make_cast(key_type, *pa, loc);
  8430            }
  8431        }
  8432        break;
  8433  
  8434      case BUILTIN_PRINT:
  8435      case BUILTIN_PRINTLN:
  8436        // Force all the arguments into temporary variables, so that we
  8437        // don't try to evaluate something while holding the print lock.
  8438        if (this->args() == NULL)
  8439  	break;
  8440        for (Expression_list::iterator pa = this->args()->begin();
  8441  	   pa != this->args()->end();
  8442  	   ++pa)
  8443  	{
  8444  	  if (!(*pa)->is_multi_eval_safe())
  8445  	    {
  8446  	      Temporary_statement* temp =
  8447  		Statement::make_temporary(NULL, *pa, loc);
  8448  	      inserter->insert(temp);
  8449  	      *pa = Expression::make_temporary_reference(temp, loc);
  8450  	    }
  8451  	}
  8452        break;
  8453      }
  8454  
  8455    return this;
  8456  }
  8457  
  8458  // Flatten a builtin call expression.  This turns the arguments of some
  8459  // builtin calls into temporary expressions.  Also expand copy and append
  8460  // to runtime calls.
  8461  
  8462  Expression*
  8463  Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
  8464                                      Statement_inserter* inserter)
  8465  {
  8466    if (this->is_error_expression())
  8467      {
  8468        go_assert(saw_errors());
  8469        return this;
  8470      }
  8471  
  8472    Location loc = this->location();
  8473  
  8474    switch (this->code_)
  8475      {
  8476      default:
  8477        break;
  8478  
  8479      case BUILTIN_APPEND:
  8480        return this->flatten_append(gogo, function, inserter, NULL, NULL);
  8481  
  8482      case BUILTIN_COPY:
  8483        {
  8484  	Type* at = this->args()->front()->type();
  8485  	for (Expression_list::iterator pa = this->args()->begin();
  8486  	     pa != this->args()->end();
  8487  	     ++pa)
  8488  	  {
  8489  	    if ((*pa)->is_error_expression())
  8490  	      {
  8491  		go_assert(saw_errors());
  8492  		return Expression::make_error(loc);
  8493  	      }
  8494  	    if ((*pa)->is_nil_expression())
  8495  	      {
  8496  		Expression* nil = Expression::make_nil(loc);
  8497  		Expression* zero = Expression::make_integer_ul(0, NULL, loc);
  8498  		*pa = Expression::make_slice_value(at, nil, zero, zero, loc);
  8499  	      }
  8500  	    if (!(*pa)->is_multi_eval_safe())
  8501  	      {
  8502  		Temporary_statement* temp =
  8503                    Statement::make_temporary(NULL, *pa, loc);
  8504  		inserter->insert(temp);
  8505  		*pa = Expression::make_temporary_reference(temp, loc);
  8506  	      }
  8507  	  }
  8508  
  8509          // Lower to runtime call.
  8510          const Expression_list* args = this->args();
  8511          go_assert(args != NULL && args->size() == 2);
  8512          Expression* arg1 = args->front();
  8513          Expression* arg2 = args->back();
  8514  	go_assert(arg1->is_multi_eval_safe());
  8515  	go_assert(arg2->is_multi_eval_safe());
  8516          bool arg2_is_string = arg2->type()->is_string_type();
  8517  
  8518          Expression* ret;
  8519          Type* et = at->array_type()->element_type();
  8520          if (et->has_pointer())
  8521            {
  8522              Expression* td = Expression::make_type_descriptor(et, loc);
  8523  	    Expression* pd =
  8524  	      Expression::make_slice_info(arg1, SLICE_INFO_VALUE_POINTER, loc);
  8525  	    Expression* ld =
  8526  	      Expression::make_slice_info(arg1, SLICE_INFO_LENGTH, loc);
  8527  	    Expression* ps =
  8528  	      Expression::make_slice_info(arg2, SLICE_INFO_VALUE_POINTER, loc);
  8529  	    Expression* ls =
  8530  	      Expression::make_slice_info(arg2, SLICE_INFO_LENGTH, loc);
  8531              ret = Runtime::make_call(Runtime::TYPEDSLICECOPY, loc,
  8532                                       5, td, pd, ld, ps, ls);
  8533            }
  8534          else
  8535            {
  8536              Type* int_type = Type::lookup_integer_type("int");
  8537              Type* uintptr_type = Type::lookup_integer_type("uintptr");
  8538  
  8539              // l1 = len(arg1)
  8540              Named_object* lenfn = gogo->lookup_global("len");
  8541              Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
  8542              Expression_list* len_args = new Expression_list();
  8543              len_args->push_back(arg1->copy());
  8544              Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
  8545              gogo->lower_expression(function, inserter, &len1);
  8546              gogo->flatten_expression(function, inserter, &len1);
  8547              Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
  8548              inserter->insert(l1tmp);
  8549  
  8550              // l2 = len(arg2)
  8551              len_args = new Expression_list();
  8552              len_args->push_back(arg2->copy());
  8553              Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
  8554              gogo->lower_expression(function, inserter, &len2);
  8555              gogo->flatten_expression(function, inserter, &len2);
  8556              Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
  8557              inserter->insert(l2tmp);
  8558  
  8559              // n = (l1 < l2 ? l1 : l2)
  8560              Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
  8561              Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
  8562              Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
  8563              Expression* n = Expression::make_conditional(cond,
  8564                                                           l1ref->copy(),
  8565                                                           l2ref->copy(),
  8566                                                           loc);
  8567              Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
  8568              inserter->insert(ntmp);
  8569  
  8570              // sz = n * sizeof(elem_type)
  8571              Expression* nref = Expression::make_temporary_reference(ntmp, loc);
  8572              nref = Expression::make_cast(uintptr_type, nref, loc);
  8573              Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
  8574              sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
  8575  
  8576              // memmove(arg1.ptr, arg2.ptr, sz)
  8577              Expression* p1 = Expression::make_slice_info(arg1,
  8578                                                           SLICE_INFO_VALUE_POINTER,
  8579                                                           loc);
  8580              Expression* p2 = (arg2_is_string
  8581                                ? Expression::make_string_info(arg2,
  8582                                                               STRING_INFO_DATA,
  8583                                                               loc)
  8584                                : Expression::make_slice_info(arg2,
  8585                                                              SLICE_INFO_VALUE_POINTER,
  8586                                                              loc));
  8587              Expression* call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
  8588                                                    p1, p2, sz);
  8589  
  8590              // n is the return value of copy
  8591              nref = Expression::make_temporary_reference(ntmp, loc);
  8592              ret = Expression::make_compound(call, nref, loc);
  8593            }
  8594          return ret;
  8595        }
  8596        break;
  8597  
  8598      case BUILTIN_PANIC:
  8599        for (Expression_list::iterator pa = this->args()->begin();
  8600  	   pa != this->args()->end();
  8601  	   ++pa)
  8602  	{
  8603  	  if (!(*pa)->is_multi_eval_safe()
  8604  	      && (*pa)->type()->interface_type() != NULL)
  8605  	    {
  8606  	      Temporary_statement* temp =
  8607  		Statement::make_temporary(NULL, *pa, loc);
  8608  	      inserter->insert(temp);
  8609  	      *pa = Expression::make_temporary_reference(temp, loc);
  8610  	    }
  8611  	}
  8612        break;
  8613  
  8614      case BUILTIN_LEN:
  8615      case BUILTIN_CAP:
  8616        {
  8617  	Expression_list::iterator pa = this->args()->begin();
  8618  	if (!(*pa)->is_multi_eval_safe()
  8619  	    && ((*pa)->type()->map_type() != NULL
  8620  		|| (*pa)->type()->channel_type() != NULL))
  8621  	  {
  8622  	    Temporary_statement* temp =
  8623  	      Statement::make_temporary(NULL, *pa, loc);
  8624  	    inserter->insert(temp);
  8625  	    *pa = Expression::make_temporary_reference(temp, loc);
  8626  	  }
  8627        }
  8628        break;
  8629  
  8630      case BUILTIN_DELETE:
  8631        {
  8632          // Lower to a runtime function call.
  8633          const Expression_list* args = this->args();
  8634  
  8635          // Since this function returns no value it must appear in
  8636          // a statement by itself, so we don't have to worry about
  8637          // order of evaluation of values around it.  Evaluate the
  8638          // map first to get order of evaluation right.
  8639          Map_type* mt = args->front()->type()->map_type();
  8640          Temporary_statement* map_temp =
  8641            Statement::make_temporary(mt, args->front(), loc);
  8642          inserter->insert(map_temp);
  8643  
  8644          Temporary_statement* key_temp =
  8645            Statement::make_temporary(mt->key_type(), args->back(), loc);
  8646          inserter->insert(key_temp);
  8647  
  8648          Expression* e1 = Expression::make_type_descriptor(mt, loc);
  8649          Expression* e2 = Expression::make_temporary_reference(map_temp,
  8650                                                                loc);
  8651          Expression* e3 = Expression::make_temporary_reference(key_temp,
  8652                                                                loc);
  8653  
  8654          Runtime::Function code;
  8655          switch (mt->algorithm(gogo))
  8656            {
  8657              case Map_type::MAP_ALG_FAST32:
  8658              case Map_type::MAP_ALG_FAST32PTR:
  8659                {
  8660                  code = Runtime::MAPDELETE_FAST32;
  8661                  Type* uint32_type = Type::lookup_integer_type("uint32");
  8662                  Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
  8663                  e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
  8664                  e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
  8665                                                    loc);
  8666                  e3 = Expression::make_dereference(e3,
  8667                                                    Expression::NIL_CHECK_NOT_NEEDED,
  8668                                                    loc);
  8669                  break;
  8670                }
  8671              case Map_type::MAP_ALG_FAST64:
  8672              case Map_type::MAP_ALG_FAST64PTR:
  8673                {
  8674                  code = Runtime::MAPDELETE_FAST64;
  8675                  Type* uint64_type = Type::lookup_integer_type("uint64");
  8676                  Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
  8677                  e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
  8678                  e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
  8679                                                    loc);
  8680                  e3 = Expression::make_dereference(e3,
  8681                                                    Expression::NIL_CHECK_NOT_NEEDED,
  8682                                                    loc);
  8683                  break;
  8684                }
  8685              case Map_type::MAP_ALG_FASTSTR:
  8686                code = Runtime::MAPDELETE_FASTSTR;
  8687                break;
  8688              default:
  8689                code = Runtime::MAPDELETE;
  8690  
  8691                // If the call to delete is deferred, and is in a loop,
  8692                // then the loop will only have a single instance of the
  8693                // temporary variable.  Passing the address of the
  8694                // temporary variable here means that the deferred call
  8695                // will see the last value in the loop, not the current
  8696                // value.  So for this unusual case copy the value into
  8697                // the heap.
  8698                if (!this->is_deferred())
  8699                  e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
  8700                else
  8701                  {
  8702                    Expression* a = Expression::make_allocation(mt->key_type(),
  8703                                                                loc);
  8704                    Temporary_statement* atemp =
  8705                      Statement::make_temporary(NULL, a, loc);
  8706                    inserter->insert(atemp);
  8707  
  8708                    a = Expression::make_temporary_reference(atemp, loc);
  8709                    a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
  8710                    Statement* s = Statement::make_assignment(a, e3, loc);
  8711                    inserter->insert(s);
  8712  
  8713                    e3 = Expression::make_temporary_reference(atemp, loc);
  8714                  }
  8715            }
  8716  
  8717          return Runtime::make_call(code, loc, 3, e1, e2, e3);
  8718        }
  8719  
  8720      case BUILTIN_ADD:
  8721        {
  8722  	Expression* ptr = this->args()->front();
  8723  	Type* uintptr_type = Type::lookup_integer_type("uintptr");
  8724  	ptr = Expression::make_cast(uintptr_type, ptr, loc);
  8725  	Expression* len = this->args()->back();
  8726  	len = Expression::make_cast(uintptr_type, len, loc);
  8727  	Expression* add = Expression::make_binary(OPERATOR_PLUS, ptr, len,
  8728  						  loc);
  8729  	return Expression::make_cast(this->args()->front()->type(), add, loc);
  8730        }
  8731  
  8732      case BUILTIN_SLICE:
  8733        {
  8734  	Expression* ptr = this->args()->front();
  8735  	Temporary_statement* ptr_temp = NULL;
  8736  	if (!ptr->is_multi_eval_safe())
  8737  	  {
  8738  	    ptr_temp = Statement::make_temporary(NULL, ptr, loc);
  8739  	    inserter->insert(ptr_temp);
  8740  	    ptr = Expression::make_temporary_reference(ptr_temp, loc);
  8741  	  }
  8742  
  8743  	Expression* len = this->args()->back();
  8744  	Temporary_statement* len_temp = NULL;
  8745  	if (!len->is_multi_eval_safe())
  8746  	  {
  8747  	    len_temp = Statement::make_temporary(NULL, len, loc);
  8748  	    inserter->insert(len_temp);
  8749  	    len = Expression::make_temporary_reference(len_temp, loc);
  8750  	  }
  8751  
  8752  	bool fits_in_int;
  8753  	Numeric_constant nc;
  8754  	if (this->args()->back()->numeric_constant_value(&nc))
  8755  	  {
  8756  	    // We gave an error for constants that don't fit in int in
  8757  	    // check_types.
  8758  	    fits_in_int = true;
  8759  	  }
  8760  	else
  8761  	  {
  8762  	    Integer_type* itype = this->args()->back()->type()->integer_type();
  8763  	    go_assert(itype != NULL);
  8764  	    int ebits = itype->bits();
  8765  	    int intbits =
  8766  	      Type::lookup_integer_type("int")->integer_type()->bits();
  8767  
  8768  	    // We can treat ebits == intbits as small even for an
  8769  	    // unsigned integer type, because we will convert the
  8770  	    // value to int and then reject it in the runtime if it is
  8771  	    // negative.
  8772  
  8773  	    fits_in_int = ebits <= intbits;
  8774  	  }
  8775  
  8776  	Runtime::Function code = (fits_in_int
  8777  				  ? Runtime::UNSAFESLICE
  8778  				  : Runtime::UNSAFESLICE64);
  8779  	Expression* td =
  8780  	  Expression::make_type_descriptor(ptr->type()->points_to(), loc);
  8781  	Expression* check = Runtime::make_call(code, loc, 3,
  8782  					       td, ptr, len);
  8783  
  8784  	if (ptr_temp == NULL)
  8785  	  ptr = ptr->copy();
  8786  	else
  8787  	  ptr = Expression::make_temporary_reference(ptr_temp, loc);
  8788  	Expression* nil = Expression::make_nil(loc);
  8789  	nil = Expression::make_cast(ptr->type(), nil, loc);
  8790  	Expression* is_nil = Expression::make_binary(OPERATOR_EQEQ, ptr, nil,
  8791  						     loc);
  8792  
  8793  	if (len_temp == NULL)
  8794  	  len = len->copy();
  8795  	else
  8796  	  len = Expression::make_temporary_reference(len_temp, loc);
  8797  	Expression* zero = Expression::make_integer_ul(0, len->type(), loc);
  8798  	Expression* is_zero = Expression::make_binary(OPERATOR_EQEQ, len, zero,
  8799  						      loc);
  8800  
  8801  	Expression* cond = Expression::make_binary(OPERATOR_ANDAND, is_nil,
  8802  						   is_zero, loc);
  8803  
  8804  	Type* slice_type = Type::make_array_type(ptr->type()->points_to(),
  8805  						 NULL);
  8806  	nil = Expression::make_nil(loc);
  8807  	Expression* nil_slice = Expression::make_cast(slice_type, nil, loc);
  8808  
  8809  	if (ptr_temp == NULL)
  8810  	  ptr = ptr->copy();
  8811  	else
  8812  	  ptr = Expression::make_temporary_reference(ptr_temp, loc);
  8813  
  8814  	if (len_temp == NULL)
  8815  	  len = len->copy();
  8816  	else
  8817  	  len = Expression::make_temporary_reference(len_temp, loc);
  8818  
  8819  	Expression* cap;
  8820  	if (len_temp == NULL)
  8821  	  cap = len->copy();
  8822  	else
  8823  	  cap = Expression::make_temporary_reference(len_temp, loc);
  8824  
  8825  	Expression* slice = Expression::make_slice_value(slice_type, ptr,
  8826  							 len, cap, loc);
  8827  
  8828  	slice = Expression::make_conditional(cond, nil_slice, slice, loc);
  8829  
  8830  	return Expression::make_compound(check, slice, loc);
  8831        }
  8832      }
  8833  
  8834    return this;
  8835  }
  8836  
  8837  // Lower a make expression.
  8838  
  8839  Expression*
  8840  Builtin_call_expression::lower_make(Statement_inserter* inserter)
  8841  {
  8842    Location loc = this->location();
  8843  
  8844    const Expression_list* args = this->args();
  8845    if (args == NULL || args->size() < 1)
  8846      {
  8847        this->report_error(_("not enough arguments"));
  8848        return Expression::make_error(this->location());
  8849      }
  8850  
  8851    Expression_list::const_iterator parg = args->begin();
  8852  
  8853    Expression* first_arg = *parg;
  8854    if (!first_arg->is_type_expression())
  8855      {
  8856        go_error_at(first_arg->location(), "expected type");
  8857        this->set_is_error();
  8858        return Expression::make_error(this->location());
  8859      }
  8860    Type* type = first_arg->type();
  8861  
  8862    if (!type->in_heap())
  8863      go_error_at(first_arg->location(),
  8864  		"cannot make slice of go:notinheap type");
  8865  
  8866    bool is_slice = false;
  8867    bool is_map = false;
  8868    bool is_chan = false;
  8869    if (type->is_slice_type())
  8870      is_slice = true;
  8871    else if (type->map_type() != NULL)
  8872      is_map = true;
  8873    else if (type->channel_type() != NULL)
  8874      is_chan = true;
  8875    else
  8876      {
  8877        this->report_error(_("invalid type for make function"));
  8878        return Expression::make_error(this->location());
  8879      }
  8880  
  8881    Type_context int_context(Type::lookup_integer_type("int"), false);
  8882  
  8883    ++parg;
  8884    Expression* len_arg;
  8885    bool len_small = false;
  8886    if (parg == args->end())
  8887      {
  8888        if (is_slice)
  8889  	{
  8890  	  this->report_error(_("length required when allocating a slice"));
  8891  	  return Expression::make_error(this->location());
  8892  	}
  8893        len_arg = Expression::make_integer_ul(0, NULL, loc);
  8894        len_small = true;
  8895      }
  8896    else
  8897      {
  8898        len_arg = *parg;
  8899        len_arg->determine_type(&int_context);
  8900        if (len_arg->type()->integer_type() == NULL)
  8901  	{
  8902  	  go_error_at(len_arg->location(), "non-integer len argument in make");
  8903  	  return Expression::make_error(this->location());
  8904  	}
  8905        if (!this->check_int_value(len_arg, true, &len_small))
  8906  	return Expression::make_error(this->location());
  8907        ++parg;
  8908      }
  8909  
  8910    Expression* cap_arg = NULL;
  8911    bool cap_small = false;
  8912    Numeric_constant nclen;
  8913    Numeric_constant nccap;
  8914    unsigned long vlen;
  8915    unsigned long vcap;
  8916    if (is_slice && parg != args->end())
  8917      {
  8918        cap_arg = *parg;
  8919        cap_arg->determine_type(&int_context);
  8920        if (cap_arg->type()->integer_type() == NULL)
  8921  	{
  8922  	  go_error_at(cap_arg->location(), "non-integer cap argument in make");
  8923  	  return Expression::make_error(this->location());
  8924  	}
  8925        if (!this->check_int_value(cap_arg, false, &cap_small))
  8926  	return Expression::make_error(this->location());
  8927  
  8928        if (len_arg->numeric_constant_value(&nclen)
  8929  	  && cap_arg->numeric_constant_value(&nccap)
  8930  	  && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
  8931  	  && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
  8932  	  && vlen > vcap)
  8933  	{
  8934  	  this->report_error(_("len larger than cap"));
  8935  	  return Expression::make_error(this->location());
  8936  	}
  8937  
  8938        ++parg;
  8939      }
  8940  
  8941    if (parg != args->end())
  8942      {
  8943        this->report_error(_("too many arguments to make"));
  8944        return Expression::make_error(this->location());
  8945      }
  8946  
  8947    Location type_loc = first_arg->location();
  8948  
  8949    Expression* call;
  8950    if (is_slice)
  8951      {
  8952        Temporary_statement* len_temp = NULL;
  8953        if (!len_arg->is_constant())
  8954  	{
  8955  	  len_temp = Statement::make_temporary(NULL, len_arg, loc);
  8956  	  inserter->insert(len_temp);
  8957  	  len_arg = Expression::make_temporary_reference(len_temp, loc);
  8958  	}
  8959  
  8960        if (cap_arg == NULL)
  8961  	{
  8962            cap_small = len_small;
  8963  	  if (len_temp == NULL)
  8964  	    cap_arg = len_arg->copy();
  8965  	  else
  8966  	    cap_arg = Expression::make_temporary_reference(len_temp, loc);
  8967  	}
  8968        else if (!cap_arg->is_constant())
  8969  	{
  8970  	  Temporary_statement* cap_temp = Statement::make_temporary(NULL,
  8971  								    cap_arg,
  8972  								    loc);
  8973  	  inserter->insert(cap_temp);
  8974  	  cap_arg = Expression::make_temporary_reference(cap_temp, loc);
  8975  	}
  8976  
  8977        Type* et = type->array_type()->element_type();
  8978        Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
  8979        Runtime::Function code = Runtime::MAKESLICE;
  8980        if (!len_small || !cap_small)
  8981  	code = Runtime::MAKESLICE64;
  8982        Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
  8983  					   cap_arg);
  8984        mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
  8985  					 loc);
  8986        Type* int_type = Type::lookup_integer_type("int");
  8987        len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
  8988        cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
  8989        call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
  8990      }
  8991    else if (is_map)
  8992      {
  8993        Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
  8994        if (!len_small)
  8995  	call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
  8996  				  len_arg,
  8997  				  Expression::make_nil(loc));
  8998        else
  8999  	{
  9000  	  if (len_arg->numeric_constant_value(&nclen)
  9001  	      && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
  9002  	      && vlen <= Map_type::bucket_size)
  9003  	    call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
  9004  	  else
  9005  	    call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
  9006  				      len_arg,
  9007  				      Expression::make_nil(loc));
  9008  	}
  9009      }
  9010    else if (is_chan)
  9011      {
  9012        Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
  9013        Runtime::Function code = Runtime::MAKECHAN;
  9014        if (!len_small)
  9015  	code = Runtime::MAKECHAN64;
  9016        call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
  9017      }
  9018    else
  9019      go_unreachable();
  9020  
  9021    return Expression::make_unsafe_cast(type, call, loc);
  9022  }
  9023  
  9024  // Flatten a call to the predeclared append function.  We do this in
  9025  // the flatten phase, not the lowering phase, so that we run after
  9026  // type checking and after order_evaluations.  If ASSIGN_LHS is not
  9027  // NULL, this append is the right-hand-side of an assignment and
  9028  // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
  9029  // rather than returning a slice.  This lets us omit a write barrier
  9030  // in common cases like a = append(a, ...) when the slice does not
  9031  // need to grow.  ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
  9032  
  9033  Expression*
  9034  Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
  9035  					Statement_inserter* inserter,
  9036  					Expression* assign_lhs,
  9037  					Block* enclosing)
  9038  {
  9039    if (this->is_error_expression())
  9040      return this;
  9041  
  9042    Location loc = this->location();
  9043  
  9044    const Expression_list* args = this->args();
  9045    go_assert(args != NULL && !args->empty());
  9046  
  9047    Type* slice_type = args->front()->type();
  9048    go_assert(slice_type->is_slice_type());
  9049    Type* element_type = slice_type->array_type()->element_type();
  9050  
  9051    if (args->size() == 1)
  9052      {
  9053        // append(s) evaluates to s.
  9054        if (assign_lhs != NULL)
  9055  	return NULL;
  9056        return args->front();
  9057      }
  9058  
  9059    Type* int_type = Type::lookup_integer_type("int");
  9060    Type* uint_type = Type::lookup_integer_type("uint");
  9061  
  9062    // Implementing
  9063    //   append(s1, s2...)
  9064    // or
  9065    //   append(s1, a1, a2, a3, ...)
  9066  
  9067    // s1tmp := s1
  9068    Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
  9069  							 loc);
  9070    inserter->insert(s1tmp);
  9071  
  9072    // l1tmp := len(s1tmp)
  9073    Named_object* lenfn = gogo->lookup_global("len");
  9074    Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
  9075    Expression_list* call_args = new Expression_list();
  9076    call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
  9077    Expression* len = Expression::make_call(lenref, call_args, false, loc);
  9078    gogo->lower_expression(function, inserter, &len);
  9079    gogo->flatten_expression(function, inserter, &len);
  9080    Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
  9081    inserter->insert(l1tmp);
  9082  
  9083    Temporary_statement* s2tmp = NULL;
  9084    Temporary_statement* l2tmp = NULL;
  9085    Expression_list* add = NULL;
  9086    Expression* len2;
  9087    Call_expression* makecall = NULL;
  9088    if (this->is_varargs())
  9089      {
  9090        go_assert(args->size() == 2);
  9091  
  9092        std::pair<Call_expression*, Temporary_statement*> p =
  9093          Expression::find_makeslice_call(args->back());
  9094        makecall = p.first;
  9095        if (makecall != NULL)
  9096          {
  9097            // We are handling
  9098            // 	append(s, make([]T, len[, cap])...))
  9099            // which has already been lowered to
  9100            // 	append(s, runtime.makeslice(T, len, cap)).
  9101            // We will optimize this to directly zeroing the tail,
  9102            // instead of allocating a new slice then copy.
  9103  
  9104            // Retrieve the length and capacity. Cannot reference s2 as
  9105            // we will remove the makeslice call.
  9106            Expression* len_arg = makecall->args()->at(1);
  9107            len_arg = Expression::make_cast(int_type, len_arg, loc);
  9108            l2tmp = Statement::make_temporary(int_type, len_arg, loc);
  9109            inserter->insert(l2tmp);
  9110  
  9111            Expression* cap_arg = makecall->args()->at(2);
  9112            cap_arg = Expression::make_cast(int_type, cap_arg, loc);
  9113            Temporary_statement* c2tmp =
  9114              Statement::make_temporary(int_type, cap_arg, loc);
  9115            inserter->insert(c2tmp);
  9116  
  9117            // Check bad len/cap here.
  9118  	  // checkmakeslice(type, len, cap)
  9119  	  // (Note that if len and cap are constants, we won't see a
  9120  	  // makeslice call here, as it will be rewritten to a stack
  9121  	  // allocated array by Mark_address_taken::expression.)
  9122  	  Expression* elem = Expression::make_type_descriptor(element_type,
  9123  							      loc);
  9124            len2 = Expression::make_temporary_reference(l2tmp, loc);
  9125            Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
  9126  	  Expression* check = Runtime::make_call(Runtime::CHECK_MAKE_SLICE,
  9127  						 loc, 3, elem, len2, cap2);
  9128            gogo->lower_expression(function, inserter, &check);
  9129            gogo->flatten_expression(function, inserter, &check);
  9130            Statement* s = Statement::make_statement(check, false);
  9131            inserter->insert(s);
  9132  
  9133            // Remove the original makeslice call.
  9134            Temporary_statement* ts = p.second;
  9135            if (ts != NULL && ts->uses() == 1)
  9136              ts->set_init(Expression::make_nil(loc));
  9137          }
  9138        else
  9139          {
  9140            // s2tmp := s2
  9141            s2tmp = Statement::make_temporary(NULL, args->back(), loc);
  9142            inserter->insert(s2tmp);
  9143  
  9144            // l2tmp := len(s2tmp)
  9145            lenref = Expression::make_func_reference(lenfn, NULL, loc);
  9146            call_args = new Expression_list();
  9147            call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
  9148            len = Expression::make_call(lenref, call_args, false, loc);
  9149            gogo->lower_expression(function, inserter, &len);
  9150            gogo->flatten_expression(function, inserter, &len);
  9151            l2tmp = Statement::make_temporary(int_type, len, loc);
  9152            inserter->insert(l2tmp);
  9153          }
  9154  
  9155        // len2 = l2tmp
  9156        len2 = Expression::make_temporary_reference(l2tmp, loc);
  9157      }
  9158    else
  9159      {
  9160        // We have to ensure that all the arguments are in variables
  9161        // now, because otherwise if one of them is an index expression
  9162        // into the current slice we could overwrite it before we fetch
  9163        // it.
  9164        add = new Expression_list();
  9165        Expression_list::const_iterator pa = args->begin();
  9166        for (++pa; pa != args->end(); ++pa)
  9167  	{
  9168  	  if ((*pa)->is_multi_eval_safe())
  9169  	    add->push_back(*pa);
  9170  	  else
  9171  	    {
  9172  	      Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
  9173  								   loc);
  9174  	      inserter->insert(tmp);
  9175  	      add->push_back(Expression::make_temporary_reference(tmp, loc));
  9176  	    }
  9177  	}
  9178  
  9179        // len2 = len(add)
  9180        len2 = Expression::make_integer_ul(add->size(), int_type, loc);
  9181      }
  9182  
  9183    // ntmp := l1tmp + len2
  9184    Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
  9185    Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
  9186    gogo->lower_expression(function, inserter, &sum);
  9187    gogo->flatten_expression(function, inserter, &sum);
  9188    Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
  9189    inserter->insert(ntmp);
  9190  
  9191    // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
  9192    //   growslice(type, s1tmp, ntmp) :
  9193    //   s1tmp[:ntmp]
  9194    // Using uint here means that if the computation of ntmp overflowed,
  9195    // we will call growslice which will panic.
  9196  
  9197    Named_object* capfn = gogo->lookup_global("cap");
  9198    Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
  9199    call_args = new Expression_list();
  9200    call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
  9201    Expression* cap = Expression::make_call(capref, call_args, false, loc);
  9202    gogo->lower_expression(function, inserter, &cap);
  9203    gogo->flatten_expression(function, inserter, &cap);
  9204    Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
  9205    inserter->insert(c1tmp);
  9206  
  9207    Expression* left = Expression::make_temporary_reference(ntmp, loc);
  9208    left = Expression::make_cast(uint_type, left, loc);
  9209    Expression* right = Expression::make_temporary_reference(c1tmp, loc);
  9210    right = Expression::make_cast(uint_type, right, loc);
  9211  
  9212    Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
  9213  
  9214    Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
  9215    Expression* a1 = Expression::make_type_descriptor(element_type, loc);
  9216    Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
  9217    a2 = slice_type->array_type()->get_value_pointer(gogo, a2);
  9218    a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
  9219    Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
  9220    Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
  9221    Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
  9222    Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
  9223  					a1, a2, a3, a4, a5);
  9224    call = Expression::make_unsafe_cast(slice_type, call, loc);
  9225  
  9226    ref = Expression::make_temporary_reference(s1tmp, loc);
  9227    Expression* zero = Expression::make_integer_ul(0, int_type, loc);
  9228    Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
  9229    ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
  9230    ref->array_index_expression()->set_needs_bounds_check(false);
  9231  
  9232    if (assign_lhs == NULL)
  9233      {
  9234        Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
  9235  
  9236        gogo->lower_expression(function, inserter, &rhs);
  9237        gogo->flatten_expression(function, inserter, &rhs);
  9238  
  9239        ref = Expression::make_temporary_reference(s1tmp, loc);
  9240        Statement* assign = Statement::make_assignment(ref, rhs, loc);
  9241        inserter->insert(assign);
  9242      }
  9243    else
  9244      {
  9245        gogo->lower_expression(function, inserter, &cond);
  9246        gogo->flatten_expression(function, inserter, &cond);
  9247        gogo->lower_expression(function, inserter, &call);
  9248        gogo->flatten_expression(function, inserter, &call);
  9249        gogo->lower_expression(function, inserter, &ref);
  9250        gogo->flatten_expression(function, inserter, &ref);
  9251  
  9252        Block* then_block = new Block(enclosing, loc);
  9253        Assignment_statement* assign =
  9254  	Statement::make_assignment(assign_lhs, call, loc);
  9255        then_block->add_statement(assign);
  9256  
  9257        Block* else_block = new Block(enclosing, loc);
  9258        assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
  9259        // This assignment will not change the pointer value, so it does
  9260        // not need a write barrier.
  9261        assign->set_omit_write_barrier();
  9262        else_block->add_statement(assign);
  9263  
  9264        Statement* s = Statement::make_if_statement(cond, then_block,
  9265  						  else_block, loc);
  9266        inserter->insert(s);
  9267  
  9268        ref = Expression::make_temporary_reference(s1tmp, loc);
  9269        assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
  9270        inserter->insert(assign);
  9271      }
  9272  
  9273    Type* uintptr_type = Type::lookup_integer_type("uintptr");
  9274  
  9275    if (this->is_varargs())
  9276      {
  9277        if (makecall != NULL)
  9278          {
  9279            // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
  9280            a1 = Expression::make_temporary_reference(s1tmp, loc);
  9281            ref = Expression::make_temporary_reference(l1tmp, loc);
  9282            a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
  9283            a1->array_index_expression()->set_needs_bounds_check(false);
  9284            a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
  9285  
  9286            ref = Expression::make_temporary_reference(l2tmp, loc);
  9287            ref = Expression::make_cast(uintptr_type, ref, loc);
  9288            a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
  9289            a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
  9290  
  9291            if (element_type->has_pointer())
  9292              call = Runtime::make_call(Runtime::MEMCLRHASPTR, loc, 2, a1, a2);
  9293            else
  9294              {
  9295                Type* int32_type = Type::lookup_integer_type("int32");
  9296                zero = Expression::make_integer_ul(0, int32_type, loc);
  9297                call = Runtime::make_call(Runtime::BUILTIN_MEMSET, loc, 3, a1,
  9298                                          zero, a2);
  9299              }
  9300  
  9301            if (element_type->has_pointer())
  9302              {
  9303                // For a slice containing pointers, growslice already zeroed
  9304                // the memory. We only need to zero in non-growing case.
  9305                // Note: growslice does not zero the memory in non-pointer case.
  9306                ref = Expression::make_temporary_reference(ntmp, loc);
  9307                ref = Expression::make_cast(uint_type, ref, loc);
  9308                ref2 = Expression::make_temporary_reference(c1tmp, loc);
  9309                ref2 = Expression::make_cast(uint_type, ref2, loc);
  9310                cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
  9311                zero = Expression::make_integer_ul(0, int_type, loc);
  9312                call = Expression::make_conditional(cond, zero, call, loc);
  9313              }
  9314          }
  9315        else
  9316          {
  9317            if (element_type->has_pointer())
  9318              {
  9319                // copy(s1tmp[l1tmp:], s2tmp)
  9320                a1 = Expression::make_temporary_reference(s1tmp, loc);
  9321                ref = Expression::make_temporary_reference(l1tmp, loc);
  9322                Expression* nil = Expression::make_nil(loc);
  9323                a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
  9324                a1->array_index_expression()->set_needs_bounds_check(false);
  9325  
  9326                a2 = Expression::make_temporary_reference(s2tmp, loc);
  9327  
  9328                Named_object* copyfn = gogo->lookup_global("copy");
  9329                Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
  9330                call_args = new Expression_list();
  9331                call_args->push_back(a1);
  9332                call_args->push_back(a2);
  9333                call = Expression::make_call(copyref, call_args, false, loc);
  9334              }
  9335            else
  9336              {
  9337                // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
  9338                a1 = Expression::make_temporary_reference(s1tmp, loc);
  9339                ref = Expression::make_temporary_reference(l1tmp, loc);
  9340                a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
  9341                a1->array_index_expression()->set_needs_bounds_check(false);
  9342                a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
  9343  
  9344                a2 = Expression::make_temporary_reference(s2tmp, loc);
  9345                a2 = (a2->type()->is_string_type()
  9346                      ? Expression::make_string_info(a2,
  9347                                                     STRING_INFO_DATA,
  9348                                                     loc)
  9349                      : Expression::make_slice_info(a2,
  9350                                                    SLICE_INFO_VALUE_POINTER,
  9351                                                    loc));
  9352  
  9353                ref = Expression::make_temporary_reference(l2tmp, loc);
  9354                ref = Expression::make_cast(uintptr_type, ref, loc);
  9355                a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
  9356                a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
  9357  
  9358                call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
  9359                                          a1, a2, a3);
  9360              }
  9361          }
  9362        gogo->lower_expression(function, inserter, &call);
  9363        gogo->flatten_expression(function, inserter, &call);
  9364        inserter->insert(Statement::make_statement(call, false));
  9365      }
  9366    else
  9367      {
  9368        // For each argument:
  9369        //  s1tmp[l1tmp+i] = a
  9370        unsigned long i = 0;
  9371        for (Expression_list::const_iterator pa = add->begin();
  9372  	   pa != add->end();
  9373  	   ++pa, ++i)
  9374  	{
  9375  	  ref = Expression::make_temporary_reference(s1tmp, loc);
  9376  	  ref2 = Expression::make_temporary_reference(l1tmp, loc);
  9377  	  Expression* off = Expression::make_integer_ul(i, int_type, loc);
  9378  	  ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
  9379  	  Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
  9380                                                           NULL, loc);
  9381            lhs->array_index_expression()->set_needs_bounds_check(false);
  9382  	  gogo->lower_expression(function, inserter, &lhs);
  9383  	  gogo->flatten_expression(function, inserter, &lhs);
  9384        Expression* elem = *pa;
  9385        if (!Type::are_identical(element_type, elem->type(), 0, NULL)
  9386            && element_type->interface_type() != NULL)
  9387          elem = Expression::make_cast(element_type, elem, loc);
  9388  	  // The flatten pass runs after the write barrier pass, so we
  9389  	  // need to insert a write barrier here if necessary.
  9390  	  // However, if ASSIGN_LHS is not NULL, we have been called
  9391  	  // directly before the write barrier pass.
  9392  	  Statement* assign;
  9393  	  if (assign_lhs != NULL
  9394  	      || !gogo->assign_needs_write_barrier(lhs, NULL))
  9395  	    assign = Statement::make_assignment(lhs, elem, loc);
  9396  	  else
  9397  	    {
  9398  	      Function* f = function == NULL ? NULL : function->func_value();
  9399  	      assign = gogo->assign_with_write_barrier(f, NULL, inserter,
  9400  						       lhs, elem, loc);
  9401  	    }
  9402  	  inserter->insert(assign);
  9403  	}
  9404      }
  9405  
  9406    if (assign_lhs != NULL)
  9407      return NULL;
  9408  
  9409    return Expression::make_temporary_reference(s1tmp, loc);
  9410  }
  9411  
  9412  // Return whether an expression has an integer value.  Report an error
  9413  // if not.  This is used when handling calls to the predeclared make
  9414  // function.  Set *SMALL if the value is known to fit in type "int".
  9415  
  9416  bool
  9417  Builtin_call_expression::check_int_value(Expression* e, bool is_length,
  9418  					 bool *small)
  9419  {
  9420    *small = false;
  9421  
  9422    Numeric_constant nc;
  9423    if (e->numeric_constant_value(&nc))
  9424      {
  9425        unsigned long v;
  9426        switch (nc.to_unsigned_long(&v))
  9427  	{
  9428  	case Numeric_constant::NC_UL_VALID:
  9429  	  break;
  9430  	case Numeric_constant::NC_UL_NOTINT:
  9431  	  go_error_at(e->location(), "non-integer %s argument to make",
  9432  		      is_length ? "len" : "cap");
  9433  	  return false;
  9434  	case Numeric_constant::NC_UL_NEGATIVE:
  9435  	  go_error_at(e->location(), "negative %s argument to make",
  9436  		      is_length ? "len" : "cap");
  9437  	  return false;
  9438  	case Numeric_constant::NC_UL_BIG:
  9439  	  // We don't want to give a compile-time error for a 64-bit
  9440  	  // value on a 32-bit target.
  9441  	  break;
  9442  	}
  9443  
  9444        mpz_t val;
  9445        if (!nc.to_int(&val))
  9446  	go_unreachable();
  9447        int bits = mpz_sizeinbase(val, 2);
  9448        mpz_clear(val);
  9449        Type* int_type = Type::lookup_integer_type("int");
  9450        if (bits >= int_type->integer_type()->bits())
  9451  	{
  9452  	  go_error_at(e->location(), "%s argument too large for make",
  9453  		      is_length ? "len" : "cap");
  9454  	  return false;
  9455  	}
  9456  
  9457        *small = true;
  9458        return true;
  9459      }
  9460  
  9461    if (e->type()->integer_type() != NULL)
  9462      {
  9463        int ebits = e->type()->integer_type()->bits();
  9464        int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
  9465  
  9466        // We can treat ebits == intbits as small even for an unsigned
  9467        // integer type, because we will convert the value to int and
  9468        // then reject it in the runtime if it is negative.
  9469        *small = ebits <= intbits;
  9470  
  9471        return true;
  9472      }
  9473  
  9474    go_error_at(e->location(), "non-integer %s argument to make",
  9475  	      is_length ? "len" : "cap");
  9476    return false;
  9477  }
  9478  
  9479  // Return the type of the real or imag functions, given the type of
  9480  // the argument.  We need to map complex64 to float32 and complex128
  9481  // to float64, so it has to be done by name.  This returns NULL if it
  9482  // can't figure out the type.
  9483  
  9484  Type*
  9485  Builtin_call_expression::real_imag_type(Type* arg_type)
  9486  {
  9487    if (arg_type == NULL || arg_type->is_abstract())
  9488      return NULL;
  9489    Named_type* nt = arg_type->named_type();
  9490    if (nt == NULL)
  9491      return NULL;
  9492    while (nt->real_type()->named_type() != NULL)
  9493      nt = nt->real_type()->named_type();
  9494    if (nt->name() == "complex64")
  9495      return Type::lookup_float_type("float32");
  9496    else if (nt->name() == "complex128")
  9497      return Type::lookup_float_type("float64");
  9498    else
  9499      return NULL;
  9500  }
  9501  
  9502  // Return the type of the complex function, given the type of one of the
  9503  // argments.  Like real_imag_type, we have to map by name.
  9504  
  9505  Type*
  9506  Builtin_call_expression::complex_type(Type* arg_type)
  9507  {
  9508    if (arg_type == NULL || arg_type->is_abstract())
  9509      return NULL;
  9510    Named_type* nt = arg_type->named_type();
  9511    if (nt == NULL)
  9512      return NULL;
  9513    while (nt->real_type()->named_type() != NULL)
  9514      nt = nt->real_type()->named_type();
  9515    if (nt->name() == "float32")
  9516      return Type::lookup_complex_type("complex64");
  9517    else if (nt->name() == "float64")
  9518      return Type::lookup_complex_type("complex128");
  9519    else
  9520      return NULL;
  9521  }
  9522  
  9523  // Return a single argument, or NULL if there isn't one.
  9524  
  9525  Expression*
  9526  Builtin_call_expression::one_arg() const
  9527  {
  9528    const Expression_list* args = this->args();
  9529    if (args == NULL || args->size() != 1)
  9530      return NULL;
  9531    return args->front();
  9532  }
  9533  
  9534  // A traversal class which looks for a call or receive expression.
  9535  
  9536  class Find_call_expression : public Traverse
  9537  {
  9538   public:
  9539    Find_call_expression()
  9540      : Traverse(traverse_expressions),
  9541        found_(false)
  9542    { }
  9543  
  9544    int
  9545    expression(Expression**);
  9546  
  9547    bool
  9548    found()
  9549    { return this->found_; }
  9550  
  9551   private:
  9552    bool found_;
  9553  };
  9554  
  9555  int
  9556  Find_call_expression::expression(Expression** pexpr)
  9557  {
  9558    Expression* expr = *pexpr;
  9559    if (!expr->is_constant()
  9560        && (expr->call_expression() != NULL
  9561  	  || expr->receive_expression() != NULL))
  9562      {
  9563        this->found_ = true;
  9564        return TRAVERSE_EXIT;
  9565      }
  9566    return TRAVERSE_CONTINUE;
  9567  }
  9568  
  9569  // Return whether calling len or cap on EXPR, of array type, is a
  9570  // constant.  The language spec says "the expressions len(s) and
  9571  // cap(s) are constants if the type of s is an array or pointer to an
  9572  // array and the expression s does not contain channel receives or
  9573  // (non-constant) function calls."
  9574  
  9575  bool
  9576  Builtin_call_expression::array_len_is_constant(Expression* expr)
  9577  {
  9578    go_assert(expr->type()->deref()->array_type() != NULL
  9579  	    && !expr->type()->deref()->is_slice_type());
  9580    if (expr->is_constant())
  9581      return true;
  9582    Find_call_expression find_call;
  9583    Expression::traverse(&expr, &find_call);
  9584    return !find_call.found();
  9585  }
  9586  
  9587  // Return whether this is constant: len of a string constant, or len
  9588  // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
  9589  // unsafe.Alignof.
  9590  
  9591  bool
  9592  Builtin_call_expression::do_is_constant() const
  9593  {
  9594    if (this->is_error_expression())
  9595      return true;
  9596    switch (this->code_)
  9597      {
  9598      case BUILTIN_LEN:
  9599      case BUILTIN_CAP:
  9600        {
  9601  	if (this->seen_)
  9602  	  return false;
  9603  
  9604  	Expression* arg = this->one_arg();
  9605  	if (arg == NULL)
  9606  	  return false;
  9607  	Type* arg_type = arg->type();
  9608  	if (arg_type->is_error())
  9609  	  return true;
  9610  
  9611  	if (arg_type->points_to() != NULL
  9612  	    && arg_type->points_to()->array_type() != NULL
  9613  	    && !arg_type->points_to()->is_slice_type())
  9614  	  arg_type = arg_type->points_to();
  9615  
  9616  	if (arg_type->array_type() != NULL
  9617  	    && arg_type->array_type()->length() != NULL)
  9618            {
  9619  	    this->seen_ = true;
  9620  	    bool ret = Builtin_call_expression::array_len_is_constant(arg);
  9621  	    this->seen_ = false;
  9622  	    return ret;
  9623            }
  9624  
  9625  	if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
  9626  	  {
  9627  	    this->seen_ = true;
  9628  	    bool ret = arg->is_constant();
  9629  	    this->seen_ = false;
  9630  	    return ret;
  9631  	  }
  9632        }
  9633        break;
  9634  
  9635      case BUILTIN_SIZEOF:
  9636      case BUILTIN_ALIGNOF:
  9637        return this->one_arg() != NULL;
  9638  
  9639      case BUILTIN_OFFSETOF:
  9640        {
  9641  	Expression* arg = this->one_arg();
  9642  	if (arg == NULL)
  9643  	  return false;
  9644  	return arg->field_reference_expression() != NULL;
  9645        }
  9646  
  9647      case BUILTIN_COMPLEX:
  9648        {
  9649  	const Expression_list* args = this->args();
  9650  	if (args != NULL && args->size() == 2)
  9651  	  return args->front()->is_constant() && args->back()->is_constant();
  9652        }
  9653        break;
  9654  
  9655      case BUILTIN_REAL:
  9656      case BUILTIN_IMAG:
  9657        {
  9658  	Expression* arg = this->one_arg();
  9659  	return arg != NULL && arg->is_constant();
  9660        }
  9661  
  9662      default:
  9663        break;
  9664      }
  9665  
  9666    return false;
  9667  }
  9668  
  9669  // Return a numeric constant if possible.
  9670  
  9671  bool
  9672  Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
  9673  {
  9674    if (this->code_ == BUILTIN_LEN
  9675        || this->code_ == BUILTIN_CAP)
  9676      {
  9677        Expression* arg = this->one_arg();
  9678        if (arg == NULL)
  9679  	return false;
  9680        Type* arg_type = arg->type();
  9681        if (arg_type->is_error())
  9682  	return false;
  9683  
  9684        if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
  9685  	{
  9686  	  std::string sval;
  9687  	  if (arg->string_constant_value(&sval))
  9688  	    {
  9689  	      nc->set_unsigned_long(Type::lookup_integer_type("int"),
  9690  				    sval.length());
  9691  	      return true;
  9692  	    }
  9693  	}
  9694  
  9695        if (arg_type->points_to() != NULL
  9696  	  && arg_type->points_to()->array_type() != NULL
  9697  	  && !arg_type->points_to()->is_slice_type())
  9698  	arg_type = arg_type->points_to();
  9699  
  9700        if (arg_type->array_type() != NULL
  9701  	  && arg_type->array_type()->length() != NULL)
  9702  	{
  9703  	  if (this->seen_)
  9704  	    return false;
  9705  
  9706  	  // We may be replacing this expression with a constant
  9707  	  // during lowering, so verify the type to report any errors.
  9708  	  // It's OK to verify an array type more than once.
  9709  	  arg_type->verify();
  9710  	  if (!arg_type->is_error())
  9711  	    {
  9712  	      Expression* e = arg_type->array_type()->length();
  9713  	      this->seen_ = true;
  9714  	      bool r = e->numeric_constant_value(nc);
  9715  	      this->seen_ = false;
  9716  	      if (r)
  9717  		{
  9718  		  if (!nc->set_type(Type::lookup_integer_type("int"), false,
  9719  				    this->location()))
  9720  		    r = false;
  9721  		}
  9722  	      return r;
  9723  	    }
  9724  	}
  9725      }
  9726    else if (this->code_ == BUILTIN_SIZEOF
  9727  	   || this->code_ == BUILTIN_ALIGNOF)
  9728      {
  9729        Expression* arg = this->one_arg();
  9730        if (arg == NULL)
  9731  	return false;
  9732        Type* arg_type = arg->type();
  9733        if (arg_type->is_error())
  9734  	return false;
  9735        if (arg_type->is_abstract())
  9736  	arg_type = arg_type->make_non_abstract_type();
  9737        if (this->seen_)
  9738          return false;
  9739  
  9740        int64_t ret;
  9741        if (this->code_ == BUILTIN_SIZEOF)
  9742  	{
  9743            this->seen_ = true;
  9744  	  bool ok = arg_type->backend_type_size(this->gogo_, &ret);
  9745            this->seen_ = false;
  9746  	  if (!ok)
  9747  	    return false;
  9748  	}
  9749        else if (this->code_ == BUILTIN_ALIGNOF)
  9750  	{
  9751  	  bool ok;
  9752            this->seen_ = true;
  9753  	  if (arg->field_reference_expression() == NULL)
  9754  	    ok = arg_type->backend_type_align(this->gogo_, &ret);
  9755  	  else
  9756  	    {
  9757  	      // Calling unsafe.Alignof(s.f) returns the alignment of
  9758  	      // the type of f when it is used as a field in a struct.
  9759  	      ok = arg_type->backend_type_field_align(this->gogo_, &ret);
  9760  	    }
  9761            this->seen_ = false;
  9762  	  if (!ok)
  9763  	    return false;
  9764  	}
  9765        else
  9766  	go_unreachable();
  9767  
  9768        mpz_t zval;
  9769        set_mpz_from_int64(&zval, ret);
  9770        nc->set_int(Type::lookup_integer_type("uintptr"), zval);
  9771        mpz_clear(zval);
  9772        return true;
  9773      }
  9774    else if (this->code_ == BUILTIN_OFFSETOF)
  9775      {
  9776        Expression* arg = this->one_arg();
  9777        if (arg == NULL)
  9778  	return false;
  9779        Field_reference_expression* farg = arg->field_reference_expression();
  9780        if (farg == NULL)
  9781  	return false;
  9782        if (this->seen_)
  9783          return false;
  9784  
  9785        int64_t total_offset = 0;
  9786        while (true)
  9787          {
  9788            Expression* struct_expr = farg->expr();
  9789            Type* st = struct_expr->type();
  9790            if (st->struct_type() == NULL)
  9791              return false;
  9792            if (st->named_type() != NULL)
  9793              st->named_type()->convert(this->gogo_);
  9794            if (st->is_error_type())
  9795              {
  9796                go_assert(saw_errors());
  9797                return false;
  9798              }
  9799            int64_t offset;
  9800            this->seen_ = true;
  9801            bool ok = st->struct_type()->backend_field_offset(this->gogo_,
  9802  							    farg->field_index(),
  9803  							    &offset);
  9804            this->seen_ = false;
  9805  	  if (!ok)
  9806  	    return false;
  9807            total_offset += offset;
  9808            if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
  9809              {
  9810                // Go up until we reach the original base.
  9811                farg = struct_expr->field_reference_expression();
  9812                continue;
  9813              }
  9814            break;
  9815          }
  9816        mpz_t zval;
  9817        set_mpz_from_int64(&zval, total_offset);
  9818        nc->set_int(Type::lookup_integer_type("uintptr"), zval);
  9819        mpz_clear(zval);
  9820        return true;
  9821      }
  9822    else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
  9823      {
  9824        Expression* arg = this->one_arg();
  9825        if (arg == NULL)
  9826  	return false;
  9827  
  9828        Numeric_constant argnc;
  9829        if (!arg->numeric_constant_value(&argnc))
  9830  	return false;
  9831  
  9832        mpc_t val;
  9833        if (!argnc.to_complex(&val))
  9834  	return false;
  9835  
  9836        Type* type = Builtin_call_expression::real_imag_type(argnc.type());
  9837        if (this->code_ == BUILTIN_REAL)
  9838  	nc->set_float(type, mpc_realref(val));
  9839        else
  9840  	nc->set_float(type, mpc_imagref(val));
  9841        mpc_clear(val);
  9842        return true;
  9843      }
  9844    else if (this->code_ == BUILTIN_COMPLEX)
  9845      {
  9846        const Expression_list* args = this->args();
  9847        if (args == NULL || args->size() != 2)
  9848  	return false;
  9849  
  9850        Numeric_constant rnc;
  9851        if (!args->front()->numeric_constant_value(&rnc))
  9852  	return false;
  9853        Numeric_constant inc;
  9854        if (!args->back()->numeric_constant_value(&inc))
  9855  	return false;
  9856  
  9857        if (rnc.type() != NULL
  9858  	  && !rnc.type()->is_abstract()
  9859  	  && inc.type() != NULL
  9860  	  && !inc.type()->is_abstract()
  9861  	  && !Type::are_identical(rnc.type(), inc.type(),
  9862  				  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
  9863  				  NULL))
  9864  	return false;
  9865  
  9866        mpfr_t r;
  9867        if (!rnc.to_float(&r))
  9868  	return false;
  9869        mpfr_t i;
  9870        if (!inc.to_float(&i))
  9871  	{
  9872  	  mpfr_clear(r);
  9873  	  return false;
  9874  	}
  9875  
  9876        Type* arg_type = rnc.type();
  9877        if (arg_type == NULL || arg_type->is_abstract())
  9878  	arg_type = inc.type();
  9879  
  9880        mpc_t val;
  9881        mpc_init2(val, mpc_precision);
  9882        mpc_set_fr_fr(val, r, i, MPC_RNDNN);
  9883        mpfr_clear(r);
  9884        mpfr_clear(i);
  9885  
  9886        Type* type = Builtin_call_expression::complex_type(arg_type);
  9887        nc->set_complex(type, val);
  9888  
  9889        mpc_clear(val);
  9890  
  9891        return true;
  9892      }
  9893  
  9894    return false;
  9895  }
  9896  
  9897  // Give an error if we are discarding the value of an expression which
  9898  // should not normally be discarded.  We don't give an error for
  9899  // discarding the value of an ordinary function call, but we do for
  9900  // builtin functions, purely for consistency with the gc compiler.
  9901  
  9902  bool
  9903  Builtin_call_expression::do_discarding_value()
  9904  {
  9905    switch (this->code_)
  9906      {
  9907      case BUILTIN_INVALID:
  9908      default:
  9909        go_unreachable();
  9910  
  9911      case BUILTIN_APPEND:
  9912      case BUILTIN_CAP:
  9913      case BUILTIN_COMPLEX:
  9914      case BUILTIN_IMAG:
  9915      case BUILTIN_LEN:
  9916      case BUILTIN_MAKE:
  9917      case BUILTIN_NEW:
  9918      case BUILTIN_REAL:
  9919      case BUILTIN_ADD:
  9920      case BUILTIN_ALIGNOF:
  9921      case BUILTIN_OFFSETOF:
  9922      case BUILTIN_SIZEOF:
  9923      case BUILTIN_SLICE:
  9924        this->unused_value_error();
  9925        return false;
  9926  
  9927      case BUILTIN_CLOSE:
  9928      case BUILTIN_COPY:
  9929      case BUILTIN_DELETE:
  9930      case BUILTIN_PANIC:
  9931      case BUILTIN_PRINT:
  9932      case BUILTIN_PRINTLN:
  9933      case BUILTIN_RECOVER:
  9934        return true;
  9935      }
  9936  }
  9937  
  9938  // Return the type.
  9939  
  9940  Type*
  9941  Builtin_call_expression::do_type()
  9942  {
  9943    if (this->is_error_expression())
  9944      return Type::make_error_type();
  9945    switch (this->code_)
  9946      {
  9947      case BUILTIN_INVALID:
  9948      default:
  9949        return Type::make_error_type();
  9950  
  9951      case BUILTIN_NEW:
  9952        {
  9953  	const Expression_list* args = this->args();
  9954  	if (args == NULL || args->empty())
  9955  	  return Type::make_error_type();
  9956  	return Type::make_pointer_type(args->front()->type());
  9957        }
  9958  
  9959      case BUILTIN_MAKE:
  9960        {
  9961  	const Expression_list* args = this->args();
  9962  	if (args == NULL || args->empty())
  9963  	  return Type::make_error_type();
  9964  	return args->front()->type();
  9965        }
  9966  
  9967      case BUILTIN_CAP:
  9968      case BUILTIN_COPY:
  9969      case BUILTIN_LEN:
  9970        return Type::lookup_integer_type("int");
  9971  
  9972      case BUILTIN_ALIGNOF:
  9973      case BUILTIN_OFFSETOF:
  9974      case BUILTIN_SIZEOF:
  9975        return Type::lookup_integer_type("uintptr");
  9976  
  9977      case BUILTIN_CLOSE:
  9978      case BUILTIN_DELETE:
  9979      case BUILTIN_PANIC:
  9980      case BUILTIN_PRINT:
  9981      case BUILTIN_PRINTLN:
  9982        return Type::make_void_type();
  9983  
  9984      case BUILTIN_RECOVER:
  9985        return Type::make_empty_interface_type(Linemap::predeclared_location());
  9986  
  9987      case BUILTIN_APPEND:
  9988        {
  9989  	const Expression_list* args = this->args();
  9990  	if (args == NULL || args->empty())
  9991  	  return Type::make_error_type();
  9992  	Type *ret = args->front()->type();
  9993  	if (!ret->is_slice_type())
  9994  	  return Type::make_error_type();
  9995  	return ret;
  9996        }
  9997  
  9998      case BUILTIN_REAL:
  9999      case BUILTIN_IMAG:
 10000        {
 10001  	Expression* arg = this->one_arg();
 10002  	if (arg == NULL)
 10003  	  return Type::make_error_type();
 10004  	Type* t = arg->type();
 10005  	if (t->is_abstract())
 10006  	  t = t->make_non_abstract_type();
 10007  	t = Builtin_call_expression::real_imag_type(t);
 10008  	if (t == NULL)
 10009  	  t = Type::make_error_type();
 10010  	return t;
 10011        }
 10012  
 10013      case BUILTIN_COMPLEX:
 10014        {
 10015  	const Expression_list* args = this->args();
 10016  	if (args == NULL || args->size() != 2)
 10017  	  return Type::make_error_type();
 10018  	Type* t = args->front()->type();
 10019  	if (t->is_abstract())
 10020  	  {
 10021  	    t = args->back()->type();
 10022  	    if (t->is_abstract())
 10023  	      t = t->make_non_abstract_type();
 10024  	  }
 10025  	t = Builtin_call_expression::complex_type(t);
 10026  	if (t == NULL)
 10027  	  t = Type::make_error_type();
 10028  	return t;
 10029        }
 10030  
 10031      case BUILTIN_ADD:
 10032        return Type::make_pointer_type(Type::make_void_type());
 10033  
 10034      case BUILTIN_SLICE:
 10035        const Expression_list* args = this->args();
 10036        if (args == NULL || args->size() != 2)
 10037  	return Type::make_error_type();
 10038        Type* pt = args->front()->type()->points_to();
 10039        if (pt == NULL)
 10040  	return Type::make_error_type();
 10041        return Type::make_array_type(pt, NULL);
 10042      }
 10043  }
 10044  
 10045  // Determine the type.
 10046  
 10047  void
 10048  Builtin_call_expression::do_determine_type(const Type_context* context)
 10049  {
 10050    if (!this->determining_types())
 10051      return;
 10052  
 10053    this->fn()->determine_type_no_context();
 10054  
 10055    const Expression_list* args = this->args();
 10056  
 10057    bool is_print;
 10058    Type* arg_type = NULL;
 10059    Type* trailing_arg_types = NULL;
 10060    switch (this->code_)
 10061      {
 10062      case BUILTIN_PRINT:
 10063      case BUILTIN_PRINTLN:
 10064        // Do not force a large integer constant to "int".
 10065        is_print = true;
 10066        break;
 10067  
 10068      case BUILTIN_REAL:
 10069      case BUILTIN_IMAG:
 10070        arg_type = Builtin_call_expression::complex_type(context->type);
 10071        if (arg_type == NULL)
 10072  	arg_type = Type::lookup_complex_type("complex128");
 10073        is_print = false;
 10074        break;
 10075  
 10076      case BUILTIN_COMPLEX:
 10077        {
 10078  	// For the complex function the type of one operand can
 10079  	// determine the type of the other, as in a binary expression.
 10080  	arg_type = Builtin_call_expression::real_imag_type(context->type);
 10081  	if (arg_type == NULL)
 10082  	  arg_type = Type::lookup_float_type("float64");
 10083  	if (args != NULL && args->size() == 2)
 10084  	  {
 10085  	    Type* t1 = args->front()->type();
 10086  	    Type* t2 = args->back()->type();
 10087  	    if (!t1->is_abstract())
 10088  	      arg_type = t1;
 10089  	    else if (!t2->is_abstract())
 10090  	      arg_type = t2;
 10091  	  }
 10092  	is_print = false;
 10093        }
 10094        break;
 10095  
 10096      case BUILTIN_APPEND:
 10097        if (!this->is_varargs()
 10098  	  && args != NULL
 10099  	  && !args->empty()
 10100  	  && args->front()->type()->is_slice_type())
 10101  	trailing_arg_types =
 10102  	  args->front()->type()->array_type()->element_type();
 10103        is_print = false;
 10104        break;
 10105  
 10106      case BUILTIN_ADD:
 10107      case BUILTIN_SLICE:
 10108        // Both unsafe.Add and unsafe.Slice take two arguments, and the
 10109        // second arguments defaults to "int".
 10110        if (args != NULL && args->size() == 2)
 10111  	{
 10112  	  if (this->code_ == BUILTIN_SLICE)
 10113  	    args->front()->determine_type_no_context();
 10114  	  else
 10115  	    {
 10116  	      Type* pointer = Type::make_pointer_type(Type::make_void_type());
 10117  	      Type_context subcontext(pointer, false);
 10118  	      args->front()->determine_type(&subcontext);
 10119  	    }
 10120  	  Type* int_type = Type::lookup_integer_type("int");
 10121  	  Type_context subcontext(int_type, false);
 10122  	  args->back()->determine_type(&subcontext);
 10123  	  return;
 10124  	}
 10125        is_print = false;
 10126        break;
 10127  
 10128      default:
 10129        is_print = false;
 10130        break;
 10131      }
 10132  
 10133    if (args != NULL)
 10134      {
 10135        for (Expression_list::const_iterator pa = args->begin();
 10136  	   pa != args->end();
 10137  	   ++pa)
 10138  	{
 10139  	  Type_context subcontext;
 10140  	  subcontext.type = arg_type;
 10141  
 10142  	  if (is_print)
 10143  	    {
 10144  	      // We want to print large constants, we so can't just
 10145  	      // use the appropriate nonabstract type.  Use uint64 for
 10146  	      // an integer if we know it is nonnegative, otherwise
 10147  	      // use int64 for a integer, otherwise use float64 for a
 10148  	      // float or complex128 for a complex.
 10149  	      Type* want_type = NULL;
 10150  	      Type* atype = (*pa)->type();
 10151  	      if (atype->is_abstract())
 10152  		{
 10153  		  if (atype->integer_type() != NULL)
 10154  		    {
 10155  		      Numeric_constant nc;
 10156  		      if (this->numeric_constant_value(&nc))
 10157  			{
 10158  			  mpz_t val;
 10159  			  if (nc.to_int(&val))
 10160  			    {
 10161  			      if (mpz_sgn(val) >= 0)
 10162  				want_type = Type::lookup_integer_type("uint64");
 10163  			      mpz_clear(val);
 10164  			    }
 10165  			}
 10166  		      if (want_type == NULL)
 10167  			want_type = Type::lookup_integer_type("int64");
 10168  		    }
 10169  		  else if (atype->float_type() != NULL)
 10170  		    want_type = Type::lookup_float_type("float64");
 10171  		  else if (atype->complex_type() != NULL)
 10172  		    want_type = Type::lookup_complex_type("complex128");
 10173  		  else if (atype->is_abstract_string_type())
 10174  		    want_type = Type::lookup_string_type();
 10175  		  else if (atype->is_abstract_boolean_type())
 10176  		    want_type = Type::lookup_bool_type();
 10177  		  else
 10178  		    go_unreachable();
 10179  		  subcontext.type = want_type;
 10180  		}
 10181  	    }
 10182  
 10183  	  (*pa)->determine_type(&subcontext);
 10184  
 10185  	  if (trailing_arg_types != NULL)
 10186  	    {
 10187  	      arg_type = trailing_arg_types;
 10188  	      trailing_arg_types = NULL;
 10189  	    }
 10190  	}
 10191      }
 10192  }
 10193  
 10194  // If there is exactly one argument, return true.  Otherwise give an
 10195  // error message and return false.
 10196  
 10197  bool
 10198  Builtin_call_expression::check_one_arg()
 10199  {
 10200    const Expression_list* args = this->args();
 10201    if (args == NULL || args->size() < 1)
 10202      {
 10203        this->report_error(_("not enough arguments"));
 10204        return false;
 10205      }
 10206    else if (args->size() > 1)
 10207      {
 10208        this->report_error(_("too many arguments"));
 10209        return false;
 10210      }
 10211    if (args->front()->is_error_expression()
 10212        || args->front()->type()->is_error())
 10213      {
 10214        this->set_is_error();
 10215        return false;
 10216      }
 10217    return true;
 10218  }
 10219  
 10220  // Check argument types for a builtin function.
 10221  
 10222  void
 10223  Builtin_call_expression::do_check_types(Gogo*)
 10224  {
 10225    if (this->is_error_expression())
 10226      return;
 10227    switch (this->code_)
 10228      {
 10229      case BUILTIN_INVALID:
 10230      case BUILTIN_NEW:
 10231      case BUILTIN_MAKE:
 10232      case BUILTIN_DELETE:
 10233        return;
 10234  
 10235      case BUILTIN_LEN:
 10236      case BUILTIN_CAP:
 10237        {
 10238  	// The single argument may be either a string or an array or a
 10239  	// map or a channel, or a pointer to a closed array.
 10240  	if (this->check_one_arg())
 10241  	  {
 10242  	    Type* arg_type = this->one_arg()->type();
 10243  	    if (arg_type->points_to() != NULL
 10244  		&& arg_type->points_to()->array_type() != NULL
 10245  		&& !arg_type->points_to()->is_slice_type())
 10246  	      arg_type = arg_type->points_to();
 10247  	    if (this->code_ == BUILTIN_CAP)
 10248  	      {
 10249  		if (!arg_type->is_error()
 10250  		    && arg_type->array_type() == NULL
 10251  		    && arg_type->channel_type() == NULL)
 10252  		  this->report_error(_("argument must be array or slice "
 10253  				       "or channel"));
 10254  	      }
 10255  	    else
 10256  	      {
 10257  		if (!arg_type->is_error()
 10258  		    && !arg_type->is_string_type()
 10259  		    && arg_type->array_type() == NULL
 10260  		    && arg_type->map_type() == NULL
 10261  		    && arg_type->channel_type() == NULL)
 10262  		  this->report_error(_("argument must be string or "
 10263  				       "array or slice or map or channel"));
 10264  	      }
 10265  	  }
 10266        }
 10267        break;
 10268  
 10269      case BUILTIN_PRINT:
 10270      case BUILTIN_PRINTLN:
 10271        {
 10272  	const Expression_list* args = this->args();
 10273  	if (args != NULL)
 10274  	  {
 10275  	    for (Expression_list::const_iterator p = args->begin();
 10276  		 p != args->end();
 10277  		 ++p)
 10278  	      {
 10279  		Type* type = (*p)->type();
 10280  		if (type->is_error()
 10281  		    || type->is_string_type()
 10282  		    || type->integer_type() != NULL
 10283  		    || type->float_type() != NULL
 10284  		    || type->complex_type() != NULL
 10285  		    || type->is_boolean_type()
 10286  		    || type->points_to() != NULL
 10287  		    || type->interface_type() != NULL
 10288  		    || type->channel_type() != NULL
 10289  		    || type->map_type() != NULL
 10290  		    || type->function_type() != NULL
 10291  		    || type->is_slice_type())
 10292  		  ;
 10293  		else if ((*p)->is_type_expression())
 10294  		  {
 10295  		    // If this is a type expression it's going to give
 10296  		    // an error anyhow, so we don't need one here.
 10297  		  }
 10298  		else
 10299  		  this->report_error(_("unsupported argument type to "
 10300  				       "builtin function"));
 10301  	      }
 10302  	  }
 10303        }
 10304        break;
 10305  
 10306      case BUILTIN_CLOSE:
 10307        if (this->check_one_arg())
 10308  	{
 10309  	  if (this->one_arg()->type()->channel_type() == NULL)
 10310  	    this->report_error(_("argument must be channel"));
 10311  	  else if (!this->one_arg()->type()->channel_type()->may_send())
 10312  	    this->report_error(_("cannot close receive-only channel"));
 10313  	}
 10314        break;
 10315  
 10316      case BUILTIN_PANIC:
 10317      case BUILTIN_SIZEOF:
 10318      case BUILTIN_ALIGNOF:
 10319        this->check_one_arg();
 10320        break;
 10321  
 10322      case BUILTIN_RECOVER:
 10323        if (this->args() != NULL
 10324  	  && !this->args()->empty()
 10325  	  && !this->recover_arg_is_set_)
 10326  	this->report_error(_("too many arguments"));
 10327        break;
 10328  
 10329      case BUILTIN_OFFSETOF:
 10330        if (this->check_one_arg())
 10331  	{
 10332  	  Expression* arg = this->one_arg();
 10333  	  if (arg->field_reference_expression() == NULL)
 10334  	    this->report_error(_("argument must be a field reference"));
 10335  	}
 10336        break;
 10337  
 10338      case BUILTIN_COPY:
 10339        {
 10340  	const Expression_list* args = this->args();
 10341  	if (args == NULL || args->size() < 2)
 10342  	  {
 10343  	    this->report_error(_("not enough arguments"));
 10344  	    break;
 10345  	  }
 10346  	else if (args->size() > 2)
 10347  	  {
 10348  	    this->report_error(_("too many arguments"));
 10349  	    break;
 10350  	  }
 10351  	Type* arg1_type = args->front()->type();
 10352  	Type* arg2_type = args->back()->type();
 10353  	if (arg1_type->is_error() || arg2_type->is_error())
 10354  	  {
 10355  	    this->set_is_error();
 10356  	    break;
 10357  	  }
 10358  
 10359  	Type* e1;
 10360  	if (arg1_type->is_slice_type())
 10361  	  e1 = arg1_type->array_type()->element_type();
 10362  	else
 10363  	  {
 10364  	    this->report_error(_("left argument must be a slice"));
 10365  	    break;
 10366  	  }
 10367  
 10368  	if (arg2_type->is_slice_type())
 10369  	  {
 10370  	    Type* e2 = arg2_type->array_type()->element_type();
 10371  	    if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
 10372  	      this->report_error(_("element types must be the same"));
 10373  	  }
 10374  	else if (arg2_type->is_string_type())
 10375  	  {
 10376  	    if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
 10377  	      this->report_error(_("first argument must be []byte"));
 10378  	  }
 10379  	else
 10380  	    this->report_error(_("second argument must be slice or string"));
 10381        }
 10382        break;
 10383  
 10384      case BUILTIN_APPEND:
 10385        {
 10386  	const Expression_list* args = this->args();
 10387  	if (args == NULL || args->empty())
 10388  	  {
 10389  	    this->report_error(_("not enough arguments"));
 10390  	    break;
 10391  	  }
 10392  
 10393  	Type* slice_type = args->front()->type();
 10394  	if (!slice_type->is_slice_type())
 10395  	  {
 10396  	    if (slice_type->is_error_type())
 10397  	      break;
 10398  	    if (slice_type->is_nil_type())
 10399  	      go_error_at(args->front()->location(), "use of untyped nil");
 10400  	    else
 10401  	      go_error_at(args->front()->location(),
 10402  			  "argument 1 must be a slice");
 10403  	    this->set_is_error();
 10404  	    break;
 10405  	  }
 10406  
 10407  	Type* element_type = slice_type->array_type()->element_type();
 10408  	if (!element_type->in_heap())
 10409  	  go_error_at(args->front()->location(),
 10410  		      "cannot append to slice of go:notinheap type");
 10411  	if (this->is_varargs())
 10412  	  {
 10413  	    if (!args->back()->type()->is_slice_type()
 10414  		&& !args->back()->type()->is_string_type())
 10415  	      {
 10416  		go_error_at(args->back()->location(),
 10417  			    "invalid use of %<...%> with non-slice/non-string");
 10418  		this->set_is_error();
 10419  		break;
 10420  	      }
 10421  
 10422  	    if (args->size() < 2)
 10423  	      {
 10424  		this->report_error(_("not enough arguments"));
 10425  		break;
 10426  	      }
 10427  	    if (args->size() > 2)
 10428  	      {
 10429  		this->report_error(_("too many arguments"));
 10430  		break;
 10431  	      }
 10432  
 10433  	    if (args->back()->type()->is_string_type()
 10434  		&& element_type->integer_type() != NULL
 10435  		&& element_type->integer_type()->is_byte())
 10436  	      {
 10437  		// Permit append(s1, s2...) when s1 is a slice of
 10438  		// bytes and s2 is a string type.
 10439  	      }
 10440  	    else
 10441  	      {
 10442  		// We have to test for assignment compatibility to a
 10443  		// slice of the element type, which is not necessarily
 10444  		// the same as the type of the first argument: the
 10445  		// first argument might have a named type.
 10446  		Type* check_type = Type::make_array_type(element_type, NULL);
 10447  		std::string reason;
 10448  		if (!Type::are_assignable(check_type, args->back()->type(),
 10449  					  &reason))
 10450  		  {
 10451  		    if (reason.empty())
 10452  		      go_error_at(args->back()->location(),
 10453  				  "argument 2 has invalid type");
 10454  		    else
 10455  		      go_error_at(args->back()->location(),
 10456  				  "argument 2 has invalid type (%s)",
 10457  				  reason.c_str());
 10458  		    this->set_is_error();
 10459  		    break;
 10460  		  }
 10461  	      }
 10462  	  }
 10463  	else
 10464  	  {
 10465  	    Expression_list::const_iterator pa = args->begin();
 10466  	    int i = 2;
 10467  	    for (++pa; pa != args->end(); ++pa, ++i)
 10468  	      {
 10469  		std::string reason;
 10470  		if (!Type::are_assignable(element_type, (*pa)->type(),
 10471  					  &reason))
 10472  		  {
 10473  		    if (reason.empty())
 10474  		      go_error_at((*pa)->location(),
 10475  				  "argument %d has incompatible type", i);
 10476  		    else
 10477  		      go_error_at((*pa)->location(),
 10478  				  "argument %d has incompatible type (%s)",
 10479  				  i, reason.c_str());
 10480  		    this->set_is_error();
 10481  		  }
 10482  	      }
 10483  	  }
 10484        }
 10485        break;
 10486  
 10487      case BUILTIN_REAL:
 10488      case BUILTIN_IMAG:
 10489        if (this->check_one_arg())
 10490  	{
 10491  	  if (this->one_arg()->type()->complex_type() == NULL)
 10492  	    this->report_error(_("argument must have complex type"));
 10493  	}
 10494        break;
 10495  
 10496      case BUILTIN_COMPLEX:
 10497        {
 10498  	const Expression_list* args = this->args();
 10499  	if (args == NULL || args->size() < 2)
 10500  	  this->report_error(_("not enough arguments"));
 10501  	else if (args->size() > 2)
 10502  	  this->report_error(_("too many arguments"));
 10503  	else if (args->front()->is_error_expression()
 10504  		 || args->front()->type()->is_error()
 10505  		 || args->back()->is_error_expression()
 10506  		 || args->back()->type()->is_error())
 10507  	  this->set_is_error();
 10508  	else if (!Type::are_identical(args->front()->type(),
 10509  				      args->back()->type(),
 10510  				      Type::COMPARE_TAGS, NULL))
 10511  	  this->report_error(_("complex arguments must have identical types"));
 10512  	else if (args->front()->type()->float_type() == NULL)
 10513  	  this->report_error(_("complex arguments must have "
 10514  			       "floating-point type"));
 10515        }
 10516        break;
 10517  
 10518      case BUILTIN_ADD:
 10519      case BUILTIN_SLICE:
 10520        {
 10521  	Numeric_constant nc;
 10522  	unsigned long v;
 10523  	const Expression_list* args = this->args();
 10524  	if (args == NULL || args->size() < 2)
 10525  	  this->report_error(_("not enough arguments"));
 10526  	else if (args->size() > 2)
 10527  	  this->report_error(_("too many arguments"));
 10528  	else if (args->front()->is_error_expression()
 10529  		 || args->front()->type()->is_error()
 10530  		 || args->back()->is_error_expression()
 10531  		 || args->back()->type()->is_error())
 10532  	  this->set_is_error();
 10533  	else if (args->back()->type()->integer_type() == NULL
 10534  		 && (!args->back()->type()->is_abstract()
 10535  		     || !args->back()->numeric_constant_value(&nc)
 10536  		     || (nc.to_unsigned_long(&v)
 10537  			 == Numeric_constant::NC_UL_NOTINT)))
 10538  	  {
 10539  	    if (this->code_ == BUILTIN_ADD)
 10540  	      go_error_at(args->back()->location(), "non-integer offset");
 10541  	    else
 10542  	      go_error_at(args->back()->location(), "non-integer size");
 10543  	  }
 10544  	else if (this->code_ == BUILTIN_ADD)
 10545  	  {
 10546  	    Type* pointer_type =
 10547  	      Type::make_pointer_type(Type::make_void_type());
 10548  	    std::string reason;
 10549  	    if (!Type::are_assignable(pointer_type, args->front()->type(),
 10550  				      &reason))
 10551  	      {
 10552  		if (reason.empty())
 10553  		  go_error_at(args->front()->location(),
 10554  			      "argument 1 has incompatible type");
 10555  		else
 10556  		  go_error_at(args->front()->location(),
 10557  			      "argument 1 has incompatible type (%s)",
 10558  			      reason.c_str());
 10559  		this->set_is_error();
 10560  	      }
 10561  	  }
 10562  	else
 10563  	  {
 10564  	    if (args->front()->type()->points_to() == NULL)
 10565  	      {
 10566  		go_error_at(args->front()->location(),
 10567  			    "argument 1 must be a pointer");
 10568  		this->set_is_error();
 10569  	      }
 10570  
 10571  	    unsigned int int_bits =
 10572  	      Type::lookup_integer_type("int")->integer_type()->bits();
 10573  
 10574  	    mpz_t ival;
 10575  	    if (args->back()->numeric_constant_value(&nc) && nc.to_int(&ival))
 10576  	      {
 10577  		if (mpz_sgn(ival) < 0
 10578  		    || mpz_sizeinbase(ival, 2) >= int_bits)
 10579  		  {
 10580  		    go_error_at(args->back()->location(),
 10581  				"slice length out of range");
 10582  		    this->set_is_error();
 10583  		  }
 10584  		mpz_clear(ival);
 10585  	      }
 10586  	  }
 10587        }
 10588        break;
 10589  
 10590      default:
 10591        go_unreachable();
 10592      }
 10593  }
 10594  
 10595  Expression*
 10596  Builtin_call_expression::do_copy()
 10597  {
 10598    Call_expression* bce =
 10599      new Builtin_call_expression(this->gogo_, this->fn()->copy(),
 10600  				(this->args() == NULL
 10601  				 ? NULL
 10602  				 : this->args()->copy()),
 10603  				this->is_varargs(),
 10604  				this->location());
 10605  
 10606    if (this->varargs_are_lowered())
 10607      bce->set_varargs_are_lowered();
 10608    if (this->is_deferred())
 10609      bce->set_is_deferred();
 10610    if (this->is_concurrent())
 10611      bce->set_is_concurrent();
 10612    return bce;
 10613  }
 10614  
 10615  // Return the backend representation for a builtin function.
 10616  
 10617  Bexpression*
 10618  Builtin_call_expression::do_get_backend(Translate_context* context)
 10619  {
 10620    Gogo* gogo = context->gogo();
 10621    Location location = this->location();
 10622  
 10623    if (this->is_erroneous_call())
 10624      {
 10625        go_assert(saw_errors());
 10626        return gogo->backend()->error_expression();
 10627      }
 10628  
 10629    switch (this->code_)
 10630      {
 10631      case BUILTIN_INVALID:
 10632      case BUILTIN_NEW:
 10633      case BUILTIN_MAKE:
 10634      case BUILTIN_ADD:
 10635      case BUILTIN_SLICE:
 10636        go_unreachable();
 10637  
 10638      case BUILTIN_LEN:
 10639      case BUILTIN_CAP:
 10640        {
 10641  	const Expression_list* args = this->args();
 10642  	go_assert(args != NULL && args->size() == 1);
 10643  	Expression* arg = args->front();
 10644  	Type* arg_type = arg->type();
 10645  
 10646  	if (this->seen_)
 10647  	  {
 10648  	    go_assert(saw_errors());
 10649  	    return context->backend()->error_expression();
 10650  	  }
 10651  	this->seen_ = true;
 10652  	this->seen_ = false;
 10653  	if (arg_type->points_to() != NULL)
 10654  	  {
 10655  	    arg_type = arg_type->points_to();
 10656  	    go_assert(arg_type->array_type() != NULL
 10657  		       && !arg_type->is_slice_type());
 10658              arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
 10659                                                 location);
 10660  	  }
 10661  
 10662  	Type* int_type = Type::lookup_integer_type("int");
 10663          Expression* val;
 10664  	if (this->code_ == BUILTIN_LEN)
 10665  	  {
 10666  	    if (arg_type->is_string_type())
 10667  	      val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
 10668  						 location);
 10669  	    else if (arg_type->array_type() != NULL)
 10670  	      {
 10671  		if (this->seen_)
 10672  		  {
 10673  		    go_assert(saw_errors());
 10674  		    return context->backend()->error_expression();
 10675  		  }
 10676  		this->seen_ = true;
 10677  	        val = arg_type->array_type()->get_length(gogo, arg);
 10678  		this->seen_ = false;
 10679  	      }
 10680  	    else if (arg_type->map_type() != NULL
 10681  		     || arg_type->channel_type() != NULL)
 10682  	      {
 10683  		// The first field is the length.  If the pointer is
 10684  		// nil, the length is zero.
 10685  		Type* pint_type = Type::make_pointer_type(int_type);
 10686  		arg = Expression::make_unsafe_cast(pint_type, arg, location);
 10687  		Expression* nil = Expression::make_nil(location);
 10688  		nil = Expression::make_cast(pint_type, nil, location);
 10689  		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
 10690  							  arg, nil, location);
 10691  		Expression* zero = Expression::make_integer_ul(0, int_type,
 10692  							       location);
 10693                  Expression* indir =
 10694                      Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
 10695                                                   location);
 10696  		val = Expression::make_conditional(cmp, zero, indir, location);
 10697  	      }
 10698  	    else
 10699  	      go_unreachable();
 10700  	  }
 10701  	else
 10702  	  {
 10703  	    if (arg_type->array_type() != NULL)
 10704  	      {
 10705  		if (this->seen_)
 10706  		  {
 10707  		    go_assert(saw_errors());
 10708  		    return context->backend()->error_expression();
 10709  		  }
 10710  		this->seen_ = true;
 10711                  val = arg_type->array_type()->get_capacity(gogo, arg);
 10712  		this->seen_ = false;
 10713  	      }
 10714  	    else if (arg_type->channel_type() != NULL)
 10715  	      {
 10716  		// The second field is the capacity.  If the pointer
 10717  		// is nil, the capacity is zero.
 10718  		Type* uintptr_type = Type::lookup_integer_type("uintptr");
 10719  		Type* pint_type = Type::make_pointer_type(int_type);
 10720  		Expression* parg = Expression::make_unsafe_cast(uintptr_type,
 10721  								arg,
 10722  								location);
 10723  		int off = int_type->integer_type()->bits() / 8;
 10724  		Expression* eoff = Expression::make_integer_ul(off,
 10725  							       uintptr_type,
 10726  							       location);
 10727  		parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
 10728  					       location);
 10729  		parg = Expression::make_unsafe_cast(pint_type, parg, location);
 10730  		Expression* nil = Expression::make_nil(location);
 10731  		nil = Expression::make_cast(pint_type, nil, location);
 10732  		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
 10733  							  arg, nil, location);
 10734  		Expression* zero = Expression::make_integer_ul(0, int_type,
 10735  							       location);
 10736                  Expression* indir =
 10737                      Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
 10738                                                   location);
 10739  		val = Expression::make_conditional(cmp, zero, indir, location);
 10740  	      }
 10741  	    else
 10742  	      go_unreachable();
 10743  	  }
 10744  
 10745  	return Expression::make_cast(int_type, val,
 10746  				     location)->get_backend(context);
 10747        }
 10748  
 10749      case BUILTIN_PRINT:
 10750      case BUILTIN_PRINTLN:
 10751        {
 10752  	const bool is_ln = this->code_ == BUILTIN_PRINTLN;
 10753  
 10754  	Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
 10755  						     location, 0);
 10756  
 10757  	const Expression_list* call_args = this->args();
 10758  	if (call_args != NULL)
 10759  	  {
 10760  	    for (Expression_list::const_iterator p = call_args->begin();
 10761  		 p != call_args->end();
 10762  		 ++p)
 10763  	      {
 10764  		if (is_ln && p != call_args->begin())
 10765  		  {
 10766                      Expression* print_space =
 10767  		      Runtime::make_call(Runtime::PRINTSP, location, 0);
 10768  
 10769                      print_stmts =
 10770                          Expression::make_compound(print_stmts, print_space,
 10771                                                    location);
 10772  		  }
 10773  
 10774                  Expression* arg = *p;
 10775  		Type* type = arg->type();
 10776                  Runtime::Function code;
 10777  		if (type->is_string_type())
 10778                    code = Runtime::PRINTSTRING;
 10779  		else if (type->integer_type() != NULL
 10780  			 && type->integer_type()->is_unsigned())
 10781  		  {
 10782  		    Type* itype = Type::lookup_integer_type("uint64");
 10783  		    arg = Expression::make_cast(itype, arg, location);
 10784                      if (gogo->compiling_runtime()
 10785                          && type->named_type() != NULL
 10786                          && gogo->unpack_hidden_name(type->named_type()->name())
 10787                             == "hex")
 10788                        code = Runtime::PRINTHEX;
 10789                      else
 10790                        code = Runtime::PRINTUINT;
 10791  		  }
 10792  		else if (type->integer_type() != NULL)
 10793  		  {
 10794  		    Type* itype = Type::lookup_integer_type("int64");
 10795  		    arg = Expression::make_cast(itype, arg, location);
 10796                      code = Runtime::PRINTINT;
 10797  		  }
 10798  		else if (type->float_type() != NULL)
 10799  		  {
 10800                      Type* dtype = Type::lookup_float_type("float64");
 10801                      arg = Expression::make_cast(dtype, arg, location);
 10802                      code = Runtime::PRINTFLOAT;
 10803  		  }
 10804  		else if (type->complex_type() != NULL)
 10805  		  {
 10806                      Type* ctype = Type::lookup_complex_type("complex128");
 10807                      arg = Expression::make_cast(ctype, arg, location);
 10808                      code = Runtime::PRINTCOMPLEX;
 10809  		  }
 10810  		else if (type->is_boolean_type())
 10811                    code = Runtime::PRINTBOOL;
 10812  		else if (type->points_to() != NULL
 10813  			 || type->channel_type() != NULL
 10814  			 || type->map_type() != NULL
 10815  			 || type->function_type() != NULL)
 10816  		  {
 10817                      arg = Expression::make_cast(type, arg, location);
 10818                      code = Runtime::PRINTPOINTER;
 10819  		  }
 10820  		else if (type->interface_type() != NULL)
 10821  		  {
 10822  		    if (type->interface_type()->is_empty())
 10823                        code = Runtime::PRINTEFACE;
 10824  		    else
 10825                        code = Runtime::PRINTIFACE;
 10826  		  }
 10827  		else if (type->is_slice_type())
 10828                    code = Runtime::PRINTSLICE;
 10829  		else
 10830  		  {
 10831  		    go_assert(saw_errors());
 10832  		    return context->backend()->error_expression();
 10833  		  }
 10834  
 10835                  Expression* call = Runtime::make_call(code, location, 1, arg);
 10836  		print_stmts = Expression::make_compound(print_stmts, call,
 10837  							location);
 10838  	      }
 10839  	  }
 10840  
 10841  	if (is_ln)
 10842  	  {
 10843              Expression* print_nl =
 10844                  Runtime::make_call(Runtime::PRINTNL, location, 0);
 10845  	    print_stmts = Expression::make_compound(print_stmts, print_nl,
 10846  						    location);
 10847  	  }
 10848  
 10849  	Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
 10850  						location, 0);
 10851  	print_stmts = Expression::make_compound(print_stmts, unlock, location);
 10852  
 10853          return print_stmts->get_backend(context);
 10854        }
 10855  
 10856      case BUILTIN_PANIC:
 10857        {
 10858  	const Expression_list* args = this->args();
 10859  	go_assert(args != NULL && args->size() == 1);
 10860  	Expression* arg = args->front();
 10861  	Type *empty =
 10862  	  Type::make_empty_interface_type(Linemap::predeclared_location());
 10863          arg = Expression::convert_for_assignment(gogo, empty, arg, location);
 10864  
 10865          Expression* panic =
 10866              Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
 10867          return panic->get_backend(context);
 10868        }
 10869  
 10870      case BUILTIN_RECOVER:
 10871        {
 10872  	// The argument is set when building recover thunks.  It's a
 10873  	// boolean value which is true if we can recover a value now.
 10874  	const Expression_list* args = this->args();
 10875  	go_assert(args != NULL && args->size() == 1);
 10876  	Expression* arg = args->front();
 10877  	Type *empty =
 10878  	  Type::make_empty_interface_type(Linemap::predeclared_location());
 10879  
 10880  	Expression* nil = Expression::make_nil(location);
 10881          nil = Expression::make_interface_value(empty, nil, nil, location);
 10882  
 10883  	// We need to handle a deferred call to recover specially,
 10884  	// because it changes whether it can recover a panic or not.
 10885  	// See test7 in test/recover1.go.
 10886          Expression* recover = Runtime::make_call((this->is_deferred()
 10887                                                    ? Runtime::DEFERREDRECOVER
 10888                                                    : Runtime::GORECOVER),
 10889                                                   location, 0);
 10890          Expression* cond =
 10891              Expression::make_conditional(arg, recover, nil, location);
 10892          return cond->get_backend(context);
 10893        }
 10894  
 10895      case BUILTIN_CLOSE:
 10896        {
 10897  	const Expression_list* args = this->args();
 10898  	go_assert(args != NULL && args->size() == 1);
 10899  	Expression* arg = args->front();
 10900          Expression* close = Runtime::make_call(Runtime::CLOSE, location,
 10901  					       1, arg);
 10902          return close->get_backend(context);
 10903        }
 10904  
 10905      case BUILTIN_SIZEOF:
 10906      case BUILTIN_OFFSETOF:
 10907      case BUILTIN_ALIGNOF:
 10908        {
 10909  	Numeric_constant nc;
 10910  	unsigned long val;
 10911  	if (!this->numeric_constant_value(&nc)
 10912  	    || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
 10913  	  {
 10914  	    go_assert(saw_errors());
 10915  	    return context->backend()->error_expression();
 10916  	  }
 10917  	Type* uintptr_type = Type::lookup_integer_type("uintptr");
 10918          mpz_t ival;
 10919          nc.get_int(&ival);
 10920          Expression* int_cst =
 10921              Expression::make_integer_z(&ival, uintptr_type, location);
 10922          mpz_clear(ival);
 10923          return int_cst->get_backend(context);
 10924        }
 10925  
 10926      case BUILTIN_COPY:
 10927        // Handled in Builtin_call_expression::do_flatten.
 10928        go_unreachable();
 10929  
 10930      case BUILTIN_APPEND:
 10931        // Handled in Builtin_call_expression::flatten_append.
 10932        go_unreachable();
 10933  
 10934      case BUILTIN_REAL:
 10935      case BUILTIN_IMAG:
 10936        {
 10937  	const Expression_list* args = this->args();
 10938  	go_assert(args != NULL && args->size() == 1);
 10939  
 10940          Bexpression* ret;
 10941          Bexpression* bcomplex = args->front()->get_backend(context);
 10942          if (this->code_ == BUILTIN_REAL)
 10943            ret = gogo->backend()->real_part_expression(bcomplex, location);
 10944          else
 10945            ret = gogo->backend()->imag_part_expression(bcomplex, location);
 10946          return ret;
 10947        }
 10948  
 10949      case BUILTIN_COMPLEX:
 10950        {
 10951  	const Expression_list* args = this->args();
 10952  	go_assert(args != NULL && args->size() == 2);
 10953  	Bexpression* breal = args->front()->get_backend(context);
 10954  	Bexpression* bimag = args->back()->get_backend(context);
 10955  	return gogo->backend()->complex_expression(breal, bimag, location);
 10956        }
 10957  
 10958      default:
 10959        go_unreachable();
 10960      }
 10961  }
 10962  
 10963  // We have to support exporting a builtin call expression, because
 10964  // code can set a constant to the result of a builtin expression.
 10965  
 10966  void
 10967  Builtin_call_expression::do_export(Export_function_body* efb) const
 10968  {
 10969    Numeric_constant nc;
 10970    if (this->numeric_constant_value(&nc))
 10971      {
 10972        if (nc.is_int())
 10973  	{
 10974  	  mpz_t val;
 10975  	  nc.get_int(&val);
 10976  	  Integer_expression::export_integer(efb, val);
 10977  	  mpz_clear(val);
 10978  	}
 10979        else if (nc.is_float())
 10980  	{
 10981  	  mpfr_t fval;
 10982  	  nc.get_float(&fval);
 10983  	  Float_expression::export_float(efb, fval);
 10984  	  mpfr_clear(fval);
 10985  	}
 10986        else if (nc.is_complex())
 10987  	{
 10988  	  mpc_t cval;
 10989  	  nc.get_complex(&cval);
 10990  	  Complex_expression::export_complex(efb, cval);
 10991  	  mpc_clear(cval);
 10992  	}
 10993        else
 10994  	go_unreachable();
 10995  
 10996        // A trailing space lets us reliably identify the end of the number.
 10997        efb->write_c_string(" ");
 10998      }
 10999    else if (this->code_ == BUILTIN_ADD || this->code_ == BUILTIN_SLICE)
 11000      {
 11001        char buf[50];
 11002        snprintf(buf, sizeof buf, "<p%d>%s", efb->unsafe_package_index(),
 11003  	       (this->code_ == BUILTIN_ADD ? "Add" : "Slice"));
 11004        efb->write_c_string(buf);
 11005        this->export_arguments(efb);
 11006      }
 11007    else
 11008      {
 11009        const char *s = NULL;
 11010        switch (this->code_)
 11011  	{
 11012  	default:
 11013  	  go_unreachable();
 11014  	case BUILTIN_APPEND:
 11015  	  s = "append";
 11016  	  break;
 11017  	case BUILTIN_COPY:
 11018  	  s = "copy";
 11019  	  break;
 11020  	case BUILTIN_LEN:
 11021  	  s = "len";
 11022  	  break;
 11023  	case BUILTIN_CAP:
 11024  	  s = "cap";
 11025  	  break;
 11026  	case BUILTIN_DELETE:
 11027  	  s = "delete";
 11028  	  break;
 11029  	case BUILTIN_PRINT:
 11030  	  s = "print";
 11031  	  break;
 11032  	case BUILTIN_PRINTLN:
 11033  	  s = "println";
 11034  	  break;
 11035  	case BUILTIN_PANIC:
 11036  	  s = "panic";
 11037  	  break;
 11038  	case BUILTIN_RECOVER:
 11039  	  s = "recover";
 11040  	  break;
 11041  	case BUILTIN_CLOSE:
 11042  	  s = "close";
 11043  	  break;
 11044  	case BUILTIN_REAL:
 11045  	  s = "real";
 11046  	  break;
 11047  	case BUILTIN_IMAG:
 11048  	  s = "imag";
 11049  	  break;
 11050  	case BUILTIN_COMPLEX:
 11051  	  s = "complex";
 11052  	  break;
 11053  	}
 11054        efb->write_c_string(s);
 11055        this->export_arguments(efb);
 11056      }
 11057  }
 11058  
 11059  // Class Call_expression.
 11060  
 11061  // A Go function can be viewed in a couple of different ways.  The
 11062  // code of a Go function becomes a backend function with parameters
 11063  // whose types are simply the backend representation of the Go types.
 11064  // If there are multiple results, they are returned as a backend
 11065  // struct.
 11066  
 11067  // However, when Go code refers to a function other than simply
 11068  // calling it, the backend type of that function is actually a struct.
 11069  // The first field of the struct points to the Go function code
 11070  // (sometimes a wrapper as described below).  The remaining fields
 11071  // hold addresses of closed-over variables.  This struct is called a
 11072  // closure.
 11073  
 11074  // There are a few cases to consider.
 11075  
 11076  // A direct function call of a known function in package scope.  In
 11077  // this case there are no closed-over variables, and we know the name
 11078  // of the function code.  We can simply produce a backend call to the
 11079  // function directly, and not worry about the closure.
 11080  
 11081  // A direct function call of a known function literal.  In this case
 11082  // we know the function code and we know the closure.  We generate the
 11083  // function code such that it expects an additional final argument of
 11084  // the closure type.  We pass the closure as the last argument, after
 11085  // the other arguments.
 11086  
 11087  // An indirect function call.  In this case we have a closure.  We
 11088  // load the pointer to the function code from the first field of the
 11089  // closure.  We pass the address of the closure as the last argument.
 11090  
 11091  // A call to a method of an interface.  Type methods are always at
 11092  // package scope, so we call the function directly, and don't worry
 11093  // about the closure.
 11094  
 11095  // This means that for a function at package scope we have two cases.
 11096  // One is the direct call, which has no closure.  The other is the
 11097  // indirect call, which does have a closure.  We can't simply ignore
 11098  // the closure, even though it is the last argument, because that will
 11099  // fail on targets where the function pops its arguments.  So when
 11100  // generating a closure for a package-scope function we set the
 11101  // function code pointer in the closure to point to a wrapper
 11102  // function.  This wrapper function accepts a final argument that
 11103  // points to the closure, ignores it, and calls the real function as a
 11104  // direct function call.  This wrapper will normally be efficient, and
 11105  // can often simply be a tail call to the real function.
 11106  
 11107  // We don't use GCC's static chain pointer because 1) we don't need
 11108  // it; 2) GCC only permits using a static chain to call a known
 11109  // function, so we can't use it for an indirect call anyhow.  Since we
 11110  // can't use it for an indirect call, we may as well not worry about
 11111  // using it for a direct call either.
 11112  
 11113  // We pass the closure last rather than first because it means that
 11114  // the function wrapper we put into a closure for a package-scope
 11115  // function can normally just be a tail call to the real function.
 11116  
 11117  // For method expressions we generate a wrapper that loads the
 11118  // receiver from the closure and then calls the method.  This
 11119  // unfortunately forces reshuffling the arguments, since there is a
 11120  // new first argument, but we can't avoid reshuffling either for
 11121  // method expressions or for indirect calls of package-scope
 11122  // functions, and since the latter are more common we reshuffle for
 11123  // method expressions.
 11124  
 11125  // Note that the Go code retains the Go types.  The extra final
 11126  // argument only appears when we convert to the backend
 11127  // representation.
 11128  
 11129  // Traversal.
 11130  
 11131  int
 11132  Call_expression::do_traverse(Traverse* traverse)
 11133  {
 11134    // If we are calling a function in a different package that returns
 11135    // an unnamed type, this may be the only chance we get to traverse
 11136    // that type.  We don't traverse this->type_ because it may be a
 11137    // Call_multiple_result_type that will just lead back here.
 11138    if (this->type_ != NULL && !this->type_->is_error_type())
 11139      {
 11140        Function_type *fntype = this->get_function_type();
 11141        if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
 11142  	return TRAVERSE_EXIT;
 11143      }
 11144    if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
 11145      return TRAVERSE_EXIT;
 11146    if (this->args_ != NULL)
 11147      {
 11148        if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
 11149  	return TRAVERSE_EXIT;
 11150      }
 11151    return TRAVERSE_CONTINUE;
 11152  }
 11153  
 11154  // Lower a call statement.
 11155  
 11156  Expression*
 11157  Call_expression::do_lower(Gogo* gogo, Named_object* function,
 11158  			  Statement_inserter* inserter, int)
 11159  {
 11160    Location loc = this->location();
 11161  
 11162    if (this->is_error_expression())
 11163      return Expression::make_error(loc);
 11164  
 11165    // A type cast can look like a function call.
 11166    if (this->fn_->is_type_expression()
 11167        && this->args_ != NULL
 11168        && this->args_->size() == 1)
 11169      {
 11170        if (this->expected_result_count_ != 0
 11171  	  && this->expected_result_count_ != 1)
 11172  	{
 11173  	  this->report_error(_("type conversion result count mismatch"));
 11174  	  return Expression::make_error(loc);
 11175  	}
 11176        return Expression::make_cast(this->fn_->type(), this->args_->front(),
 11177  				   loc);
 11178      }
 11179  
 11180    // Because do_type will return an error type and thus prevent future
 11181    // errors, check for that case now to ensure that the error gets
 11182    // reported.
 11183    Function_type* fntype = this->get_function_type();
 11184    if (fntype == NULL)
 11185      {
 11186        if (!this->fn_->type()->is_error())
 11187  	this->report_error(_("expected function"));
 11188        this->set_is_error();
 11189        return this;
 11190      }
 11191  
 11192    // Handle an argument which is a call to a function which returns
 11193    // multiple results.
 11194    if (this->args_ != NULL
 11195        && this->args_->size() == 1
 11196        && this->args_->front()->call_expression() != NULL)
 11197      {
 11198        size_t rc = this->args_->front()->call_expression()->result_count();
 11199        if (rc > 1
 11200  	  && ((fntype->parameters() != NULL
 11201                 && (fntype->parameters()->size() == rc
 11202                     || (fntype->is_varargs()
 11203                         && fntype->parameters()->size() - 1 <= rc)))
 11204                || fntype->is_builtin()))
 11205  	{
 11206  	  Call_expression* call = this->args_->front()->call_expression();
 11207  	  call->set_is_multi_value_arg();
 11208  	  if (this->is_varargs_)
 11209  	    {
 11210  	      // It is not clear which result of a multiple result call
 11211  	      // the ellipsis operator should be applied to.  If we unpack the
 11212  	      // the call into its individual results here, the ellipsis will be
 11213  	      // applied to the last result.
 11214  	      go_error_at(call->location(),
 11215  			  _("multiple-value argument in single-value context"));
 11216  	      return Expression::make_error(call->location());
 11217  	    }
 11218  
 11219  	  Expression_list* args = new Expression_list;
 11220  	  for (size_t i = 0; i < rc; ++i)
 11221  	    args->push_back(Expression::make_call_result(call, i));
 11222  	  // We can't return a new call expression here, because this
 11223  	  // one may be referenced by Call_result expressions.  We
 11224  	  // also can't delete the old arguments, because we may still
 11225  	  // traverse them somewhere up the call stack.  FIXME.
 11226  	  this->args_ = args;
 11227  	}
 11228      }
 11229  
 11230    // Recognize a call to a builtin function.
 11231    if (fntype->is_builtin())
 11232      {
 11233        Builtin_call_expression* bce =
 11234  	new Builtin_call_expression(gogo, this->fn_, this->args_,
 11235  				    this->is_varargs_, loc);
 11236        if (this->is_deferred_)
 11237  	bce->set_is_deferred();
 11238        if (this->is_concurrent_)
 11239  	bce->set_is_concurrent();
 11240        return bce;
 11241      }
 11242  
 11243    // If this call returns multiple results, create a temporary
 11244    // variable to hold them.
 11245    if (this->result_count() > 1 && this->call_temp_ == NULL)
 11246      {
 11247        Struct_field_list* sfl = new Struct_field_list();
 11248        const Typed_identifier_list* results = fntype->results();
 11249  
 11250        int i = 0;
 11251        char buf[20];
 11252        for (Typed_identifier_list::const_iterator p = results->begin();
 11253             p != results->end();
 11254             ++p, ++i)
 11255          {
 11256            snprintf(buf, sizeof buf, "res%d", i);
 11257            sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
 11258          }
 11259  
 11260        Struct_type* st = Type::make_struct_type(sfl, loc);
 11261        st->set_is_struct_incomparable();
 11262        this->call_temp_ = Statement::make_temporary(st, NULL, loc);
 11263        inserter->insert(this->call_temp_);
 11264      }
 11265  
 11266    // Handle a call to a varargs function by packaging up the extra
 11267    // parameters.
 11268    if (fntype->is_varargs())
 11269      {
 11270        const Typed_identifier_list* parameters = fntype->parameters();
 11271        go_assert(parameters != NULL && !parameters->empty());
 11272        Type* varargs_type = parameters->back().type();
 11273        this->lower_varargs(gogo, function, inserter, varargs_type,
 11274  			  parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
 11275      }
 11276  
 11277    // If this is call to a method, call the method directly passing the
 11278    // object as the first parameter.
 11279    Bound_method_expression* bme = this->fn_->bound_method_expression();
 11280    if (bme != NULL && !this->is_deferred_ && !this->is_concurrent_)
 11281      {
 11282        Named_object* methodfn = bme->function();
 11283        Function_type* mft = (methodfn->is_function()
 11284                              ? methodfn->func_value()->type()
 11285                              : methodfn->func_declaration_value()->type());
 11286        Expression* first_arg = bme->first_argument();
 11287  
 11288        // We always pass a pointer when calling a method, except for
 11289        // direct interface types when calling a value method.
 11290        if (!first_arg->type()->is_error()
 11291            && first_arg->type()->points_to() == NULL
 11292            && !first_arg->type()->is_direct_iface_type())
 11293  	{
 11294  	  first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
 11295  	  // We may need to create a temporary variable so that we can
 11296  	  // take the address.  We can't do that here because it will
 11297  	  // mess up the order of evaluation.
 11298  	  Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
 11299  	  ue->set_create_temp();
 11300  	}
 11301        else if (mft->receiver()->type()->points_to() == NULL
 11302                 && first_arg->type()->points_to() != NULL
 11303                 && first_arg->type()->points_to()->is_direct_iface_type())
 11304          first_arg = Expression::make_dereference(first_arg,
 11305                                                   Expression::NIL_CHECK_DEFAULT,
 11306                                                   loc);
 11307  
 11308        // If we are calling a method which was inherited from an
 11309        // embedded struct, and the method did not get a stub, then the
 11310        // first type may be wrong.
 11311        Type* fatype = bme->first_argument_type();
 11312        if (fatype != NULL)
 11313  	{
 11314  	  if (fatype->points_to() == NULL)
 11315  	    fatype = Type::make_pointer_type(fatype);
 11316  	  first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
 11317  	}
 11318  
 11319        Expression_list* new_args = new Expression_list();
 11320        new_args->push_back(first_arg);
 11321        if (this->args_ != NULL)
 11322  	{
 11323  	  for (Expression_list::const_iterator p = this->args_->begin();
 11324  	       p != this->args_->end();
 11325  	       ++p)
 11326  	    new_args->push_back(*p);
 11327  	}
 11328  
 11329        // We have to change in place because this structure may be
 11330        // referenced by Call_result_expressions.  We can't delete the
 11331        // old arguments, because we may be traversing them up in some
 11332        // caller.  FIXME.
 11333        this->args_ = new_args;
 11334        this->fn_ = Expression::make_func_reference(methodfn, NULL,
 11335  						  bme->location());
 11336      }
 11337  
 11338    // If this is a call to an imported function for which we have an
 11339    // inlinable function body, add it to the list of functions to give
 11340    // to the backend as inlining opportunities.
 11341    Func_expression* fe = this->fn_->func_expression();
 11342    if (fe != NULL
 11343        && fe->named_object()->is_function_declaration()
 11344        && fe->named_object()->func_declaration_value()->has_imported_body())
 11345      gogo->add_imported_inlinable_function(fe->named_object());
 11346  
 11347    return this;
 11348  }
 11349  
 11350  // Lower a call to a varargs function.  FUNCTION is the function in
 11351  // which the call occurs--it's not the function we are calling.
 11352  // VARARGS_TYPE is the type of the varargs parameter, a slice type.
 11353  // PARAM_COUNT is the number of parameters of the function we are
 11354  // calling; the last of these parameters will be the varargs
 11355  // parameter.
 11356  
 11357  void
 11358  Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
 11359  			       Statement_inserter* inserter,
 11360  			       Type* varargs_type, size_t param_count,
 11361                                 Slice_storage_escape_disp escape_disp)
 11362  {
 11363    if (this->varargs_are_lowered_)
 11364      return;
 11365  
 11366    Location loc = this->location();
 11367  
 11368    go_assert(param_count > 0);
 11369    go_assert(varargs_type->is_slice_type());
 11370  
 11371    size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
 11372    if (arg_count < param_count - 1)
 11373      {
 11374        // Not enough arguments; will be caught in check_types.
 11375        return;
 11376      }
 11377  
 11378    Expression_list* old_args = this->args_;
 11379    Expression_list* new_args = new Expression_list();
 11380    bool push_empty_arg = false;
 11381    if (old_args == NULL || old_args->empty())
 11382      {
 11383        go_assert(param_count == 1);
 11384        push_empty_arg = true;
 11385      }
 11386    else
 11387      {
 11388        Expression_list::const_iterator pa;
 11389        int i = 1;
 11390        for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
 11391  	{
 11392  	  if (static_cast<size_t>(i) == param_count)
 11393  	    break;
 11394  	  new_args->push_back(*pa);
 11395  	}
 11396  
 11397        // We have reached the varargs parameter.
 11398  
 11399        bool issued_error = false;
 11400        if (pa == old_args->end())
 11401  	push_empty_arg = true;
 11402        else if (pa + 1 == old_args->end() && this->is_varargs_)
 11403  	new_args->push_back(*pa);
 11404        else if (this->is_varargs_)
 11405  	{
 11406  	  if ((*pa)->type()->is_slice_type())
 11407  	    this->report_error(_("too many arguments"));
 11408  	  else
 11409  	    {
 11410  	      go_error_at(this->location(),
 11411  			  _("invalid use of %<...%> with non-slice"));
 11412  	      this->set_is_error();
 11413  	    }
 11414  	  return;
 11415  	}
 11416        else
 11417  	{
 11418  	  Type* element_type = varargs_type->array_type()->element_type();
 11419  	  Expression_list* vals = new Expression_list;
 11420  	  for (; pa != old_args->end(); ++pa, ++i)
 11421  	    {
 11422  	      // Check types here so that we get a better message.
 11423  	      Type* patype = (*pa)->type();
 11424  	      Location paloc = (*pa)->location();
 11425  	      if (!this->check_argument_type(i, element_type, patype,
 11426  					     paloc, issued_error))
 11427  		continue;
 11428  	      vals->push_back(*pa);
 11429  	    }
 11430  	  Slice_construction_expression* sce =
 11431  	    Expression::make_slice_composite_literal(varargs_type, vals, loc);
 11432  	  if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
 11433  	      sce->set_storage_does_not_escape();
 11434            Expression* val = sce;
 11435  	  gogo->lower_expression(function, inserter, &val);
 11436  	  new_args->push_back(val);
 11437  	}
 11438      }
 11439  
 11440    if (push_empty_arg)
 11441      new_args->push_back(Expression::make_nil(loc));
 11442  
 11443    // We can't return a new call expression here, because this one may
 11444    // be referenced by Call_result expressions.  FIXME.  We can't
 11445    // delete OLD_ARGS because we may have both a Call_expression and a
 11446    // Builtin_call_expression which refer to them.  FIXME.
 11447    this->args_ = new_args;
 11448    this->varargs_are_lowered_ = true;
 11449  }
 11450  
 11451  // Flatten a call with multiple results into a temporary.
 11452  
 11453  Expression*
 11454  Call_expression::do_flatten(Gogo* gogo, Named_object*,
 11455  			    Statement_inserter* inserter)
 11456  {
 11457    if (this->is_erroneous_call())
 11458      {
 11459        go_assert(saw_errors());
 11460        return Expression::make_error(this->location());
 11461      }
 11462  
 11463    if (this->is_flattened_)
 11464      return this;
 11465    this->is_flattened_ = true;
 11466  
 11467    // Add temporary variables for all arguments that require type
 11468    // conversion.
 11469    Function_type* fntype = this->get_function_type();
 11470    if (fntype == NULL)
 11471      {
 11472        go_assert(saw_errors());
 11473        return this;
 11474      }
 11475    if (this->args_ != NULL && !this->args_->empty()
 11476        && fntype->parameters() != NULL && !fntype->parameters()->empty())
 11477      {
 11478        bool is_interface_method =
 11479  	this->fn_->interface_field_reference_expression() != NULL;
 11480  
 11481        Expression_list *args = new Expression_list();
 11482        Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
 11483        Expression_list::const_iterator pa = this->args_->begin();
 11484        if (!is_interface_method && fntype->is_method())
 11485  	{
 11486  	  // The receiver argument.
 11487  	  args->push_back(*pa);
 11488  	  ++pa;
 11489  	}
 11490        for (; pa != this->args_->end(); ++pa, ++pp)
 11491  	{
 11492  	  go_assert(pp != fntype->parameters()->end());
 11493  	  if (Type::are_identical(pp->type(), (*pa)->type(),
 11494  				  Type::COMPARE_TAGS, NULL))
 11495  	    args->push_back(*pa);
 11496  	  else
 11497  	    {
 11498  	      Location loc = (*pa)->location();
 11499  	      Expression* arg = *pa;
 11500  	      if (!arg->is_multi_eval_safe())
 11501  		{
 11502  		  Temporary_statement *temp =
 11503  		    Statement::make_temporary(NULL, arg, loc);
 11504  		  inserter->insert(temp);
 11505  		  arg = Expression::make_temporary_reference(temp, loc);
 11506  		}
 11507  	      arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
 11508  						       loc);
 11509  	      args->push_back(arg);
 11510  	    }
 11511  	}
 11512        delete this->args_;
 11513        this->args_ = args;
 11514      }
 11515  
 11516    // Lower to compiler intrinsic if possible.
 11517    Func_expression* fe = this->fn_->func_expression();
 11518    if (!this->is_concurrent_ && !this->is_deferred_
 11519        && fe != NULL
 11520        && (fe->named_object()->is_function_declaration()
 11521            || fe->named_object()->is_function()))
 11522      {
 11523        Expression* ret = this->intrinsify(gogo, inserter);
 11524        if (ret != NULL)
 11525          return ret;
 11526      }
 11527  
 11528    // Add an implicit conversion to a boolean type, if needed.  See the
 11529    // comment in Binary_expression::lower_array_comparison.
 11530    if (this->is_equal_function_
 11531        && this->type_ != NULL
 11532        && this->type_ != Type::lookup_bool_type())
 11533      return Expression::make_cast(this->type_, this, this->location());
 11534  
 11535    return this;
 11536  }
 11537  
 11538  // Lower a call to a compiler intrinsic if possible.
 11539  // Returns NULL if it is not an intrinsic.
 11540  
 11541  Expression*
 11542  Call_expression::intrinsify(Gogo* gogo,
 11543                              Statement_inserter* inserter)
 11544  {
 11545    Func_expression* fe = this->fn_->func_expression();
 11546    Named_object* no = fe->named_object();
 11547    std::string name = Gogo::unpack_hidden_name(no->name());
 11548    std::string package = (no->package() != NULL
 11549                           ? no->package()->pkgpath()
 11550                           : gogo->pkgpath());
 11551    bool is_method = ((no->is_function() && no->func_value()->is_method())
 11552  		    || (no->is_function_declaration()
 11553  			&& no->func_declaration_value()->is_method()));
 11554    Location loc = this->location();
 11555  
 11556    Type* int_type = Type::lookup_integer_type("int");
 11557    Type* int32_type = Type::lookup_integer_type("int32");
 11558    Type* int64_type = Type::lookup_integer_type("int64");
 11559    Type* uint_type = Type::lookup_integer_type("uint");
 11560    Type* uint8_type = Type::lookup_integer_type("uint8");
 11561    Type* uint32_type = Type::lookup_integer_type("uint32");
 11562    Type* uint64_type = Type::lookup_integer_type("uint64");
 11563    Type* uintptr_type = Type::lookup_integer_type("uintptr");
 11564    Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
 11565  
 11566    int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
 11567    int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
 11568  
 11569    if (package == "sync/atomic")
 11570      {
 11571        if (is_method)
 11572  	return NULL;
 11573  
 11574        // sync/atomic functions and runtime/internal/atomic functions
 11575        // are very similar. In order not to duplicate code, we just
 11576        // redirect to the latter and let the code below to handle them.
 11577        // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
 11578        // as they need write barriers.
 11579        if (name == "LoadInt32")
 11580          name = "Loadint32";
 11581        else if (name == "LoadInt64")
 11582          name = "Loadint64";
 11583        else if (name == "LoadUint32")
 11584          name = "Load";
 11585        else if (name == "LoadUint64")
 11586          name = "Load64";
 11587        else if (name == "LoadUintptr")
 11588          name = "Loaduintptr";
 11589        else if (name == "LoadPointer")
 11590          name = "Loadp";
 11591        else if (name == "StoreInt32")
 11592          name = "Storeint32";
 11593        else if (name == "StoreInt64")
 11594          name = "Storeint64";
 11595        else if (name == "StoreUint32")
 11596          name = "Store";
 11597        else if (name == "StoreUint64")
 11598          name = "Store64";
 11599        else if (name == "StoreUintptr")
 11600          name = "Storeuintptr";
 11601        else if (name == "AddInt32")
 11602          name = "Xaddint32";
 11603        else if (name == "AddInt64")
 11604          name = "Xaddint64";
 11605        else if (name == "AddUint32")
 11606          name = "Xadd";
 11607        else if (name == "AddUint64")
 11608          name = "Xadd64";
 11609        else if (name == "AddUintptr")
 11610          name = "Xadduintptr";
 11611        else if (name == "SwapInt32")
 11612          name = "Xchgint32";
 11613        else if (name == "SwapInt64")
 11614          name = "Xchgint64";
 11615        else if (name == "SwapUint32")
 11616          name = "Xchg";
 11617        else if (name == "SwapUint64")
 11618          name = "Xchg64";
 11619        else if (name == "SwapUintptr")
 11620          name = "Xchguintptr";
 11621        else if (name == "CompareAndSwapInt32")
 11622          name = "Casint32";
 11623        else if (name == "CompareAndSwapInt64")
 11624          name = "Casint64";
 11625        else if (name == "CompareAndSwapUint32")
 11626          name = "Cas";
 11627        else if (name == "CompareAndSwapUint64")
 11628          name = "Cas64";
 11629        else if (name == "CompareAndSwapUintptr")
 11630          name = "Casuintptr";
 11631        else
 11632          return NULL;
 11633  
 11634        package = "runtime/internal/atomic";
 11635      }
 11636  
 11637    if (package == "runtime/internal/sys")
 11638      {
 11639        if (is_method)
 11640  	return NULL;
 11641  
 11642        // runtime/internal/sys functions and math/bits functions
 11643        // are very similar. In order not to duplicate code, we just
 11644        // redirect to the latter and let the code below to handle them.
 11645        if (name == "Bswap32")
 11646          name = "ReverseBytes32";
 11647        else if (name == "Bswap64")
 11648          name = "ReverseBytes64";
 11649        else if (name == "Ctz32")
 11650          name = "TrailingZeros32";
 11651        else if (name == "Ctz64")
 11652          name = "TrailingZeros64";
 11653        else
 11654          return NULL;
 11655  
 11656        package = "math/bits";
 11657      }
 11658  
 11659    if (package == "runtime")
 11660      {
 11661        if (is_method)
 11662  	return NULL;
 11663  
 11664        // Handle a couple of special runtime functions.  In the runtime
 11665        // package, getcallerpc returns the PC of the caller, and
 11666        // getcallersp returns the frame pointer of the caller.  Implement
 11667        // these by turning them into calls to GCC builtin functions.  We
 11668        // could implement them in normal code, but then we would have to
 11669        // explicitly unwind the stack.  These functions are intended to be
 11670        // efficient.  Note that this technique obviously only works for
 11671        // direct calls, but that is the only way they are used.
 11672        if (name == "getcallerpc"
 11673            && (this->args_ == NULL || this->args_->size() == 0))
 11674          {
 11675            Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
 11676            Expression* call =
 11677              Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, loc,
 11678                                 1, arg);
 11679            // The builtin functions return void*, but the Go functions return uintptr.
 11680            return Expression::make_cast(uintptr_type, call, loc);
 11681          }
 11682        else if (name == "getcallersp"
 11683                 && (this->args_ == NULL || this->args_->size() == 0))
 11684  
 11685          {
 11686            Expression* call =
 11687              Runtime::make_call(Runtime::BUILTIN_DWARF_CFA, loc, 0);
 11688            // The builtin functions return void*, but the Go functions return uintptr.
 11689            return Expression::make_cast(uintptr_type, call, loc);
 11690          }
 11691      }
 11692    else if (package == "math/bits")
 11693      {
 11694        if (is_method)
 11695  	return NULL;
 11696  
 11697        if ((name == "ReverseBytes16" || name == "ReverseBytes32"
 11698             || name == "ReverseBytes64" || name == "ReverseBytes")
 11699            && this->args_ != NULL && this->args_->size() == 1)
 11700          {
 11701            Runtime::Function code;
 11702            if (name == "ReverseBytes16")
 11703              code = Runtime::BUILTIN_BSWAP16;
 11704            else if (name == "ReverseBytes32")
 11705              code = Runtime::BUILTIN_BSWAP32;
 11706            else if (name == "ReverseBytes64")
 11707              code = Runtime::BUILTIN_BSWAP64;
 11708            else if (name == "ReverseBytes")
 11709              code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
 11710            else
 11711              go_unreachable();
 11712            Expression* arg = this->args_->front();
 11713            Expression* call = Runtime::make_call(code, loc, 1, arg);
 11714            if (name == "ReverseBytes")
 11715              return Expression::make_cast(uint_type, call, loc);
 11716            return call;
 11717          }
 11718        else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
 11719                 && this->args_ != NULL && this->args_->size() == 1)
 11720          {
 11721            // GCC does not have a ctz8 or ctz16 intrinsic. We do
 11722            // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
 11723            Expression* arg = this->args_->front();
 11724            arg = Expression::make_cast(uint32_type, arg, loc);
 11725            unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
 11726            Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
 11727            arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
 11728            Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg);
 11729            return Expression::make_cast(int_type, call, loc);
 11730          }
 11731        else if ((name == "TrailingZeros32"
 11732                  || (name == "TrailingZeros" && int_size == 4))
 11733                 && this->args_ != NULL && this->args_->size() == 1)
 11734          {
 11735            Expression* arg = this->args_->front();
 11736            if (!arg->is_multi_eval_safe())
 11737              {
 11738                Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
 11739                inserter->insert(ts);
 11740                arg = Expression::make_temporary_reference(ts, loc);
 11741              }
 11742            // arg == 0 ? 32 : __builtin_ctz(arg)
 11743            Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
 11744            Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
 11745            Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
 11746            Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg->copy());
 11747            call = Expression::make_cast(int_type, call, loc);
 11748            return Expression::make_conditional(cmp, c32, call, loc);
 11749          }
 11750        else if ((name == "TrailingZeros64"
 11751                  || (name == "TrailingZeros" && int_size == 8))
 11752                 && this->args_ != NULL && this->args_->size() == 1)
 11753          {
 11754            Expression* arg = this->args_->front();
 11755            if (!arg->is_multi_eval_safe())
 11756              {
 11757                Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
 11758                inserter->insert(ts);
 11759                arg = Expression::make_temporary_reference(ts, loc);
 11760              }
 11761            // arg == 0 ? 64 : __builtin_ctzll(arg)
 11762            Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
 11763            Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
 11764            Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
 11765            Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZLL, loc, 1, arg->copy());
 11766            call = Expression::make_cast(int_type, call, loc);
 11767            return Expression::make_conditional(cmp, c64, call, loc);
 11768          }
 11769        else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
 11770                  || name == "Len8" || name == "Len16")
 11771                 && this->args_ != NULL && this->args_->size() == 1)
 11772          {
 11773            // GCC does not have a clz8 ir clz16 intrinsic. We do
 11774            // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
 11775            Expression* arg = this->args_->front();
 11776            arg = Expression::make_cast(uint32_type, arg, loc);
 11777            unsigned long shift =
 11778              ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
 11779            Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
 11780            arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
 11781            unsigned long mask =
 11782              ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
 11783            c = Expression::make_integer_ul(mask, uint32_type, loc);
 11784            arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
 11785            Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg);
 11786            call = Expression::make_cast(int_type, call, loc);
 11787            // len = width - clz
 11788            if (name == "Len8")
 11789              {
 11790                c = Expression::make_integer_ul(8, int_type, loc);
 11791                return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
 11792              }
 11793            else if (name == "Len16")
 11794              {
 11795                c = Expression::make_integer_ul(16, int_type, loc);
 11796                return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
 11797              }
 11798            return call;
 11799          }
 11800        else if ((name == "LeadingZeros32" || name == "Len32"
 11801                  || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
 11802                 && this->args_ != NULL && this->args_->size() == 1)
 11803          {
 11804            Expression* arg = this->args_->front();
 11805            if (!arg->is_multi_eval_safe())
 11806              {
 11807                Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
 11808                inserter->insert(ts);
 11809                arg = Expression::make_temporary_reference(ts, loc);
 11810              }
 11811            // arg == 0 ? 32 : __builtin_clz(arg)
 11812            Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
 11813            Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
 11814            Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
 11815            Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg->copy());
 11816            call = Expression::make_cast(int_type, call, loc);
 11817            Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
 11818            // len = 32 - clz
 11819            if (name == "Len32" || name == "Len")
 11820              return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
 11821            return cond;
 11822          }
 11823        else if ((name == "LeadingZeros64" || name == "Len64"
 11824                  || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
 11825                 && this->args_ != NULL && this->args_->size() == 1)
 11826          {
 11827            Expression* arg = this->args_->front();
 11828            if (!arg->is_multi_eval_safe())
 11829              {
 11830                Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
 11831                inserter->insert(ts);
 11832                arg = Expression::make_temporary_reference(ts, loc);
 11833              }
 11834            // arg == 0 ? 64 : __builtin_clzll(arg)
 11835            Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
 11836            Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
 11837            Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
 11838            Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZLL, loc, 1, arg->copy());
 11839            call = Expression::make_cast(int_type, call, loc);
 11840            Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
 11841            // len = 64 - clz
 11842            if (name == "Len64" || name == "Len")
 11843              return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
 11844            return cond;
 11845          }
 11846        else if ((name == "OnesCount8" || name == "OnesCount16"
 11847             || name == "OnesCount32" || name == "OnesCount64"
 11848             || name == "OnesCount")
 11849            && this->args_ != NULL && this->args_->size() == 1)
 11850          {
 11851            Runtime::Function code;
 11852            if (name == "OnesCount64")
 11853              code = Runtime::BUILTIN_POPCOUNTLL;
 11854            else if (name == "OnesCount")
 11855              code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
 11856            else
 11857              code = Runtime::BUILTIN_POPCOUNT;
 11858            Expression* arg = this->args_->front();
 11859            Expression* call = Runtime::make_call(code, loc, 1, arg);
 11860            return Expression::make_cast(int_type, call, loc);
 11861          }
 11862      }
 11863    else if (package == "runtime/internal/atomic")
 11864      {
 11865        int memorder = __ATOMIC_SEQ_CST;
 11866  
 11867        if (is_method)
 11868  	{
 11869  	  Function_type* ftype = (no->is_function()
 11870  				  ? no->func_value()->type()
 11871  				  : no->func_declaration_value()->type());
 11872  	  Type* rtype = ftype->receiver()->type()->deref();
 11873  	  go_assert(rtype->named_type() != NULL);
 11874  	  const std::string& rname(rtype->named_type()->name());
 11875  	  if (rname == "Int32")
 11876  	    {
 11877  	      if (name == "Load")
 11878  		name = "LoadInt32";
 11879  	      else if (name == "Store")
 11880  		name = "Storeint32";
 11881  	      else if (name == "CompareAndSwap")
 11882  		name = "Casint32";
 11883  	      else if (name == "Swap")
 11884  		name = "Xchgint32";
 11885  	      else if (name == "Add")
 11886  		name = "Xaddint32";
 11887  	      else
 11888  		go_unreachable();
 11889  	    }
 11890  	  else if (rname == "Int64")
 11891  	    {
 11892  	      if (name == "Load")
 11893  		name = "LoadInt64";
 11894  	      else if (name == "Store")
 11895  		name = "Storeint64";
 11896  	      else if (name == "CompareAndSwap")
 11897  		name = "Casint64";
 11898  	      else if (name == "Swap")
 11899  		name = "Xchgint64";
 11900  	      else if (name == "Add")
 11901  		name = "Xaddint64";
 11902  	      else
 11903  		go_unreachable();
 11904  	    }
 11905  	  else if (rname == "Uint8")
 11906  	    {
 11907  	      if (name == "Load")
 11908  		name = "Load8";
 11909  	      else if (name == "Store")
 11910  		name = "Store8";
 11911  	      else if (name == "And")
 11912  		name = "And8";
 11913  	      else if (name == "Or")
 11914  		name = "Or8";
 11915  	      else
 11916  		go_unreachable();
 11917  	    }
 11918  	  else if (rname == "Uint32")
 11919  	    {
 11920  	      if (name == "Load")
 11921  		name = "Load";
 11922  	      else if (name == "LoadAcquire")
 11923  		name = "LoadAcq";
 11924  	      else if (name == "Store")
 11925  		name = "Store";
 11926  	      else if (name == "CompareAndSwap")
 11927  		name = "Cas";
 11928  	      else if (name == "CompareAndSwapRelease")
 11929  		name = "CasRel";
 11930  	      else if (name == "Swap")
 11931  		name = "Xchg";
 11932  	      else if (name == "And")
 11933  		name = "And";
 11934  	      else if (name == "Or")
 11935  		name = "Or";
 11936  	      else if (name == "Add")
 11937  		name = "Xadd";
 11938  	      else
 11939  		go_unreachable();
 11940  	    }
 11941  	  else if (rname == "Uint64")
 11942  	    {
 11943  	      if (name == "Load")
 11944  		name = "Load64";
 11945  	      else if (name == "Store")
 11946  		name = "Store64";
 11947  	      else if (name == "CompareAndSwap")
 11948  		name = "Cas64";
 11949  	      else if (name == "Swap")
 11950  		name = "Xchgt64";
 11951  	      else if (name == "Add")
 11952  		name = "Xadd64";
 11953  	      else
 11954  		go_unreachable();
 11955  	    }
 11956  	  else if (rname == "Uintptr")
 11957  	    {
 11958  	      if (name == "Load")
 11959  		name = "Loaduintptr";
 11960  	      else if (name == "LoadAcquire")
 11961  		name = "Loadacquintptr";
 11962  	      else if (name == "Store")
 11963  		name = "Storeuintptr";
 11964  	      else if (name == "StoreRelease")
 11965  		name = "StoreReluintptr";
 11966  	      else if (name == "CompareAndSwap")
 11967  		name = "Casuintptr";
 11968  	      else if (name == "Swap")
 11969  		name = "Xchguintptr";
 11970  	      else if (name == "Add")
 11971  		name = "Xadduintptr";
 11972  	      else
 11973  		go_unreachable();
 11974  	    }
 11975  	  else if (rname == "Float64")
 11976  	    {
 11977  	      // Needs unsafe type conversion.  Don't intrinsify for now.
 11978  	      return NULL;
 11979  	    }
 11980  	  else if (rname == "UnsafePointer")
 11981  	    {
 11982  	      if (name == "Load")
 11983  		name = "Loadp";
 11984  	      else if (name == "StoreNoWB")
 11985  		name = "StorepoWB";
 11986  	      else if (name == "CompareAndSwapNoWB")
 11987  		name = "Casp1";
 11988  	      else
 11989  		go_unreachable();
 11990  	    }
 11991  	  else
 11992  	    go_unreachable();
 11993  	}
 11994  
 11995        if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
 11996             || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
 11997             || name == "Loadint32" || name == "Load8")
 11998            && this->args_ != NULL && this->args_->size() == 1)
 11999          {
 12000            if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
 12001              // On 32-bit architectures we need to check alignment.
 12002              // Not intrinsify for now.
 12003              return NULL;
 12004  
 12005            Runtime::Function code;
 12006            Type* res_type;
 12007            if (name == "Load")
 12008              {
 12009                code = Runtime::ATOMIC_LOAD_4;
 12010                res_type = uint32_type;
 12011              }
 12012            else if (name == "Load64")
 12013              {
 12014                code = Runtime::ATOMIC_LOAD_8;
 12015                res_type = uint64_type;
 12016              }
 12017            else if (name == "Loadint32")
 12018              {
 12019                code = Runtime::ATOMIC_LOAD_4;
 12020                res_type = int32_type;
 12021              }
 12022            else if (name == "Loadint64")
 12023              {
 12024                code = Runtime::ATOMIC_LOAD_8;
 12025                res_type = int64_type;
 12026              }
 12027            else if (name == "Loaduint")
 12028              {
 12029                code = (int_size == 8
 12030                        ? Runtime::ATOMIC_LOAD_8
 12031                        : Runtime::ATOMIC_LOAD_4);
 12032                res_type = uint_type;
 12033              }
 12034            else if (name == "Loaduintptr")
 12035              {
 12036                code = (ptr_size == 8
 12037                        ? Runtime::ATOMIC_LOAD_8
 12038                        : Runtime::ATOMIC_LOAD_4);
 12039                res_type = uintptr_type;
 12040              }
 12041            else if (name == "Loadp")
 12042              {
 12043                code = (ptr_size == 8
 12044                        ? Runtime::ATOMIC_LOAD_8
 12045                        : Runtime::ATOMIC_LOAD_4);
 12046                res_type = pointer_type;
 12047              }
 12048            else if (name == "LoadAcq")
 12049              {
 12050                code = Runtime::ATOMIC_LOAD_4;
 12051                res_type = uint32_type;
 12052                memorder = __ATOMIC_ACQUIRE;
 12053              }
 12054  	  else if (name == "Load8")
 12055  	    {
 12056  	      code = Runtime::ATOMIC_LOAD_1;
 12057  	      res_type = uint8_type;
 12058  	    }
 12059            else
 12060              go_unreachable();
 12061            Expression* a1 = this->args_->front();
 12062            Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
 12063            Expression* call = Runtime::make_call(code, loc, 2, a1, a2);
 12064            return Expression::make_unsafe_cast(res_type, call, loc);
 12065          }
 12066  
 12067        if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
 12068             || name == "Storeuintptr" || name == "StoreRel"
 12069             || name == "Storeint32" || name == "Storeint64")
 12070            && this->args_ != NULL && this->args_->size() == 2)
 12071          {
 12072            if (int_size < 8 && (name == "Store64" || name == "Storeint64"))
 12073              return NULL;
 12074  
 12075            Runtime::Function code;
 12076            Expression* a1 = this->args_->at(0);
 12077            Expression* a2 = this->args_->at(1);
 12078            if (name == "Store")
 12079              code = Runtime::ATOMIC_STORE_4;
 12080            else if (name == "Store64")
 12081              code = Runtime::ATOMIC_STORE_8;
 12082            else if (name == "Storeint32")
 12083              code = Runtime::ATOMIC_STORE_4;
 12084            else if (name == "Storeint64")
 12085              code = Runtime::ATOMIC_STORE_8;
 12086            else if (name == "Storeuintptr")
 12087              code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
 12088            else if (name == "StorepNoWB")
 12089              {
 12090                code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
 12091                a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
 12092                a2 = Expression::make_cast(uint64_type, a2, loc);
 12093              }
 12094            else if (name == "StoreRel")
 12095              {
 12096                code = Runtime::ATOMIC_STORE_4;
 12097                memorder = __ATOMIC_RELEASE;
 12098              }
 12099  	  else if (name == "Store8")
 12100  	    code = Runtime::ATOMIC_STORE_1;
 12101            else
 12102              go_unreachable();
 12103            Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
 12104            return Runtime::make_call(code, loc, 3, a1, a2, a3);
 12105          }
 12106  
 12107        if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
 12108             || name == "Xchgint32" || name == "Xchgint64")
 12109            && this->args_ != NULL && this->args_->size() == 2)
 12110          {
 12111            if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
 12112              return NULL;
 12113  
 12114            Runtime::Function code;
 12115            Type* res_type;
 12116            if (name == "Xchg")
 12117              {
 12118                code = Runtime::ATOMIC_EXCHANGE_4;
 12119                res_type = uint32_type;
 12120              }
 12121            else if (name == "Xchg64")
 12122              {
 12123                code = Runtime::ATOMIC_EXCHANGE_8;
 12124                res_type = uint64_type;
 12125              }
 12126            else if (name == "Xchgint32")
 12127              {
 12128                code = Runtime::ATOMIC_EXCHANGE_4;
 12129                res_type = int32_type;
 12130              }
 12131            else if (name == "Xchgint64")
 12132              {
 12133                code = Runtime::ATOMIC_EXCHANGE_8;
 12134                res_type = int64_type;
 12135              }
 12136            else if (name == "Xchguintptr")
 12137              {
 12138                code = (ptr_size == 8
 12139                        ? Runtime::ATOMIC_EXCHANGE_8
 12140                        : Runtime::ATOMIC_EXCHANGE_4);
 12141                res_type = uintptr_type;
 12142              }
 12143            else
 12144              go_unreachable();
 12145            Expression* a1 = this->args_->at(0);
 12146            Expression* a2 = this->args_->at(1);
 12147            Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
 12148            Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
 12149            return Expression::make_cast(res_type, call, loc);
 12150          }
 12151  
 12152        if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
 12153             || name == "Casp1" || name == "CasRel"
 12154             || name == "Casint32" || name == "Casint64")
 12155            && this->args_ != NULL && this->args_->size() == 3)
 12156          {
 12157            if (int_size < 8 && (name == "Cas64" || name == "Casint64"))
 12158              return NULL;
 12159  
 12160            Runtime::Function code;
 12161            Expression* a1 = this->args_->at(0);
 12162  
 12163            // Builtin cas takes a pointer to the old value.
 12164            // Store it in a temporary and take the address.
 12165            Expression* a2 = this->args_->at(1);
 12166            Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
 12167            inserter->insert(ts);
 12168            a2 = Expression::make_temporary_reference(ts, loc);
 12169            a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
 12170  
 12171            Expression* a3 = this->args_->at(2);
 12172            if (name == "Cas")
 12173              code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
 12174            else if (name == "Cas64")
 12175              code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
 12176            else if (name == "Casint32")
 12177              code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
 12178            else if (name == "Casint64")
 12179              code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
 12180            else if (name == "Casuintptr")
 12181              code = (ptr_size == 8
 12182                      ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
 12183                      : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
 12184            else if (name == "Casp1")
 12185              {
 12186                code = (ptr_size == 8
 12187                        ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
 12188                        : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
 12189                a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
 12190                a3 = Expression::make_cast(uint64_type, a3, loc);
 12191              }
 12192            else if (name == "CasRel")
 12193              {
 12194                code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
 12195                memorder = __ATOMIC_RELEASE;
 12196              }
 12197            else
 12198              go_unreachable();
 12199            Expression* a4 = Expression::make_boolean(false, loc);
 12200            Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
 12201            Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
 12202            return Runtime::make_call(code, loc, 6, a1, a2, a3, a4, a5, a6);
 12203          }
 12204  
 12205        if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
 12206             || name == "Xadduintptr" || name == "Xaddint32")
 12207            && this->args_ != NULL && this->args_->size() == 2)
 12208          {
 12209            if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
 12210              return NULL;
 12211  
 12212            Runtime::Function code;
 12213            Type* res_type;
 12214            if (name == "Xadd")
 12215              {
 12216                code = Runtime::ATOMIC_ADD_FETCH_4;
 12217                res_type = uint32_type;
 12218              }
 12219            else if (name == "Xadd64")
 12220              {
 12221                code = Runtime::ATOMIC_ADD_FETCH_8;
 12222                res_type = uint64_type;
 12223              }
 12224            else if (name == "Xaddint32")
 12225              {
 12226                code = Runtime::ATOMIC_ADD_FETCH_4;
 12227                res_type = int32_type;
 12228              }
 12229            else if (name == "Xaddint64")
 12230              {
 12231                code = Runtime::ATOMIC_ADD_FETCH_8;
 12232                res_type = int64_type;
 12233              }
 12234            else if (name == "Xadduintptr")
 12235              {
 12236                code = (ptr_size == 8
 12237                        ? Runtime::ATOMIC_ADD_FETCH_8
 12238                        : Runtime::ATOMIC_ADD_FETCH_4);
 12239                res_type = uintptr_type;
 12240              }
 12241            else
 12242              go_unreachable();
 12243            Expression* a1 = this->args_->at(0);
 12244            Expression* a2 = this->args_->at(1);
 12245            Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
 12246            Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
 12247            return Expression::make_cast(res_type, call, loc);
 12248          }
 12249  
 12250        if ((name == "And8" || name == "Or8")
 12251            && this->args_ != NULL && this->args_->size() == 2)
 12252          {
 12253            Runtime::Function code;
 12254            if (name == "And8")
 12255              code = Runtime::ATOMIC_AND_FETCH_1;
 12256            else if (name == "Or8")
 12257              code = Runtime::ATOMIC_OR_FETCH_1;
 12258            else
 12259              go_unreachable();
 12260            Expression* a1 = this->args_->at(0);
 12261            Expression* a2 = this->args_->at(1);
 12262            Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
 12263            return Runtime::make_call(code, loc, 3, a1, a2, a3);
 12264          }
 12265      }
 12266    else if (package == "internal/abi")
 12267      {
 12268        if (is_method)
 12269  	return NULL;
 12270  
 12271        if ((name == "FuncPCABI0" || name == "FuncPCABIInternal")
 12272  	  && this->args_ != NULL
 12273  	  && this->args_->size() == 1)
 12274  	{
 12275  	  // We expect to see a conversion from the expression to "any".
 12276  	  Expression* expr = this->args_->front();
 12277  	  Type_conversion_expression* tce = expr->conversion_expression();
 12278  	  if (tce != NULL)
 12279  	    expr = tce->expr();
 12280  	  Func_expression* fe = expr->func_expression();
 12281  	  Interface_field_reference_expression* interface_method =
 12282  	    expr->interface_field_reference_expression();
 12283  	  if (fe != NULL)
 12284  	    {
 12285  	      Named_object* no = fe->named_object();
 12286  	      Expression* ref = Expression::make_func_code_reference(no, loc);
 12287  	      Type* uintptr_type = Type::lookup_integer_type("uintptr");
 12288  	      return Expression::make_cast(uintptr_type, ref, loc);
 12289  	    }
 12290  	  else if (interface_method != NULL)
 12291  	    return interface_method->get_function();
 12292  	  else
 12293  	    {
 12294  	      expr = this->args_->front();
 12295  	      go_assert(expr->type()->interface_type() != NULL
 12296  			&& expr->type()->interface_type()->is_empty());
 12297  	      expr = Expression::make_interface_info(expr,
 12298  						     INTERFACE_INFO_OBJECT,
 12299  						     loc);
 12300  	      // Trust that this is a function type, which means that
 12301  	      // it is a direct iface type and we can use EXPR
 12302  	      // directly.  The backend representation of this
 12303  	      // function is a pointer to a struct whose first field
 12304  	      // is the actual function to call.
 12305  	      Type* pvoid = Type::make_pointer_type(Type::make_void_type());
 12306  	      Type* pfntype = Type::make_pointer_type(pvoid);
 12307  	      Expression* ref = make_unsafe_cast(pfntype, expr, loc);
 12308  	      return Expression::make_dereference(ref, NIL_CHECK_NOT_NEEDED,
 12309  						  loc);
 12310  	    }
 12311  	}
 12312      }
 12313  
 12314    return NULL;
 12315  }
 12316  
 12317  // Make implicit type conversions explicit.
 12318  
 12319  void
 12320  Call_expression::do_add_conversions()
 12321  {
 12322    // Skip call that requires a thunk. We generate conversions inside the thunk.
 12323    if (this->is_concurrent_ || this->is_deferred_)
 12324      return;
 12325  
 12326    if (this->args_ == NULL || this->args_->empty())
 12327      return;
 12328  
 12329    Function_type* fntype = this->get_function_type();
 12330    if (fntype == NULL)
 12331      {
 12332        go_assert(saw_errors());
 12333        return;
 12334      }
 12335    if (fntype->parameters() == NULL || fntype->parameters()->empty())
 12336      return;
 12337  
 12338    Location loc = this->location();
 12339    Expression_list::iterator pa = this->args_->begin();
 12340    Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
 12341    bool is_interface_method =
 12342      this->fn_->interface_field_reference_expression() != NULL;
 12343    size_t argcount = this->args_->size();
 12344    if (!is_interface_method && fntype->is_method())
 12345      {
 12346        // Skip the receiver argument, which cannot be interface.
 12347        pa++;
 12348        argcount--;
 12349      }
 12350    if (argcount != fntype->parameters()->size())
 12351      {
 12352        go_assert(saw_errors());
 12353        return;
 12354      }
 12355    for (; pa != this->args_->end(); ++pa, ++pp)
 12356      {
 12357        Type* pt = pp->type();
 12358        if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
 12359            && pt->interface_type() != NULL)
 12360          *pa = Expression::make_cast(pt, *pa, loc);
 12361      }
 12362  }
 12363  
 12364  // Get the function type.  This can return NULL in error cases.
 12365  
 12366  Function_type*
 12367  Call_expression::get_function_type() const
 12368  {
 12369    return this->fn_->type()->function_type();
 12370  }
 12371  
 12372  // Return the number of values which this call will return.
 12373  
 12374  size_t
 12375  Call_expression::result_count() const
 12376  {
 12377    const Function_type* fntype = this->get_function_type();
 12378    if (fntype == NULL)
 12379      return 0;
 12380    if (fntype->results() == NULL)
 12381      return 0;
 12382    return fntype->results()->size();
 12383  }
 12384  
 12385  // Return the temporary that holds the result for a call with multiple
 12386  // results.
 12387  
 12388  Temporary_statement*
 12389  Call_expression::results() const
 12390  {
 12391    if (this->call_temp_ == NULL)
 12392      {
 12393        go_assert(saw_errors());
 12394        return NULL;
 12395      }
 12396    return this->call_temp_;
 12397  }
 12398  
 12399  // Set the number of results expected from a call expression.
 12400  
 12401  void
 12402  Call_expression::set_expected_result_count(size_t count)
 12403  {
 12404    go_assert(this->expected_result_count_ == 0);
 12405    this->expected_result_count_ = count;
 12406  }
 12407  
 12408  // Return whether this is a call to the predeclared function recover.
 12409  
 12410  bool
 12411  Call_expression::is_recover_call() const
 12412  {
 12413    return this->do_is_recover_call();
 12414  }
 12415  
 12416  // Set the argument to the recover function.
 12417  
 12418  void
 12419  Call_expression::set_recover_arg(Expression* arg)
 12420  {
 12421    this->do_set_recover_arg(arg);
 12422  }
 12423  
 12424  // Virtual functions also implemented by Builtin_call_expression.
 12425  
 12426  bool
 12427  Call_expression::do_is_recover_call() const
 12428  {
 12429    return false;
 12430  }
 12431  
 12432  void
 12433  Call_expression::do_set_recover_arg(Expression*)
 12434  {
 12435    go_unreachable();
 12436  }
 12437  
 12438  // We have found an error with this call expression; return true if
 12439  // we should report it.
 12440  
 12441  bool
 12442  Call_expression::issue_error()
 12443  {
 12444    if (this->issued_error_)
 12445      return false;
 12446    else
 12447      {
 12448        this->issued_error_ = true;
 12449        return true;
 12450      }
 12451  }
 12452  
 12453  // Whether or not this call contains errors, either in the call or the
 12454  // arguments to the call.
 12455  
 12456  bool
 12457  Call_expression::is_erroneous_call()
 12458  {
 12459    if (this->is_error_expression() || this->fn()->is_error_expression())
 12460      return true;
 12461  
 12462    if (this->args() == NULL)
 12463      return false;
 12464    for (Expression_list::iterator pa = this->args()->begin();
 12465         pa != this->args()->end();
 12466         ++pa)
 12467      {
 12468        if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
 12469          return true;
 12470      }
 12471    return false;
 12472  }
 12473  
 12474  // Get the type.
 12475  
 12476  Type*
 12477  Call_expression::do_type()
 12478  {
 12479    if (this->is_error_expression())
 12480      return Type::make_error_type();
 12481    if (this->type_ != NULL)
 12482      return this->type_;
 12483  
 12484    Type* ret;
 12485    Function_type* fntype = this->get_function_type();
 12486    if (fntype == NULL)
 12487      return Type::make_error_type();
 12488  
 12489    const Typed_identifier_list* results = fntype->results();
 12490    if (results == NULL)
 12491      ret = Type::make_void_type();
 12492    else if (results->size() == 1)
 12493      ret = results->begin()->type();
 12494    else
 12495      ret = Type::make_call_multiple_result_type(this);
 12496  
 12497    this->type_ = ret;
 12498  
 12499    return this->type_;
 12500  }
 12501  
 12502  // Determine types for a call expression.  We can use the function
 12503  // parameter types to set the types of the arguments.
 12504  
 12505  void
 12506  Call_expression::do_determine_type(const Type_context* context)
 12507  {
 12508    if (!this->determining_types())
 12509      return;
 12510  
 12511    this->fn_->determine_type_no_context();
 12512    Function_type* fntype = this->get_function_type();
 12513    const Typed_identifier_list* parameters = NULL;
 12514    if (fntype != NULL)
 12515      parameters = fntype->parameters();
 12516    if (this->args_ != NULL)
 12517      {
 12518        Typed_identifier_list::const_iterator pt;
 12519        if (parameters != NULL)
 12520  	pt = parameters->begin();
 12521        bool first = true;
 12522        for (Expression_list::const_iterator pa = this->args_->begin();
 12523  	   pa != this->args_->end();
 12524  	   ++pa)
 12525  	{
 12526  	  if (first)
 12527  	    {
 12528  	      first = false;
 12529  	      // If this is a method, the first argument is the
 12530  	      // receiver.
 12531  	      if (fntype != NULL && fntype->is_method())
 12532  		{
 12533  		  Type* rtype = fntype->receiver()->type();
 12534  		  // The receiver is always passed as a pointer.
 12535  		  if (rtype->points_to() == NULL)
 12536  		    rtype = Type::make_pointer_type(rtype);
 12537  		  Type_context subcontext(rtype, false);
 12538  		  (*pa)->determine_type(&subcontext);
 12539  		  continue;
 12540  		}
 12541  	    }
 12542  
 12543  	  if (parameters != NULL && pt != parameters->end())
 12544  	    {
 12545  	      Type_context subcontext(pt->type(), false);
 12546  	      (*pa)->determine_type(&subcontext);
 12547  	      ++pt;
 12548  	    }
 12549  	  else
 12550  	    (*pa)->determine_type_no_context();
 12551  	}
 12552      }
 12553  
 12554    // If this is a call to a generated equality function, we determine
 12555    // the type based on the context.  See the comment in
 12556    // Binary_expression::lower_array_comparison.
 12557    if (this->is_equal_function_
 12558        && !context->may_be_abstract
 12559        && context->type != NULL
 12560        && context->type->is_boolean_type()
 12561        && context->type != Type::lookup_bool_type())
 12562      {
 12563        go_assert(this->type_ == NULL
 12564  		|| this->type_ == Type::lookup_bool_type()
 12565  		|| this->type_ == context->type
 12566  		|| this->type_->is_error());
 12567        this->type_ = context->type;
 12568      }
 12569  }
 12570  
 12571  // Called when determining types for a Call_expression.  Return true
 12572  // if we should go ahead, false if they have already been determined.
 12573  
 12574  bool
 12575  Call_expression::determining_types()
 12576  {
 12577    if (this->types_are_determined_)
 12578      return false;
 12579    else
 12580      {
 12581        this->types_are_determined_ = true;
 12582        return true;
 12583      }
 12584  }
 12585  
 12586  // Check types for parameter I.
 12587  
 12588  bool
 12589  Call_expression::check_argument_type(int i, const Type* parameter_type,
 12590  				     const Type* argument_type,
 12591  				     Location argument_location,
 12592  				     bool issued_error)
 12593  {
 12594    std::string reason;
 12595    if (!Type::are_assignable(parameter_type, argument_type, &reason))
 12596      {
 12597        if (!issued_error)
 12598  	{
 12599  	  if (reason.empty())
 12600  	    go_error_at(argument_location, "argument %d has incompatible type", i);
 12601  	  else
 12602  	    go_error_at(argument_location,
 12603  			"argument %d has incompatible type (%s)",
 12604  			i, reason.c_str());
 12605  	}
 12606        this->set_is_error();
 12607        return false;
 12608      }
 12609    return true;
 12610  }
 12611  
 12612  // Check types.
 12613  
 12614  void
 12615  Call_expression::do_check_types(Gogo*)
 12616  {
 12617    if (this->classification() == EXPRESSION_ERROR)
 12618      return;
 12619  
 12620    Function_type* fntype = this->get_function_type();
 12621    if (fntype == NULL)
 12622      {
 12623        if (!this->fn_->type()->is_error())
 12624  	this->report_error(_("expected function"));
 12625        return;
 12626      }
 12627  
 12628    if (this->expected_result_count_ != 0
 12629        && this->expected_result_count_ != this->result_count())
 12630      {
 12631        if (this->issue_error())
 12632  	this->report_error(_("function result count mismatch"));
 12633        this->set_is_error();
 12634        return;
 12635      }
 12636  
 12637    bool is_method = fntype->is_method();
 12638    if (is_method)
 12639      {
 12640        go_assert(this->args_ != NULL && !this->args_->empty());
 12641        Type* rtype = fntype->receiver()->type();
 12642        Expression* first_arg = this->args_->front();
 12643        // We dereference the values since receivers are always passed
 12644        // as pointers.
 12645        std::string reason;
 12646        if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
 12647  				&reason))
 12648  	{
 12649  	  if (reason.empty())
 12650  	    this->report_error(_("incompatible type for receiver"));
 12651  	  else
 12652  	    {
 12653  	      go_error_at(this->location(),
 12654                            "incompatible type for receiver (%s)",
 12655                            reason.c_str());
 12656  	      this->set_is_error();
 12657  	    }
 12658  	}
 12659      }
 12660  
 12661    // Note that varargs was handled by the lower_varargs() method, so
 12662    // we don't have to worry about it here unless something is wrong.
 12663    if (this->is_varargs_ && !this->varargs_are_lowered_)
 12664      {
 12665        if (!fntype->is_varargs())
 12666  	{
 12667  	  go_error_at(this->location(),
 12668                        _("invalid use of %<...%> calling non-variadic function"));
 12669  	  this->set_is_error();
 12670  	  return;
 12671  	}
 12672      }
 12673  
 12674    const Typed_identifier_list* parameters = fntype->parameters();
 12675    if (this->args_ == NULL || this->args_->size() == 0)
 12676      {
 12677        if (parameters != NULL && !parameters->empty())
 12678  	this->report_error(_("not enough arguments"));
 12679      }
 12680    else if (parameters == NULL)
 12681      {
 12682        if (!is_method || this->args_->size() > 1)
 12683  	this->report_error(_("too many arguments"));
 12684      }
 12685    else if (this->args_->size() == 1
 12686  	   && this->args_->front()->call_expression() != NULL
 12687  	   && this->args_->front()->call_expression()->result_count() > 1)
 12688      {
 12689        // This is F(G()) when G returns more than one result.  If the
 12690        // results can be matched to parameters, it would have been
 12691        // lowered in do_lower.  If we get here we know there is a
 12692        // mismatch.
 12693        if (this->args_->front()->call_expression()->result_count()
 12694  	  < parameters->size())
 12695  	this->report_error(_("not enough arguments"));
 12696        else
 12697  	this->report_error(_("too many arguments"));
 12698      }
 12699    else
 12700      {
 12701        int i = 0;
 12702        Expression_list::const_iterator pa = this->args_->begin();
 12703        if (is_method)
 12704  	++pa;
 12705        for (Typed_identifier_list::const_iterator pt = parameters->begin();
 12706  	   pt != parameters->end();
 12707  	   ++pt, ++pa, ++i)
 12708  	{
 12709  	  if (pa == this->args_->end())
 12710  	    {
 12711  	      this->report_error(_("not enough arguments"));
 12712  	      return;
 12713  	    }
 12714  	  this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
 12715  				    (*pa)->location(), false);
 12716  	}
 12717        if (pa != this->args_->end())
 12718  	this->report_error(_("too many arguments"));
 12719      }
 12720  }
 12721  
 12722  Expression*
 12723  Call_expression::do_copy()
 12724  {
 12725    Call_expression* call =
 12726      Expression::make_call(this->fn_->copy(),
 12727  			  (this->args_ == NULL
 12728  			   ? NULL
 12729  			   : this->args_->copy()),
 12730  			  this->is_varargs_, this->location());
 12731  
 12732    if (this->varargs_are_lowered_)
 12733      call->set_varargs_are_lowered();
 12734    if (this->is_deferred_)
 12735      call->set_is_deferred();
 12736    if (this->is_concurrent_)
 12737      call->set_is_concurrent();
 12738    return call;
 12739  }
 12740  
 12741  // Return whether we have to use a temporary variable to ensure that
 12742  // we evaluate this call expression in order.  If the call returns no
 12743  // results then it will inevitably be executed last.
 12744  
 12745  bool
 12746  Call_expression::do_must_eval_in_order() const
 12747  {
 12748    return this->result_count() > 0;
 12749  }
 12750  
 12751  // Get the function and the first argument to use when calling an
 12752  // interface method.
 12753  
 12754  Expression*
 12755  Call_expression::interface_method_function(
 12756      Interface_field_reference_expression* interface_method,
 12757      Expression** first_arg_ptr,
 12758      Location location)
 12759  {
 12760    Expression* object = interface_method->get_underlying_object();
 12761    Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
 12762    *first_arg_ptr =
 12763        Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
 12764    return interface_method->get_function();
 12765  }
 12766  
 12767  // Build the call expression.
 12768  
 12769  Bexpression*
 12770  Call_expression::do_get_backend(Translate_context* context)
 12771  {
 12772    Location location = this->location();
 12773  
 12774    if (this->call_ != NULL)
 12775      {
 12776        // If the call returns multiple results, make a new reference to
 12777        // the temporary.
 12778        if (this->call_temp_ != NULL)
 12779  	{
 12780  	  Expression* ref =
 12781  	    Expression::make_temporary_reference(this->call_temp_, location);
 12782  	  return ref->get_backend(context);
 12783  	}
 12784  
 12785        return this->call_;
 12786      }
 12787  
 12788    Function_type* fntype = this->get_function_type();
 12789    if (fntype == NULL)
 12790      return context->backend()->error_expression();
 12791  
 12792    if (this->fn_->is_error_expression())
 12793      return context->backend()->error_expression();
 12794  
 12795    Gogo* gogo = context->gogo();
 12796  
 12797    Func_expression* func = this->fn_->func_expression();
 12798    Interface_field_reference_expression* interface_method =
 12799      this->fn_->interface_field_reference_expression();
 12800    const bool has_closure = func != NULL && func->closure() != NULL;
 12801    const bool is_interface_method = interface_method != NULL;
 12802  
 12803    bool has_closure_arg;
 12804    if (has_closure)
 12805      has_closure_arg = true;
 12806    else if (func != NULL)
 12807      has_closure_arg = false;
 12808    else if (is_interface_method)
 12809      has_closure_arg = false;
 12810    else
 12811      has_closure_arg = true;
 12812  
 12813    Expression* first_arg = NULL;
 12814    if (!is_interface_method && fntype->is_method())
 12815      {
 12816        first_arg = this->args_->front();
 12817        if (first_arg->type()->points_to() == NULL
 12818            && first_arg->type()->is_direct_iface_type())
 12819          first_arg = Expression::unpack_direct_iface(first_arg,
 12820                                                      first_arg->location());
 12821      }
 12822  
 12823    int nargs;
 12824    std::vector<Bexpression*> fn_args;
 12825    if (this->args_ == NULL || this->args_->empty())
 12826      {
 12827        nargs = is_interface_method ? 1 : 0;
 12828        if (nargs > 0)
 12829          fn_args.resize(1);
 12830      }
 12831    else if (fntype->parameters() == NULL || fntype->parameters()->empty())
 12832      {
 12833        // Passing a receiver parameter.
 12834        go_assert(!is_interface_method
 12835  		&& fntype->is_method()
 12836  		&& this->args_->size() == 1);
 12837        nargs = 1;
 12838        fn_args.resize(1);
 12839        fn_args[0] = first_arg->get_backend(context);
 12840      }
 12841    else
 12842      {
 12843        const Typed_identifier_list* params = fntype->parameters();
 12844  
 12845        nargs = this->args_->size();
 12846        int i = is_interface_method ? 1 : 0;
 12847        nargs += i;
 12848        fn_args.resize(nargs);
 12849  
 12850        Typed_identifier_list::const_iterator pp = params->begin();
 12851        Expression_list::const_iterator pe = this->args_->begin();
 12852        if (!is_interface_method && fntype->is_method())
 12853  	{
 12854            fn_args[i] = first_arg->get_backend(context);
 12855  	  ++pe;
 12856  	  ++i;
 12857  	}
 12858        for (; pe != this->args_->end(); ++pe, ++pp, ++i)
 12859  	{
 12860  	  go_assert(pp != params->end());
 12861            Expression* arg =
 12862                Expression::convert_for_assignment(gogo, pp->type(), *pe,
 12863                                                   location);
 12864            fn_args[i] = arg->get_backend(context);
 12865  	}
 12866        go_assert(pp == params->end());
 12867        go_assert(i == nargs);
 12868      }
 12869  
 12870    Expression* fn;
 12871    Expression* closure = NULL;
 12872    if (func != NULL)
 12873      {
 12874        Named_object* no = func->named_object();
 12875        fn = Expression::make_func_code_reference(no, location);
 12876        if (has_closure)
 12877          closure = func->closure();
 12878      }
 12879    else if (!is_interface_method)
 12880      {
 12881        closure = this->fn_;
 12882  
 12883        // The backend representation of this function type is a pointer
 12884        // to a struct whose first field is the actual function to call.
 12885        Type* pfntype =
 12886            Type::make_pointer_type(
 12887                Type::make_pointer_type(Type::make_void_type()));
 12888        fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
 12889        fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
 12890      }
 12891    else
 12892      {
 12893        Expression* arg0;
 12894        fn = this->interface_method_function(interface_method, &arg0,
 12895                                             location);
 12896        fn_args[0] = arg0->get_backend(context);
 12897      }
 12898  
 12899    Bexpression* bclosure = NULL;
 12900    if (has_closure_arg)
 12901      bclosure = closure->get_backend(context);
 12902    else
 12903      go_assert(closure == NULL);
 12904  
 12905    Bexpression* bfn = fn->get_backend(context);
 12906  
 12907    // When not calling a named function directly, use a type conversion
 12908    // in case the type of the function is a recursive type which refers
 12909    // to itself.  We don't do this for an interface method because 1)
 12910    // an interface method never refers to itself, so we always have a
 12911    // function type here; 2) we pass an extra first argument to an
 12912    // interface method, so fntype is not correct.
 12913    if (func == NULL && !is_interface_method)
 12914      {
 12915        Btype* bft = fntype->get_backend_fntype(gogo);
 12916        bfn = gogo->backend()->convert_expression(bft, bfn, location);
 12917      }
 12918  
 12919    Bfunction* bfunction = NULL;
 12920    if (context->function())
 12921      bfunction = context->function()->func_value()->get_decl();
 12922    Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
 12923                                                         fn_args, bclosure,
 12924                                                         location);
 12925  
 12926    if (this->call_temp_ != NULL)
 12927      {
 12928        // This case occurs when the call returns multiple results.
 12929  
 12930        Expression* ref = Expression::make_temporary_reference(this->call_temp_,
 12931  							     location);
 12932        Bexpression* bref = ref->get_backend(context);
 12933        Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
 12934  								bref, call,
 12935  								location);
 12936  
 12937        ref = Expression::make_temporary_reference(this->call_temp_, location);
 12938        this->call_ = ref->get_backend(context);
 12939  
 12940        return gogo->backend()->compound_expression(bassn, this->call_,
 12941  						  location);
 12942      }
 12943  
 12944    this->call_ = call;
 12945    return this->call_;
 12946  }
 12947  
 12948  // The cost of inlining a call expression.
 12949  
 12950  int
 12951  Call_expression::do_inlining_cost() const
 12952  {
 12953    Func_expression* fn = this->fn_->func_expression();
 12954  
 12955    // FIXME: We don't yet support all kinds of calls.
 12956    if (fn != NULL && fn->closure() != NULL)
 12957      return 0x100000;
 12958    if (this->fn_->interface_field_reference_expression())
 12959      return 0x100000;
 12960    if (this->get_function_type()->is_method())
 12961      return 0x100000;
 12962  
 12963    return 5;
 12964  }
 12965  
 12966  // Export a call expression.
 12967  
 12968  void
 12969  Call_expression::do_export(Export_function_body* efb) const
 12970  {
 12971    bool simple_call = (this->fn_->func_expression() != NULL);
 12972    if (!simple_call)
 12973      efb->write_c_string("(");
 12974    this->fn_->export_expression(efb);
 12975    if (!simple_call)
 12976      efb->write_c_string(")");
 12977    this->export_arguments(efb);
 12978  }
 12979  
 12980  // Export call expression arguments.
 12981  
 12982  void
 12983  Call_expression::export_arguments(Export_function_body* efb) const
 12984  {
 12985    efb->write_c_string("(");
 12986    if (this->args_ != NULL && !this->args_->empty())
 12987      {
 12988        Expression_list::const_iterator pa = this->args_->begin();
 12989        (*pa)->export_expression(efb);
 12990        for (pa++; pa != this->args_->end(); pa++)
 12991  	{
 12992  	  efb->write_c_string(", ");
 12993  	  (*pa)->export_expression(efb);
 12994  	}
 12995        if (this->is_varargs_)
 12996  	efb->write_c_string("...");
 12997      }
 12998    efb->write_c_string(")");
 12999  }
 13000  
 13001  // Dump ast representation for a call expression.
 13002  
 13003  void
 13004  Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
 13005  {
 13006    this->fn_->dump_expression(ast_dump_context);
 13007    ast_dump_context->ostream() << "(";
 13008    if (args_ != NULL)
 13009      ast_dump_context->dump_expression_list(this->args_);
 13010  
 13011    ast_dump_context->ostream() << ") ";
 13012  }
 13013  
 13014  // Make a call expression.
 13015  
 13016  Call_expression*
 13017  Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
 13018  		      Location location)
 13019  {
 13020    return new Call_expression(fn, args, is_varargs, location);
 13021  }
 13022  
 13023  // Class Call_result_expression.
 13024  
 13025  // Traverse a call result.
 13026  
 13027  int
 13028  Call_result_expression::do_traverse(Traverse* traverse)
 13029  {
 13030    if (traverse->remember_expression(this->call_))
 13031      {
 13032        // We have already traversed the call expression.
 13033        return TRAVERSE_CONTINUE;
 13034      }
 13035    return Expression::traverse(&this->call_, traverse);
 13036  }
 13037  
 13038  // Get the type.
 13039  
 13040  Type*
 13041  Call_result_expression::do_type()
 13042  {
 13043    if (this->classification() == EXPRESSION_ERROR)
 13044      return Type::make_error_type();
 13045  
 13046    // THIS->CALL_ can be replaced with a temporary reference due to
 13047    // Call_expression::do_must_eval_in_order when there is an error.
 13048    Call_expression* ce = this->call_->call_expression();
 13049    if (ce == NULL)
 13050      {
 13051        this->set_is_error();
 13052        return Type::make_error_type();
 13053      }
 13054    Function_type* fntype = ce->get_function_type();
 13055    if (fntype == NULL)
 13056      {
 13057        if (ce->issue_error())
 13058  	{
 13059  	  if (!ce->fn()->type()->is_error())
 13060  	    this->report_error(_("expected function"));
 13061  	}
 13062        this->set_is_error();
 13063        return Type::make_error_type();
 13064      }
 13065    const Typed_identifier_list* results = fntype->results();
 13066    if (results == NULL || results->size() < 2)
 13067      {
 13068        if (ce->issue_error())
 13069  	this->report_error(_("number of results does not match "
 13070  			     "number of values"));
 13071        return Type::make_error_type();
 13072      }
 13073    Typed_identifier_list::const_iterator pr = results->begin();
 13074    for (unsigned int i = 0; i < this->index_; ++i)
 13075      {
 13076        if (pr == results->end())
 13077  	break;
 13078        ++pr;
 13079      }
 13080    if (pr == results->end())
 13081      {
 13082        if (ce->issue_error())
 13083  	this->report_error(_("number of results does not match "
 13084  			     "number of values"));
 13085        return Type::make_error_type();
 13086      }
 13087    return pr->type();
 13088  }
 13089  
 13090  // Check the type.  Just make sure that we trigger the warning in
 13091  // do_type.
 13092  
 13093  void
 13094  Call_result_expression::do_check_types(Gogo*)
 13095  {
 13096    this->type();
 13097  }
 13098  
 13099  // Determine the type.  We have nothing to do here, but the 0 result
 13100  // needs to pass down to the caller.
 13101  
 13102  void
 13103  Call_result_expression::do_determine_type(const Type_context*)
 13104  {
 13105    this->call_->determine_type_no_context();
 13106  }
 13107  
 13108  // Return the backend representation.  We just refer to the temporary set by the
 13109  // call expression.  We don't do this at lowering time because it makes it
 13110  // hard to evaluate the call at the right time.
 13111  
 13112  Bexpression*
 13113  Call_result_expression::do_get_backend(Translate_context* context)
 13114  {
 13115    Call_expression* ce = this->call_->call_expression();
 13116    if (ce == NULL)
 13117      {
 13118        go_assert(this->call_->is_error_expression());
 13119        return context->backend()->error_expression();
 13120      }
 13121    Temporary_statement* ts = ce->results();
 13122    if (ts == NULL)
 13123      {
 13124        go_assert(saw_errors());
 13125        return context->backend()->error_expression();
 13126      }
 13127    Expression* ref = Expression::make_temporary_reference(ts, this->location());
 13128    ref = Expression::make_field_reference(ref, this->index_, this->location());
 13129    return ref->get_backend(context);
 13130  }
 13131  
 13132  // Dump ast representation for a call result expression.
 13133  
 13134  void
 13135  Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 13136      const
 13137  {
 13138    // FIXME: Wouldn't it be better if the call is assigned to a temporary
 13139    // (struct) and the fields are referenced instead.
 13140    ast_dump_context->ostream() << this->index_ << "@(";
 13141    ast_dump_context->dump_expression(this->call_);
 13142    ast_dump_context->ostream() << ")";
 13143  }
 13144  
 13145  // Make a reference to a single result of a call which returns
 13146  // multiple results.
 13147  
 13148  Expression*
 13149  Expression::make_call_result(Call_expression* call, unsigned int index)
 13150  {
 13151    return new Call_result_expression(call, index);
 13152  }
 13153  
 13154  // Class Index_expression.
 13155  
 13156  // Traversal.
 13157  
 13158  int
 13159  Index_expression::do_traverse(Traverse* traverse)
 13160  {
 13161    if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
 13162        || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
 13163        || (this->end_ != NULL
 13164  	  && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
 13165        || (this->cap_ != NULL
 13166            && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
 13167      return TRAVERSE_EXIT;
 13168    return TRAVERSE_CONTINUE;
 13169  }
 13170  
 13171  // Lower an index expression.  This converts the generic index
 13172  // expression into an array index, a string index, or a map index.
 13173  
 13174  Expression*
 13175  Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
 13176  {
 13177    Location location = this->location();
 13178    Expression* left = this->left_;
 13179    Expression* start = this->start_;
 13180    Expression* end = this->end_;
 13181    Expression* cap = this->cap_;
 13182  
 13183    Type* type = left->type();
 13184    if (type->is_error())
 13185      {
 13186        go_assert(saw_errors());
 13187        return Expression::make_error(location);
 13188      }
 13189    else if (left->is_type_expression())
 13190      {
 13191        go_error_at(location, "attempt to index type expression");
 13192        return Expression::make_error(location);
 13193      }
 13194    else if (type->array_type() != NULL)
 13195      return Expression::make_array_index(left, start, end, cap, location);
 13196    else if (type->points_to() != NULL
 13197  	   && type->points_to()->array_type() != NULL
 13198  	   && !type->points_to()->is_slice_type())
 13199      {
 13200        Expression* deref =
 13201            Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
 13202  
 13203        // For an ordinary index into the array, the pointer will be
 13204        // dereferenced.  For a slice it will not--the resulting slice
 13205        // will simply reuse the pointer, which is incorrect if that
 13206        // pointer is nil.
 13207        if (end != NULL || cap != NULL)
 13208  	deref->issue_nil_check();
 13209  
 13210        return Expression::make_array_index(deref, start, end, cap, location);
 13211      }
 13212    else if (type->is_string_type())
 13213      {
 13214        if (cap != NULL)
 13215          {
 13216            go_error_at(location, "invalid 3-index slice of string");
 13217            return Expression::make_error(location);
 13218          }
 13219        return Expression::make_string_index(left, start, end, location);
 13220      }
 13221    else if (type->map_type() != NULL)
 13222      {
 13223        if (end != NULL || cap != NULL)
 13224  	{
 13225  	  go_error_at(location, "invalid slice of map");
 13226  	  return Expression::make_error(location);
 13227  	}
 13228        return Expression::make_map_index(left, start, location);
 13229      }
 13230    else if (cap != NULL)
 13231      {
 13232        go_error_at(location,
 13233  		  "invalid 3-index slice of object that is not a slice");
 13234        return Expression::make_error(location);
 13235      }
 13236    else if (end != NULL)
 13237      {
 13238        go_error_at(location,
 13239  		  ("attempt to slice object that is not "
 13240  		   "array, slice, or string"));
 13241        return Expression::make_error(location);
 13242      }
 13243    else
 13244      {
 13245        go_error_at(location,
 13246                    ("attempt to index object that is not "
 13247  		   "array, slice, string, or map"));
 13248        return Expression::make_error(location);
 13249      }
 13250  }
 13251  
 13252  // Write an indexed expression
 13253  // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
 13254  
 13255  void
 13256  Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
 13257  					const Expression* expr,
 13258  					const Expression* start,
 13259  					const Expression* end,
 13260  					const Expression* cap)
 13261  {
 13262    expr->dump_expression(ast_dump_context);
 13263    ast_dump_context->ostream() << "[";
 13264    start->dump_expression(ast_dump_context);
 13265    if (end != NULL)
 13266      {
 13267        ast_dump_context->ostream() << ":";
 13268        end->dump_expression(ast_dump_context);
 13269      }
 13270    if (cap != NULL)
 13271      {
 13272        ast_dump_context->ostream() << ":";
 13273        cap->dump_expression(ast_dump_context);
 13274      }
 13275    ast_dump_context->ostream() << "]";
 13276  }
 13277  
 13278  // Dump ast representation for an index expression.
 13279  
 13280  void
 13281  Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 13282      const
 13283  {
 13284    Index_expression::dump_index_expression(ast_dump_context, this->left_,
 13285                                            this->start_, this->end_, this->cap_);
 13286  }
 13287  
 13288  // Make an index expression.
 13289  
 13290  Expression*
 13291  Expression::make_index(Expression* left, Expression* start, Expression* end,
 13292  		       Expression* cap, Location location)
 13293  {
 13294    return new Index_expression(left, start, end, cap, location);
 13295  }
 13296  
 13297  // Class Array_index_expression.
 13298  
 13299  // Array index traversal.
 13300  
 13301  int
 13302  Array_index_expression::do_traverse(Traverse* traverse)
 13303  {
 13304    if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
 13305      return TRAVERSE_EXIT;
 13306    if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
 13307      return TRAVERSE_EXIT;
 13308    if (this->end_ != NULL)
 13309      {
 13310        if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
 13311  	return TRAVERSE_EXIT;
 13312      }
 13313    if (this->cap_ != NULL)
 13314      {
 13315        if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
 13316          return TRAVERSE_EXIT;
 13317      }
 13318    return TRAVERSE_CONTINUE;
 13319  }
 13320  
 13321  // Return the type of an array index.
 13322  
 13323  Type*
 13324  Array_index_expression::do_type()
 13325  {
 13326    if (this->type_ == NULL)
 13327      {
 13328       Array_type* type = this->array_->type()->array_type();
 13329        if (type == NULL)
 13330  	this->type_ = Type::make_error_type();
 13331        else if (this->end_ == NULL)
 13332  	this->type_ = type->element_type();
 13333        else if (type->is_slice_type())
 13334  	{
 13335  	  // A slice of a slice has the same type as the original
 13336  	  // slice.
 13337  	  this->type_ = this->array_->type()->deref();
 13338  	}
 13339        else
 13340  	{
 13341  	  // A slice of an array is a slice.
 13342  	  this->type_ = Type::make_array_type(type->element_type(), NULL);
 13343  	}
 13344      }
 13345    return this->type_;
 13346  }
 13347  
 13348  // Set the type of an array index.
 13349  
 13350  void
 13351  Array_index_expression::do_determine_type(const Type_context*)
 13352  {
 13353    this->array_->determine_type_no_context();
 13354  
 13355    Type_context index_context(Type::lookup_integer_type("int"), false);
 13356    this->start_->determine_type(&index_context);
 13357    if (this->end_ != NULL)
 13358      this->end_->determine_type(&index_context);
 13359    if (this->cap_ != NULL)
 13360      this->cap_->determine_type(&index_context);
 13361  }
 13362  
 13363  // Check types of an array index.
 13364  
 13365  void
 13366  Array_index_expression::do_check_types(Gogo*)
 13367  {
 13368    Numeric_constant nc;
 13369    unsigned long v;
 13370    if (this->start_->type()->integer_type() == NULL
 13371        && !this->start_->type()->is_error()
 13372        && (!this->start_->type()->is_abstract()
 13373  	  || !this->start_->numeric_constant_value(&nc)
 13374  	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
 13375      this->report_error(_("index must be integer"));
 13376    if (this->end_ != NULL
 13377        && this->end_->type()->integer_type() == NULL
 13378        && !this->end_->type()->is_error()
 13379        && !this->end_->is_nil_expression()
 13380        && !this->end_->is_error_expression()
 13381        && (!this->end_->type()->is_abstract()
 13382  	  || !this->end_->numeric_constant_value(&nc)
 13383  	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
 13384      this->report_error(_("slice end must be integer"));
 13385    if (this->cap_ != NULL
 13386        && this->cap_->type()->integer_type() == NULL
 13387        && !this->cap_->type()->is_error()
 13388        && !this->cap_->is_nil_expression()
 13389        && !this->cap_->is_error_expression()
 13390        && (!this->cap_->type()->is_abstract()
 13391  	  || !this->cap_->numeric_constant_value(&nc)
 13392  	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
 13393      this->report_error(_("slice capacity must be integer"));
 13394  
 13395    Array_type* array_type = this->array_->type()->array_type();
 13396    if (array_type == NULL)
 13397      {
 13398        go_assert(this->array_->type()->is_error());
 13399        this->set_is_error();
 13400        return;
 13401      }
 13402  
 13403    unsigned int int_bits =
 13404      Type::lookup_integer_type("int")->integer_type()->bits();
 13405  
 13406    Numeric_constant lvalnc;
 13407    mpz_t lval;
 13408    bool lval_valid = (array_type->length() != NULL
 13409  		     && array_type->length()->numeric_constant_value(&lvalnc)
 13410  		     && lvalnc.to_int(&lval));
 13411    Numeric_constant inc;
 13412    mpz_t ival;
 13413    bool ival_valid = false;
 13414    if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
 13415      {
 13416        ival_valid = true;
 13417        if (mpz_sgn(ival) < 0
 13418  	  || mpz_sizeinbase(ival, 2) >= int_bits
 13419  	  || (lval_valid
 13420  	      && (this->end_ == NULL
 13421  		  ? mpz_cmp(ival, lval) >= 0
 13422  		  : mpz_cmp(ival, lval) > 0)))
 13423  	{
 13424  	  go_error_at(this->start_->location(), "array index out of bounds");
 13425  	  this->set_is_error();
 13426  	}
 13427      }
 13428    if (this->end_ != NULL && !this->end_->is_nil_expression())
 13429      {
 13430        Numeric_constant enc;
 13431        mpz_t eval;
 13432        bool eval_valid = false;
 13433        if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
 13434  	{
 13435  	  eval_valid = true;
 13436  	  if (mpz_sgn(eval) < 0
 13437  	      || mpz_sizeinbase(eval, 2) >= int_bits
 13438  	      || (lval_valid && mpz_cmp(eval, lval) > 0))
 13439  	    {
 13440  	      go_error_at(this->end_->location(), "array index out of bounds");
 13441  	      this->set_is_error();
 13442  	    }
 13443  	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
 13444  	    this->report_error(_("inverted slice range"));
 13445  	}
 13446  
 13447        Numeric_constant cnc;
 13448        mpz_t cval;
 13449        if (this->cap_ != NULL
 13450            && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
 13451          {
 13452            if (mpz_sgn(cval) < 0
 13453                || mpz_sizeinbase(cval, 2) >= int_bits
 13454                || (lval_valid && mpz_cmp(cval, lval) > 0))
 13455              {
 13456                go_error_at(this->cap_->location(), "array index out of bounds");
 13457                this->set_is_error();
 13458              }
 13459  	  else if (ival_valid && mpz_cmp(ival, cval) > 0)
 13460  	    {
 13461  	      go_error_at(this->cap_->location(),
 13462                            "invalid slice index: capacity less than start");
 13463  	      this->set_is_error();
 13464  	    }
 13465            else if (eval_valid && mpz_cmp(eval, cval) > 0)
 13466              {
 13467                go_error_at(this->cap_->location(),
 13468                            "invalid slice index: capacity less than length");
 13469                this->set_is_error();
 13470              }
 13471            mpz_clear(cval);
 13472          }
 13473  
 13474        if (eval_valid)
 13475          mpz_clear(eval);
 13476      }
 13477    if (ival_valid)
 13478      mpz_clear(ival);
 13479    if (lval_valid)
 13480      mpz_clear(lval);
 13481  
 13482    // A slice of an array requires an addressable array.  A slice of a
 13483    // slice is always possible.
 13484    if (this->end_ != NULL && !array_type->is_slice_type())
 13485      {
 13486        if (!this->array_->is_addressable())
 13487  	this->report_error(_("slice of unaddressable value"));
 13488        else
 13489          // Set the array address taken but not escape. The escape
 13490          // analysis will make it escape to heap when needed.
 13491          this->array_->address_taken(false);
 13492      }
 13493  }
 13494  
 13495  // The subexpressions of an array index must be evaluated in order.
 13496  // If this is indexing into an array, rather than a slice, then only
 13497  // the index should be evaluated.  Since this is called for values on
 13498  // the left hand side of an assigment, evaluating the array, meaning
 13499  // copying the array, will cause a different array to be modified.
 13500  
 13501  bool
 13502  Array_index_expression::do_must_eval_subexpressions_in_order(
 13503      int* skip) const
 13504  {
 13505    *skip = this->array_->type()->is_slice_type() ? 0 : 1;
 13506    return true;
 13507  }
 13508  
 13509  // Flatten array indexing: add temporary variables and bounds checks.
 13510  
 13511  Expression*
 13512  Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
 13513                                     Statement_inserter* inserter)
 13514  {
 13515    if (this->is_flattened_)
 13516      return this;
 13517    this->is_flattened_ = true;
 13518  
 13519    Location loc = this->location();
 13520  
 13521    if (this->is_error_expression())
 13522      return Expression::make_error(loc);
 13523  
 13524    Expression* array = this->array_;
 13525    Expression* start = this->start_;
 13526    Expression* end = this->end_;
 13527    Expression* cap = this->cap_;
 13528    if (array->is_error_expression()
 13529        || array->type()->is_error_type()
 13530        || start->is_error_expression()
 13531        || start->type()->is_error_type()
 13532        || (end != NULL
 13533            && (end->is_error_expression() || end->type()->is_error_type()))
 13534        || (cap != NULL
 13535            && (cap->is_error_expression() || cap->type()->is_error_type())))
 13536      {
 13537        go_assert(saw_errors());
 13538        return Expression::make_error(loc);
 13539      }
 13540  
 13541    Array_type* array_type = this->array_->type()->array_type();
 13542    if (array_type == NULL)
 13543      {
 13544        go_assert(saw_errors());
 13545        return Expression::make_error(loc);
 13546      }
 13547  
 13548    Temporary_statement* temp;
 13549    if (array_type->is_slice_type() && !array->is_multi_eval_safe())
 13550      {
 13551        temp = Statement::make_temporary(NULL, array, loc);
 13552        inserter->insert(temp);
 13553        this->array_ = Expression::make_temporary_reference(temp, loc);
 13554        array = this->array_;
 13555      }
 13556    if (!start->is_multi_eval_safe())
 13557      {
 13558        temp = Statement::make_temporary(NULL, start, loc);
 13559        inserter->insert(temp);
 13560        this->start_ = Expression::make_temporary_reference(temp, loc);
 13561        start = this->start_;
 13562      }
 13563    if (end != NULL
 13564        && !end->is_nil_expression()
 13565        && !end->is_multi_eval_safe())
 13566      {
 13567        temp = Statement::make_temporary(NULL, end, loc);
 13568        inserter->insert(temp);
 13569        this->end_ = Expression::make_temporary_reference(temp, loc);
 13570        end = this->end_;
 13571      }
 13572    if (cap != NULL && !cap->is_multi_eval_safe())
 13573      {
 13574        temp = Statement::make_temporary(NULL, cap, loc);
 13575        inserter->insert(temp);
 13576        this->cap_ = Expression::make_temporary_reference(temp, loc);
 13577        cap = this->cap_;
 13578      }
 13579  
 13580    if (!this->needs_bounds_check_)
 13581      return this;
 13582  
 13583    Expression* len;
 13584    if (!array_type->is_slice_type())
 13585      {
 13586        len = array_type->get_length(gogo, this->array_);
 13587        go_assert(len->is_constant());
 13588      }
 13589    else
 13590      {
 13591        len = array_type->get_length(gogo, this->array_->copy());
 13592        temp = Statement::make_temporary(NULL, len, loc);
 13593        inserter->insert(temp);
 13594        len = Expression::make_temporary_reference(temp, loc);
 13595      }
 13596  
 13597    Expression* scap = NULL;
 13598    if (array_type->is_slice_type())
 13599      {
 13600        scap = array_type->get_capacity(gogo, this->array_->copy());
 13601        temp = Statement::make_temporary(NULL, scap, loc);
 13602        inserter->insert(temp);
 13603        scap = Expression::make_temporary_reference(temp, loc);
 13604      }
 13605  
 13606    // The order of bounds checks here matches the order used by the gc
 13607    // compiler, as tested by issue30116[u].go.
 13608  
 13609    if (cap != NULL)
 13610      {
 13611        if (array_type->is_slice_type())
 13612  	Expression::check_bounds(cap, OPERATOR_LE, scap,
 13613  				 Runtime::PANIC_SLICE3_ACAP,
 13614  				 Runtime::PANIC_SLICE3_ACAP_U,
 13615  				 Runtime::PANIC_EXTEND_SLICE3_ACAP,
 13616  				 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
 13617  				 inserter, loc);
 13618        else
 13619  	Expression::check_bounds(cap, OPERATOR_LE, len,
 13620  				 Runtime::PANIC_SLICE3_ALEN,
 13621  				 Runtime::PANIC_SLICE3_ALEN_U,
 13622  				 Runtime::PANIC_EXTEND_SLICE3_ALEN,
 13623  				 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
 13624  				 inserter, loc);
 13625  
 13626        Expression* start_bound = cap;
 13627        if (end != NULL && !end->is_nil_expression())
 13628  	{
 13629  	  Expression::check_bounds(end, OPERATOR_LE, cap,
 13630  				   Runtime::PANIC_SLICE3_B,
 13631  				   Runtime::PANIC_SLICE3_B_U,
 13632  				   Runtime::PANIC_EXTEND_SLICE3_B,
 13633  				   Runtime::PANIC_EXTEND_SLICE3_B_U,
 13634  				   inserter, loc);
 13635  	  start_bound = end;
 13636  	}
 13637  
 13638        Expression::check_bounds(start, OPERATOR_LE, start_bound,
 13639  			       Runtime::PANIC_SLICE3_C,
 13640  			       Runtime::PANIC_SLICE3_C_U,
 13641  			       Runtime::PANIC_EXTEND_SLICE3_C,
 13642  			       Runtime::PANIC_EXTEND_SLICE3_C_U,
 13643  			       inserter, loc);
 13644      }
 13645    else if (end != NULL && !end->is_nil_expression())
 13646      {
 13647        if (array_type->is_slice_type())
 13648  	Expression::check_bounds(end, OPERATOR_LE, scap,
 13649  				 Runtime::PANIC_SLICE_ACAP,
 13650  				 Runtime::PANIC_SLICE_ACAP_U,
 13651  				 Runtime::PANIC_EXTEND_SLICE_ACAP,
 13652  				 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
 13653  				 inserter, loc);
 13654        else
 13655  	Expression::check_bounds(end, OPERATOR_LE, len,
 13656  				 Runtime::PANIC_SLICE_ALEN,
 13657  				 Runtime::PANIC_SLICE_ALEN_U,
 13658  				 Runtime::PANIC_EXTEND_SLICE_ALEN,
 13659  				 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
 13660  				 inserter, loc);
 13661  
 13662        Expression::check_bounds(start, OPERATOR_LE, end,
 13663  			       Runtime::PANIC_SLICE_B,
 13664  			       Runtime::PANIC_SLICE_B_U,
 13665  			       Runtime::PANIC_EXTEND_SLICE_B,
 13666  			       Runtime::PANIC_EXTEND_SLICE_B_U,
 13667  			       inserter, loc);
 13668      }
 13669    else if (end != NULL)
 13670      {
 13671        Expression* start_bound;
 13672        if (array_type->is_slice_type())
 13673  	start_bound = scap;
 13674        else
 13675  	start_bound = len;
 13676        Expression::check_bounds(start, OPERATOR_LE, start_bound,
 13677  			       Runtime::PANIC_SLICE_B,
 13678  			       Runtime::PANIC_SLICE_B_U,
 13679  			       Runtime::PANIC_EXTEND_SLICE_B,
 13680  			       Runtime::PANIC_EXTEND_SLICE_B_U,
 13681  			       inserter, loc);
 13682      }
 13683    else
 13684      Expression::check_bounds(start, OPERATOR_LT, len,
 13685  			     Runtime::PANIC_INDEX,
 13686  			     Runtime::PANIC_INDEX_U,
 13687  			     Runtime::PANIC_EXTEND_INDEX,
 13688  			     Runtime::PANIC_EXTEND_INDEX_U,
 13689  			     inserter, loc);
 13690  
 13691    return this;
 13692  }
 13693  
 13694  // Return whether this expression is addressable.
 13695  
 13696  bool
 13697  Array_index_expression::do_is_addressable() const
 13698  {
 13699    // A slice expression is not addressable.
 13700    if (this->end_ != NULL)
 13701      return false;
 13702  
 13703    // An index into a slice is addressable.
 13704    if (this->array_->type()->is_slice_type())
 13705      return true;
 13706  
 13707    // An index into an array is addressable if the array is
 13708    // addressable.
 13709    return this->array_->is_addressable();
 13710  }
 13711  
 13712  void
 13713  Array_index_expression::do_address_taken(bool escapes)
 13714  {
 13715    // In &x[0], if x is a slice, then x's address is not taken.
 13716    if (!this->array_->type()->is_slice_type())
 13717      this->array_->address_taken(escapes);
 13718  }
 13719  
 13720  // Get the backend representation for an array index.
 13721  
 13722  Bexpression*
 13723  Array_index_expression::do_get_backend(Translate_context* context)
 13724  {
 13725    Array_type* array_type = this->array_->type()->array_type();
 13726    if (array_type == NULL)
 13727      {
 13728        go_assert(this->array_->type()->is_error());
 13729        return context->backend()->error_expression();
 13730      }
 13731    go_assert(!array_type->is_slice_type()
 13732  	    || this->array_->is_multi_eval_safe());
 13733  
 13734    Location loc = this->location();
 13735    Gogo* gogo = context->gogo();
 13736  
 13737    Type* int_type = Type::lookup_integer_type("int");
 13738    Btype* int_btype = int_type->get_backend(gogo);
 13739  
 13740    // Convert the length and capacity to "int".  FIXME: Do we need to
 13741    // do this?
 13742    Bexpression* length = NULL;
 13743    if (this->end_ == NULL || this->end_->is_nil_expression())
 13744      {
 13745        Expression* len = array_type->get_length(gogo, this->array_);
 13746        length = len->get_backend(context);
 13747        length = gogo->backend()->convert_expression(int_btype, length, loc);
 13748      }
 13749  
 13750    Bexpression* capacity = NULL;
 13751    if (this->end_ != NULL)
 13752      {
 13753        Expression* cap = array_type->get_capacity(gogo, this->array_);
 13754        capacity = cap->get_backend(context);
 13755        capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
 13756      }
 13757  
 13758    Bexpression* cap_arg = capacity;
 13759    if (this->cap_ != NULL)
 13760      {
 13761        cap_arg = this->cap_->get_backend(context);
 13762        cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
 13763      }
 13764  
 13765    if (length == NULL)
 13766      length = cap_arg;
 13767  
 13768    if (this->start_->type()->integer_type() == NULL
 13769        && !Type::are_convertible(int_type, this->start_->type(), NULL))
 13770      {
 13771        go_assert(saw_errors());
 13772        return context->backend()->error_expression();
 13773      }
 13774  
 13775    Bexpression* start = this->start_->get_backend(context);
 13776    start = gogo->backend()->convert_expression(int_btype, start, loc);
 13777  
 13778    Bfunction* bfn = context->function()->func_value()->get_decl();
 13779    if (this->end_ == NULL)
 13780      {
 13781        // Simple array indexing.
 13782        Bexpression* ret;
 13783        if (!array_type->is_slice_type())
 13784  	{
 13785  	  Bexpression* array = this->array_->get_backend(context);
 13786  	  ret = gogo->backend()->array_index_expression(array, start, loc);
 13787  	}
 13788        else
 13789  	{
 13790  	  Expression* valptr = array_type->get_value_pointer(gogo,
 13791  							     this->array_);
 13792  	  Bexpression* ptr = valptr->get_backend(context);
 13793            ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
 13794  
 13795  	  Type* ele_type = this->array_->type()->array_type()->element_type();
 13796  	  Btype* ele_btype = ele_type->get_backend(gogo);
 13797  	  ret = gogo->backend()->indirect_expression(ele_btype, ptr, false,
 13798  						     loc);
 13799  	}
 13800        return ret;
 13801      }
 13802  
 13803    // Slice expression.
 13804  
 13805    Bexpression* end;
 13806    if (this->end_->is_nil_expression())
 13807      end = length;
 13808    else
 13809      {
 13810        end = this->end_->get_backend(context);
 13811        end = gogo->backend()->convert_expression(int_btype, end, loc);
 13812      }
 13813  
 13814    Bexpression* result_length =
 13815      gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
 13816  
 13817    Bexpression* result_capacity =
 13818      gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
 13819  
 13820    // If the new capacity is zero, don't change val.  Otherwise we can
 13821    // get a pointer to the next object in memory, keeping it live
 13822    // unnecessarily.  When the capacity is zero, the actual pointer
 13823    // value doesn't matter.
 13824    Bexpression* zero =
 13825      Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
 13826    Bexpression* cond =
 13827      gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
 13828  				       loc);
 13829    Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
 13830  								cond, zero,
 13831  								start, loc);
 13832    Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
 13833    Bexpression* val = valptr->get_backend(context);
 13834    val = gogo->backend()->pointer_offset_expression(val, offset, loc);
 13835  
 13836    Btype* struct_btype = this->type()->get_backend(gogo);
 13837    std::vector<Bexpression*> init;
 13838    init.push_back(val);
 13839    init.push_back(result_length);
 13840    init.push_back(result_capacity);
 13841  
 13842    return gogo->backend()->constructor_expression(struct_btype, init, loc);
 13843  }
 13844  
 13845  // Export an array index expression.
 13846  
 13847  void
 13848  Array_index_expression::do_export(Export_function_body* efb) const
 13849  {
 13850    efb->write_c_string("(");
 13851    this->array_->export_expression(efb);
 13852    efb->write_c_string(")[");
 13853  
 13854    Type* old_context = efb->type_context();
 13855    efb->set_type_context(Type::lookup_integer_type("int"));
 13856  
 13857    this->start_->export_expression(efb);
 13858    if (this->end_ == NULL)
 13859      go_assert(this->cap_ == NULL);
 13860    else
 13861      {
 13862        efb->write_c_string(":");
 13863        if (!this->end_->is_nil_expression())
 13864  	this->end_->export_expression(efb);
 13865        if (this->cap_ != NULL)
 13866  	{
 13867  	  efb->write_c_string(":");
 13868  	  this->cap_->export_expression(efb);
 13869  	}
 13870      }
 13871  
 13872    efb->set_type_context(old_context);
 13873  
 13874    efb->write_c_string("]");
 13875  }
 13876  
 13877  // Dump ast representation for an array index expression.
 13878  
 13879  void
 13880  Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 13881      const
 13882  {
 13883    Index_expression::dump_index_expression(ast_dump_context, this->array_,
 13884                                            this->start_, this->end_, this->cap_);
 13885  }
 13886  
 13887  // Make an array index expression.  END and CAP may be NULL.
 13888  
 13889  Expression*
 13890  Expression::make_array_index(Expression* array, Expression* start,
 13891                               Expression* end, Expression* cap,
 13892                               Location location)
 13893  {
 13894    return new Array_index_expression(array, start, end, cap, location);
 13895  }
 13896  
 13897  // Class String_index_expression.
 13898  
 13899  // String index traversal.
 13900  
 13901  int
 13902  String_index_expression::do_traverse(Traverse* traverse)
 13903  {
 13904    if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
 13905      return TRAVERSE_EXIT;
 13906    if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
 13907      return TRAVERSE_EXIT;
 13908    if (this->end_ != NULL)
 13909      {
 13910        if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
 13911  	return TRAVERSE_EXIT;
 13912      }
 13913    return TRAVERSE_CONTINUE;
 13914  }
 13915  
 13916  Expression*
 13917  String_index_expression::do_flatten(Gogo*, Named_object*,
 13918                                      Statement_inserter* inserter)
 13919  {
 13920    if (this->is_flattened_)
 13921      return this;
 13922    this->is_flattened_ = true;
 13923  
 13924    Location loc = this->location();
 13925  
 13926    if (this->is_error_expression())
 13927      return Expression::make_error(loc);
 13928  
 13929    Expression* string = this->string_;
 13930    Expression* start = this->start_;
 13931    Expression* end = this->end_;
 13932    if (string->is_error_expression()
 13933        || string->type()->is_error_type()
 13934        || start->is_error_expression()
 13935        || start->type()->is_error_type()
 13936        || (end != NULL
 13937            && (end->is_error_expression() || end->type()->is_error_type())))
 13938      {
 13939        go_assert(saw_errors());
 13940        return Expression::make_error(loc);
 13941      }
 13942  
 13943    Temporary_statement* temp;
 13944    if (!string->is_multi_eval_safe())
 13945      {
 13946        temp = Statement::make_temporary(NULL, string, loc);
 13947        inserter->insert(temp);
 13948        this->string_ = Expression::make_temporary_reference(temp, loc);
 13949        string = this->string_;
 13950      }
 13951    if (!start->is_multi_eval_safe())
 13952      {
 13953        temp = Statement::make_temporary(NULL, start, loc);
 13954        inserter->insert(temp);
 13955        this->start_ = Expression::make_temporary_reference(temp, loc);
 13956        start = this->start_;
 13957      }
 13958    if (end != NULL
 13959        && !end->is_nil_expression()
 13960        && !end->is_multi_eval_safe())
 13961      {
 13962        temp = Statement::make_temporary(NULL, end, loc);
 13963        inserter->insert(temp);
 13964        this->end_ = Expression::make_temporary_reference(temp, loc);
 13965        end = this->end_;
 13966      }
 13967  
 13968    Expression* len = Expression::make_string_info(string->copy(),
 13969  						 STRING_INFO_LENGTH, loc);
 13970    temp = Statement::make_temporary(NULL, len, loc);
 13971    inserter->insert(temp);
 13972    len = Expression::make_temporary_reference(temp, loc);
 13973  
 13974    // The order of bounds checks here matches the order used by the gc
 13975    // compiler, as tested by issue30116[u].go.
 13976  
 13977    if (end != NULL && !end->is_nil_expression())
 13978      {
 13979        Expression::check_bounds(end, OPERATOR_LE, len,
 13980  			       Runtime::PANIC_SLICE_ALEN,
 13981  			       Runtime::PANIC_SLICE_ALEN_U,
 13982  			       Runtime::PANIC_EXTEND_SLICE_ALEN,
 13983  			       Runtime::PANIC_EXTEND_SLICE_ALEN_U,
 13984  			       inserter, loc);
 13985        Expression::check_bounds(start, OPERATOR_LE, end,
 13986  			       Runtime::PANIC_SLICE_B,
 13987  			       Runtime::PANIC_SLICE_B_U,
 13988  			       Runtime::PANIC_EXTEND_SLICE_B,
 13989  			       Runtime::PANIC_EXTEND_SLICE_B_U,
 13990  			       inserter, loc);
 13991      }
 13992    else if (end != NULL)
 13993      Expression::check_bounds(start, OPERATOR_LE, len,
 13994  			     Runtime::PANIC_SLICE_B,
 13995  			     Runtime::PANIC_SLICE_B_U,
 13996  			     Runtime::PANIC_EXTEND_SLICE_B,
 13997  			     Runtime::PANIC_EXTEND_SLICE_B_U,
 13998  			     inserter, loc);
 13999    else
 14000      Expression::check_bounds(start, OPERATOR_LT, len,
 14001  			     Runtime::PANIC_INDEX,
 14002  			     Runtime::PANIC_INDEX_U,
 14003  			     Runtime::PANIC_EXTEND_INDEX,
 14004  			     Runtime::PANIC_EXTEND_INDEX_U,
 14005  			     inserter, loc);
 14006  
 14007    return this;
 14008  }
 14009  
 14010  // Return the type of a string index.
 14011  
 14012  Type*
 14013  String_index_expression::do_type()
 14014  {
 14015    if (this->end_ == NULL)
 14016      return Type::lookup_integer_type("byte");
 14017    else
 14018      return this->string_->type();
 14019  }
 14020  
 14021  // Determine the type of a string index.
 14022  
 14023  void
 14024  String_index_expression::do_determine_type(const Type_context*)
 14025  {
 14026    this->string_->determine_type_no_context();
 14027  
 14028    Type_context index_context(Type::lookup_integer_type("int"), false);
 14029    this->start_->determine_type(&index_context);
 14030    if (this->end_ != NULL)
 14031      this->end_->determine_type(&index_context);
 14032  }
 14033  
 14034  // Check types of a string index.
 14035  
 14036  void
 14037  String_index_expression::do_check_types(Gogo*)
 14038  {
 14039    Numeric_constant nc;
 14040    unsigned long v;
 14041    if (this->start_->type()->integer_type() == NULL
 14042        && !this->start_->type()->is_error()
 14043        && (!this->start_->type()->is_abstract()
 14044  	  || !this->start_->numeric_constant_value(&nc)
 14045  	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
 14046      this->report_error(_("index must be integer"));
 14047    if (this->end_ != NULL
 14048        && this->end_->type()->integer_type() == NULL
 14049        && !this->end_->type()->is_error()
 14050        && !this->end_->is_nil_expression()
 14051        && !this->end_->is_error_expression()
 14052        && (!this->end_->type()->is_abstract()
 14053  	  || !this->end_->numeric_constant_value(&nc)
 14054  	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
 14055      this->report_error(_("slice end must be integer"));
 14056  
 14057    std::string sval;
 14058    bool sval_valid = this->string_->string_constant_value(&sval);
 14059  
 14060    Numeric_constant inc;
 14061    mpz_t ival;
 14062    bool ival_valid = false;
 14063    if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
 14064      {
 14065        ival_valid = true;
 14066        if (mpz_sgn(ival) < 0
 14067  	  || (sval_valid
 14068  	      && (this->end_ == NULL
 14069  		  ? mpz_cmp_ui(ival, sval.length()) >= 0
 14070  		  : mpz_cmp_ui(ival, sval.length()) > 0)))
 14071  	{
 14072  	  go_error_at(this->start_->location(), "string index out of bounds");
 14073  	  this->set_is_error();
 14074  	}
 14075      }
 14076    if (this->end_ != NULL && !this->end_->is_nil_expression())
 14077      {
 14078        Numeric_constant enc;
 14079        mpz_t eval;
 14080        if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
 14081  	{
 14082  	  if (mpz_sgn(eval) < 0
 14083  	      || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
 14084  	    {
 14085  	      go_error_at(this->end_->location(), "string index out of bounds");
 14086  	      this->set_is_error();
 14087  	    }
 14088  	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
 14089  	    this->report_error(_("inverted slice range"));
 14090  	  mpz_clear(eval);
 14091  	}
 14092      }
 14093    if (ival_valid)
 14094      mpz_clear(ival);
 14095  }
 14096  
 14097  // Get the backend representation for a string index.
 14098  
 14099  Bexpression*
 14100  String_index_expression::do_get_backend(Translate_context* context)
 14101  {
 14102    Location loc = this->location();
 14103    Gogo* gogo = context->gogo();
 14104  
 14105    Type* int_type = Type::lookup_integer_type("int");
 14106  
 14107    // It is possible that an error occurred earlier because the start index
 14108    // cannot be represented as an integer type.  In this case, we shouldn't
 14109    // try casting the starting index into an integer since
 14110    // Type_conversion_expression will fail to get the backend representation.
 14111    // FIXME.
 14112    if (this->start_->type()->integer_type() == NULL
 14113        && !Type::are_convertible(int_type, this->start_->type(), NULL))
 14114      {
 14115        go_assert(saw_errors());
 14116        return context->backend()->error_expression();
 14117      }
 14118  
 14119    go_assert(this->string_->is_multi_eval_safe());
 14120    go_assert(this->start_->is_multi_eval_safe());
 14121  
 14122    Expression* start = Expression::make_cast(int_type, this->start_, loc);
 14123    Bfunction* bfn = context->function()->func_value()->get_decl();
 14124  
 14125    Expression* length =
 14126      Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
 14127    Expression* bytes =
 14128      Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
 14129  
 14130    Bexpression* bstart = start->get_backend(context);
 14131    Bexpression* ptr = bytes->get_backend(context);
 14132  
 14133    if (this->end_ == NULL)
 14134      {
 14135        ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
 14136        Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
 14137        return gogo->backend()->indirect_expression(ubtype, ptr, false, loc);
 14138      }
 14139  
 14140    Expression* end = NULL;
 14141    if (this->end_->is_nil_expression())
 14142      end = length;
 14143    else
 14144      {
 14145        go_assert(this->end_->is_multi_eval_safe());
 14146        end = Expression::make_cast(int_type, this->end_, loc);
 14147      }
 14148  
 14149    end = end->copy();
 14150    Bexpression* bend = end->get_backend(context);
 14151    Bexpression* new_length =
 14152      gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
 14153  
 14154    // If the new length is zero, don't change pointer.  Otherwise we can
 14155    // get a pointer to the next object in memory, keeping it live
 14156    // unnecessarily.  When the length is zero, the actual pointer
 14157    // value doesn't matter.
 14158    Btype* int_btype = int_type->get_backend(gogo);
 14159    Bexpression* zero =
 14160      Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
 14161    Bexpression* cond =
 14162      gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
 14163                                         loc);
 14164    Bexpression* offset =
 14165      gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
 14166                                              bstart, loc);
 14167  
 14168    ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
 14169  
 14170    Btype* str_btype = this->type()->get_backend(gogo);
 14171    std::vector<Bexpression*> init;
 14172    init.push_back(ptr);
 14173    init.push_back(new_length);
 14174    return gogo->backend()->constructor_expression(str_btype, init, loc);
 14175  }
 14176  
 14177  // Export a string index expression.
 14178  
 14179  void
 14180  String_index_expression::do_export(Export_function_body* efb) const
 14181  {
 14182    efb->write_c_string("(");
 14183    this->string_->export_expression(efb);
 14184    efb->write_c_string(")[");
 14185  
 14186    Type* old_context = efb->type_context();
 14187    efb->set_type_context(Type::lookup_integer_type("int"));
 14188  
 14189    this->start_->export_expression(efb);
 14190    if (this->end_ != NULL)
 14191      {
 14192        efb->write_c_string(":");
 14193        if (!this->end_->is_nil_expression())
 14194  	this->end_->export_expression(efb);
 14195      }
 14196  
 14197    efb->set_type_context(old_context);
 14198  
 14199    efb->write_c_string("]");
 14200  }
 14201  
 14202  // Dump ast representation for a string index expression.
 14203  
 14204  void
 14205  String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 14206      const
 14207  {
 14208    Index_expression::dump_index_expression(ast_dump_context, this->string_,
 14209                                            this->start_, this->end_, NULL);
 14210  }
 14211  
 14212  // Make a string index expression.  END may be NULL.
 14213  
 14214  Expression*
 14215  Expression::make_string_index(Expression* string, Expression* start,
 14216  			      Expression* end, Location location)
 14217  {
 14218    return new String_index_expression(string, start, end, location);
 14219  }
 14220  
 14221  // Class Map_index.
 14222  
 14223  // Get the type of the map.
 14224  
 14225  Map_type*
 14226  Map_index_expression::get_map_type() const
 14227  {
 14228    Map_type* mt = this->map_->type()->map_type();
 14229    if (mt == NULL)
 14230      go_assert(saw_errors());
 14231    return mt;
 14232  }
 14233  
 14234  // Map index traversal.
 14235  
 14236  int
 14237  Map_index_expression::do_traverse(Traverse* traverse)
 14238  {
 14239    if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
 14240      return TRAVERSE_EXIT;
 14241    return Expression::traverse(&this->index_, traverse);
 14242  }
 14243  
 14244  // We need to pass in a pointer to the key, so flatten the index into a
 14245  // temporary variable if it isn't already.  The value pointer will be
 14246  // dereferenced and checked for nil, so flatten into a temporary to avoid
 14247  // recomputation.
 14248  
 14249  Expression*
 14250  Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
 14251  				 Statement_inserter* inserter)
 14252  {
 14253    Location loc = this->location();
 14254    Map_type* mt = this->get_map_type();
 14255    if (this->index()->is_error_expression()
 14256        || this->index()->type()->is_error_type()
 14257        || mt->is_error_type())
 14258      {
 14259        go_assert(saw_errors());
 14260        return Expression::make_error(loc);
 14261      }
 14262  
 14263    // Avoid copy for string([]byte) conversions used in map keys.
 14264    // mapaccess doesn't keep the reference, so this is safe.
 14265    Type_conversion_expression* ce = this->index_->conversion_expression();
 14266    if (ce != NULL && ce->type()->is_string_type()
 14267        && ce->expr()->type()->is_slice_type())
 14268      ce->set_no_copy(true);
 14269  
 14270    if (!Type::are_identical(mt->key_type(), this->index_->type(),
 14271  			   Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
 14272  			   NULL))
 14273      {
 14274        if (this->index_->type()->interface_type() != NULL
 14275  	  && !this->index_->is_multi_eval_safe())
 14276  	{
 14277  	  Temporary_statement* temp =
 14278  	    Statement::make_temporary(NULL, this->index_, loc);
 14279  	  inserter->insert(temp);
 14280  	  this->index_ = Expression::make_temporary_reference(temp, loc);
 14281  	}
 14282        this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
 14283  							this->index_, loc);
 14284      }
 14285  
 14286    if (!this->index_->is_multi_eval_safe())
 14287      {
 14288        Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
 14289                                                              loc);
 14290        inserter->insert(temp);
 14291        this->index_ = Expression::make_temporary_reference(temp, loc);
 14292      }
 14293  
 14294    if (this->value_pointer_ == NULL)
 14295      this->get_value_pointer(gogo);
 14296    if (this->value_pointer_->is_error_expression()
 14297        || this->value_pointer_->type()->is_error_type())
 14298      return Expression::make_error(loc);
 14299    if (!this->value_pointer_->is_multi_eval_safe())
 14300      {
 14301        Temporary_statement* temp =
 14302  	Statement::make_temporary(NULL, this->value_pointer_, loc);
 14303        inserter->insert(temp);
 14304        this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
 14305      }
 14306  
 14307    return this;
 14308  }
 14309  
 14310  // Return the type of a map index.
 14311  
 14312  Type*
 14313  Map_index_expression::do_type()
 14314  {
 14315    Map_type* mt = this->get_map_type();
 14316    if (mt == NULL)
 14317      return Type::make_error_type();
 14318    return mt->val_type();
 14319  }
 14320  
 14321  // Fix the type of a map index.
 14322  
 14323  void
 14324  Map_index_expression::do_determine_type(const Type_context*)
 14325  {
 14326    this->map_->determine_type_no_context();
 14327    Map_type* mt = this->get_map_type();
 14328    Type* key_type = mt == NULL ? NULL : mt->key_type();
 14329    Type_context subcontext(key_type, false);
 14330    this->index_->determine_type(&subcontext);
 14331  }
 14332  
 14333  // Check types of a map index.
 14334  
 14335  void
 14336  Map_index_expression::do_check_types(Gogo*)
 14337  {
 14338    std::string reason;
 14339    Map_type* mt = this->get_map_type();
 14340    if (mt == NULL)
 14341      return;
 14342    if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
 14343      {
 14344        if (reason.empty())
 14345  	this->report_error(_("incompatible type for map index"));
 14346        else
 14347  	{
 14348  	  go_error_at(this->location(), "incompatible type for map index (%s)",
 14349                        reason.c_str());
 14350  	  this->set_is_error();
 14351  	}
 14352      }
 14353  }
 14354  
 14355  // Add explicit type conversions.
 14356  
 14357  void
 14358  Map_index_expression::do_add_conversions()
 14359  {
 14360    Map_type* mt = this->get_map_type();
 14361    if (mt == NULL)
 14362      return;
 14363    Type* lt = mt->key_type();
 14364    Type* rt = this->index_->type();
 14365    if (!Type::are_identical(lt, rt, 0, NULL)
 14366        && lt->interface_type() != NULL)
 14367      this->index_ = Expression::make_cast(lt, this->index_, this->location());
 14368  }
 14369  
 14370  // Get the backend representation for a map index.
 14371  
 14372  Bexpression*
 14373  Map_index_expression::do_get_backend(Translate_context* context)
 14374  {
 14375    Map_type* type = this->get_map_type();
 14376    if (type == NULL)
 14377      {
 14378        go_assert(saw_errors());
 14379        return context->backend()->error_expression();
 14380      }
 14381  
 14382    go_assert(this->value_pointer_ != NULL
 14383              && this->value_pointer_->is_multi_eval_safe());
 14384  
 14385    Expression* val = Expression::make_dereference(this->value_pointer_,
 14386                                                   NIL_CHECK_NOT_NEEDED,
 14387                                                   this->location());
 14388    return val->get_backend(context);
 14389  }
 14390  
 14391  // Get an expression for the map index.  This returns an expression
 14392  // that evaluates to a pointer to a value.  If the key is not in the
 14393  // map, the pointer will point to a zero value.
 14394  
 14395  Expression*
 14396  Map_index_expression::get_value_pointer(Gogo* gogo)
 14397  {
 14398    if (this->value_pointer_ == NULL)
 14399      {
 14400        Map_type* type = this->get_map_type();
 14401        if (type == NULL)
 14402  	{
 14403  	  go_assert(saw_errors());
 14404  	  return Expression::make_error(this->location());
 14405  	}
 14406  
 14407        Location loc = this->location();
 14408        Expression* map_ref = this->map_;
 14409  
 14410        Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
 14411  						     this->index_,
 14412                                                       loc);
 14413  
 14414        Expression* type_expr = Expression::make_type_descriptor(type, loc);
 14415        Expression* zero = type->fat_zero_value(gogo);
 14416        Expression* map_index;
 14417        if (zero == NULL)
 14418          {
 14419            Runtime::Function code;
 14420            Expression* key;
 14421            switch (type->algorithm(gogo))
 14422              {
 14423                case Map_type::MAP_ALG_FAST32:
 14424                case Map_type::MAP_ALG_FAST32PTR:
 14425                  {
 14426                    Type* uint32_type = Type::lookup_integer_type("uint32");
 14427                    Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
 14428                    key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
 14429                                                       loc);
 14430                    key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
 14431                                                       loc);
 14432                    code = Runtime::MAPACCESS1_FAST32;
 14433                    break;
 14434                  }
 14435                case Map_type::MAP_ALG_FAST64:
 14436                case Map_type::MAP_ALG_FAST64PTR:
 14437                  {
 14438                    Type* uint64_type = Type::lookup_integer_type("uint64");
 14439                    Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
 14440                    key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
 14441                                                       loc);
 14442                    key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
 14443                                                       loc);
 14444                    code = Runtime::MAPACCESS1_FAST64;
 14445                    break;
 14446                  }
 14447                case Map_type::MAP_ALG_FASTSTR:
 14448                  key = this->index_;
 14449                  code = Runtime::MAPACCESS1_FASTSTR;
 14450                  break;
 14451                default:
 14452                  key = index_ptr;
 14453                  code = Runtime::MAPACCESS1;
 14454                  break;
 14455              }
 14456            map_index = Runtime::make_call(code, loc, 3,
 14457                                           type_expr, map_ref, key);
 14458          }
 14459        else
 14460          map_index = Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
 14461                                         type_expr, map_ref, index_ptr, zero);
 14462  
 14463        Type* val_type = type->val_type();
 14464        this->value_pointer_ =
 14465            Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
 14466                                         map_index, this->location());
 14467      }
 14468  
 14469    return this->value_pointer_;
 14470  }
 14471  
 14472  // Export a map index expression.
 14473  
 14474  void
 14475  Map_index_expression::do_export(Export_function_body* efb) const
 14476  {
 14477    efb->write_c_string("(");
 14478    this->map_->export_expression(efb);
 14479    efb->write_c_string(")[");
 14480  
 14481    Type* old_context = efb->type_context();
 14482    efb->set_type_context(this->get_map_type()->key_type());
 14483  
 14484    this->index_->export_expression(efb);
 14485  
 14486    efb->set_type_context(old_context);
 14487  
 14488    efb->write_c_string("]");
 14489  }
 14490  
 14491  // Dump ast representation for a map index expression
 14492  
 14493  void
 14494  Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 14495      const
 14496  {
 14497    Index_expression::dump_index_expression(ast_dump_context, this->map_,
 14498                                            this->index_, NULL, NULL);
 14499  }
 14500  
 14501  // Make a map index expression.
 14502  
 14503  Map_index_expression*
 14504  Expression::make_map_index(Expression* map, Expression* index,
 14505  			   Location location)
 14506  {
 14507    return new Map_index_expression(map, index, location);
 14508  }
 14509  
 14510  // Class Field_reference_expression.
 14511  
 14512  // Lower a field reference expression.  There is nothing to lower, but
 14513  // this is where we generate the tracking information for fields with
 14514  // the magic go:"track" tag.
 14515  
 14516  Expression*
 14517  Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
 14518  				     Statement_inserter* inserter, int)
 14519  {
 14520    Struct_type* struct_type = this->expr_->type()->struct_type();
 14521    if (struct_type == NULL)
 14522      {
 14523        // Error will be reported elsewhere.
 14524        return this;
 14525      }
 14526    const Struct_field* field = struct_type->field(this->field_index_);
 14527    if (field == NULL)
 14528      return this;
 14529    if (!field->has_tag())
 14530      return this;
 14531    if (field->tag().find("go:\"track\"") == std::string::npos)
 14532      return this;
 14533  
 14534    // References from functions generated by the compiler don't count.
 14535    if (function != NULL && function->func_value()->is_type_specific_function())
 14536      return this;
 14537  
 14538    // We have found a reference to a tracked field.  Build a call to
 14539    // the runtime function __go_fieldtrack with a string that describes
 14540    // the field.  FIXME: We should only call this once per referenced
 14541    // field per function, not once for each reference to the field.
 14542  
 14543    if (this->called_fieldtrack_)
 14544      return this;
 14545    this->called_fieldtrack_ = true;
 14546  
 14547    Location loc = this->location();
 14548  
 14549    std::string s = "fieldtrack \"";
 14550    Named_type* nt = this->expr_->type()->unalias()->named_type();
 14551    if (nt == NULL || nt->named_object()->package() == NULL)
 14552      s.append(gogo->pkgpath());
 14553    else
 14554      s.append(nt->named_object()->package()->pkgpath());
 14555    s.push_back('.');
 14556    if (nt != NULL)
 14557      s.append(Gogo::unpack_hidden_name(nt->name()));
 14558    s.push_back('.');
 14559    s.append(Gogo::unpack_hidden_name(field->field_name()));
 14560    s.push_back('"');
 14561  
 14562    // We can't use a string here, because internally a string holds a
 14563    // pointer to the actual bytes; when the linker garbage collects the
 14564    // string, it won't garbage collect the bytes.  So we use a
 14565    // [...]byte.
 14566  
 14567    Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
 14568  
 14569    Type* byte_type = Type::lookup_integer_type("byte");
 14570    Array_type* array_type = Type::make_array_type(byte_type, length_expr);
 14571    array_type->set_is_array_incomparable();
 14572  
 14573    Expression_list* bytes = new Expression_list();
 14574    for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
 14575      {
 14576        unsigned char c = static_cast<unsigned char>(*p);
 14577        bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
 14578      }
 14579  
 14580    Expression* e = Expression::make_composite_literal(array_type, 0, false,
 14581  						     bytes, false, loc);
 14582  
 14583    Variable* var = new Variable(array_type, e, true, false, false, loc);
 14584  
 14585    static int count;
 14586    char buf[50];
 14587    snprintf(buf, sizeof buf, "fieldtrack.%d", count);
 14588    ++count;
 14589  
 14590    Named_object* no = gogo->add_variable(buf, var);
 14591    e = Expression::make_var_reference(no, loc);
 14592    e = Expression::make_unary(OPERATOR_AND, e, loc);
 14593  
 14594    Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
 14595    gogo->lower_expression(function, inserter, &call);
 14596    inserter->insert(Statement::make_statement(call, false));
 14597  
 14598    // Put this function, and the global variable we just created, into
 14599    // unique sections.  This will permit the linker to garbage collect
 14600    // them if they are not referenced.  The effect is that the only
 14601    // strings, indicating field references, that will wind up in the
 14602    // executable will be those for functions that are actually needed.
 14603    if (function != NULL)
 14604      function->func_value()->set_in_unique_section();
 14605    var->set_in_unique_section();
 14606  
 14607    return this;
 14608  }
 14609  
 14610  // Return the type of a field reference.
 14611  
 14612  Type*
 14613  Field_reference_expression::do_type()
 14614  {
 14615    Type* type = this->expr_->type();
 14616    if (type->is_error())
 14617      return type;
 14618    Struct_type* struct_type = type->struct_type();
 14619    go_assert(struct_type != NULL);
 14620    return struct_type->field(this->field_index_)->type();
 14621  }
 14622  
 14623  // Check the types for a field reference.
 14624  
 14625  void
 14626  Field_reference_expression::do_check_types(Gogo*)
 14627  {
 14628    Type* type = this->expr_->type();
 14629    if (type->is_error())
 14630      return;
 14631    Struct_type* struct_type = type->struct_type();
 14632    go_assert(struct_type != NULL);
 14633    go_assert(struct_type->field(this->field_index_) != NULL);
 14634  }
 14635  
 14636  // Get the backend representation for a field reference.
 14637  
 14638  Bexpression*
 14639  Field_reference_expression::do_get_backend(Translate_context* context)
 14640  {
 14641    Bexpression* bstruct = this->expr_->get_backend(context);
 14642    return context->gogo()->backend()->struct_field_expression(bstruct,
 14643  							     this->field_index_,
 14644  							     this->location());
 14645  }
 14646  
 14647  // Dump ast representation for a field reference expression.
 14648  
 14649  void
 14650  Field_reference_expression::do_dump_expression(
 14651      Ast_dump_context* ast_dump_context) const
 14652  {
 14653    this->expr_->dump_expression(ast_dump_context);
 14654    ast_dump_context->ostream() << "." <<  this->field_index_;
 14655  }
 14656  
 14657  // Make a reference to a qualified identifier in an expression.
 14658  
 14659  Field_reference_expression*
 14660  Expression::make_field_reference(Expression* expr, unsigned int field_index,
 14661  				 Location location)
 14662  {
 14663    return new Field_reference_expression(expr, field_index, location);
 14664  }
 14665  
 14666  // Class Interface_field_reference_expression.
 14667  
 14668  // Return an expression for the pointer to the function to call.
 14669  
 14670  Expression*
 14671  Interface_field_reference_expression::get_function()
 14672  {
 14673    Expression* ref = this->expr_;
 14674    Location loc = this->location();
 14675    if (ref->type()->points_to() != NULL)
 14676      ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
 14677  
 14678    Expression* mtable =
 14679        Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
 14680    Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
 14681  
 14682    std::string name = Gogo::unpack_hidden_name(this->name_);
 14683    unsigned int index;
 14684    const Struct_field* field = mtable_type->find_local_field(name, &index);
 14685    go_assert(field != NULL);
 14686  
 14687    mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
 14688    return Expression::make_field_reference(mtable, index, loc);
 14689  }
 14690  
 14691  // Return an expression for the first argument to pass to the interface
 14692  // function.
 14693  
 14694  Expression*
 14695  Interface_field_reference_expression::get_underlying_object()
 14696  {
 14697    Expression* expr = this->expr_;
 14698    if (expr->type()->points_to() != NULL)
 14699      expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
 14700                                          this->location());
 14701    return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
 14702                                           this->location());
 14703  }
 14704  
 14705  // Traversal.
 14706  
 14707  int
 14708  Interface_field_reference_expression::do_traverse(Traverse* traverse)
 14709  {
 14710    return Expression::traverse(&this->expr_, traverse);
 14711  }
 14712  
 14713  // Lower the expression.  If this expression is not called, we need to
 14714  // evaluate the expression twice when converting to the backend
 14715  // interface.  So introduce a temporary variable if necessary.
 14716  
 14717  Expression*
 14718  Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
 14719  						 Statement_inserter* inserter)
 14720  {
 14721    if (this->expr_->is_error_expression()
 14722        || this->expr_->type()->is_error_type())
 14723      {
 14724        go_assert(saw_errors());
 14725        return Expression::make_error(this->location());
 14726      }
 14727  
 14728    if (!this->expr_->is_multi_eval_safe())
 14729      {
 14730        Temporary_statement* temp =
 14731  	Statement::make_temporary(NULL, this->expr_, this->location());
 14732        inserter->insert(temp);
 14733        this->expr_ = Expression::make_temporary_reference(temp, this->location());
 14734      }
 14735    return this;
 14736  }
 14737  
 14738  // Return the type of an interface field reference.
 14739  
 14740  Type*
 14741  Interface_field_reference_expression::do_type()
 14742  {
 14743    Type* expr_type = this->expr_->type();
 14744  
 14745    Type* points_to = expr_type->points_to();
 14746    if (points_to != NULL)
 14747      expr_type = points_to;
 14748  
 14749    Interface_type* interface_type = expr_type->interface_type();
 14750    if (interface_type == NULL)
 14751      return Type::make_error_type();
 14752  
 14753    const Typed_identifier* method = interface_type->find_method(this->name_);
 14754    if (method == NULL)
 14755      return Type::make_error_type();
 14756  
 14757    return method->type();
 14758  }
 14759  
 14760  // Determine types.
 14761  
 14762  void
 14763  Interface_field_reference_expression::do_determine_type(const Type_context*)
 14764  {
 14765    this->expr_->determine_type_no_context();
 14766  }
 14767  
 14768  // Check the types for an interface field reference.
 14769  
 14770  void
 14771  Interface_field_reference_expression::do_check_types(Gogo*)
 14772  {
 14773    Type* type = this->expr_->type();
 14774  
 14775    Type* points_to = type->points_to();
 14776    if (points_to != NULL)
 14777      type = points_to;
 14778  
 14779    Interface_type* interface_type = type->interface_type();
 14780    if (interface_type == NULL)
 14781      {
 14782        if (!type->is_error_type())
 14783  	this->report_error(_("expected interface or pointer to interface"));
 14784      }
 14785    else
 14786      {
 14787        const Typed_identifier* method =
 14788  	interface_type->find_method(this->name_);
 14789        if (method == NULL)
 14790  	{
 14791  	  go_error_at(this->location(), "method %qs not in interface",
 14792                        Gogo::message_name(this->name_).c_str());
 14793  	  this->set_is_error();
 14794  	}
 14795      }
 14796  }
 14797  
 14798  // If an interface field reference is not simply called, then it is
 14799  // represented as a closure.  The closure will hold a single variable,
 14800  // the value of the interface on which the method should be called.
 14801  // The function will be a simple thunk that pulls the value from the
 14802  // closure and calls the method with the remaining arguments.
 14803  
 14804  // Because method values are not common, we don't build all thunks for
 14805  // all possible interface methods, but instead only build them as we
 14806  // need them.  In particular, we even build them on demand for
 14807  // interface methods defined in other packages.
 14808  
 14809  Interface_field_reference_expression::Interface_method_thunks
 14810    Interface_field_reference_expression::interface_method_thunks;
 14811  
 14812  // Find or create the thunk to call method NAME on TYPE.
 14813  
 14814  Named_object*
 14815  Interface_field_reference_expression::create_thunk(Gogo* gogo,
 14816  						   Interface_type* type,
 14817  						   const std::string& name)
 14818  {
 14819    std::pair<Interface_type*, Method_thunks*> val(type, NULL);
 14820    std::pair<Interface_method_thunks::iterator, bool> ins =
 14821      Interface_field_reference_expression::interface_method_thunks.insert(val);
 14822    if (ins.second)
 14823      {
 14824        // This is the first time we have seen this interface.
 14825        ins.first->second = new Method_thunks();
 14826      }
 14827  
 14828    for (Method_thunks::const_iterator p = ins.first->second->begin();
 14829         p != ins.first->second->end();
 14830         p++)
 14831      if (p->first == name)
 14832        return p->second;
 14833  
 14834    Location loc = type->location();
 14835  
 14836    const Typed_identifier* method_id = type->find_method(name);
 14837    if (method_id == NULL)
 14838      return Named_object::make_erroneous_name(gogo->thunk_name());
 14839  
 14840    Function_type* orig_fntype = method_id->type()->function_type();
 14841    if (orig_fntype == NULL)
 14842      return Named_object::make_erroneous_name(gogo->thunk_name());
 14843  
 14844    Struct_field_list* sfl = new Struct_field_list();
 14845    // The type here is wrong--it should be the C function type.  But it
 14846    // doesn't really matter.
 14847    Type* vt = Type::make_pointer_type(Type::make_void_type());
 14848    sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
 14849    sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
 14850    Struct_type* st = Type::make_struct_type(sfl, loc);
 14851    st->set_is_struct_incomparable();
 14852    Type* closure_type = Type::make_pointer_type(st);
 14853  
 14854    Function_type* new_fntype = orig_fntype->copy_with_names();
 14855  
 14856    std::string thunk_name = gogo->thunk_name();
 14857    Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
 14858  					      false, loc);
 14859  
 14860    Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
 14861    cvar->set_is_used();
 14862    cvar->set_is_closure();
 14863    Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
 14864  						 NULL, cvar);
 14865    new_no->func_value()->set_closure_var(cp);
 14866  
 14867    gogo->start_block(loc);
 14868  
 14869    // Field 0 of the closure is the function code pointer, field 1 is
 14870    // the value on which to invoke the method.
 14871    Expression* arg = Expression::make_var_reference(cp, loc);
 14872    arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
 14873    arg = Expression::make_field_reference(arg, 1, loc);
 14874  
 14875    Expression *ifre = Expression::make_interface_field_reference(arg, name,
 14876  								loc);
 14877  
 14878    const Typed_identifier_list* orig_params = orig_fntype->parameters();
 14879    Expression_list* args;
 14880    if (orig_params == NULL || orig_params->empty())
 14881      args = NULL;
 14882    else
 14883      {
 14884        const Typed_identifier_list* new_params = new_fntype->parameters();
 14885        args = new Expression_list();
 14886        for (Typed_identifier_list::const_iterator p = new_params->begin();
 14887  	   p != new_params->end();
 14888  	   ++p)
 14889  	{
 14890  	  Named_object* p_no = gogo->lookup(p->name(), NULL);
 14891  	  go_assert(p_no != NULL
 14892  		    && p_no->is_variable()
 14893  		    && p_no->var_value()->is_parameter());
 14894  	  args->push_back(Expression::make_var_reference(p_no, loc));
 14895  	}
 14896      }
 14897  
 14898    Call_expression* call = Expression::make_call(ifre, args,
 14899  						orig_fntype->is_varargs(),
 14900  						loc);
 14901    call->set_varargs_are_lowered();
 14902  
 14903    Statement* s = Statement::make_return_from_call(call, loc);
 14904    gogo->add_statement(s);
 14905    Block* b = gogo->finish_block(loc);
 14906    gogo->add_block(b, loc);
 14907  
 14908    // This is called after lowering but before determine_types.
 14909    gogo->lower_block(new_no, b);
 14910  
 14911    gogo->finish_function(loc);
 14912  
 14913    ins.first->second->push_back(std::make_pair(name, new_no));
 14914    return new_no;
 14915  }
 14916  
 14917  // Lookup a thunk to call method NAME on TYPE.
 14918  
 14919  Named_object*
 14920  Interface_field_reference_expression::lookup_thunk(Interface_type* type,
 14921  						   const std::string& name)
 14922  {
 14923    Interface_method_thunks::const_iterator p =
 14924      Interface_field_reference_expression::interface_method_thunks.find(type);
 14925    if (p == Interface_field_reference_expression::interface_method_thunks.end())
 14926      return NULL;
 14927    for (Method_thunks::const_iterator pm = p->second->begin();
 14928         pm != p->second->end();
 14929         ++pm)
 14930      if (pm->first == name)
 14931        return pm->second;
 14932    return NULL;
 14933  }
 14934  
 14935  // Get the backend representation for a method value.
 14936  
 14937  Bexpression*
 14938  Interface_field_reference_expression::do_get_backend(Translate_context* context)
 14939  {
 14940    Interface_type* type = this->expr_->type()->interface_type();
 14941    if (type == NULL)
 14942      {
 14943        go_assert(saw_errors());
 14944        return context->backend()->error_expression();
 14945      }
 14946  
 14947    Named_object* thunk =
 14948      Interface_field_reference_expression::lookup_thunk(type, this->name_);
 14949  
 14950    // The thunk should have been created during the
 14951    // create_function_descriptors pass.
 14952    if (thunk == NULL || thunk->is_erroneous())
 14953      {
 14954        go_assert(saw_errors());
 14955        return context->backend()->error_expression();
 14956      }
 14957  
 14958    // FIXME: We should lower this earlier, but we can't it lower it in
 14959    // the lowering pass because at that point we don't know whether we
 14960    // need to create the thunk or not.  If the expression is called, we
 14961    // don't need the thunk.
 14962  
 14963    Location loc = this->location();
 14964  
 14965    Struct_field_list* fields = new Struct_field_list();
 14966    fields->push_back(Struct_field(Typed_identifier("fn",
 14967  						  thunk->func_value()->type(),
 14968  						  loc)));
 14969    fields->push_back(Struct_field(Typed_identifier("val",
 14970  						  this->expr_->type(),
 14971  						  loc)));
 14972    Struct_type* st = Type::make_struct_type(fields, loc);
 14973    st->set_is_struct_incomparable();
 14974  
 14975    Expression_list* vals = new Expression_list();
 14976    vals->push_back(Expression::make_func_code_reference(thunk, loc));
 14977    vals->push_back(this->expr_);
 14978  
 14979    Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
 14980    Bexpression* bclosure =
 14981      Expression::make_heap_expression(expr, loc)->get_backend(context);
 14982  
 14983    Gogo* gogo = context->gogo();
 14984    Btype* btype = this->type()->get_backend(gogo);
 14985    bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
 14986  
 14987    Expression* nil_check =
 14988        Expression::make_binary(OPERATOR_EQEQ, this->expr_,
 14989                                Expression::make_nil(loc), loc);
 14990    Bexpression* bnil_check = nil_check->get_backend(context);
 14991  
 14992    Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
 14993    Bexpression* bcrash = crash->get_backend(context);
 14994  
 14995    Bfunction* bfn = context->function()->func_value()->get_decl();
 14996    Bexpression* bcond =
 14997        gogo->backend()->conditional_expression(bfn, NULL,
 14998                                                bnil_check, bcrash, NULL, loc);
 14999    Bfunction* bfunction = context->function()->func_value()->get_decl();
 15000    Bstatement* cond_statement =
 15001        gogo->backend()->expression_statement(bfunction, bcond);
 15002    return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
 15003  }
 15004  
 15005  // Dump ast representation for an interface field reference.
 15006  
 15007  void
 15008  Interface_field_reference_expression::do_dump_expression(
 15009      Ast_dump_context* ast_dump_context) const
 15010  {
 15011    this->expr_->dump_expression(ast_dump_context);
 15012    ast_dump_context->ostream() << "." << this->name_;
 15013  }
 15014  
 15015  // Make a reference to a field in an interface.
 15016  
 15017  Expression*
 15018  Expression::make_interface_field_reference(Expression* expr,
 15019  					   const std::string& field,
 15020  					   Location location)
 15021  {
 15022    return new Interface_field_reference_expression(expr, field, location);
 15023  }
 15024  
 15025  // A general selector.  This is a Parser_expression for LEFT.NAME.  It
 15026  // is lowered after we know the type of the left hand side.
 15027  
 15028  class Selector_expression : public Parser_expression
 15029  {
 15030   public:
 15031    Selector_expression(Expression* left, const std::string& name,
 15032  		      Location location)
 15033      : Parser_expression(EXPRESSION_SELECTOR, location),
 15034        left_(left), name_(name)
 15035    { }
 15036  
 15037   protected:
 15038    int
 15039    do_traverse(Traverse* traverse)
 15040    { return Expression::traverse(&this->left_, traverse); }
 15041  
 15042    Expression*
 15043    do_lower(Gogo*, Named_object*, Statement_inserter*, int);
 15044  
 15045    Expression*
 15046    do_copy()
 15047    {
 15048      return new Selector_expression(this->left_->copy(), this->name_,
 15049  				   this->location());
 15050    }
 15051  
 15052    void
 15053    do_dump_expression(Ast_dump_context* ast_dump_context) const;
 15054  
 15055   private:
 15056    Expression*
 15057    lower_method_expression(Gogo*);
 15058  
 15059    // The expression on the left hand side.
 15060    Expression* left_;
 15061    // The name on the right hand side.
 15062    std::string name_;
 15063  };
 15064  
 15065  // Lower a selector expression once we know the real type of the left
 15066  // hand side.
 15067  
 15068  Expression*
 15069  Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
 15070  			      int)
 15071  {
 15072    Expression* left = this->left_;
 15073    if (left->is_type_expression())
 15074      return this->lower_method_expression(gogo);
 15075    return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
 15076  				    this->location());
 15077  }
 15078  
 15079  // Lower a method expression T.M or (*T).M.  We turn this into a
 15080  // function literal.
 15081  
 15082  Expression*
 15083  Selector_expression::lower_method_expression(Gogo* gogo)
 15084  {
 15085    Location location = this->location();
 15086    Type* left_type = this->left_->type();
 15087    Type* type = left_type;
 15088    const std::string& name(this->name_);
 15089  
 15090    bool is_pointer;
 15091    if (type->points_to() == NULL)
 15092      is_pointer = false;
 15093    else
 15094      {
 15095        is_pointer = true;
 15096        type = type->points_to();
 15097      }
 15098  
 15099    Named_type* nt = type->named_type();
 15100    Struct_type* st = type->struct_type();
 15101    bool is_ambiguous;
 15102    Method* method = NULL;
 15103    if (nt != NULL)
 15104      method = nt->method_function(name, &is_ambiguous);
 15105    else if (st != NULL)
 15106      method = st->method_function(name, &is_ambiguous);
 15107    const Typed_identifier* imethod = NULL;
 15108    if (method == NULL && !is_pointer)
 15109      {
 15110        Interface_type* it = type->interface_type();
 15111        if (it != NULL)
 15112  	imethod = it->find_method(name);
 15113      }
 15114  
 15115    if ((method == NULL && imethod == NULL)
 15116        || (left_type->named_type() != NULL && left_type->points_to() != NULL))
 15117      {
 15118        if (nt != NULL)
 15119  	{
 15120  	  if (!is_ambiguous)
 15121  	    go_error_at(location, "type %<%s%s%> has no method %<%s%>",
 15122  			is_pointer ? "*" : "",
 15123  			nt->message_name().c_str(),
 15124  			Gogo::message_name(name).c_str());
 15125  	  else
 15126  	    go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
 15127  			Gogo::message_name(name).c_str(),
 15128  			is_pointer ? "*" : "",
 15129  			nt->message_name().c_str());
 15130  	}
 15131        else
 15132  	{
 15133  	  if (!is_ambiguous)
 15134  	    go_error_at(location, "type has no method %<%s%>",
 15135  			Gogo::message_name(name).c_str());
 15136  	  else
 15137  	    go_error_at(location, "method %<%s%> is ambiguous",
 15138  			Gogo::message_name(name).c_str());
 15139  	}
 15140        return Expression::make_error(location);
 15141      }
 15142  
 15143    if (method != NULL && !is_pointer && !method->is_value_method())
 15144      {
 15145        go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
 15146                    nt->message_name().c_str(),
 15147                    Gogo::message_name(name).c_str());
 15148        return Expression::make_error(location);
 15149      }
 15150  
 15151    // Build a new function type in which the receiver becomes the first
 15152    // argument.
 15153    Function_type* method_type;
 15154    if (method != NULL)
 15155      {
 15156        method_type = method->type();
 15157        go_assert(method_type->is_method());
 15158      }
 15159    else
 15160      {
 15161        method_type = imethod->type()->function_type();
 15162        go_assert(method_type != NULL && !method_type->is_method());
 15163      }
 15164  
 15165    const char* const receiver_name = "$this";
 15166    Typed_identifier_list* parameters = new Typed_identifier_list();
 15167    parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
 15168  					 location));
 15169  
 15170    const Typed_identifier_list* method_parameters = method_type->parameters();
 15171    if (method_parameters != NULL)
 15172      {
 15173        int i = 0;
 15174        for (Typed_identifier_list::const_iterator p = method_parameters->begin();
 15175  	   p != method_parameters->end();
 15176  	   ++p, ++i)
 15177  	{
 15178  	  if (!p->name().empty() && !Gogo::is_sink_name(p->name()))
 15179  	    parameters->push_back(*p);
 15180  	  else
 15181  	    {
 15182  	      char buf[20];
 15183  	      snprintf(buf, sizeof buf, "$param%d", i);
 15184  	      parameters->push_back(Typed_identifier(buf, p->type(),
 15185  						     p->location()));
 15186  	    }
 15187  	}
 15188      }
 15189  
 15190    const Typed_identifier_list* method_results = method_type->results();
 15191    Typed_identifier_list* results;
 15192    if (method_results == NULL)
 15193      results = NULL;
 15194    else
 15195      {
 15196        results = new Typed_identifier_list();
 15197        for (Typed_identifier_list::const_iterator p = method_results->begin();
 15198  	   p != method_results->end();
 15199  	   ++p)
 15200  	results->push_back(*p);
 15201      }
 15202  
 15203    Function_type* fntype = Type::make_function_type(NULL, parameters, results,
 15204  						   location);
 15205    if (method_type->is_varargs())
 15206      fntype->set_is_varargs();
 15207  
 15208    // We generate methods which always takes a pointer to the receiver
 15209    // as their first argument.  If this is for a pointer type, we can
 15210    // simply reuse the existing function.  We use an internal hack to
 15211    // get the right type.
 15212    // FIXME: This optimization is disabled because it doesn't yet work
 15213    // with function descriptors when the method expression is not
 15214    // directly called.
 15215    if (method != NULL && is_pointer && false)
 15216      {
 15217        Named_object* mno = (method->needs_stub_method()
 15218  			   ? method->stub_object()
 15219  			   : method->named_object());
 15220        Expression* f = Expression::make_func_reference(mno, NULL, location);
 15221        f = Expression::make_cast(fntype, f, location);
 15222        Type_conversion_expression* tce =
 15223  	static_cast<Type_conversion_expression*>(f);
 15224        tce->set_may_convert_function_types();
 15225        return f;
 15226      }
 15227  
 15228    Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
 15229  					  location);
 15230  
 15231    Named_object* vno = gogo->lookup(receiver_name, NULL);
 15232    go_assert(vno != NULL);
 15233    Expression* ve = Expression::make_var_reference(vno, location);
 15234    Expression* bm;
 15235    if (method != NULL)
 15236      bm = Type::bind_field_or_method(gogo, type, ve, name, location);
 15237    else
 15238      bm = Expression::make_interface_field_reference(ve, name, location);
 15239  
 15240    // Even though we found the method above, if it has an error type we
 15241    // may see an error here.
 15242    if (bm->is_error_expression())
 15243      {
 15244        gogo->finish_function(location);
 15245        return bm;
 15246      }
 15247  
 15248    Expression_list* args;
 15249    if (parameters->size() <= 1)
 15250      args = NULL;
 15251    else
 15252      {
 15253        args = new Expression_list();
 15254        Typed_identifier_list::const_iterator p = parameters->begin();
 15255        ++p;
 15256        for (; p != parameters->end(); ++p)
 15257  	{
 15258  	  vno = gogo->lookup(p->name(), NULL);
 15259  	  go_assert(vno != NULL);
 15260  	  args->push_back(Expression::make_var_reference(vno, location));
 15261  	}
 15262      }
 15263  
 15264    gogo->start_block(location);
 15265  
 15266    Call_expression* call = Expression::make_call(bm, args,
 15267  						method_type->is_varargs(),
 15268  						location);
 15269  
 15270    Statement* s = Statement::make_return_from_call(call, location);
 15271    gogo->add_statement(s);
 15272  
 15273    Block* b = gogo->finish_block(location);
 15274  
 15275    gogo->add_block(b, location);
 15276  
 15277    // Lower the call in case there are multiple results.
 15278    gogo->lower_block(no, b);
 15279    gogo->flatten_block(no, b);
 15280  
 15281    gogo->finish_function(location);
 15282  
 15283    return Expression::make_func_reference(no, NULL, location);
 15284  }
 15285  
 15286  // Dump the ast for a selector expression.
 15287  
 15288  void
 15289  Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 15290      const
 15291  {
 15292    ast_dump_context->dump_expression(this->left_);
 15293    ast_dump_context->ostream() << ".";
 15294    ast_dump_context->ostream() << this->name_;
 15295  }
 15296  
 15297  // Make a selector expression.
 15298  
 15299  Expression*
 15300  Expression::make_selector(Expression* left, const std::string& name,
 15301  			  Location location)
 15302  {
 15303    return new Selector_expression(left, name, location);
 15304  }
 15305  
 15306  // Class Allocation_expression.
 15307  
 15308  int
 15309  Allocation_expression::do_traverse(Traverse* traverse)
 15310  {
 15311    return Type::traverse(this->type_, traverse);
 15312  }
 15313  
 15314  Type*
 15315  Allocation_expression::do_type()
 15316  {
 15317    return Type::make_pointer_type(this->type_);
 15318  }
 15319  
 15320  void
 15321  Allocation_expression::do_check_types(Gogo*)
 15322  {
 15323    if (!this->type_->in_heap())
 15324      go_error_at(this->location(), "cannot heap allocate go:notinheap type");
 15325  }
 15326  
 15327  // Make a copy of an allocation expression.
 15328  
 15329  Expression*
 15330  Allocation_expression::do_copy()
 15331  {
 15332    Allocation_expression* alloc =
 15333      new Allocation_expression(this->type_->copy_expressions(),
 15334  			      this->location());
 15335    if (this->allocate_on_stack_)
 15336      alloc->set_allocate_on_stack();
 15337    if (this->no_zero_)
 15338      alloc->set_no_zero();
 15339    return alloc;
 15340  }
 15341  
 15342  // Return the backend representation for an allocation expression.
 15343  
 15344  Bexpression*
 15345  Allocation_expression::do_get_backend(Translate_context* context)
 15346  {
 15347    Gogo* gogo = context->gogo();
 15348    Location loc = this->location();
 15349    Btype* btype = this->type_->get_backend(gogo);
 15350  
 15351    if (this->allocate_on_stack_)
 15352      {
 15353        int64_t size;
 15354        bool ok = this->type_->backend_type_size(gogo, &size);
 15355        if (!ok)
 15356          {
 15357            go_assert(saw_errors());
 15358            return gogo->backend()->error_expression();
 15359          }
 15360        Bstatement* decl;
 15361        Named_object* fn = context->function();
 15362        go_assert(fn != NULL);
 15363        Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
 15364        Bexpression* init = (this->no_zero_
 15365                             ? NULL
 15366                             : gogo->backend()->zero_expression(btype));
 15367        Bvariable* temp =
 15368          gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
 15369                                              init,
 15370  					    Backend::variable_address_is_taken,
 15371  					    loc, &decl);
 15372        Bexpression* ret = gogo->backend()->var_expression(temp, loc);
 15373        ret = gogo->backend()->address_expression(ret, loc);
 15374        ret = gogo->backend()->compound_expression(decl, ret, loc);
 15375        return ret;
 15376      }
 15377  
 15378    Bexpression* space =
 15379      gogo->allocate_memory(this->type_, loc)->get_backend(context);
 15380    Btype* pbtype = gogo->backend()->pointer_type(btype);
 15381    return gogo->backend()->convert_expression(pbtype, space, loc);
 15382  }
 15383  
 15384  // Dump ast representation for an allocation expression.
 15385  
 15386  void
 15387  Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 15388      const
 15389  {
 15390    ast_dump_context->ostream() << "new(";
 15391    ast_dump_context->dump_type(this->type_);
 15392    ast_dump_context->ostream() << ")";
 15393  }
 15394  
 15395  // Make an allocation expression.
 15396  
 15397  Expression*
 15398  Expression::make_allocation(Type* type, Location location)
 15399  {
 15400    return new Allocation_expression(type, location);
 15401  }
 15402  
 15403  // Class Ordered_value_list.
 15404  
 15405  int
 15406  Ordered_value_list::traverse_vals(Traverse* traverse)
 15407  {
 15408    if (this->vals_ != NULL)
 15409      {
 15410        if (this->traverse_order_ == NULL)
 15411  	{
 15412  	  if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
 15413  	    return TRAVERSE_EXIT;
 15414  	}
 15415        else
 15416  	{
 15417  	  for (std::vector<unsigned long>::const_iterator p =
 15418  		   this->traverse_order_->begin();
 15419  	       p != this->traverse_order_->end();
 15420  	       ++p)
 15421  	    {
 15422  	      if (Expression::traverse(&this->vals_->at(*p), traverse)
 15423  		  == TRAVERSE_EXIT)
 15424  		return TRAVERSE_EXIT;
 15425  	    }
 15426  	}
 15427      }
 15428    return TRAVERSE_CONTINUE;
 15429  }
 15430  
 15431  // Class Struct_construction_expression.
 15432  
 15433  // Traversal.
 15434  
 15435  int
 15436  Struct_construction_expression::do_traverse(Traverse* traverse)
 15437  {
 15438    if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
 15439      return TRAVERSE_EXIT;
 15440    if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 15441      return TRAVERSE_EXIT;
 15442    return TRAVERSE_CONTINUE;
 15443  }
 15444  
 15445  // Return whether this is a constant initializer.
 15446  
 15447  bool
 15448  Struct_construction_expression::is_constant_struct() const
 15449  {
 15450    if (this->vals() == NULL)
 15451      return true;
 15452    for (Expression_list::const_iterator pv = this->vals()->begin();
 15453         pv != this->vals()->end();
 15454         ++pv)
 15455      {
 15456        if (*pv != NULL
 15457  	  && !(*pv)->is_constant()
 15458  	  && (!(*pv)->is_composite_literal()
 15459  	      || (*pv)->is_nonconstant_composite_literal()))
 15460  	return false;
 15461      }
 15462  
 15463    const Struct_field_list* fields = this->type_->struct_type()->fields();
 15464    for (Struct_field_list::const_iterator pf = fields->begin();
 15465         pf != fields->end();
 15466         ++pf)
 15467      {
 15468        // There are no constant constructors for interfaces.
 15469        if (pf->type()->interface_type() != NULL)
 15470  	return false;
 15471      }
 15472  
 15473    return true;
 15474  }
 15475  
 15476  // Return whether this is a zero value.
 15477  
 15478  bool
 15479  Struct_construction_expression::do_is_zero_value() const
 15480  {
 15481    if (this->vals() == NULL)
 15482      return true;
 15483    for (Expression_list::const_iterator pv = this->vals()->begin();
 15484         pv != this->vals()->end();
 15485         ++pv)
 15486      if (*pv != NULL && !(*pv)->is_zero_value())
 15487        return false;
 15488  
 15489    const Struct_field_list* fields = this->type_->struct_type()->fields();
 15490    for (Struct_field_list::const_iterator pf = fields->begin();
 15491         pf != fields->end();
 15492         ++pf)
 15493      {
 15494        // Interface conversion may cause a zero value being converted
 15495        // to a non-zero value, like interface{}(0).  Be conservative.
 15496        if (pf->type()->interface_type() != NULL)
 15497          return false;
 15498      }
 15499  
 15500    return true;
 15501  }
 15502  
 15503  // Return whether this struct can be used as a constant initializer.
 15504  
 15505  bool
 15506  Struct_construction_expression::do_is_static_initializer() const
 15507  {
 15508    if (this->vals() == NULL)
 15509      return true;
 15510    for (Expression_list::const_iterator pv = this->vals()->begin();
 15511         pv != this->vals()->end();
 15512         ++pv)
 15513      {
 15514        if (*pv != NULL && !(*pv)->is_static_initializer())
 15515  	return false;
 15516      }
 15517  
 15518    const Struct_field_list* fields = this->type_->struct_type()->fields();
 15519    for (Struct_field_list::const_iterator pf = fields->begin();
 15520         pf != fields->end();
 15521         ++pf)
 15522      {
 15523        // There are no constant constructors for interfaces.
 15524        if (pf->type()->interface_type() != NULL)
 15525  	return false;
 15526      }
 15527  
 15528    return true;
 15529  }
 15530  
 15531  // Final type determination.
 15532  
 15533  void
 15534  Struct_construction_expression::do_determine_type(const Type_context*)
 15535  {
 15536    if (this->vals() == NULL)
 15537      return;
 15538    const Struct_field_list* fields = this->type_->struct_type()->fields();
 15539    Expression_list::const_iterator pv = this->vals()->begin();
 15540    for (Struct_field_list::const_iterator pf = fields->begin();
 15541         pf != fields->end();
 15542         ++pf, ++pv)
 15543      {
 15544        if (pv == this->vals()->end())
 15545  	return;
 15546        if (*pv != NULL)
 15547  	{
 15548  	  Type_context subcontext(pf->type(), false);
 15549  	  (*pv)->determine_type(&subcontext);
 15550  	}
 15551      }
 15552    // Extra values are an error we will report elsewhere; we still want
 15553    // to determine the type to avoid knockon errors.
 15554    for (; pv != this->vals()->end(); ++pv)
 15555      (*pv)->determine_type_no_context();
 15556  }
 15557  
 15558  // Check types.
 15559  
 15560  void
 15561  Struct_construction_expression::do_check_types(Gogo*)
 15562  {
 15563    if (this->vals() == NULL)
 15564      return;
 15565  
 15566    Struct_type* st = this->type_->struct_type();
 15567    if (this->vals()->size() > st->field_count())
 15568      {
 15569        this->report_error(_("too many expressions for struct"));
 15570        return;
 15571      }
 15572  
 15573    const Struct_field_list* fields = st->fields();
 15574    Expression_list::const_iterator pv = this->vals()->begin();
 15575    int i = 0;
 15576    for (Struct_field_list::const_iterator pf = fields->begin();
 15577         pf != fields->end();
 15578         ++pf, ++pv, ++i)
 15579      {
 15580        if (pv == this->vals()->end())
 15581  	{
 15582  	  this->report_error(_("too few expressions for struct"));
 15583  	  break;
 15584  	}
 15585  
 15586        if (*pv == NULL)
 15587  	continue;
 15588  
 15589        std::string reason;
 15590        if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
 15591  	{
 15592  	  if (reason.empty())
 15593  	    go_error_at((*pv)->location(),
 15594                          "incompatible type for field %d in struct construction",
 15595                          i + 1);
 15596  	  else
 15597  	    go_error_at((*pv)->location(),
 15598                          ("incompatible type for field %d in "
 15599                           "struct construction (%s)"),
 15600                          i + 1, reason.c_str());
 15601  	  this->set_is_error();
 15602  	}
 15603      }
 15604    go_assert(pv == this->vals()->end());
 15605  }
 15606  
 15607  // Copy.
 15608  
 15609  Expression*
 15610  Struct_construction_expression::do_copy()
 15611  {
 15612    Struct_construction_expression* ret =
 15613      new Struct_construction_expression(this->type_->copy_expressions(),
 15614  				       (this->vals() == NULL
 15615  					? NULL
 15616  					: this->vals()->copy()),
 15617  				       this->location());
 15618    if (this->traverse_order() != NULL)
 15619      ret->set_traverse_order(this->traverse_order());
 15620    return ret;
 15621  }
 15622  
 15623  // Make implicit type conversions explicit.
 15624  
 15625  void
 15626  Struct_construction_expression::do_add_conversions()
 15627  {
 15628    if (this->vals() == NULL)
 15629      return;
 15630  
 15631    Location loc = this->location();
 15632    const Struct_field_list* fields = this->type_->struct_type()->fields();
 15633    Expression_list::iterator pv = this->vals()->begin();
 15634    for (Struct_field_list::const_iterator pf = fields->begin();
 15635         pf != fields->end();
 15636         ++pf, ++pv)
 15637      {
 15638        if (pv == this->vals()->end())
 15639          break;
 15640        if (*pv != NULL)
 15641          {
 15642            Type* ft = pf->type();
 15643            if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
 15644                && ft->interface_type() != NULL)
 15645             *pv = Expression::make_cast(ft, *pv, loc);
 15646          }
 15647      }
 15648  }
 15649  
 15650  // Return the backend representation for constructing a struct.
 15651  
 15652  Bexpression*
 15653  Struct_construction_expression::do_get_backend(Translate_context* context)
 15654  {
 15655    Gogo* gogo = context->gogo();
 15656  
 15657    Btype* btype = this->type_->get_backend(gogo);
 15658    if (this->vals() == NULL)
 15659      return gogo->backend()->zero_expression(btype);
 15660  
 15661    const Struct_field_list* fields = this->type_->struct_type()->fields();
 15662    Expression_list::const_iterator pv = this->vals()->begin();
 15663    std::vector<Bexpression*> init;
 15664    for (Struct_field_list::const_iterator pf = fields->begin();
 15665         pf != fields->end();
 15666         ++pf)
 15667      {
 15668        Btype* fbtype = pf->type()->get_backend(gogo);
 15669        if (pv == this->vals()->end())
 15670          init.push_back(gogo->backend()->zero_expression(fbtype));
 15671        else if (*pv == NULL)
 15672  	{
 15673            init.push_back(gogo->backend()->zero_expression(fbtype));
 15674  	  ++pv;
 15675  	}
 15676        else
 15677  	{
 15678            Expression* val =
 15679                Expression::convert_for_assignment(gogo, pf->type(),
 15680                                                   *pv, this->location());
 15681            init.push_back(val->get_backend(context));
 15682  	  ++pv;
 15683  	}
 15684      }
 15685    if (this->type_->struct_type()->has_padding())
 15686      {
 15687        // Feed an extra value if there is a padding field.
 15688        Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
 15689        init.push_back(gogo->backend()->zero_expression(fbtype));
 15690      }
 15691    return gogo->backend()->constructor_expression(btype, init, this->location());
 15692  }
 15693  
 15694  // Export a struct construction.
 15695  
 15696  void
 15697  Struct_construction_expression::do_export(Export_function_body* efb) const
 15698  {
 15699    efb->write_c_string("$convert(");
 15700    efb->write_type(this->type_);
 15701    for (Expression_list::const_iterator pv = this->vals()->begin();
 15702         pv != this->vals()->end();
 15703         ++pv)
 15704      {
 15705        efb->write_c_string(", ");
 15706        if (*pv != NULL)
 15707  	(*pv)->export_expression(efb);
 15708      }
 15709    efb->write_c_string(")");
 15710  }
 15711  
 15712  // Dump ast representation of a struct construction expression.
 15713  
 15714  void
 15715  Struct_construction_expression::do_dump_expression(
 15716      Ast_dump_context* ast_dump_context) const
 15717  {
 15718    ast_dump_context->dump_type(this->type_);
 15719    ast_dump_context->ostream() << "{";
 15720    ast_dump_context->dump_expression_list(this->vals());
 15721    ast_dump_context->ostream() << "}";
 15722  }
 15723  
 15724  // Make a struct composite literal.  This used by the thunk code.
 15725  
 15726  Expression*
 15727  Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
 15728  					  Location location)
 15729  {
 15730    go_assert(type->struct_type() != NULL);
 15731    return new Struct_construction_expression(type, vals, location);
 15732  }
 15733  
 15734  // Class Array_construction_expression.
 15735  
 15736  // Traversal.
 15737  
 15738  int
 15739  Array_construction_expression::do_traverse(Traverse* traverse)
 15740  {
 15741    if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
 15742      return TRAVERSE_EXIT;
 15743    if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 15744      return TRAVERSE_EXIT;
 15745    return TRAVERSE_CONTINUE;
 15746  }
 15747  
 15748  // Return whether this is a constant initializer.
 15749  
 15750  bool
 15751  Array_construction_expression::is_constant_array() const
 15752  {
 15753    if (this->vals() == NULL)
 15754      return true;
 15755  
 15756    // There are no constant constructors for interfaces.
 15757    if (this->type_->array_type()->element_type()->interface_type() != NULL)
 15758      return false;
 15759  
 15760    for (Expression_list::const_iterator pv = this->vals()->begin();
 15761         pv != this->vals()->end();
 15762         ++pv)
 15763      {
 15764        if (*pv != NULL
 15765  	  && !(*pv)->is_constant()
 15766  	  && (!(*pv)->is_composite_literal()
 15767  	      || (*pv)->is_nonconstant_composite_literal()))
 15768  	return false;
 15769      }
 15770    return true;
 15771  }
 15772  
 15773  // Return whether this is a zero value.
 15774  
 15775  bool
 15776  Array_construction_expression::do_is_zero_value() const
 15777  {
 15778    if (this->vals() == NULL)
 15779      return true;
 15780  
 15781    // Interface conversion may cause a zero value being converted
 15782    // to a non-zero value, like interface{}(0).  Be conservative.
 15783    if (this->type_->array_type()->element_type()->interface_type() != NULL)
 15784      return false;
 15785  
 15786    for (Expression_list::const_iterator pv = this->vals()->begin();
 15787         pv != this->vals()->end();
 15788         ++pv)
 15789      if (*pv != NULL && !(*pv)->is_zero_value())
 15790        return false;
 15791  
 15792    return true;
 15793  }
 15794  
 15795  // Return whether this can be used a constant initializer.
 15796  
 15797  bool
 15798  Array_construction_expression::do_is_static_initializer() const
 15799  {
 15800    if (this->vals() == NULL)
 15801      return true;
 15802  
 15803    // There are no constant constructors for interfaces.
 15804    if (this->type_->array_type()->element_type()->interface_type() != NULL)
 15805      return false;
 15806  
 15807    for (Expression_list::const_iterator pv = this->vals()->begin();
 15808         pv != this->vals()->end();
 15809         ++pv)
 15810      {
 15811        if (*pv != NULL && !(*pv)->is_static_initializer())
 15812  	return false;
 15813      }
 15814    return true;
 15815  }
 15816  
 15817  // Final type determination.
 15818  
 15819  void
 15820  Array_construction_expression::do_determine_type(const Type_context*)
 15821  {
 15822    if (this->is_error_expression())
 15823      {
 15824        go_assert(saw_errors());
 15825        return;
 15826      }
 15827  
 15828    if (this->vals() == NULL)
 15829      return;
 15830    Array_type* at = this->type_->array_type();
 15831    if (at == NULL || at->is_error() || at->element_type()->is_error())
 15832      {
 15833        go_assert(saw_errors());
 15834        this->set_is_error();
 15835        return;
 15836      }
 15837    Type_context subcontext(at->element_type(), false);
 15838    for (Expression_list::const_iterator pv = this->vals()->begin();
 15839         pv != this->vals()->end();
 15840         ++pv)
 15841      {
 15842        if (*pv != NULL)
 15843  	(*pv)->determine_type(&subcontext);
 15844      }
 15845  }
 15846  
 15847  // Check types.
 15848  
 15849  void
 15850  Array_construction_expression::do_check_types(Gogo*)
 15851  {
 15852    if (this->is_error_expression())
 15853      {
 15854        go_assert(saw_errors());
 15855        return;
 15856      }
 15857  
 15858    if (this->vals() == NULL)
 15859      return;
 15860  
 15861    Array_type* at = this->type_->array_type();
 15862    if (at == NULL || at->is_error() || at->element_type()->is_error())
 15863      {
 15864        go_assert(saw_errors());
 15865        this->set_is_error();
 15866        return;
 15867      }
 15868    int i = 0;
 15869    Type* element_type = at->element_type();
 15870    for (Expression_list::const_iterator pv = this->vals()->begin();
 15871         pv != this->vals()->end();
 15872         ++pv, ++i)
 15873      {
 15874        if (*pv != NULL
 15875  	  && !Type::are_assignable(element_type, (*pv)->type(), NULL))
 15876  	{
 15877  	  go_error_at((*pv)->location(),
 15878                        "incompatible type for element %d in composite literal",
 15879                        i + 1);
 15880  	  this->set_is_error();
 15881  	}
 15882      }
 15883  }
 15884  
 15885  // Make implicit type conversions explicit.
 15886  
 15887  void
 15888  Array_construction_expression::do_add_conversions()
 15889  {
 15890    if (this->is_error_expression())
 15891      {
 15892        go_assert(saw_errors());
 15893        return;
 15894      }
 15895  
 15896    if (this->vals() == NULL)
 15897      return;
 15898  
 15899    Type* et = this->type_->array_type()->element_type();
 15900    if (et->interface_type() == NULL)
 15901      return;
 15902  
 15903    Location loc = this->location();
 15904    for (Expression_list::iterator pv = this->vals()->begin();
 15905         pv != this->vals()->end();
 15906         ++pv)
 15907      if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
 15908        *pv = Expression::make_cast(et, *pv, loc);
 15909  }
 15910  
 15911  // Get a constructor expression for the array values.
 15912  
 15913  Bexpression*
 15914  Array_construction_expression::get_constructor(Translate_context* context,
 15915                                                 Btype* array_btype)
 15916  {
 15917    Type* element_type = this->type_->array_type()->element_type();
 15918  
 15919    std::vector<unsigned long> indexes;
 15920    std::vector<Bexpression*> vals;
 15921    Gogo* gogo = context->gogo();
 15922    if (this->vals() != NULL)
 15923      {
 15924        size_t i = 0;
 15925        std::vector<unsigned long>::const_iterator pi;
 15926        if (this->indexes_ != NULL)
 15927  	pi = this->indexes_->begin();
 15928        for (Expression_list::const_iterator pv = this->vals()->begin();
 15929  	   pv != this->vals()->end();
 15930  	   ++pv, ++i)
 15931  	{
 15932  	  if (this->indexes_ != NULL)
 15933  	    go_assert(pi != this->indexes_->end());
 15934  
 15935  	  if (this->indexes_ == NULL)
 15936  	    indexes.push_back(i);
 15937  	  else
 15938  	    indexes.push_back(*pi);
 15939  	  if (*pv == NULL)
 15940  	    {
 15941  	      Btype* ebtype = element_type->get_backend(gogo);
 15942  	      Bexpression *zv = gogo->backend()->zero_expression(ebtype);
 15943  	      vals.push_back(zv);
 15944  	    }
 15945  	  else
 15946  	    {
 15947                Expression* val_expr =
 15948                    Expression::convert_for_assignment(gogo, element_type, *pv,
 15949                                                       this->location());
 15950  	      vals.push_back(val_expr->get_backend(context));
 15951  	    }
 15952  	  if (this->indexes_ != NULL)
 15953  	    ++pi;
 15954  	}
 15955        if (this->indexes_ != NULL)
 15956  	go_assert(pi == this->indexes_->end());
 15957      }
 15958    return gogo->backend()->array_constructor_expression(array_btype, indexes,
 15959                                                         vals, this->location());
 15960  }
 15961  
 15962  // Export an array construction.
 15963  
 15964  void
 15965  Array_construction_expression::do_export(Export_function_body* efb) const
 15966  {
 15967    efb->write_c_string("$convert(");
 15968    efb->write_type(this->type_);
 15969    if (this->vals() != NULL)
 15970      {
 15971        std::vector<unsigned long>::const_iterator pi;
 15972        if (this->indexes_ != NULL)
 15973  	pi = this->indexes_->begin();
 15974        for (Expression_list::const_iterator pv = this->vals()->begin();
 15975  	   pv != this->vals()->end();
 15976  	   ++pv)
 15977  	{
 15978  	  efb->write_c_string(", ");
 15979  
 15980  	  if (this->indexes_ != NULL)
 15981  	    {
 15982  	      char buf[100];
 15983  	      snprintf(buf, sizeof buf, "%lu", *pi);
 15984  	      efb->write_c_string(buf);
 15985  	      efb->write_c_string(":");
 15986  	    }
 15987  
 15988  	  if (*pv != NULL)
 15989  	    (*pv)->export_expression(efb);
 15990  
 15991  	  if (this->indexes_ != NULL)
 15992  	    ++pi;
 15993  	}
 15994      }
 15995    efb->write_c_string(")");
 15996  }
 15997  
 15998  // Dump ast representation of an array construction expression.
 15999  
 16000  void
 16001  Array_construction_expression::do_dump_expression(
 16002      Ast_dump_context* ast_dump_context) const
 16003  {
 16004    Expression* length = this->type_->array_type()->length();
 16005  
 16006    ast_dump_context->ostream() << "[" ;
 16007    if (length != NULL)
 16008      {
 16009        ast_dump_context->dump_expression(length);
 16010      }
 16011    ast_dump_context->ostream() << "]" ;
 16012    ast_dump_context->dump_type(this->type_);
 16013    this->dump_slice_storage_expression(ast_dump_context);
 16014    ast_dump_context->ostream() << "{" ;
 16015    if (this->indexes_ == NULL)
 16016      ast_dump_context->dump_expression_list(this->vals());
 16017    else
 16018      {
 16019        Expression_list::const_iterator pv = this->vals()->begin();
 16020        for (std::vector<unsigned long>::const_iterator pi =
 16021  	     this->indexes_->begin();
 16022  	   pi != this->indexes_->end();
 16023  	   ++pi, ++pv)
 16024  	{
 16025  	  if (pi != this->indexes_->begin())
 16026  	    ast_dump_context->ostream() << ", ";
 16027  	  ast_dump_context->ostream() << *pi << ':';
 16028  	  ast_dump_context->dump_expression(*pv);
 16029  	}
 16030      }
 16031    ast_dump_context->ostream() << "}" ;
 16032  
 16033  }
 16034  
 16035  // Class Fixed_array_construction_expression.
 16036  
 16037  Fixed_array_construction_expression::Fixed_array_construction_expression(
 16038      Type* type, const std::vector<unsigned long>* indexes,
 16039      Expression_list* vals, Location location)
 16040    : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
 16041  				  type, indexes, vals, location)
 16042  { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
 16043  
 16044  
 16045  // Copy.
 16046  
 16047  Expression*
 16048  Fixed_array_construction_expression::do_copy()
 16049  {
 16050    Type* t = this->type()->copy_expressions();
 16051    return new Fixed_array_construction_expression(t, this->indexes(),
 16052  						 (this->vals() == NULL
 16053  						  ? NULL
 16054  						  : this->vals()->copy()),
 16055  						 this->location());
 16056  }
 16057  
 16058  // Return the backend representation for constructing a fixed array.
 16059  
 16060  Bexpression*
 16061  Fixed_array_construction_expression::do_get_backend(Translate_context* context)
 16062  {
 16063    Type* type = this->type();
 16064    Btype* btype = type->get_backend(context->gogo());
 16065    return this->get_constructor(context, btype);
 16066  }
 16067  
 16068  Expression*
 16069  Expression::make_array_composite_literal(Type* type, Expression_list* vals,
 16070                                           Location location)
 16071  {
 16072    go_assert(type->array_type() != NULL && !type->is_slice_type());
 16073    return new Fixed_array_construction_expression(type, NULL, vals, location);
 16074  }
 16075  
 16076  // Class Slice_construction_expression.
 16077  
 16078  Slice_construction_expression::Slice_construction_expression(
 16079    Type* type, const std::vector<unsigned long>* indexes,
 16080    Expression_list* vals, Location location)
 16081    : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
 16082  				  type, indexes, vals, location),
 16083      valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
 16084      storage_escapes_(true)
 16085  {
 16086    go_assert(type->is_slice_type());
 16087  
 16088    unsigned long lenval;
 16089    Expression* length;
 16090    if (vals == NULL || vals->empty())
 16091      lenval = 0;
 16092    else
 16093      {
 16094        if (this->indexes() == NULL)
 16095  	lenval = vals->size();
 16096        else
 16097  	lenval = indexes->back() + 1;
 16098      }
 16099    Type* int_type = Type::lookup_integer_type("int");
 16100    length = Expression::make_integer_ul(lenval, int_type, location);
 16101    Type* element_type = type->array_type()->element_type();
 16102    Array_type* array_type = Type::make_array_type(element_type, length);
 16103    array_type->set_is_array_incomparable();
 16104    this->valtype_ = array_type;
 16105  }
 16106  
 16107  // Traversal.
 16108  
 16109  int
 16110  Slice_construction_expression::do_traverse(Traverse* traverse)
 16111  {
 16112    if (this->Array_construction_expression::do_traverse(traverse)
 16113        == TRAVERSE_EXIT)
 16114      return TRAVERSE_EXIT;
 16115    if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
 16116      return TRAVERSE_EXIT;
 16117    if (this->array_val_ != NULL
 16118        && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
 16119      return TRAVERSE_EXIT;
 16120    if (this->slice_storage_ != NULL
 16121        && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
 16122      return TRAVERSE_EXIT;
 16123    return TRAVERSE_CONTINUE;
 16124  }
 16125  
 16126  // Helper routine to create fixed array value underlying the slice literal.
 16127  // May be called during flattening, or later during do_get_backend().
 16128  
 16129  Expression*
 16130  Slice_construction_expression::create_array_val()
 16131  {
 16132    Array_type* array_type = this->type()->array_type();
 16133    if (array_type == NULL)
 16134      {
 16135        go_assert(this->type()->is_error());
 16136        return NULL;
 16137      }
 16138  
 16139    Location loc = this->location();
 16140    go_assert(this->valtype_ != NULL);
 16141  
 16142    Expression_list* vals = this->vals();
 16143    return new Fixed_array_construction_expression(
 16144        this->valtype_, this->indexes(), vals, loc);
 16145  }
 16146  
 16147  // If we're previous established that the slice storage does not
 16148  // escape, then create a separate array temp val here for it. We
 16149  // need to do this as part of flattening so as to be able to insert
 16150  // the new temp statement.
 16151  
 16152  Expression*
 16153  Slice_construction_expression::do_flatten(Gogo*, Named_object*,
 16154                                            Statement_inserter* inserter)
 16155  {
 16156    if (this->type()->array_type() == NULL)
 16157      {
 16158        go_assert(saw_errors());
 16159        return Expression::make_error(this->location());
 16160      }
 16161  
 16162    // Create a stack-allocated storage temp if storage won't escape
 16163    if (!this->storage_escapes_
 16164        && this->slice_storage_ == NULL
 16165        && this->element_count() > 0)
 16166      {
 16167        Location loc = this->location();
 16168        this->array_val_ = this->create_array_val();
 16169        go_assert(this->array_val_ != NULL);
 16170        Temporary_statement* temp =
 16171            Statement::make_temporary(this->valtype_, this->array_val_, loc);
 16172        inserter->insert(temp);
 16173        this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
 16174      }
 16175    return this;
 16176  }
 16177  
 16178  // When dumping a slice construction expression that has an explicit
 16179  // storeage temp, emit the temp here (if we don't do this the storage
 16180  // temp appears unused in the AST dump).
 16181  
 16182  void
 16183  Slice_construction_expression::
 16184  dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
 16185  {
 16186    if (this->slice_storage_ == NULL)
 16187      return;
 16188    ast_dump_context->ostream() << "storage=" ;
 16189    ast_dump_context->dump_expression(this->slice_storage_);
 16190  }
 16191  
 16192  // Copy.
 16193  
 16194  Expression*
 16195  Slice_construction_expression::do_copy()
 16196  {
 16197    return new Slice_construction_expression(this->type()->copy_expressions(),
 16198  					   this->indexes(),
 16199  					   (this->vals() == NULL
 16200  					    ? NULL
 16201  					    : this->vals()->copy()),
 16202  					   this->location());
 16203  }
 16204  
 16205  // Return the backend representation for constructing a slice.
 16206  
 16207  Bexpression*
 16208  Slice_construction_expression::do_get_backend(Translate_context* context)
 16209  {
 16210    if (this->array_val_ == NULL)
 16211      this->array_val_ = this->create_array_val();
 16212    if (this->array_val_ == NULL)
 16213      {
 16214        go_assert(this->type()->is_error());
 16215        return context->backend()->error_expression();
 16216      }
 16217  
 16218    Location loc = this->location();
 16219  
 16220    bool is_static_initializer = this->array_val_->is_static_initializer();
 16221  
 16222    // We have to copy the initial values into heap memory if we are in
 16223    // a function or if the values are not constants.
 16224    bool copy_to_heap = context->function() != NULL || !is_static_initializer;
 16225  
 16226    Expression* space;
 16227  
 16228    if (this->slice_storage_ != NULL)
 16229      {
 16230        go_assert(!this->storage_escapes_);
 16231        space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
 16232      }
 16233    else if (!copy_to_heap)
 16234      {
 16235        // The initializer will only run once.
 16236        space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
 16237        space->unary_expression()->set_is_slice_init();
 16238      }
 16239    else
 16240      {
 16241        go_assert(this->storage_escapes_ || this->element_count() == 0);
 16242        space = Expression::make_heap_expression(this->array_val_, loc);
 16243      }
 16244    Array_type* at = this->valtype_->array_type();
 16245    Type* et = at->element_type();
 16246    space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
 16247  				       space, loc);
 16248  
 16249    // Build a constructor for the slice.
 16250    Expression* len = at->length();
 16251    Expression* slice_val =
 16252      Expression::make_slice_value(this->type(), space, len, len, loc);
 16253    return slice_val->get_backend(context);
 16254  }
 16255  
 16256  // Make a slice composite literal.  This is used by the type
 16257  // descriptor code.
 16258  
 16259  Slice_construction_expression*
 16260  Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
 16261  					 Location location)
 16262  {
 16263    go_assert(type->is_slice_type());
 16264    return new Slice_construction_expression(type, NULL, vals, location);
 16265  }
 16266  
 16267  // Class Map_construction_expression.
 16268  
 16269  // Traversal.
 16270  
 16271  int
 16272  Map_construction_expression::do_traverse(Traverse* traverse)
 16273  {
 16274    if (this->vals_ != NULL
 16275        && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
 16276      return TRAVERSE_EXIT;
 16277    if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 16278      return TRAVERSE_EXIT;
 16279    return TRAVERSE_CONTINUE;
 16280  }
 16281  
 16282  // Flatten constructor initializer into a temporary variable since
 16283  // we need to take its address for __go_construct_map.
 16284  
 16285  Expression*
 16286  Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
 16287                                          Statement_inserter* inserter)
 16288  {
 16289    if (!this->is_error_expression()
 16290        && this->vals_ != NULL
 16291        && !this->vals_->empty()
 16292        && this->constructor_temp_ == NULL)
 16293      {
 16294        Map_type* mt = this->type_->map_type();
 16295        Type* key_type = mt->key_type();
 16296        Type* val_type = mt->val_type();
 16297        this->element_type_ = Type::make_builtin_struct_type(2,
 16298                                                             "__key", key_type,
 16299                                                             "__val", val_type);
 16300  
 16301        Expression_list* value_pairs = new Expression_list();
 16302        Location loc = this->location();
 16303  
 16304        size_t i = 0;
 16305        for (Expression_list::const_iterator pv = this->vals_->begin();
 16306             pv != this->vals_->end();
 16307             ++pv, ++i)
 16308          {
 16309            Expression_list* key_value_pair = new Expression_list();
 16310            Expression* key = *pv;
 16311            if (key->is_error_expression() || key->type()->is_error_type())
 16312              {
 16313                go_assert(saw_errors());
 16314                return Expression::make_error(loc);
 16315              }
 16316  	  if (key->type()->interface_type() != NULL
 16317  	      && !key->is_multi_eval_safe())
 16318  	    {
 16319  	      Temporary_statement* temp =
 16320  		Statement::make_temporary(NULL, key, loc);
 16321  	      inserter->insert(temp);
 16322  	      key = Expression::make_temporary_reference(temp, loc);
 16323  	    }
 16324  	  key = Expression::convert_for_assignment(gogo, key_type, key, loc);
 16325  
 16326            ++pv;
 16327            Expression* val = *pv;
 16328            if (val->is_error_expression() || val->type()->is_error_type())
 16329              {
 16330                go_assert(saw_errors());
 16331                return Expression::make_error(loc);
 16332              }
 16333  	  if (val->type()->interface_type() != NULL
 16334  	      && !val->is_multi_eval_safe())
 16335  	    {
 16336  	      Temporary_statement* temp =
 16337  		Statement::make_temporary(NULL, val, loc);
 16338  	      inserter->insert(temp);
 16339  	      val = Expression::make_temporary_reference(temp, loc);
 16340  	    }
 16341  	  val = Expression::convert_for_assignment(gogo, val_type, val, loc);
 16342  
 16343            key_value_pair->push_back(key);
 16344            key_value_pair->push_back(val);
 16345            value_pairs->push_back(
 16346                Expression::make_struct_composite_literal(this->element_type_,
 16347                                                          key_value_pair, loc));
 16348          }
 16349  
 16350        Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
 16351        Array_type* ctor_type =
 16352            Type::make_array_type(this->element_type_, element_count);
 16353        ctor_type->set_is_array_incomparable();
 16354        Expression* constructor =
 16355            new Fixed_array_construction_expression(ctor_type, NULL,
 16356                                                    value_pairs, loc);
 16357  
 16358        this->constructor_temp_ =
 16359            Statement::make_temporary(NULL, constructor, loc);
 16360        constructor->issue_nil_check();
 16361        this->constructor_temp_->set_is_address_taken();
 16362        inserter->insert(this->constructor_temp_);
 16363      }
 16364  
 16365    return this;
 16366  }
 16367  
 16368  // Final type determination.
 16369  
 16370  void
 16371  Map_construction_expression::do_determine_type(const Type_context*)
 16372  {
 16373    if (this->vals_ == NULL)
 16374      return;
 16375  
 16376    Map_type* mt = this->type_->map_type();
 16377    Type_context key_context(mt->key_type(), false);
 16378    Type_context val_context(mt->val_type(), false);
 16379    for (Expression_list::const_iterator pv = this->vals_->begin();
 16380         pv != this->vals_->end();
 16381         ++pv)
 16382      {
 16383        (*pv)->determine_type(&key_context);
 16384        ++pv;
 16385        (*pv)->determine_type(&val_context);
 16386      }
 16387  }
 16388  
 16389  // Check types.
 16390  
 16391  void
 16392  Map_construction_expression::do_check_types(Gogo*)
 16393  {
 16394    if (this->vals_ == NULL)
 16395      return;
 16396  
 16397    Map_type* mt = this->type_->map_type();
 16398    int i = 0;
 16399    Type* key_type = mt->key_type();
 16400    Type* val_type = mt->val_type();
 16401    for (Expression_list::const_iterator pv = this->vals_->begin();
 16402         pv != this->vals_->end();
 16403         ++pv, ++i)
 16404      {
 16405        if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
 16406  	{
 16407  	  go_error_at((*pv)->location(),
 16408                        "incompatible type for element %d key in map construction",
 16409                        i + 1);
 16410  	  this->set_is_error();
 16411  	}
 16412        ++pv;
 16413        if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
 16414  	{
 16415  	  go_error_at((*pv)->location(),
 16416                        ("incompatible type for element %d value "
 16417                         "in map construction"),
 16418  		   i + 1);
 16419  	  this->set_is_error();
 16420  	}
 16421      }
 16422  }
 16423  
 16424  // Copy.
 16425  
 16426  Expression*
 16427  Map_construction_expression::do_copy()
 16428  {
 16429    return new Map_construction_expression(this->type_->copy_expressions(),
 16430  					 (this->vals_ == NULL
 16431  					  ? NULL
 16432  					  : this->vals_->copy()),
 16433  					 this->location());
 16434  }
 16435  
 16436  // Make implicit type conversions explicit.
 16437  
 16438  void
 16439  Map_construction_expression::do_add_conversions()
 16440  {
 16441    if (this->vals_ == NULL || this->vals_->empty())
 16442      return;
 16443  
 16444    Map_type* mt = this->type_->map_type();
 16445    Type* kt = mt->key_type();
 16446    Type* vt = mt->val_type();
 16447    bool key_is_interface = (kt->interface_type() != NULL);
 16448    bool val_is_interface = (vt->interface_type() != NULL);
 16449    if (!key_is_interface && !val_is_interface)
 16450      return;
 16451  
 16452    Location loc = this->location();
 16453    for (Expression_list::iterator pv = this->vals_->begin();
 16454         pv != this->vals_->end();
 16455         ++pv)
 16456      {
 16457        if (key_is_interface &&
 16458            !Type::are_identical(kt, (*pv)->type(), 0, NULL))
 16459          *pv = Expression::make_cast(kt, *pv, loc);
 16460        ++pv;
 16461        if (val_is_interface &&
 16462            !Type::are_identical(vt, (*pv)->type(), 0, NULL))
 16463          *pv = Expression::make_cast(vt, *pv, loc);
 16464      }
 16465  }
 16466  
 16467  // Return the backend representation for constructing a map.
 16468  
 16469  Bexpression*
 16470  Map_construction_expression::do_get_backend(Translate_context* context)
 16471  {
 16472    if (this->is_error_expression())
 16473      return context->backend()->error_expression();
 16474    Location loc = this->location();
 16475  
 16476    size_t i = 0;
 16477    Expression* ventries;
 16478    if (this->vals_ == NULL || this->vals_->empty())
 16479      ventries = Expression::make_nil(loc);
 16480    else
 16481      {
 16482        go_assert(this->constructor_temp_ != NULL);
 16483        i = this->vals_->size() / 2;
 16484  
 16485        Expression* ctor_ref =
 16486            Expression::make_temporary_reference(this->constructor_temp_, loc);
 16487        ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
 16488      }
 16489  
 16490    Map_type* mt = this->type_->map_type();
 16491    if (this->element_type_ == NULL)
 16492        this->element_type_ =
 16493            Type::make_builtin_struct_type(2,
 16494                                           "__key", mt->key_type(),
 16495                                           "__val", mt->val_type());
 16496    Expression* descriptor = Expression::make_type_descriptor(mt, loc);
 16497  
 16498    Type* uintptr_t = Type::lookup_integer_type("uintptr");
 16499    Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
 16500  
 16501    Expression* entry_size =
 16502        Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
 16503  
 16504    unsigned int field_index;
 16505    const Struct_field* valfield =
 16506        this->element_type_->find_local_field("__val", &field_index);
 16507    Expression* val_offset =
 16508        Expression::make_struct_field_offset(this->element_type_, valfield);
 16509  
 16510    Expression* map_ctor =
 16511        Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
 16512                           entry_size, val_offset, ventries);
 16513    return map_ctor->get_backend(context);
 16514  }
 16515  
 16516  // Export an array construction.
 16517  
 16518  void
 16519  Map_construction_expression::do_export(Export_function_body* efb) const
 16520  {
 16521    efb->write_c_string("$convert(");
 16522    efb->write_type(this->type_);
 16523    for (Expression_list::const_iterator pv = this->vals_->begin();
 16524         pv != this->vals_->end();
 16525         ++pv)
 16526      {
 16527        efb->write_c_string(", ");
 16528        (*pv)->export_expression(efb);
 16529      }
 16530    efb->write_c_string(")");
 16531  }
 16532  
 16533  // Dump ast representation for a map construction expression.
 16534  
 16535  void
 16536  Map_construction_expression::do_dump_expression(
 16537      Ast_dump_context* ast_dump_context) const
 16538  {
 16539    ast_dump_context->ostream() << "{" ;
 16540    ast_dump_context->dump_expression_list(this->vals_, true);
 16541    ast_dump_context->ostream() << "}";
 16542  }
 16543  
 16544  // A composite literal key.  This is seen during parsing, but is not
 16545  // resolved to a named_object in case this is a composite literal of
 16546  // struct type.
 16547  
 16548  class Composite_literal_key_expression : public Parser_expression
 16549  {
 16550   public:
 16551    Composite_literal_key_expression(const std::string& name, Location location)
 16552      : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
 16553        name_(name)
 16554    { }
 16555  
 16556    const std::string&
 16557    name() const
 16558    { return this->name_; }
 16559  
 16560   protected:
 16561    Expression*
 16562    do_lower(Gogo*, Named_object*, Statement_inserter*, int);
 16563  
 16564    Expression*
 16565    do_copy()
 16566    {
 16567      return new Composite_literal_key_expression(this->name_, this->location());
 16568    }
 16569  
 16570    void
 16571    do_dump_expression(Ast_dump_context*) const;
 16572  
 16573   private:
 16574    // The name.
 16575    std::string name_;
 16576  };
 16577  
 16578  // Lower a composite literal key.  We will never get here for keys in
 16579  // composite literals of struct types, because that is prevented by
 16580  // Composite_literal_expression::do_traverse.  So if we do get here,
 16581  // this must be a regular name reference after all.
 16582  
 16583  Expression*
 16584  Composite_literal_key_expression::do_lower(Gogo* gogo, Named_object*,
 16585  					   Statement_inserter*, int)
 16586  {
 16587    Named_object* no = gogo->lookup(this->name_, NULL);
 16588    if (no == NULL)
 16589      {
 16590        // Gogo::lookup doesn't look in the global namespace, and names
 16591        // used in composite literal keys aren't seen by
 16592        // Gogo::define_global_names, so we have to look in the global
 16593        // namespace ourselves.
 16594        no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
 16595        if (no == NULL)
 16596  	{
 16597  	  go_error_at(this->location(), "reference to undefined name %qs",
 16598  		      Gogo::message_name(this->name_).c_str());
 16599  	  return Expression::make_error(this->location());
 16600  	}
 16601      }
 16602    return Expression::make_unknown_reference(no, this->location());
 16603  }
 16604  
 16605  // Dump a composite literal key.
 16606  
 16607  void
 16608  Composite_literal_key_expression::do_dump_expression(
 16609      Ast_dump_context* ast_dump_context) const
 16610  {
 16611    ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
 16612  }
 16613  
 16614  // Make a composite literal key.
 16615  
 16616  Expression*
 16617  Expression::make_composite_literal_key(const std::string& name,
 16618  				       Location location)
 16619  {
 16620    return new Composite_literal_key_expression(name, location);
 16621  }
 16622  
 16623  // Class Composite_literal_expression.
 16624  
 16625  // Traversal.
 16626  
 16627  int
 16628  Composite_literal_expression::do_traverse(Traverse* traverse)
 16629  {
 16630    if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 16631      return TRAVERSE_EXIT;
 16632  
 16633    // If this is a struct composite literal with keys, then the keys
 16634    // are field names, not expressions.  We don't want to traverse them
 16635    // in that case.  If we do, we can give an erroneous error "variable
 16636    // initializer refers to itself."  See bug482.go in the testsuite.
 16637    if (this->has_keys_ && this->vals_ != NULL)
 16638      {
 16639        // The type may not be resolvable at this point.
 16640        Type* type = this->type_;
 16641  
 16642        for (int depth = 0; depth < this->depth_; ++depth)
 16643          {
 16644  	  type = type->deref();
 16645            if (type->array_type() != NULL)
 16646              type = type->array_type()->element_type();
 16647            else if (type->map_type() != NULL)
 16648              {
 16649                if (this->key_path_[depth])
 16650                  type = type->map_type()->key_type();
 16651                else
 16652                  type = type->map_type()->val_type();
 16653              }
 16654            else
 16655              {
 16656                // This error will be reported during lowering.
 16657                return TRAVERSE_CONTINUE;
 16658              }
 16659          }
 16660        type = type->deref();
 16661  
 16662        while (true)
 16663  	{
 16664  	  if (type->classification() == Type::TYPE_NAMED)
 16665  	    type = type->named_type()->real_type();
 16666  	  else if (type->classification() == Type::TYPE_FORWARD)
 16667  	    {
 16668  	      Type* t = type->forwarded();
 16669  	      if (t == type)
 16670  		break;
 16671  	      type = t;
 16672  	    }
 16673  	  else
 16674  	    break;
 16675  	}
 16676  
 16677        if (type->classification() == Type::TYPE_STRUCT)
 16678  	{
 16679  	  Expression_list::iterator p = this->vals_->begin();
 16680  	  while (p != this->vals_->end())
 16681  	    {
 16682  	      // Skip key.
 16683  	      ++p;
 16684  	      go_assert(p != this->vals_->end());
 16685  	      if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
 16686  		return TRAVERSE_EXIT;
 16687  	      ++p;
 16688  	    }
 16689  	  return TRAVERSE_CONTINUE;
 16690  	}
 16691      }
 16692  
 16693    if (this->vals_ != NULL)
 16694      return this->vals_->traverse(traverse);
 16695  
 16696    return TRAVERSE_CONTINUE;
 16697  }
 16698  
 16699  // Lower a generic composite literal into a specific version based on
 16700  // the type.
 16701  
 16702  Expression*
 16703  Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
 16704  				       Statement_inserter* inserter, int)
 16705  {
 16706    Type* type = this->type_;
 16707  
 16708    for (int depth = 0; depth < this->depth_; ++depth)
 16709      {
 16710        type = type->deref();
 16711        if (type->array_type() != NULL)
 16712  	type = type->array_type()->element_type();
 16713        else if (type->map_type() != NULL)
 16714          {
 16715            if (this->key_path_[depth])
 16716              type = type->map_type()->key_type();
 16717            else
 16718              type = type->map_type()->val_type();
 16719          }
 16720        else
 16721  	{
 16722  	  if (!type->is_error())
 16723  	    go_error_at(this->location(),
 16724                          ("may only omit types within composite literals "
 16725                           "of slice, array, or map type"));
 16726  	  return Expression::make_error(this->location());
 16727  	}
 16728      }
 16729  
 16730    Type *pt = type->points_to();
 16731    bool is_pointer = false;
 16732    if (pt != NULL)
 16733      {
 16734        is_pointer = true;
 16735        type = pt;
 16736      }
 16737  
 16738    Expression* ret;
 16739    if (type->is_error())
 16740      return Expression::make_error(this->location());
 16741    else if (type->struct_type() != NULL)
 16742      ret = this->lower_struct(gogo, type);
 16743    else if (type->array_type() != NULL)
 16744      ret = this->lower_array(type);
 16745    else if (type->map_type() != NULL)
 16746      ret = this->lower_map(gogo, function, inserter, type);
 16747    else
 16748      {
 16749        go_error_at(this->location(),
 16750                    ("expected struct, slice, array, or map type "
 16751                     "for composite literal"));
 16752        return Expression::make_error(this->location());
 16753      }
 16754  
 16755    if (is_pointer)
 16756      ret = Expression::make_heap_expression(ret, this->location());
 16757  
 16758    return ret;
 16759  }
 16760  
 16761  // Lower a struct composite literal.
 16762  
 16763  Expression*
 16764  Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
 16765  {
 16766    Location location = this->location();
 16767    Struct_type* st = type->struct_type();
 16768    if (this->vals_ == NULL || !this->has_keys_)
 16769      {
 16770        if (this->vals_ != NULL
 16771  	  && !this->vals_->empty()
 16772  	  && type->named_type() != NULL
 16773  	  && type->named_type()->named_object()->package() != NULL)
 16774  	{
 16775  	  for (Struct_field_list::const_iterator pf = st->fields()->begin();
 16776  	       pf != st->fields()->end();
 16777  	       ++pf)
 16778  	    {
 16779  	      if (Gogo::is_hidden_name(pf->field_name())
 16780  		  || pf->is_embedded_builtin(gogo))
 16781  		go_error_at(this->location(),
 16782                              "assignment of unexported field %qs in %qs literal",
 16783                              Gogo::message_name(pf->field_name()).c_str(),
 16784                              type->named_type()->message_name().c_str());
 16785  	    }
 16786  	}
 16787  
 16788        return new Struct_construction_expression(type, this->vals_, location);
 16789      }
 16790  
 16791    size_t field_count = st->field_count();
 16792    std::vector<Expression*> vals(field_count);
 16793    std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
 16794    Expression_list::const_iterator p = this->vals_->begin();
 16795    Expression* external_expr = NULL;
 16796    const Named_object* external_no = NULL;
 16797    while (p != this->vals_->end())
 16798      {
 16799        Expression* name_expr = *p;
 16800  
 16801        ++p;
 16802        go_assert(p != this->vals_->end());
 16803        Expression* val = *p;
 16804  
 16805        ++p;
 16806  
 16807        if (name_expr == NULL)
 16808  	{
 16809  	  go_error_at(val->location(),
 16810                        "mixture of field and value initializers");
 16811  	  return Expression::make_error(location);
 16812  	}
 16813  
 16814        bool bad_key = false;
 16815        std::string name;
 16816        const Named_object* no = NULL;
 16817        switch (name_expr->classification())
 16818  	{
 16819  	case EXPRESSION_COMPOSITE_LITERAL_KEY:
 16820  	  name =
 16821  	    static_cast<Composite_literal_key_expression*>(name_expr)->name();
 16822  	  break;
 16823  
 16824  	case EXPRESSION_UNKNOWN_REFERENCE:
 16825  	  name = name_expr->unknown_expression()->name();
 16826  	  if (type->named_type() != NULL)
 16827  	    {
 16828  	      // If the named object found for this field name comes from a
 16829  	      // different package than the struct it is a part of, do not count
 16830  	      // this incorrect lookup as a usage of the object's package.
 16831  	      no = name_expr->unknown_expression()->named_object();
 16832  	      if (no->package() != NULL
 16833  		  && no->package() != type->named_type()->named_object()->package())
 16834  		no->package()->forget_usage(name_expr);
 16835  	    }
 16836  	  break;
 16837  
 16838  	case EXPRESSION_CONST_REFERENCE:
 16839  	  no = static_cast<Const_expression*>(name_expr)->named_object();
 16840  	  break;
 16841  
 16842  	case EXPRESSION_TYPE:
 16843  	  {
 16844  	    Type* t = name_expr->type();
 16845  	    Named_type* nt = t->named_type();
 16846  	    if (nt == NULL)
 16847  	      bad_key = true;
 16848  	    else
 16849  	      no = nt->named_object();
 16850  	  }
 16851  	  break;
 16852  
 16853  	case EXPRESSION_VAR_REFERENCE:
 16854  	  no = name_expr->var_expression()->named_object();
 16855  	  break;
 16856  
 16857  	case EXPRESSION_ENCLOSED_VAR_REFERENCE:
 16858  	  no = name_expr->enclosed_var_expression()->variable();
 16859  	  break;
 16860  
 16861  	case EXPRESSION_FUNC_REFERENCE:
 16862  	  no = name_expr->func_expression()->named_object();
 16863  	  break;
 16864  
 16865  	default:
 16866  	  bad_key = true;
 16867  	  break;
 16868  	}
 16869        if (bad_key)
 16870  	{
 16871  	  go_error_at(name_expr->location(), "expected struct field name");
 16872  	  return Expression::make_error(location);
 16873  	}
 16874  
 16875        if (no != NULL)
 16876  	{
 16877  	  if (no->package() != NULL && external_expr == NULL)
 16878  	    {
 16879  	      external_expr = name_expr;
 16880  	      external_no = no;
 16881  	    }
 16882  
 16883  	  name = no->name();
 16884  
 16885  	  // A predefined name won't be packed.  If it starts with a
 16886  	  // lower case letter we need to check for that case, because
 16887  	  // the field name will be packed.  FIXME.
 16888  	  if (!Gogo::is_hidden_name(name)
 16889  	      && name[0] >= 'a'
 16890  	      && name[0] <= 'z')
 16891  	    {
 16892  	      Named_object* gno = gogo->lookup_global(name.c_str());
 16893  	      if (gno == no)
 16894  		name = gogo->pack_hidden_name(name, false);
 16895  	    }
 16896  	}
 16897  
 16898        unsigned int index;
 16899        const Struct_field* sf = st->find_local_field(name, &index);
 16900        if (sf == NULL)
 16901  	{
 16902  	  go_error_at(name_expr->location(), "unknown field %qs in %qs",
 16903                        Gogo::message_name(name).c_str(),
 16904                        (type->named_type() != NULL
 16905                         ? type->named_type()->message_name().c_str()
 16906                         : "unnamed struct"));
 16907  	  return Expression::make_error(location);
 16908  	}
 16909        if (vals[index] != NULL)
 16910  	{
 16911  	  go_error_at(name_expr->location(),
 16912                        "duplicate value for field %qs in %qs",
 16913                        Gogo::message_name(name).c_str(),
 16914                        (type->named_type() != NULL
 16915                         ? type->named_type()->message_name().c_str()
 16916                         : "unnamed struct"));
 16917  	  return Expression::make_error(location);
 16918  	}
 16919  
 16920        if (type->named_type() != NULL
 16921  	  && type->named_type()->named_object()->package() != NULL
 16922  	  && (Gogo::is_hidden_name(sf->field_name())
 16923  	      || sf->is_embedded_builtin(gogo)))
 16924  	go_error_at(name_expr->location(),
 16925                      "assignment of unexported field %qs in %qs literal",
 16926                      Gogo::message_name(sf->field_name()).c_str(),
 16927                      type->named_type()->message_name().c_str());
 16928  
 16929        vals[index] = val;
 16930        traverse_order->push_back(static_cast<unsigned long>(index));
 16931      }
 16932  
 16933    if (!this->all_are_names_)
 16934      {
 16935        // This is a weird case like bug462 in the testsuite.
 16936        if (external_expr == NULL)
 16937  	go_error_at(this->location(), "unknown field in %qs literal",
 16938                      (type->named_type() != NULL
 16939                       ? type->named_type()->message_name().c_str()
 16940                       : "unnamed struct"));
 16941        else
 16942  	go_error_at(external_expr->location(), "unknown field %qs in %qs",
 16943                      external_no->message_name().c_str(),
 16944                      (type->named_type() != NULL
 16945                       ? type->named_type()->message_name().c_str()
 16946                       : "unnamed struct"));
 16947        return Expression::make_error(location);
 16948      }
 16949  
 16950    Expression_list* list = new Expression_list;
 16951    list->reserve(field_count);
 16952    for (size_t i = 0; i < field_count; ++i)
 16953      list->push_back(vals[i]);
 16954  
 16955    Struct_construction_expression* ret =
 16956      new Struct_construction_expression(type, list, location);
 16957    ret->set_traverse_order(traverse_order);
 16958    return ret;
 16959  }
 16960  
 16961  // Index/value/traversal-order triple.
 16962  
 16963  struct IVT_triple {
 16964    unsigned long index;
 16965    unsigned long traversal_order;
 16966    Expression* expr;
 16967    IVT_triple(unsigned long i, unsigned long to, Expression *e)
 16968        : index(i), traversal_order(to), expr(e) { }
 16969    bool operator<(const IVT_triple& other) const
 16970    { return this->index < other.index; }
 16971  };
 16972  
 16973  // Lower an array composite literal.
 16974  
 16975  Expression*
 16976  Composite_literal_expression::lower_array(Type* type)
 16977  {
 16978    Location location = this->location();
 16979    if (this->vals_ == NULL || !this->has_keys_)
 16980      return this->make_array(type, NULL, this->vals_);
 16981  
 16982    std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
 16983    indexes->reserve(this->vals_->size());
 16984    bool indexes_out_of_order = false;
 16985    Expression_list* vals = new Expression_list();
 16986    vals->reserve(this->vals_->size());
 16987    unsigned long index = 0;
 16988    Expression_list::const_iterator p = this->vals_->begin();
 16989    while (p != this->vals_->end())
 16990      {
 16991        Expression* index_expr = *p;
 16992  
 16993        ++p;
 16994        go_assert(p != this->vals_->end());
 16995        Expression* val = *p;
 16996  
 16997        ++p;
 16998  
 16999        if (index_expr == NULL)
 17000  	{
 17001  	  if (std::find(indexes->begin(), indexes->end(), index)
 17002  	      != indexes->end())
 17003  	    {
 17004  	      go_error_at(val->location(),
 17005  			  "duplicate value for index %lu", index);
 17006  	      return Expression::make_error(location);
 17007  	    }
 17008  	  if (!indexes->empty())
 17009  	    indexes->push_back(index);
 17010  	}
 17011        else
 17012  	{
 17013  	  if (indexes->empty() && !vals->empty())
 17014  	    {
 17015  	      for (size_t i = 0; i < vals->size(); ++i)
 17016  		indexes->push_back(i);
 17017  	    }
 17018  
 17019  	  Numeric_constant nc;
 17020  	  if (!index_expr->numeric_constant_value(&nc))
 17021  	    {
 17022  	      go_error_at(index_expr->location(),
 17023                            "index expression is not integer constant");
 17024  	      return Expression::make_error(location);
 17025  	    }
 17026  
 17027  	  switch (nc.to_unsigned_long(&index))
 17028  	    {
 17029  	    case Numeric_constant::NC_UL_VALID:
 17030  	      break;
 17031  	    case Numeric_constant::NC_UL_NOTINT:
 17032  	      go_error_at(index_expr->location(),
 17033                            "index expression is not integer constant");
 17034  	      return Expression::make_error(location);
 17035  	    case Numeric_constant::NC_UL_NEGATIVE:
 17036  	      go_error_at(index_expr->location(),
 17037                            "index expression is negative");
 17038  	      return Expression::make_error(location);
 17039  	    case Numeric_constant::NC_UL_BIG:
 17040  	      go_error_at(index_expr->location(), "index value overflow");
 17041  	      return Expression::make_error(location);
 17042  	    default:
 17043  	      go_unreachable();
 17044  	    }
 17045  
 17046  	  Named_type* ntype = Type::lookup_integer_type("int");
 17047  	  Integer_type* inttype = ntype->integer_type();
 17048  	  if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
 17049  	      && index >> (inttype->bits() - 1) != 0)
 17050  	    {
 17051  	      go_error_at(index_expr->location(), "index value overflow");
 17052  	      return Expression::make_error(location);
 17053  	    }
 17054  
 17055  	  if (std::find(indexes->begin(), indexes->end(), index)
 17056  	      != indexes->end())
 17057  	    {
 17058  	      go_error_at(index_expr->location(),
 17059                            "duplicate value for index %lu",
 17060                            index);
 17061  	      return Expression::make_error(location);
 17062  	    }
 17063  
 17064  	  if (!indexes->empty() && index < indexes->back())
 17065  	    indexes_out_of_order = true;
 17066  
 17067  	  indexes->push_back(index);
 17068  	}
 17069  
 17070        vals->push_back(val);
 17071  
 17072        ++index;
 17073      }
 17074  
 17075    if (indexes->empty())
 17076      {
 17077        delete indexes;
 17078        indexes = NULL;
 17079      }
 17080  
 17081    std::vector<unsigned long>* traverse_order = NULL;
 17082    if (indexes_out_of_order)
 17083      {
 17084        typedef std::vector<IVT_triple> V;
 17085  
 17086        V v;
 17087        v.reserve(indexes->size());
 17088        std::vector<unsigned long>::const_iterator pi = indexes->begin();
 17089        unsigned long torder = 0;
 17090        for (Expression_list::const_iterator pe = vals->begin();
 17091  	   pe != vals->end();
 17092  	   ++pe, ++pi, ++torder)
 17093  	v.push_back(IVT_triple(*pi, torder, *pe));
 17094  
 17095        std::sort(v.begin(), v.end());
 17096  
 17097        delete indexes;
 17098        delete vals;
 17099  
 17100        indexes = new std::vector<unsigned long>();
 17101        indexes->reserve(v.size());
 17102        vals = new Expression_list();
 17103        vals->reserve(v.size());
 17104        traverse_order = new std::vector<unsigned long>();
 17105        traverse_order->reserve(v.size());
 17106  
 17107        for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
 17108  	{
 17109  	  indexes->push_back(pv->index);
 17110  	  vals->push_back(pv->expr);
 17111  	  traverse_order->push_back(pv->traversal_order);
 17112  	}
 17113      }
 17114  
 17115    Expression* ret = this->make_array(type, indexes, vals);
 17116    Array_construction_expression* ace = ret->array_literal();
 17117    if (ace != NULL && traverse_order != NULL)
 17118      ace->set_traverse_order(traverse_order);
 17119    return ret;
 17120  }
 17121  
 17122  // Actually build the array composite literal. This handles
 17123  // [...]{...}.
 17124  
 17125  Expression*
 17126  Composite_literal_expression::make_array(
 17127      Type* type,
 17128      const std::vector<unsigned long>* indexes,
 17129      Expression_list* vals)
 17130  {
 17131    Location location = this->location();
 17132    Array_type* at = type->array_type();
 17133  
 17134    if (at->length() != NULL && at->length()->is_nil_expression())
 17135      {
 17136        size_t size;
 17137        if (vals == NULL)
 17138  	size = 0;
 17139        else if (indexes != NULL)
 17140  	size = indexes->back() + 1;
 17141        else
 17142  	{
 17143  	  size = vals->size();
 17144  	  Integer_type* it = Type::lookup_integer_type("int")->integer_type();
 17145  	  if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
 17146  	      && size >> (it->bits() - 1) != 0)
 17147  	    {
 17148  	      go_error_at(location, "too many elements in composite literal");
 17149  	      return Expression::make_error(location);
 17150  	    }
 17151  	}
 17152  
 17153        Expression* elen = Expression::make_integer_ul(size, NULL, location);
 17154        at = Type::make_array_type(at->element_type(), elen);
 17155        type = at;
 17156      }
 17157    else if (at->length() != NULL
 17158  	   && !at->length()->is_error_expression()
 17159  	   && this->vals_ != NULL)
 17160      {
 17161        Numeric_constant nc;
 17162        unsigned long val;
 17163        if (at->length()->numeric_constant_value(&nc)
 17164  	  && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
 17165  	{
 17166  	  if (indexes == NULL)
 17167  	    {
 17168  	      if (this->vals_->size() > val)
 17169  		{
 17170  		  go_error_at(location,
 17171                                "too many elements in composite literal");
 17172  		  return Expression::make_error(location);
 17173  		}
 17174  	    }
 17175  	  else
 17176  	    {
 17177  	      unsigned long max = indexes->back();
 17178  	      if (max >= val)
 17179  		{
 17180  		  go_error_at(location,
 17181                                ("some element keys in composite literal "
 17182                                 "are out of range"));
 17183  		  return Expression::make_error(location);
 17184  		}
 17185  	    }
 17186  	}
 17187      }
 17188  
 17189    if (at->length() != NULL)
 17190      return new Fixed_array_construction_expression(type, indexes, vals,
 17191  						   location);
 17192    else
 17193      return new Slice_construction_expression(type, indexes, vals, location);
 17194  }
 17195  
 17196  // Lower a map composite literal.
 17197  
 17198  Expression*
 17199  Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
 17200  					Statement_inserter* inserter,
 17201  					Type* type)
 17202  {
 17203    Location location = this->location();
 17204    Unordered_map(unsigned int, std::vector<Expression*>) st;
 17205    Unordered_map(unsigned int, std::vector<Expression*>) nt;
 17206    bool saw_false = false;
 17207    bool saw_true = false;
 17208    if (this->vals_ != NULL)
 17209      {
 17210        if (!this->has_keys_)
 17211  	{
 17212  	  go_error_at(location, "map composite literal must have keys");
 17213  	  return Expression::make_error(location);
 17214  	}
 17215  
 17216        for (Expression_list::iterator p = this->vals_->begin();
 17217  	   p != this->vals_->end();
 17218  	   p += 2)
 17219  	{
 17220  	  if (*p == NULL)
 17221  	    {
 17222  	      ++p;
 17223  	      go_error_at((*p)->location(),
 17224                            ("map composite literal must "
 17225                             "have keys for every value"));
 17226  	      return Expression::make_error(location);
 17227  	    }
 17228  	  // Make sure we have lowered the key; it may not have been
 17229  	  // lowered in order to handle keys for struct composite
 17230  	  // literals.  Lower it now to get the right error message.
 17231  	  if ((*p)->unknown_expression() != NULL)
 17232  	    {
 17233  	      gogo->lower_expression(function, inserter, &*p);
 17234  	      go_assert((*p)->is_error_expression());
 17235  	      return Expression::make_error(location);
 17236  	    }
 17237  	  // Check if there are duplicate constant keys.
 17238  	  if (!(*p)->is_constant())
 17239  	    continue;
 17240  	  std::string sval;
 17241  	  Numeric_constant nval;
 17242  	  bool bval;
 17243  	  if ((*p)->string_constant_value(&sval)) // Check string keys.
 17244  	    {
 17245  	      unsigned int h = Gogo::hash_string(sval, 0);
 17246  	      // Search the index h in the hash map.
 17247  	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
 17248  	      mit = st.find(h);
 17249  	      if (mit == st.end())
 17250  		{
 17251  		  // No duplicate since h is a new index.
 17252  		  // Create a new vector indexed by h and add it to the hash map.
 17253  		  std::vector<Expression*> l;
 17254  		  l.push_back(*p);
 17255  		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
 17256  		  st.insert(val);
 17257  		}
 17258  	      else
 17259  		{
 17260  		  // Do further check since index h already exists.
 17261  		  for (std::vector<Expression*>::iterator lit =
 17262  			   mit->second.begin();
 17263  		       lit != mit->second.end();
 17264  		       lit++)
 17265  		    {
 17266  		      std::string s;
 17267  		      bool ok = (*lit)->string_constant_value(&s);
 17268  		      go_assert(ok);
 17269  		      if (s == sval)
 17270  			{
 17271  			  go_error_at((*p)->location(), ("duplicate key "
 17272  				      "in map literal"));
 17273  			  return Expression::make_error(location);
 17274  			}
 17275  		    }
 17276  		  // Add this new string key to the vector indexed by h.
 17277  		  mit->second.push_back(*p);
 17278  		}
 17279  	    }
 17280  	  else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
 17281  	    {
 17282  	      unsigned int h = nval.hash(0);
 17283  	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
 17284  	      mit = nt.find(h);
 17285  	      if (mit == nt.end())
 17286  		{
 17287  		  // No duplicate since h is a new code.
 17288  		  // Create a new vector indexed by h and add it to the hash map.
 17289  		  std::vector<Expression*> l;
 17290  		  l.push_back(*p);
 17291  		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
 17292  		  nt.insert(val);
 17293  		}
 17294  	      else
 17295  		{
 17296  		  // Do further check since h already exists.
 17297  		  for (std::vector<Expression*>::iterator lit =
 17298  			   mit->second.begin();
 17299  		       lit != mit->second.end();
 17300  		       lit++)
 17301  		    {
 17302  		      Numeric_constant rval;
 17303  		      bool ok = (*lit)->numeric_constant_value(&rval);
 17304  		      go_assert(ok);
 17305  		      if (nval.equals(rval))
 17306  			{
 17307  			  go_error_at((*p)->location(),
 17308  				      "duplicate key in map literal");
 17309  			  return Expression::make_error(location);
 17310  			}
 17311  		    }
 17312  		  // Add this new numeric key to the vector indexed by h.
 17313  		  mit->second.push_back(*p);
 17314  		}
 17315  	    }
 17316  	  else if ((*p)->boolean_constant_value(&bval))
 17317  	    {
 17318  	      if ((bval && saw_true) || (!bval && saw_false))
 17319  		{
 17320  		  go_error_at((*p)->location(),
 17321  			      "duplicate key in map literal");
 17322  		  return Expression::make_error(location);
 17323  		}
 17324  	      if (bval)
 17325  		saw_true = true;
 17326  	      else
 17327  		saw_false = true;
 17328  	    }
 17329  	}
 17330      }
 17331  
 17332    return new Map_construction_expression(type, this->vals_, location);
 17333  }
 17334  
 17335  // Copy.
 17336  
 17337  Expression*
 17338  Composite_literal_expression::do_copy()
 17339  {
 17340    Composite_literal_expression* ret =
 17341      new Composite_literal_expression(this->type_->copy_expressions(),
 17342  				     this->depth_, this->has_keys_,
 17343  				     (this->vals_ == NULL
 17344  				      ? NULL
 17345  				      : this->vals_->copy()),
 17346  				     this->all_are_names_,
 17347  				     this->location());
 17348    ret->key_path_ = this->key_path_;
 17349    return ret;
 17350  }
 17351  
 17352  // Dump ast representation for a composite literal expression.
 17353  
 17354  void
 17355  Composite_literal_expression::do_dump_expression(
 17356                                 Ast_dump_context* ast_dump_context) const
 17357  {
 17358    ast_dump_context->ostream() << "composite(";
 17359    ast_dump_context->dump_type(this->type_);
 17360    ast_dump_context->ostream() << ", {";
 17361    ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
 17362    ast_dump_context->ostream() << "})";
 17363  }
 17364  
 17365  // Make a composite literal expression.
 17366  
 17367  Expression*
 17368  Expression::make_composite_literal(Type* type, int depth, bool has_keys,
 17369  				   Expression_list* vals, bool all_are_names,
 17370  				   Location location)
 17371  {
 17372    return new Composite_literal_expression(type, depth, has_keys, vals,
 17373  					  all_are_names, location);
 17374  }
 17375  
 17376  // Return whether this expression is a composite literal.
 17377  
 17378  bool
 17379  Expression::is_composite_literal() const
 17380  {
 17381    switch (this->classification_)
 17382      {
 17383      case EXPRESSION_COMPOSITE_LITERAL:
 17384      case EXPRESSION_STRUCT_CONSTRUCTION:
 17385      case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
 17386      case EXPRESSION_SLICE_CONSTRUCTION:
 17387      case EXPRESSION_MAP_CONSTRUCTION:
 17388        return true;
 17389      default:
 17390        return false;
 17391      }
 17392  }
 17393  
 17394  // Return whether this expression is a composite literal which is not
 17395  // constant.
 17396  
 17397  bool
 17398  Expression::is_nonconstant_composite_literal() const
 17399  {
 17400    switch (this->classification_)
 17401      {
 17402      case EXPRESSION_STRUCT_CONSTRUCTION:
 17403        {
 17404  	const Struct_construction_expression *psce =
 17405  	  static_cast<const Struct_construction_expression*>(this);
 17406  	return !psce->is_constant_struct();
 17407        }
 17408      case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
 17409        {
 17410  	const Fixed_array_construction_expression *pace =
 17411  	  static_cast<const Fixed_array_construction_expression*>(this);
 17412  	return !pace->is_constant_array();
 17413        }
 17414      case EXPRESSION_SLICE_CONSTRUCTION:
 17415        {
 17416  	const Slice_construction_expression *pace =
 17417  	  static_cast<const Slice_construction_expression*>(this);
 17418  	return !pace->is_constant_array();
 17419        }
 17420      case EXPRESSION_MAP_CONSTRUCTION:
 17421        return true;
 17422      default:
 17423        return false;
 17424      }
 17425  }
 17426  
 17427  // Return true if this is a variable or temporary_variable.
 17428  
 17429  bool
 17430  Expression::is_variable() const
 17431  {
 17432    switch (this->classification_)
 17433      {
 17434      case EXPRESSION_VAR_REFERENCE:
 17435      case EXPRESSION_TEMPORARY_REFERENCE:
 17436      case EXPRESSION_SET_AND_USE_TEMPORARY:
 17437      case EXPRESSION_ENCLOSED_VAR_REFERENCE:
 17438        return true;
 17439      default:
 17440        return false;
 17441      }
 17442  }
 17443  
 17444  // Return true if this is a reference to a local variable.
 17445  
 17446  bool
 17447  Expression::is_local_variable() const
 17448  {
 17449    const Var_expression* ve = this->var_expression();
 17450    if (ve == NULL)
 17451      return false;
 17452    const Named_object* no = ve->named_object();
 17453    return (no->is_result_variable()
 17454  	  || (no->is_variable() && !no->var_value()->is_global()));
 17455  }
 17456  
 17457  // Return true if multiple evaluations are OK.
 17458  
 17459  bool
 17460  Expression::is_multi_eval_safe()
 17461  {
 17462    switch (this->classification_)
 17463      {
 17464      case EXPRESSION_VAR_REFERENCE:
 17465        {
 17466  	// A variable is a simple reference if not stored in the heap.
 17467  	const Named_object* no = this->var_expression()->named_object();
 17468  	if (no->is_variable())
 17469  	  return !no->var_value()->is_in_heap();
 17470  	else if (no->is_result_variable())
 17471  	  return !no->result_var_value()->is_in_heap();
 17472  	else
 17473  	  go_unreachable();
 17474        }
 17475  
 17476      case EXPRESSION_TEMPORARY_REFERENCE:
 17477        return true;
 17478  
 17479      default:
 17480        break;
 17481      }
 17482  
 17483    if (!this->is_constant())
 17484      return false;
 17485  
 17486    // Only numeric and boolean constants are really multi-evaluation
 17487    // safe.  We don't want multiple copies of string constants.
 17488    Type* type = this->type();
 17489    return type->is_numeric_type() || type->is_boolean_type();
 17490  }
 17491  
 17492  const Named_object*
 17493  Expression::named_constant() const
 17494  {
 17495    if (this->classification() != EXPRESSION_CONST_REFERENCE)
 17496      return NULL;
 17497    const Const_expression* ce = static_cast<const Const_expression*>(this);
 17498    return ce->named_object();
 17499  }
 17500  
 17501  // Class Type_guard_expression.
 17502  
 17503  // Traversal.
 17504  
 17505  int
 17506  Type_guard_expression::do_traverse(Traverse* traverse)
 17507  {
 17508    if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
 17509        || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 17510      return TRAVERSE_EXIT;
 17511    return TRAVERSE_CONTINUE;
 17512  }
 17513  
 17514  Expression*
 17515  Type_guard_expression::do_flatten(Gogo*, Named_object*,
 17516                                    Statement_inserter* inserter)
 17517  {
 17518    if (this->expr_->is_error_expression()
 17519        || this->expr_->type()->is_error_type())
 17520      {
 17521        go_assert(saw_errors());
 17522        return Expression::make_error(this->location());
 17523      }
 17524  
 17525    if (!this->expr_->is_multi_eval_safe())
 17526      {
 17527        Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
 17528                                                              this->location());
 17529        inserter->insert(temp);
 17530        this->expr_ =
 17531            Expression::make_temporary_reference(temp, this->location());
 17532      }
 17533    return this;
 17534  }
 17535  
 17536  // Check types of a type guard expression.  The expression must have
 17537  // an interface type, but the actual type conversion is checked at run
 17538  // time.
 17539  
 17540  void
 17541  Type_guard_expression::do_check_types(Gogo*)
 17542  {
 17543    Type* expr_type = this->expr_->type();
 17544    if (expr_type->interface_type() == NULL)
 17545      {
 17546        if (!expr_type->is_error() && !this->type_->is_error())
 17547  	this->report_error(_("type assertion only valid for interface types"));
 17548        this->set_is_error();
 17549      }
 17550    else if (this->type_->interface_type() == NULL)
 17551      {
 17552        std::string reason;
 17553        if (!expr_type->interface_type()->implements_interface(this->type_,
 17554  							     &reason))
 17555  	{
 17556  	  if (!this->type_->is_error())
 17557  	    {
 17558  	      if (reason.empty())
 17559  		this->report_error(_("impossible type assertion: "
 17560  				     "type does not implement interface"));
 17561  	      else
 17562  		go_error_at(this->location(),
 17563                              ("impossible type assertion: "
 17564                               "type does not implement interface (%s)"),
 17565                              reason.c_str());
 17566  	    }
 17567  	  this->set_is_error();
 17568  	}
 17569      }
 17570  }
 17571  
 17572  // Copy.
 17573  
 17574  Expression*
 17575  Type_guard_expression::do_copy()
 17576  {
 17577    return new Type_guard_expression(this->expr_->copy(),
 17578  				   this->type_->copy_expressions(),
 17579  				   this->location());
 17580  }
 17581  
 17582  // Return the backend representation for a type guard expression.
 17583  
 17584  Bexpression*
 17585  Type_guard_expression::do_get_backend(Translate_context* context)
 17586  {
 17587    Expression* conversion;
 17588    if (this->type_->interface_type() != NULL)
 17589      conversion =
 17590          Expression::convert_interface_to_interface(this->type_, this->expr_,
 17591                                                     true, this->location());
 17592    else
 17593      conversion =
 17594          Expression::convert_for_assignment(context->gogo(), this->type_,
 17595                                             this->expr_, this->location());
 17596  
 17597    Gogo* gogo = context->gogo();
 17598    Btype* bt = this->type_->get_backend(gogo);
 17599    Bexpression* bexpr = conversion->get_backend(context);
 17600    return gogo->backend()->convert_expression(bt, bexpr, this->location());
 17601  }
 17602  
 17603  // Dump ast representation for a type guard expression.
 17604  
 17605  void
 17606  Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
 17607      const
 17608  {
 17609    this->expr_->dump_expression(ast_dump_context);
 17610    ast_dump_context->ostream() <<  ".";
 17611    ast_dump_context->dump_type(this->type_);
 17612  }
 17613  
 17614  // Make a type guard expression.
 17615  
 17616  Expression*
 17617  Expression::make_type_guard(Expression* expr, Type* type,
 17618  			    Location location)
 17619  {
 17620    return new Type_guard_expression(expr, type, location);
 17621  }
 17622  
 17623  // Class Heap_expression.
 17624  
 17625  // Return the type of the expression stored on the heap.
 17626  
 17627  Type*
 17628  Heap_expression::do_type()
 17629  { return Type::make_pointer_type(this->expr_->type()); }
 17630  
 17631  // Return the backend representation for allocating an expression on the heap.
 17632  
 17633  Bexpression*
 17634  Heap_expression::do_get_backend(Translate_context* context)
 17635  {
 17636    Type* etype = this->expr_->type();
 17637    if (this->expr_->is_error_expression() || etype->is_error())
 17638      return context->backend()->error_expression();
 17639  
 17640    Location loc = this->location();
 17641    Gogo* gogo = context->gogo();
 17642    Btype* btype = this->type()->get_backend(gogo);
 17643  
 17644    Expression* alloc = Expression::make_allocation(etype, loc);
 17645    if (this->allocate_on_stack_)
 17646      alloc->allocation_expression()->set_allocate_on_stack();
 17647    Bexpression* space = alloc->get_backend(context);
 17648  
 17649    Bstatement* decl;
 17650    Named_object* fn = context->function();
 17651    go_assert(fn != NULL);
 17652    Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
 17653    Bvariable* space_temp =
 17654      gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
 17655  					space,
 17656  					Backend::variable_address_is_taken,
 17657  					loc, &decl);
 17658    Btype* expr_btype = etype->get_backend(gogo);
 17659  
 17660    Bexpression* bexpr = this->expr_->get_backend(context);
 17661  
 17662    // If this assignment needs a write barrier, call typedmemmove.  We
 17663    // don't do this in the write barrier pass because in some cases
 17664    // backend conversion can introduce new Heap_expression values.
 17665    Bstatement* assn;
 17666    if (!etype->has_pointer() || this->allocate_on_stack_)
 17667      {
 17668        space = gogo->backend()->var_expression(space_temp, loc);
 17669        Bexpression* ref =
 17670  	gogo->backend()->indirect_expression(expr_btype, space, true, loc);
 17671        assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
 17672      }
 17673    else
 17674      {
 17675        Bstatement* edecl;
 17676        Bvariable* btemp =
 17677  	gogo->backend()->temporary_variable(fndecl, context->bblock(),
 17678  					    expr_btype, bexpr,
 17679  					    Backend::variable_address_is_taken,
 17680  					    loc, &edecl);
 17681        Bexpression* btempref = gogo->backend()->var_expression(btemp,
 17682  							      loc);
 17683        space = gogo->backend()->var_expression(space_temp, loc);
 17684        Type* etype_ptr = Type::make_pointer_type(etype);
 17685        Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
 17686        Expression* erhs;
 17687        Expression* call;
 17688        if (etype->is_direct_iface_type())
 17689          {
 17690            // Single pointer.
 17691            Type* uintptr_type = Type::lookup_integer_type("uintptr");
 17692            erhs = Expression::make_backend(btempref, etype, loc);
 17693            erhs = Expression::unpack_direct_iface(erhs, loc);
 17694            erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
 17695            call = Runtime::make_call(Runtime::GCWRITEBARRIER, loc, 2,
 17696                                      elhs, erhs);
 17697          }
 17698        else
 17699          {
 17700            Expression* td = Expression::make_type_descriptor(etype, loc);
 17701            Bexpression* addr =
 17702              gogo->backend()->address_expression(btempref, loc);
 17703            erhs = Expression::make_backend(addr, etype_ptr, loc);
 17704            call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
 17705                                      td, elhs, erhs);
 17706          }
 17707        Statement* cs = Statement::make_statement(call, false);
 17708  
 17709        space = gogo->backend()->var_expression(space_temp, loc);
 17710        Bexpression* ref =
 17711          gogo->backend()->indirect_expression(expr_btype, space, true, loc);
 17712        Expression* eref = Expression::make_backend(ref, etype, loc);
 17713        btempref = gogo->backend()->var_expression(btemp, loc);
 17714        erhs = Expression::make_backend(btempref, etype, loc);
 17715        Statement* as = Statement::make_assignment(eref, erhs, loc);
 17716  
 17717        as = gogo->check_write_barrier(context->block(), as, cs);
 17718        Bstatement* s = as->get_backend(context);
 17719  
 17720        assn = gogo->backend()->compound_statement(edecl, s);
 17721      }
 17722    decl = gogo->backend()->compound_statement(decl, assn);
 17723    space = gogo->backend()->var_expression(space_temp, loc);
 17724    return gogo->backend()->compound_expression(decl, space, loc);
 17725  }
 17726  
 17727  // Dump ast representation for a heap expression.
 17728  
 17729  void
 17730  Heap_expression::do_dump_expression(
 17731      Ast_dump_context* ast_dump_context) const
 17732  {
 17733    ast_dump_context->ostream() << "&(";
 17734    ast_dump_context->dump_expression(this->expr_);
 17735    ast_dump_context->ostream() << ")";
 17736  }
 17737  
 17738  // Allocate an expression on the heap.
 17739  
 17740  Expression*
 17741  Expression::make_heap_expression(Expression* expr, Location location)
 17742  {
 17743    return new Heap_expression(expr, location);
 17744  }
 17745  
 17746  // Class Receive_expression.
 17747  
 17748  // Return the type of a receive expression.
 17749  
 17750  Type*
 17751  Receive_expression::do_type()
 17752  {
 17753    if (this->is_error_expression())
 17754      return Type::make_error_type();
 17755    Channel_type* channel_type = this->channel_->type()->channel_type();
 17756    if (channel_type == NULL)
 17757      {
 17758        this->report_error(_("expected channel"));
 17759        return Type::make_error_type();
 17760      }
 17761    return channel_type->element_type();
 17762  }
 17763  
 17764  // Check types for a receive expression.
 17765  
 17766  void
 17767  Receive_expression::do_check_types(Gogo*)
 17768  {
 17769    Type* type = this->channel_->type();
 17770    if (type->is_error())
 17771      {
 17772        go_assert(saw_errors());
 17773        this->set_is_error();
 17774        return;
 17775      }
 17776    if (type->channel_type() == NULL)
 17777      {
 17778        this->report_error(_("expected channel"));
 17779        return;
 17780      }
 17781    if (!type->channel_type()->may_receive())
 17782      {
 17783        this->report_error(_("invalid receive on send-only channel"));
 17784        return;
 17785      }
 17786  }
 17787  
 17788  // Flattening for receive expressions creates a temporary variable to store
 17789  // received data in for receives.
 17790  
 17791  Expression*
 17792  Receive_expression::do_flatten(Gogo*, Named_object*,
 17793                                 Statement_inserter* inserter)
 17794  {
 17795    Channel_type* channel_type = this->channel_->type()->channel_type();
 17796    if (channel_type == NULL)
 17797      {
 17798        go_assert(saw_errors());
 17799        return this;
 17800      }
 17801    else if (this->channel_->is_error_expression())
 17802     {
 17803       go_assert(saw_errors());
 17804       return Expression::make_error(this->location());
 17805     }
 17806  
 17807    Type* element_type = channel_type->element_type();
 17808    if (this->temp_receiver_ == NULL)
 17809      {
 17810        this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
 17811  						       this->location());
 17812        this->temp_receiver_->set_is_address_taken();
 17813        inserter->insert(this->temp_receiver_);
 17814      }
 17815  
 17816    return this;
 17817  }
 17818  
 17819  // Get the backend representation for a receive expression.
 17820  
 17821  Bexpression*
 17822  Receive_expression::do_get_backend(Translate_context* context)
 17823  {
 17824    Location loc = this->location();
 17825  
 17826    Channel_type* channel_type = this->channel_->type()->channel_type();
 17827    if (channel_type == NULL)
 17828      {
 17829        go_assert(this->channel_->type()->is_error());
 17830        return context->backend()->error_expression();
 17831      }
 17832  
 17833    Expression* recv_ref =
 17834      Expression::make_temporary_reference(this->temp_receiver_, loc);
 17835    Expression* recv_addr =
 17836      Expression::make_temporary_reference(this->temp_receiver_, loc);
 17837    recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
 17838    Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
 17839  					this->channel_, recv_addr);
 17840    return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
 17841  }
 17842  
 17843  // Export a receive expression.
 17844  
 17845  void
 17846  Receive_expression::do_export(Export_function_body* efb) const
 17847  {
 17848    efb->write_c_string("<-");
 17849    this->channel_->export_expression(efb);
 17850  }
 17851  
 17852  // Dump ast representation for a receive expression.
 17853  
 17854  void
 17855  Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
 17856  {
 17857    ast_dump_context->ostream() << " <- " ;
 17858    ast_dump_context->dump_expression(channel_);
 17859  }
 17860  
 17861  // Import a receive expression.
 17862  
 17863  Expression*
 17864  Receive_expression::do_import(Import_expression* imp, Location loc)
 17865  {
 17866    imp->require_c_string("<-");
 17867    Expression* expr = Expression::import_expression(imp, loc);
 17868    return Expression::make_receive(expr, loc);
 17869  }
 17870  
 17871  // Make a receive expression.
 17872  
 17873  Receive_expression*
 17874  Expression::make_receive(Expression* channel, Location location)
 17875  {
 17876    return new Receive_expression(channel, location);
 17877  }
 17878  
 17879  // An expression which evaluates to a pointer to the type descriptor
 17880  // of a type.
 17881  
 17882  class Type_descriptor_expression : public Expression
 17883  {
 17884   public:
 17885    Type_descriptor_expression(Type* type, Location location)
 17886      : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
 17887        type_(type)
 17888    { }
 17889  
 17890   protected:
 17891    int
 17892    do_traverse(Traverse*);
 17893  
 17894    Type*
 17895    do_type()
 17896    { return Type::make_type_descriptor_ptr_type(); }
 17897  
 17898    bool
 17899    do_is_static_initializer() const
 17900    { return true; }
 17901  
 17902    void
 17903    do_determine_type(const Type_context*)
 17904    { }
 17905  
 17906    Expression*
 17907    do_copy()
 17908    { return this; }
 17909  
 17910    Bexpression*
 17911    do_get_backend(Translate_context* context)
 17912    {
 17913      return this->type_->type_descriptor_pointer(context->gogo(),
 17914  						this->location());
 17915    }
 17916  
 17917    void
 17918    do_dump_expression(Ast_dump_context*) const;
 17919  
 17920   private:
 17921    // The type for which this is the descriptor.
 17922    Type* type_;
 17923  };
 17924  
 17925  int
 17926  Type_descriptor_expression::do_traverse(Traverse* traverse)
 17927  {
 17928    if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 17929      return TRAVERSE_EXIT;
 17930    return TRAVERSE_CONTINUE;
 17931  }
 17932  
 17933  // Dump ast representation for a type descriptor expression.
 17934  
 17935  void
 17936  Type_descriptor_expression::do_dump_expression(
 17937      Ast_dump_context* ast_dump_context) const
 17938  {
 17939    ast_dump_context->dump_type(this->type_);
 17940  }
 17941  
 17942  // Make a type descriptor expression.
 17943  
 17944  Expression*
 17945  Expression::make_type_descriptor(Type* type, Location location)
 17946  {
 17947    return new Type_descriptor_expression(type, location);
 17948  }
 17949  
 17950  // An expression which evaluates to a pointer to the Garbage Collection symbol
 17951  // of a type.
 17952  
 17953  class GC_symbol_expression : public Expression
 17954  {
 17955   public:
 17956    GC_symbol_expression(Type* type)
 17957      : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
 17958        type_(type)
 17959    {}
 17960  
 17961   protected:
 17962    Type*
 17963    do_type()
 17964    { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
 17965  
 17966    bool
 17967    do_is_static_initializer() const
 17968    { return true; }
 17969  
 17970    void
 17971    do_determine_type(const Type_context*)
 17972    { }
 17973  
 17974    Expression*
 17975    do_copy()
 17976    { return this; }
 17977  
 17978    Bexpression*
 17979    do_get_backend(Translate_context* context)
 17980    { return this->type_->gc_symbol_pointer(context->gogo()); }
 17981  
 17982    void
 17983    do_dump_expression(Ast_dump_context*) const;
 17984  
 17985   private:
 17986    // The type which this gc symbol describes.
 17987    Type* type_;
 17988  };
 17989  
 17990  // Dump ast representation for a gc symbol expression.
 17991  
 17992  void
 17993  GC_symbol_expression::do_dump_expression(
 17994      Ast_dump_context* ast_dump_context) const
 17995  {
 17996    ast_dump_context->ostream() << "gcdata(";
 17997    ast_dump_context->dump_type(this->type_);
 17998    ast_dump_context->ostream() << ")";
 17999  }
 18000  
 18001  // Make a gc symbol expression.
 18002  
 18003  Expression*
 18004  Expression::make_gc_symbol(Type* type)
 18005  {
 18006    return new GC_symbol_expression(type);
 18007  }
 18008  
 18009  // An expression that evaluates to a pointer to a symbol holding the
 18010  // ptrmask data of a type.
 18011  
 18012  class Ptrmask_symbol_expression : public Expression
 18013  {
 18014   public:
 18015    Ptrmask_symbol_expression(Type* type)
 18016      : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
 18017        type_(type)
 18018    {}
 18019  
 18020   protected:
 18021    Type*
 18022    do_type()
 18023    { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
 18024  
 18025    bool
 18026    do_is_static_initializer() const
 18027    { return true; }
 18028  
 18029    void
 18030    do_determine_type(const Type_context*)
 18031    { }
 18032  
 18033    Expression*
 18034    do_copy()
 18035    { return this; }
 18036  
 18037    Bexpression*
 18038    do_get_backend(Translate_context*);
 18039  
 18040    void
 18041    do_dump_expression(Ast_dump_context*) const;
 18042  
 18043   private:
 18044    // The type that this ptrmask symbol describes.
 18045    Type* type_;
 18046  };
 18047  
 18048  // Return the ptrmask variable.
 18049  
 18050  Bexpression*
 18051  Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
 18052  {
 18053    Gogo* gogo = context->gogo();
 18054  
 18055    // If this type does not need a gcprog, then we can use the standard
 18056    // GC symbol.
 18057    int64_t ptrsize, ptrdata;
 18058    if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
 18059      return this->type_->gc_symbol_pointer(gogo);
 18060  
 18061    // Otherwise we have to build a ptrmask variable, and return a
 18062    // pointer to it.
 18063  
 18064    Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
 18065    Location bloc = Linemap::predeclared_location();
 18066    Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
 18067    Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
 18068  
 18069    Type* uint8_type = Type::lookup_integer_type("uint8");
 18070    Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
 18071    Btype* ubtype = pointer_uint8_type->get_backend(gogo);
 18072    return gogo->backend()->convert_expression(ubtype, baddr, bloc);
 18073  }
 18074  
 18075  // Dump AST for a ptrmask symbol expression.
 18076  
 18077  void
 18078  Ptrmask_symbol_expression::do_dump_expression(
 18079      Ast_dump_context* ast_dump_context) const
 18080  {
 18081    ast_dump_context->ostream() << "ptrmask(";
 18082    ast_dump_context->dump_type(this->type_);
 18083    ast_dump_context->ostream() << ")";
 18084  }
 18085  
 18086  // Make a ptrmask symbol expression.
 18087  
 18088  Expression*
 18089  Expression::make_ptrmask_symbol(Type* type)
 18090  {
 18091    return new Ptrmask_symbol_expression(type);
 18092  }
 18093  
 18094  // An expression which evaluates to some characteristic of a type.
 18095  // This is only used to initialize fields of a type descriptor.  Using
 18096  // a new expression class is slightly inefficient but gives us a good
 18097  // separation between the frontend and the middle-end with regard to
 18098  // how types are laid out.
 18099  
 18100  class Type_info_expression : public Expression
 18101  {
 18102   public:
 18103    Type_info_expression(Type* type, Type_info type_info)
 18104      : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
 18105        type_(type), type_info_(type_info)
 18106    { }
 18107  
 18108   protected:
 18109    bool
 18110    do_is_static_initializer() const
 18111    { return true; }
 18112  
 18113    Type*
 18114    do_type();
 18115  
 18116    void
 18117    do_determine_type(const Type_context*)
 18118    { }
 18119  
 18120    Expression*
 18121    do_copy()
 18122    { return this; }
 18123  
 18124    Bexpression*
 18125    do_get_backend(Translate_context* context);
 18126  
 18127    void
 18128    do_dump_expression(Ast_dump_context*) const;
 18129  
 18130   private:
 18131    // The type for which we are getting information.
 18132    Type* type_;
 18133    // What information we want.
 18134    Type_info type_info_;
 18135  };
 18136  
 18137  // The type is chosen to match what the type descriptor struct
 18138  // expects.
 18139  
 18140  Type*
 18141  Type_info_expression::do_type()
 18142  {
 18143    switch (this->type_info_)
 18144      {
 18145      case TYPE_INFO_SIZE:
 18146      case TYPE_INFO_BACKEND_PTRDATA:
 18147      case TYPE_INFO_DESCRIPTOR_PTRDATA:
 18148        return Type::lookup_integer_type("uintptr");
 18149      case TYPE_INFO_ALIGNMENT:
 18150      case TYPE_INFO_FIELD_ALIGNMENT:
 18151        return Type::lookup_integer_type("uint8");
 18152      default:
 18153        go_unreachable();
 18154      }
 18155  }
 18156  
 18157  // Return the backend representation for type information.
 18158  
 18159  Bexpression*
 18160  Type_info_expression::do_get_backend(Translate_context* context)
 18161  {
 18162    Gogo* gogo = context->gogo();
 18163    bool ok = true;
 18164    int64_t val;
 18165    switch (this->type_info_)
 18166      {
 18167      case TYPE_INFO_SIZE:
 18168        ok = this->type_->backend_type_size(gogo, &val);
 18169        break;
 18170      case TYPE_INFO_ALIGNMENT:
 18171        ok = this->type_->backend_type_align(gogo, &val);
 18172        break;
 18173      case TYPE_INFO_FIELD_ALIGNMENT:
 18174        ok = this->type_->backend_type_field_align(gogo, &val);
 18175        break;
 18176      case TYPE_INFO_BACKEND_PTRDATA:
 18177        ok = this->type_->backend_type_ptrdata(gogo, &val);
 18178        break;
 18179      case TYPE_INFO_DESCRIPTOR_PTRDATA:
 18180        ok = this->type_->descriptor_ptrdata(gogo, &val);
 18181        break;
 18182      default:
 18183        go_unreachable();
 18184      }
 18185    if (!ok)
 18186      {
 18187        go_assert(saw_errors());
 18188        return gogo->backend()->error_expression();
 18189      }
 18190    Expression* e = Expression::make_integer_int64(val, this->type(),
 18191  						 this->location());
 18192    return e->get_backend(context);
 18193  }
 18194  
 18195  // Dump ast representation for a type info expression.
 18196  
 18197  void
 18198  Type_info_expression::do_dump_expression(
 18199      Ast_dump_context* ast_dump_context) const
 18200  {
 18201    ast_dump_context->ostream() << "typeinfo(";
 18202    ast_dump_context->dump_type(this->type_);
 18203    ast_dump_context->ostream() << ",";
 18204    ast_dump_context->ostream() <<
 18205      (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
 18206      : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
 18207      : this->type_info_ == TYPE_INFO_SIZE ? "size"
 18208      : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
 18209      : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
 18210      : "unknown");
 18211    ast_dump_context->ostream() << ")";
 18212  }
 18213  
 18214  // Make a type info expression.
 18215  
 18216  Expression*
 18217  Expression::make_type_info(Type* type, Type_info type_info)
 18218  {
 18219    return new Type_info_expression(type, type_info);
 18220  }
 18221  
 18222  // Slice_info_expression.
 18223  
 18224  // Return the type of the slice info.
 18225  
 18226  Type*
 18227  Slice_info_expression::do_type()
 18228  {
 18229    switch (this->slice_info_)
 18230      {
 18231      case SLICE_INFO_VALUE_POINTER:
 18232        return Type::make_pointer_type(
 18233            this->slice_->type()->array_type()->element_type());
 18234      case SLICE_INFO_LENGTH:
 18235      case SLICE_INFO_CAPACITY:
 18236          return Type::lookup_integer_type("int");
 18237      default:
 18238        go_unreachable();
 18239      }
 18240  }
 18241  
 18242  // Return the backend information for slice information.
 18243  
 18244  Bexpression*
 18245  Slice_info_expression::do_get_backend(Translate_context* context)
 18246  {
 18247    Gogo* gogo = context->gogo();
 18248    Bexpression* bslice = this->slice_->get_backend(context);
 18249    switch (this->slice_info_)
 18250      {
 18251      case SLICE_INFO_VALUE_POINTER:
 18252      case SLICE_INFO_LENGTH:
 18253      case SLICE_INFO_CAPACITY:
 18254        return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
 18255  						      this->location());
 18256        break;
 18257      default:
 18258        go_unreachable();
 18259      }
 18260  }
 18261  
 18262  // Dump ast representation for a type info expression.
 18263  
 18264  void
 18265  Slice_info_expression::do_dump_expression(
 18266      Ast_dump_context* ast_dump_context) const
 18267  {
 18268    ast_dump_context->ostream() << "sliceinfo(";
 18269    this->slice_->dump_expression(ast_dump_context);
 18270    ast_dump_context->ostream() << ",";
 18271    ast_dump_context->ostream() <<
 18272        (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
 18273      : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
 18274      : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
 18275      : "unknown");
 18276    ast_dump_context->ostream() << ")";
 18277  }
 18278  
 18279  // Make a slice info expression.
 18280  
 18281  Expression*
 18282  Expression::make_slice_info(Expression* slice, Slice_info slice_info,
 18283                              Location location)
 18284  {
 18285    return new Slice_info_expression(slice, slice_info, location);
 18286  }
 18287  
 18288  // Class Slice_value_expression.
 18289  
 18290  int
 18291  Slice_value_expression::do_traverse(Traverse* traverse)
 18292  {
 18293    if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
 18294        || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
 18295        || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
 18296        || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
 18297      return TRAVERSE_EXIT;
 18298    return TRAVERSE_CONTINUE;
 18299  }
 18300  
 18301  Expression*
 18302  Slice_value_expression::do_copy()
 18303  {
 18304    return new Slice_value_expression(this->type_->copy_expressions(),
 18305  				    this->valmem_->copy(),
 18306  				    this->len_->copy(), this->cap_->copy(),
 18307  				    this->location());
 18308  }
 18309  
 18310  Bexpression*
 18311  Slice_value_expression::do_get_backend(Translate_context* context)
 18312  {
 18313    std::vector<Bexpression*> vals(3);
 18314    vals[0] = this->valmem_->get_backend(context);
 18315    vals[1] = this->len_->get_backend(context);
 18316    vals[2] = this->cap_->get_backend(context);
 18317  
 18318    Gogo* gogo = context->gogo();
 18319    Btype* btype = this->type_->get_backend(gogo);
 18320    return gogo->backend()->constructor_expression(btype, vals, this->location());
 18321  }
 18322  
 18323  void
 18324  Slice_value_expression::do_dump_expression(
 18325      Ast_dump_context* ast_dump_context) const
 18326  {
 18327    ast_dump_context->ostream() << "slicevalue(";
 18328    ast_dump_context->ostream() << "values: ";
 18329    this->valmem_->dump_expression(ast_dump_context);
 18330    ast_dump_context->ostream() << ", length: ";
 18331    this->len_->dump_expression(ast_dump_context);
 18332    ast_dump_context->ostream() << ", capacity: ";
 18333    this->cap_->dump_expression(ast_dump_context);
 18334    ast_dump_context->ostream() << ")";
 18335  }
 18336  
 18337  Expression*
 18338  Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
 18339                               Expression* cap, Location location)
 18340  {
 18341    go_assert(at->is_slice_type());
 18342    go_assert(valmem->is_nil_expression()
 18343  	    || (at->array_type()->element_type()
 18344  		== valmem->type()->points_to()));
 18345    return new Slice_value_expression(at, valmem, len, cap, location);
 18346  }
 18347  
 18348  // Look through the expression of a Slice_value_expression's valmem to
 18349  // find an call to makeslice.  If found, return the call expression and
 18350  // the containing temporary statement (if any).
 18351  
 18352  std::pair<Call_expression*, Temporary_statement*>
 18353  Expression::find_makeslice_call(Expression* expr)
 18354  {
 18355    Unsafe_type_conversion_expression* utce =
 18356      expr->unsafe_conversion_expression();
 18357    if (utce != NULL)
 18358      expr = utce->expr();
 18359  
 18360    Slice_value_expression* sve = expr->slice_value_expression();
 18361    if (sve == NULL)
 18362      return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
 18363    expr = sve->valmem();
 18364  
 18365    utce = expr->unsafe_conversion_expression();
 18366    if (utce != NULL)
 18367      expr = utce->expr();
 18368  
 18369    Temporary_reference_expression* tre = expr->temporary_reference_expression();
 18370    Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
 18371    if (ts != NULL && ts->init() != NULL && !ts->assigned()
 18372        && !ts->is_address_taken())
 18373      expr = ts->init();
 18374  
 18375    Call_expression* call = expr->call_expression();
 18376    if (call == NULL)
 18377      return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
 18378  
 18379    Func_expression* fe = call->fn()->func_expression();
 18380    if (fe != NULL
 18381        && fe->runtime_code() == Runtime::MAKESLICE)
 18382      return std::make_pair(call, ts);
 18383  
 18384    return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
 18385  }
 18386  
 18387  // An expression that evaluates to some characteristic of a non-empty interface.
 18388  // This is used to access the method table or underlying object of an interface.
 18389  
 18390  class Interface_info_expression : public Expression
 18391  {
 18392   public:
 18393    Interface_info_expression(Expression* iface, Interface_info iface_info,
 18394                              Location location)
 18395      : Expression(EXPRESSION_INTERFACE_INFO, location),
 18396        iface_(iface), iface_info_(iface_info)
 18397    { }
 18398  
 18399   protected:
 18400    Type*
 18401    do_type();
 18402  
 18403    void
 18404    do_determine_type(const Type_context*)
 18405    { }
 18406  
 18407    Expression*
 18408    do_copy()
 18409    {
 18410      return new Interface_info_expression(this->iface_->copy(),
 18411                                           this->iface_info_, this->location());
 18412    }
 18413  
 18414    Bexpression*
 18415    do_get_backend(Translate_context* context);
 18416  
 18417    void
 18418    do_dump_expression(Ast_dump_context*) const;
 18419  
 18420    void
 18421    do_issue_nil_check()
 18422    { this->iface_->issue_nil_check(); }
 18423  
 18424   private:
 18425    // The interface for which we are getting information.
 18426    Expression* iface_;
 18427    // What information we want.
 18428    Interface_info iface_info_;
 18429  };
 18430  
 18431  // Return the type of the interface info.
 18432  
 18433  Type*
 18434  Interface_info_expression::do_type()
 18435  {
 18436    switch (this->iface_info_)
 18437      {
 18438      case INTERFACE_INFO_METHODS:
 18439        {
 18440          typedef Unordered_map(Interface_type*, Type*) Hashtable;
 18441          static Hashtable result_types;
 18442  
 18443          Interface_type* itype = this->iface_->type()->interface_type();
 18444  
 18445          Hashtable::const_iterator pr = result_types.find(itype);
 18446          if (pr != result_types.end())
 18447            return pr->second;
 18448  
 18449          Type* pdt = Type::make_type_descriptor_ptr_type();
 18450          if (itype->is_empty())
 18451            {
 18452              result_types[itype] = pdt;
 18453              return pdt;
 18454            }
 18455  
 18456          Location loc = this->location();
 18457          Struct_field_list* sfl = new Struct_field_list();
 18458          sfl->push_back(
 18459              Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
 18460  
 18461          for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
 18462               p != itype->methods()->end();
 18463               ++p)
 18464            {
 18465              Function_type* ft = p->type()->function_type();
 18466              go_assert(ft->receiver() == NULL);
 18467  
 18468              const Typed_identifier_list* params = ft->parameters();
 18469              Typed_identifier_list* mparams = new Typed_identifier_list();
 18470              if (params != NULL)
 18471                mparams->reserve(params->size() + 1);
 18472              Type* vt = Type::make_pointer_type(Type::make_void_type());
 18473              mparams->push_back(Typed_identifier("", vt, ft->location()));
 18474              if (params != NULL)
 18475                {
 18476                  for (Typed_identifier_list::const_iterator pp = params->begin();
 18477                       pp != params->end();
 18478                       ++pp)
 18479                    mparams->push_back(*pp);
 18480                }
 18481  
 18482              Typed_identifier_list* mresults = (ft->results() == NULL
 18483                                                 ? NULL
 18484                                                 : ft->results()->copy());
 18485              Backend_function_type* mft =
 18486                  Type::make_backend_function_type(NULL, mparams, mresults,
 18487                                                   ft->location());
 18488  
 18489              std::string fname = Gogo::unpack_hidden_name(p->name());
 18490              sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
 18491            }
 18492  
 18493  	Struct_type* st = Type::make_struct_type(sfl, loc);
 18494  	st->set_is_struct_incomparable();
 18495  	Pointer_type *pt = Type::make_pointer_type(st);
 18496          result_types[itype] = pt;
 18497          return pt;
 18498        }
 18499      case INTERFACE_INFO_OBJECT:
 18500        return Type::make_pointer_type(Type::make_void_type());
 18501      default:
 18502        go_unreachable();
 18503      }
 18504  }
 18505  
 18506  // Return the backend representation for interface information.
 18507  
 18508  Bexpression*
 18509  Interface_info_expression::do_get_backend(Translate_context* context)
 18510  {
 18511    Gogo* gogo = context->gogo();
 18512    Bexpression* biface = this->iface_->get_backend(context);
 18513    switch (this->iface_info_)
 18514      {
 18515      case INTERFACE_INFO_METHODS:
 18516      case INTERFACE_INFO_OBJECT:
 18517        return gogo->backend()->struct_field_expression(biface, this->iface_info_,
 18518  						      this->location());
 18519        break;
 18520      default:
 18521        go_unreachable();
 18522      }
 18523  }
 18524  
 18525  // Dump ast representation for an interface info expression.
 18526  
 18527  void
 18528  Interface_info_expression::do_dump_expression(
 18529      Ast_dump_context* ast_dump_context) const
 18530  {
 18531    bool is_empty = this->iface_->type()->interface_type()->is_empty();
 18532    ast_dump_context->ostream() << "interfaceinfo(";
 18533    this->iface_->dump_expression(ast_dump_context);
 18534    ast_dump_context->ostream() << ",";
 18535    ast_dump_context->ostream() <<
 18536        (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
 18537      : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
 18538      : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
 18539      : "unknown");
 18540    ast_dump_context->ostream() << ")";
 18541  }
 18542  
 18543  // Make an interface info expression.
 18544  
 18545  Expression*
 18546  Expression::make_interface_info(Expression* iface, Interface_info iface_info,
 18547                                  Location location)
 18548  {
 18549    return new Interface_info_expression(iface, iface_info, location);
 18550  }
 18551  
 18552  // An expression that represents an interface value.  The first field is either
 18553  // a type descriptor for an empty interface or a pointer to the interface method
 18554  // table for a non-empty interface.  The second field is always the object.
 18555  
 18556  class Interface_value_expression : public Expression
 18557  {
 18558   public:
 18559    Interface_value_expression(Type* type, Expression* first_field,
 18560                               Expression* obj, Location location)
 18561        : Expression(EXPRESSION_INTERFACE_VALUE, location),
 18562          type_(type), first_field_(first_field), obj_(obj)
 18563    { }
 18564  
 18565   protected:
 18566    int
 18567    do_traverse(Traverse*);
 18568  
 18569    Type*
 18570    do_type()
 18571    { return this->type_; }
 18572  
 18573    void
 18574    do_determine_type(const Type_context*)
 18575    { go_unreachable(); }
 18576  
 18577    Expression*
 18578    do_copy()
 18579    {
 18580      return new Interface_value_expression(this->type_->copy_expressions(),
 18581                                            this->first_field_->copy(),
 18582                                            this->obj_->copy(), this->location());
 18583    }
 18584  
 18585    Bexpression*
 18586    do_get_backend(Translate_context* context);
 18587  
 18588    void
 18589    do_dump_expression(Ast_dump_context*) const;
 18590  
 18591   private:
 18592    // The type of the interface value.
 18593    Type* type_;
 18594    // The first field of the interface (either a type descriptor or a pointer
 18595    // to the method table.
 18596    Expression* first_field_;
 18597    // The underlying object of the interface.
 18598    Expression* obj_;
 18599  };
 18600  
 18601  int
 18602  Interface_value_expression::do_traverse(Traverse* traverse)
 18603  {
 18604    if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
 18605        || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
 18606      return TRAVERSE_EXIT;
 18607    return TRAVERSE_CONTINUE;
 18608  }
 18609  
 18610  Bexpression*
 18611  Interface_value_expression::do_get_backend(Translate_context* context)
 18612  {
 18613    std::vector<Bexpression*> vals(2);
 18614    vals[0] = this->first_field_->get_backend(context);
 18615    vals[1] = this->obj_->get_backend(context);
 18616  
 18617    Gogo* gogo = context->gogo();
 18618    Btype* btype = this->type_->get_backend(gogo);
 18619    return gogo->backend()->constructor_expression(btype, vals, this->location());
 18620  }
 18621  
 18622  void
 18623  Interface_value_expression::do_dump_expression(
 18624      Ast_dump_context* ast_dump_context) const
 18625  {
 18626    ast_dump_context->ostream() << "interfacevalue(";
 18627    ast_dump_context->ostream() <<
 18628        (this->type_->interface_type()->is_empty()
 18629         ? "type_descriptor: "
 18630         : "methods: ");
 18631    this->first_field_->dump_expression(ast_dump_context);
 18632    ast_dump_context->ostream() << ", object: ";
 18633    this->obj_->dump_expression(ast_dump_context);
 18634    ast_dump_context->ostream() << ")";
 18635  }
 18636  
 18637  Expression*
 18638  Expression::make_interface_value(Type* type, Expression* first_value,
 18639                                   Expression* object, Location location)
 18640  {
 18641    return new Interface_value_expression(type, first_value, object, location);
 18642  }
 18643  
 18644  // An interface method table for a pair of types: an interface type and a type
 18645  // that implements that interface.
 18646  
 18647  class Interface_mtable_expression : public Expression
 18648  {
 18649   public:
 18650    Interface_mtable_expression(Interface_type* itype, Type* type,
 18651                                bool is_pointer, Location location)
 18652        : Expression(EXPRESSION_INTERFACE_MTABLE, location),
 18653          itype_(itype), type_(type), is_pointer_(is_pointer),
 18654  	method_table_type_(NULL), bvar_(NULL)
 18655    { }
 18656  
 18657   protected:
 18658    int
 18659    do_traverse(Traverse*);
 18660  
 18661    Type*
 18662    do_type();
 18663  
 18664    bool
 18665    do_is_static_initializer() const
 18666    { return true; }
 18667  
 18668    void
 18669    do_determine_type(const Type_context*)
 18670    { go_unreachable(); }
 18671  
 18672    Expression*
 18673    do_copy()
 18674    {
 18675      Interface_type* itype = this->itype_->copy_expressions()->interface_type();
 18676      return new Interface_mtable_expression(itype,
 18677  					   this->type_->copy_expressions(),
 18678                                             this->is_pointer_, this->location());
 18679    }
 18680  
 18681    bool
 18682    do_is_addressable() const
 18683    { return true; }
 18684  
 18685    Bexpression*
 18686    do_get_backend(Translate_context* context);
 18687  
 18688    void
 18689    do_dump_expression(Ast_dump_context*) const;
 18690  
 18691   private:
 18692    // The interface type for which the methods are defined.
 18693    Interface_type* itype_;
 18694    // The type to construct the interface method table for.
 18695    Type* type_;
 18696    // Whether this table contains the method set for the receiver type or the
 18697    // pointer receiver type.
 18698    bool is_pointer_;
 18699    // The type of the method table.
 18700    Type* method_table_type_;
 18701    // The backend variable that refers to the interface method table.
 18702    Bvariable* bvar_;
 18703  };
 18704  
 18705  int
 18706  Interface_mtable_expression::do_traverse(Traverse* traverse)
 18707  {
 18708    if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
 18709        || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
 18710      return TRAVERSE_EXIT;
 18711    return TRAVERSE_CONTINUE;
 18712  }
 18713  
 18714  Type*
 18715  Interface_mtable_expression::do_type()
 18716  {
 18717    if (this->method_table_type_ != NULL)
 18718      return this->method_table_type_;
 18719  
 18720    const Typed_identifier_list* interface_methods = this->itype_->methods();
 18721    go_assert(!interface_methods->empty());
 18722  
 18723    Struct_field_list* sfl = new Struct_field_list;
 18724    Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
 18725                         this->location());
 18726    sfl->push_back(Struct_field(tid));
 18727    Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
 18728    for (Typed_identifier_list::const_iterator p = interface_methods->begin();
 18729         p != interface_methods->end();
 18730         ++p)
 18731      {
 18732        // We want C function pointers here, not func descriptors; model
 18733        // using void* pointers.
 18734        Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
 18735        sfl->push_back(Struct_field(method));
 18736      }
 18737    Struct_type* st = Type::make_struct_type(sfl, this->location());
 18738    st->set_is_struct_incomparable();
 18739    this->method_table_type_ = st;
 18740    return this->method_table_type_;
 18741  }
 18742  
 18743  Bexpression*
 18744  Interface_mtable_expression::do_get_backend(Translate_context* context)
 18745  {
 18746    Gogo* gogo = context->gogo();
 18747    Location loc = Linemap::predeclared_location();
 18748    if (this->bvar_ != NULL)
 18749      return gogo->backend()->var_expression(this->bvar_, this->location());
 18750  
 18751    const Typed_identifier_list* interface_methods = this->itype_->methods();
 18752    go_assert(!interface_methods->empty());
 18753  
 18754    std::string mangled_name =
 18755      gogo->interface_method_table_name(this->itype_, this->type_,
 18756  				      this->is_pointer_);
 18757  
 18758    // Set is_public if we are converting a named type to an interface
 18759    // type that is defined in the same package as the named type, and
 18760    // the interface has hidden methods.  In that case the interface
 18761    // method table will be defined by the package that defines the
 18762    // types.
 18763    bool is_public = false;
 18764    if (this->type_->named_type() != NULL
 18765        && (this->type_->named_type()->named_object()->package()
 18766  	  == this->itype_->package()))
 18767      {
 18768        for (Typed_identifier_list::const_iterator p = interface_methods->begin();
 18769  	   p != interface_methods->end();
 18770  	   ++p)
 18771  	{
 18772  	  if (Gogo::is_hidden_name(p->name()))
 18773  	    {
 18774  	      is_public = true;
 18775  	      break;
 18776  	    }
 18777  	}
 18778      }
 18779  
 18780    if (is_public
 18781        && this->type_->named_type()->named_object()->package() != NULL)
 18782      {
 18783        // The interface conversion table is defined elsewhere.
 18784        Btype* btype = this->type()->get_backend(gogo);
 18785        this->bvar_ =
 18786            gogo->backend()->immutable_struct_reference(mangled_name, "",
 18787                                                        btype, loc);
 18788        return gogo->backend()->var_expression(this->bvar_, this->location());
 18789      }
 18790  
 18791    // The first element is the type descriptor.
 18792    Type* td_type;
 18793    if (!this->is_pointer_)
 18794      td_type = this->type_;
 18795    else
 18796      td_type = Type::make_pointer_type(this->type_);
 18797  
 18798    std::vector<Backend::Btyped_identifier> bstructfields;
 18799  
 18800    // Build an interface method table for a type: a type descriptor followed by a
 18801    // list of function pointers, one for each interface method.  This is used for
 18802    // interfaces.
 18803    Expression_list* svals = new Expression_list();
 18804    Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
 18805    svals->push_back(tdescriptor);
 18806  
 18807    Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
 18808    Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
 18809    bstructfields.push_back(btd);
 18810  
 18811    Named_type* nt = this->type_->named_type();
 18812    Struct_type* st = this->type_->struct_type();
 18813    go_assert(nt != NULL || st != NULL);
 18814  
 18815    for (Typed_identifier_list::const_iterator p = interface_methods->begin();
 18816         p != interface_methods->end();
 18817         ++p)
 18818      {
 18819        bool is_ambiguous;
 18820        Method* m;
 18821        if (nt != NULL)
 18822  	m = nt->method_function(p->name(), &is_ambiguous);
 18823        else
 18824  	m = st->method_function(p->name(), &is_ambiguous);
 18825        go_assert(m != NULL);
 18826  
 18827        // See the comment in Type::method_constructor.
 18828        bool use_direct_iface_stub = false;
 18829        if (m->is_value_method()
 18830  	  && this->is_pointer_
 18831  	  && this->type_->is_direct_iface_type())
 18832  	use_direct_iface_stub = true;
 18833        if (!m->is_value_method()
 18834  	  && this->is_pointer_
 18835  	  && !this->type_->in_heap())
 18836  	use_direct_iface_stub = true;
 18837        Named_object* no = (use_direct_iface_stub
 18838  			  ? m->iface_stub_object()
 18839  			  : m->named_object());
 18840  
 18841        go_assert(no->is_function() || no->is_function_declaration());
 18842  
 18843        Function_type* fcn_type = (no->is_function()
 18844                                   ? no->func_value()->type()
 18845                                   : no->func_declaration_value()->type());
 18846        Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
 18847        Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
 18848        bstructfields.push_back(bmtype);
 18849  
 18850        svals->push_back(Expression::make_func_code_reference(no, loc));
 18851      }
 18852  
 18853    Btype *btype = gogo->backend()->struct_type(bstructfields);
 18854    std::vector<Bexpression*> ctor_bexprs;
 18855    for (Expression_list::const_iterator pe = svals->begin();
 18856         pe != svals->end();
 18857         ++pe)
 18858      {
 18859        ctor_bexprs.push_back((*pe)->get_backend(context));
 18860      }
 18861    Bexpression* ctor =
 18862        gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
 18863  
 18864    unsigned int flags = 0;
 18865    if (!is_public)
 18866      flags |= Backend::variable_is_hidden;
 18867    this->bvar_ = gogo->backend()->immutable_struct(mangled_name, "", flags,
 18868  						  btype, loc);
 18869    gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, flags,
 18870  					     btype, loc, ctor);
 18871    return gogo->backend()->var_expression(this->bvar_, loc);
 18872  }
 18873  
 18874  void
 18875  Interface_mtable_expression::do_dump_expression(
 18876      Ast_dump_context* ast_dump_context) const
 18877  {
 18878    ast_dump_context->ostream() << "__go_"
 18879                                << (this->is_pointer_ ? "pimt__" : "imt_");
 18880    ast_dump_context->dump_type(this->itype_);
 18881    ast_dump_context->ostream() << "__";
 18882    ast_dump_context->dump_type(this->type_);
 18883  }
 18884  
 18885  Expression*
 18886  Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
 18887                                        bool is_pointer, Location location)
 18888  {
 18889    return new Interface_mtable_expression(itype, type, is_pointer, location);
 18890  }
 18891  
 18892  // An expression which evaluates to the offset of a field within a
 18893  // struct.  This, like Type_info_expression, q.v., is only used to
 18894  // initialize fields of a type descriptor.
 18895  
 18896  class Struct_field_offset_expression : public Expression
 18897  {
 18898   public:
 18899    Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
 18900      : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
 18901  		 Linemap::predeclared_location()),
 18902        type_(type), field_(field)
 18903    { }
 18904  
 18905   protected:
 18906    bool
 18907    do_is_static_initializer() const
 18908    { return true; }
 18909  
 18910    Type*
 18911    do_type()
 18912    { return Type::lookup_integer_type("uintptr"); }
 18913  
 18914    void
 18915    do_determine_type(const Type_context*)
 18916    { }
 18917  
 18918    Expression*
 18919    do_copy()
 18920    { return this; }
 18921  
 18922    Bexpression*
 18923    do_get_backend(Translate_context* context);
 18924  
 18925    void
 18926    do_dump_expression(Ast_dump_context*) const;
 18927  
 18928   private:
 18929    // The type of the struct.
 18930    Struct_type* type_;
 18931    // The field.
 18932    const Struct_field* field_;
 18933  };
 18934  
 18935  // Return the backend representation for a struct field offset.
 18936  
 18937  Bexpression*
 18938  Struct_field_offset_expression::do_get_backend(Translate_context* context)
 18939  {
 18940    const Struct_field_list* fields = this->type_->fields();
 18941    Struct_field_list::const_iterator p;
 18942    unsigned i = 0;
 18943    for (p = fields->begin();
 18944         p != fields->end();
 18945         ++p, ++i)
 18946      if (&*p == this->field_)
 18947        break;
 18948    go_assert(&*p == this->field_);
 18949  
 18950    Gogo* gogo = context->gogo();
 18951    Btype* btype = this->type_->get_backend(gogo);
 18952  
 18953    int64_t offset = gogo->backend()->type_field_offset(btype, i);
 18954    Type* uptr_type = Type::lookup_integer_type("uintptr");
 18955    Expression* ret =
 18956      Expression::make_integer_int64(offset, uptr_type,
 18957  				   Linemap::predeclared_location());
 18958    return ret->get_backend(context);
 18959  }
 18960  
 18961  // Dump ast representation for a struct field offset expression.
 18962  
 18963  void
 18964  Struct_field_offset_expression::do_dump_expression(
 18965      Ast_dump_context* ast_dump_context) const
 18966  {
 18967    ast_dump_context->ostream() <<  "unsafe.Offsetof(";
 18968    ast_dump_context->dump_type(this->type_);
 18969    ast_dump_context->ostream() << '.';
 18970    ast_dump_context->ostream() <<
 18971      Gogo::message_name(this->field_->field_name());
 18972    ast_dump_context->ostream() << ")";
 18973  }
 18974  
 18975  // Make an expression for a struct field offset.
 18976  
 18977  Expression*
 18978  Expression::make_struct_field_offset(Struct_type* type,
 18979  				     const Struct_field* field)
 18980  {
 18981    return new Struct_field_offset_expression(type, field);
 18982  }
 18983  
 18984  // An expression which evaluates to the address of an unnamed label.
 18985  
 18986  class Label_addr_expression : public Expression
 18987  {
 18988   public:
 18989    Label_addr_expression(Label* label, Location location)
 18990      : Expression(EXPRESSION_LABEL_ADDR, location),
 18991        label_(label)
 18992    { }
 18993  
 18994   protected:
 18995    Type*
 18996    do_type()
 18997    { return Type::make_pointer_type(Type::make_void_type()); }
 18998  
 18999    void
 19000    do_determine_type(const Type_context*)
 19001    { }
 19002  
 19003    Expression*
 19004    do_copy()
 19005    { return new Label_addr_expression(this->label_, this->location()); }
 19006  
 19007    Bexpression*
 19008    do_get_backend(Translate_context* context)
 19009    { return this->label_->get_addr(context, this->location()); }
 19010  
 19011    void
 19012    do_dump_expression(Ast_dump_context* ast_dump_context) const
 19013    { ast_dump_context->ostream() << this->label_->name(); }
 19014  
 19015   private:
 19016    // The label whose address we are taking.
 19017    Label* label_;
 19018  };
 19019  
 19020  // Make an expression for the address of an unnamed label.
 19021  
 19022  Expression*
 19023  Expression::make_label_addr(Label* label, Location location)
 19024  {
 19025    return new Label_addr_expression(label, location);
 19026  }
 19027  
 19028  // Class Conditional_expression.
 19029  
 19030  // Traversal.
 19031  
 19032  int
 19033  Conditional_expression::do_traverse(Traverse* traverse)
 19034  {
 19035    if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
 19036        || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
 19037        || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
 19038      return TRAVERSE_EXIT;
 19039    return TRAVERSE_CONTINUE;
 19040  }
 19041  
 19042  // Return the type of the conditional expression.
 19043  
 19044  Type*
 19045  Conditional_expression::do_type()
 19046  {
 19047    Type* result_type = Type::make_void_type();
 19048    if (Type::are_identical(this->then_->type(), this->else_->type(),
 19049  			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
 19050                            NULL))
 19051      result_type = this->then_->type();
 19052    else if (this->then_->is_nil_expression()
 19053             || this->else_->is_nil_expression())
 19054      result_type = (!this->then_->is_nil_expression()
 19055                     ? this->then_->type()
 19056                     : this->else_->type());
 19057    return result_type;
 19058  }
 19059  
 19060  // Determine type for a conditional expression.
 19061  
 19062  void
 19063  Conditional_expression::do_determine_type(const Type_context* context)
 19064  {
 19065    this->cond_->determine_type_no_context();
 19066    this->then_->determine_type(context);
 19067    this->else_->determine_type(context);
 19068  }
 19069  
 19070  // Get the backend representation of a conditional expression.
 19071  
 19072  Bexpression*
 19073  Conditional_expression::do_get_backend(Translate_context* context)
 19074  {
 19075    Gogo* gogo = context->gogo();
 19076    Btype* result_btype = this->type()->get_backend(gogo);
 19077    Bexpression* cond = this->cond_->get_backend(context);
 19078    Bexpression* then = this->then_->get_backend(context);
 19079    Bexpression* belse = this->else_->get_backend(context);
 19080    Bfunction* bfn = context->function()->func_value()->get_decl();
 19081    return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
 19082  						 belse, this->location());
 19083  }
 19084  
 19085  // Dump ast representation of a conditional expression.
 19086  
 19087  void
 19088  Conditional_expression::do_dump_expression(
 19089      Ast_dump_context* ast_dump_context) const
 19090  {
 19091    ast_dump_context->ostream() << "(";
 19092    ast_dump_context->dump_expression(this->cond_);
 19093    ast_dump_context->ostream() << " ? ";
 19094    ast_dump_context->dump_expression(this->then_);
 19095    ast_dump_context->ostream() << " : ";
 19096    ast_dump_context->dump_expression(this->else_);
 19097    ast_dump_context->ostream() << ") ";
 19098  }
 19099  
 19100  // Make a conditional expression.
 19101  
 19102  Expression*
 19103  Expression::make_conditional(Expression* cond, Expression* then,
 19104                               Expression* else_expr, Location location)
 19105  {
 19106    return new Conditional_expression(cond, then, else_expr, location);
 19107  }
 19108  
 19109  // Class Compound_expression.
 19110  
 19111  // Traversal.
 19112  
 19113  int
 19114  Compound_expression::do_traverse(Traverse* traverse)
 19115  {
 19116    if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
 19117        || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
 19118      return TRAVERSE_EXIT;
 19119    return TRAVERSE_CONTINUE;
 19120  }
 19121  
 19122  // Return the type of the compound expression.
 19123  
 19124  Type*
 19125  Compound_expression::do_type()
 19126  {
 19127    return this->expr_->type();
 19128  }
 19129  
 19130  // Determine type for a compound expression.
 19131  
 19132  void
 19133  Compound_expression::do_determine_type(const Type_context* context)
 19134  {
 19135    this->init_->determine_type_no_context();
 19136    this->expr_->determine_type(context);
 19137  }
 19138  
 19139  // Get the backend representation of a compound expression.
 19140  
 19141  Bexpression*
 19142  Compound_expression::do_get_backend(Translate_context* context)
 19143  {
 19144    Gogo* gogo = context->gogo();
 19145    Bexpression* binit = this->init_->get_backend(context);
 19146    Bfunction* bfunction = context->function()->func_value()->get_decl();
 19147    Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
 19148                                                                  binit);
 19149    Bexpression* bexpr = this->expr_->get_backend(context);
 19150    return gogo->backend()->compound_expression(init_stmt, bexpr,
 19151  					      this->location());
 19152  }
 19153  
 19154  // Dump ast representation of a conditional expression.
 19155  
 19156  void
 19157  Compound_expression::do_dump_expression(
 19158      Ast_dump_context* ast_dump_context) const
 19159  {
 19160    ast_dump_context->ostream() << "(";
 19161    ast_dump_context->dump_expression(this->init_);
 19162    ast_dump_context->ostream() << ",";
 19163    ast_dump_context->dump_expression(this->expr_);
 19164    ast_dump_context->ostream() << ") ";
 19165  }
 19166  
 19167  // Make a compound expression.
 19168  
 19169  Expression*
 19170  Expression::make_compound(Expression* init, Expression* expr, Location location)
 19171  {
 19172    return new Compound_expression(init, expr, location);
 19173  }
 19174  
 19175  // Class Backend_expression.
 19176  
 19177  int
 19178  Backend_expression::do_traverse(Traverse*)
 19179  {
 19180    return TRAVERSE_CONTINUE;
 19181  }
 19182  
 19183  Expression*
 19184  Backend_expression::do_copy()
 19185  {
 19186    return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
 19187  				this->location());
 19188  }
 19189  
 19190  void
 19191  Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
 19192  {
 19193    ast_dump_context->ostream() << "backend_expression<";
 19194    ast_dump_context->dump_type(this->type_);
 19195    ast_dump_context->ostream() << ">";
 19196  }
 19197  
 19198  Expression*
 19199  Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
 19200  {
 19201    return new Backend_expression(bexpr, type, location);
 19202  }
 19203  
 19204  // Import an expression.  This comes at the end in order to see the
 19205  // various class definitions.
 19206  
 19207  Expression*
 19208  Expression::import_expression(Import_expression* imp, Location loc)
 19209  {
 19210    Expression* expr = Expression::import_expression_without_suffix(imp, loc);
 19211    while (true)
 19212      {
 19213        if (imp->match_c_string("("))
 19214  	{
 19215  	  imp->advance(1);
 19216  	  Expression_list* args = new Expression_list();
 19217  	  bool is_varargs = false;
 19218  	  while (!imp->match_c_string(")"))
 19219  	    {
 19220  	      Expression* arg = Expression::import_expression(imp, loc);
 19221  	      if (arg->is_error_expression())
 19222  		return arg;
 19223  	      args->push_back(arg);
 19224  	      if (imp->match_c_string(")"))
 19225  		break;
 19226  	      else if (imp->match_c_string("...)"))
 19227  		{
 19228  		  imp->advance(3);
 19229  		  is_varargs = true;
 19230  		  break;
 19231  		}
 19232  	      imp->require_c_string(", ");
 19233  	    }
 19234  	  imp->require_c_string(")");
 19235  	  expr = Expression::make_call(expr, args, is_varargs, loc);
 19236            expr->call_expression()->set_varargs_are_lowered();
 19237  	}
 19238        else if (imp->match_c_string("["))
 19239  	{
 19240  	  imp->advance(1);
 19241  	  Expression* start = Expression::import_expression(imp, loc);
 19242  	  Expression* end = NULL;
 19243  	  Expression* cap = NULL;
 19244  	  if (imp->match_c_string(":"))
 19245  	    {
 19246  	      imp->advance(1);
 19247  	      int c = imp->peek_char();
 19248  	      if (c == ':' || c == ']')
 19249  		end = Expression::make_nil(loc);
 19250  	      else
 19251  		end = Expression::import_expression(imp, loc);
 19252  	      if (imp->match_c_string(":"))
 19253  		{
 19254  		  imp->advance(1);
 19255  		  cap = Expression::import_expression(imp, loc);
 19256  		}
 19257  	    }
 19258  	  imp->require_c_string("]");
 19259  	  expr = Expression::make_index(expr, start, end, cap, loc);
 19260  	}
 19261        else
 19262  	break;
 19263      }
 19264  
 19265    return expr;
 19266  }
 19267  
 19268  // Import an expression without considering a suffix (function
 19269  // arguments, index operations, etc.).
 19270  
 19271  Expression*
 19272  Expression::import_expression_without_suffix(Import_expression* imp,
 19273  					     Location loc)
 19274  {
 19275    int c = imp->peek_char();
 19276    if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
 19277      return Unary_expression::do_import(imp, loc);
 19278    else if (c == '(')
 19279      return Binary_expression::do_import(imp, loc);
 19280    else if (imp->match_c_string("$true")
 19281  	   || imp->match_c_string("$false")
 19282  	   || (imp->version() < EXPORT_FORMAT_V3
 19283  	       && (imp->match_c_string("true")
 19284  		   || imp->match_c_string("false"))))
 19285      return Boolean_expression::do_import(imp, loc);
 19286    else if (c == '"')
 19287      return String_expression::do_import(imp, loc);
 19288    else if (c == '-' || (c >= '0' && c <= '9'))
 19289      {
 19290        // This handles integers, floats and complex constants.
 19291        return Integer_expression::do_import(imp, loc);
 19292      }
 19293    else if (imp->match_c_string("<-"))
 19294      return Receive_expression::do_import(imp, loc);
 19295    else if (imp->match_c_string("$nil")
 19296  	   || (imp->version() < EXPORT_FORMAT_V3
 19297  	       && imp->match_c_string("nil")))
 19298      return Nil_expression::do_import(imp, loc);
 19299    else if (imp->match_c_string("$convert")
 19300  	   || (imp->version() < EXPORT_FORMAT_V3
 19301  	       && imp->match_c_string("convert")))
 19302      return Type_conversion_expression::do_import(imp, loc);
 19303  
 19304    Import_function_body* ifb = imp->ifb();
 19305    if (ifb == NULL)
 19306      {
 19307        go_error_at(imp->location(), "import error: expected expression");
 19308        return Expression::make_error(loc);
 19309      }
 19310    if (ifb->saw_error())
 19311      return Expression::make_error(loc);
 19312  
 19313    if (ifb->match_c_string("$t"))
 19314      return Temporary_reference_expression::do_import(ifb, loc);
 19315  
 19316    return Expression::import_identifier(ifb, loc);
 19317  }
 19318  
 19319  // Import an identifier in an expression.  This is a reference to a
 19320  // variable or function.
 19321  
 19322  Expression*
 19323  Expression::import_identifier(Import_function_body* ifb, Location loc)
 19324  {
 19325    std::string id;
 19326    Package* pkg;
 19327    bool is_exported;
 19328    if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
 19329      {
 19330        if (!ifb->saw_error())
 19331  	go_error_at(ifb->location(),
 19332  		    "import error for %qs: bad qualified identifier at %lu",
 19333  		    ifb->name().c_str(),
 19334  		    static_cast<unsigned long>(ifb->off()));
 19335        ifb->set_saw_error();
 19336        return Expression::make_error(loc);
 19337      }
 19338  
 19339    Named_object* no = NULL;
 19340    if (pkg == NULL && is_exported)
 19341      no = ifb->block()->bindings()->lookup(id);
 19342    if (no == NULL)
 19343      {
 19344        const Package* ipkg = pkg;
 19345        if (ipkg == NULL)
 19346  	ipkg = ifb->function()->package();
 19347        if (!is_exported)
 19348  	id = '.' + ipkg->pkgpath() + '.' + id;
 19349        no = ipkg->bindings()->lookup(id);
 19350      }
 19351    if (no == NULL)
 19352      no = ifb->gogo()->lookup_global(id.c_str());
 19353  
 19354    if (no == NULL)
 19355      {
 19356        if (!ifb->saw_error())
 19357  	go_error_at(ifb->location(),
 19358  		    "import error for %qs: lookup of %qs failed",
 19359  		    ifb->name().c_str(), id.c_str());
 19360        ifb->set_saw_error();
 19361        return Expression::make_error(loc);
 19362      }
 19363  
 19364    if (no->is_variable() || no->is_result_variable())
 19365      return Expression::make_var_reference(no, loc);
 19366    else if (no->is_function() || no->is_function_declaration())
 19367      return Expression::make_func_reference(no, NULL, loc);
 19368    else
 19369      {
 19370        if (!ifb->saw_error())
 19371  	go_error_at(ifb->location(),
 19372  		    ("import error for %qs: "
 19373  		     "unexpected type of identifier %qs (%d)"),
 19374  		    ifb->name().c_str(),
 19375  		    id.c_str(), no->classification());
 19376        ifb->set_saw_error();
 19377        return Expression::make_error(loc);
 19378      }
 19379  }
 19380  
 19381  // Class Expression_list.
 19382  
 19383  // Traverse the list.
 19384  
 19385  int
 19386  Expression_list::traverse(Traverse* traverse)
 19387  {
 19388    for (Expression_list::iterator p = this->begin();
 19389         p != this->end();
 19390         ++p)
 19391      {
 19392        if (*p != NULL)
 19393  	{
 19394  	  if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
 19395  	    return TRAVERSE_EXIT;
 19396  	}
 19397      }
 19398    return TRAVERSE_CONTINUE;
 19399  }
 19400  
 19401  // Copy the list.
 19402  
 19403  Expression_list*
 19404  Expression_list::copy()
 19405  {
 19406    Expression_list* ret = new Expression_list();
 19407    for (Expression_list::iterator p = this->begin();
 19408         p != this->end();
 19409         ++p)
 19410      {
 19411        if (*p == NULL)
 19412  	ret->push_back(NULL);
 19413        else
 19414  	ret->push_back((*p)->copy());
 19415      }
 19416    return ret;
 19417  }
 19418  
 19419  // Return whether an expression list has an error expression.
 19420  
 19421  bool
 19422  Expression_list::contains_error() const
 19423  {
 19424    for (Expression_list::const_iterator p = this->begin();
 19425         p != this->end();
 19426         ++p)
 19427      if (*p != NULL && (*p)->is_error_expression())
 19428        return true;
 19429    return false;
 19430  }
 19431  
 19432  // Class Numeric_constant.
 19433  
 19434  // Destructor.
 19435  
 19436  Numeric_constant::~Numeric_constant()
 19437  {
 19438    this->clear();
 19439  }
 19440  
 19441  // Copy constructor.
 19442  
 19443  Numeric_constant::Numeric_constant(const Numeric_constant& a)
 19444    : classification_(a.classification_), type_(a.type_)
 19445  {
 19446    switch (a.classification_)
 19447      {
 19448      case NC_INVALID:
 19449        break;
 19450      case NC_INT:
 19451      case NC_RUNE:
 19452        mpz_init_set(this->u_.int_val, a.u_.int_val);
 19453        break;
 19454      case NC_FLOAT:
 19455        mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
 19456        break;
 19457      case NC_COMPLEX:
 19458        mpc_init2(this->u_.complex_val, mpc_precision);
 19459        mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
 19460        break;
 19461      default:
 19462        go_unreachable();
 19463      }
 19464  }
 19465  
 19466  // Assignment operator.
 19467  
 19468  Numeric_constant&
 19469  Numeric_constant::operator=(const Numeric_constant& a)
 19470  {
 19471    this->clear();
 19472    this->classification_ = a.classification_;
 19473    this->type_ = a.type_;
 19474    switch (a.classification_)
 19475      {
 19476      case NC_INVALID:
 19477        break;
 19478      case NC_INT:
 19479      case NC_RUNE:
 19480        mpz_init_set(this->u_.int_val, a.u_.int_val);
 19481        break;
 19482      case NC_FLOAT:
 19483        mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
 19484        break;
 19485      case NC_COMPLEX:
 19486        mpc_init2(this->u_.complex_val, mpc_precision);
 19487        mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
 19488        break;
 19489      default:
 19490        go_unreachable();
 19491      }
 19492    return *this;
 19493  }
 19494  
 19495  // Check equality with another numeric constant.
 19496  
 19497  bool
 19498  Numeric_constant::equals(const Numeric_constant& a) const
 19499  {
 19500    if (this->classification_ != a.classification_)
 19501      return false;
 19502  
 19503    if (this->type_ != NULL && a.type_ != NULL
 19504        && !Type::are_identical(this->type_, a.type_,
 19505  			      Type::COMPARE_ALIASES, NULL))
 19506      return false;
 19507  
 19508    switch (a.classification_)
 19509      {
 19510      case NC_INVALID:
 19511        break;
 19512      case NC_INT:
 19513      case NC_RUNE:
 19514        return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
 19515      case NC_FLOAT:
 19516        return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
 19517      case NC_COMPLEX:
 19518        return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
 19519      default:
 19520        go_unreachable();
 19521      }
 19522    return false;
 19523  }
 19524  
 19525  // Clear the contents.
 19526  
 19527  void
 19528  Numeric_constant::clear()
 19529  {
 19530    switch (this->classification_)
 19531      {
 19532      case NC_INVALID:
 19533        break;
 19534      case NC_INT:
 19535      case NC_RUNE:
 19536        mpz_clear(this->u_.int_val);
 19537        break;
 19538      case NC_FLOAT:
 19539        mpfr_clear(this->u_.float_val);
 19540        break;
 19541      case NC_COMPLEX:
 19542        mpc_clear(this->u_.complex_val);
 19543        break;
 19544      default:
 19545        go_unreachable();
 19546      }
 19547    this->classification_ = NC_INVALID;
 19548  }
 19549  
 19550  // Set to an unsigned long value.
 19551  
 19552  void
 19553  Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
 19554  {
 19555    this->clear();
 19556    this->classification_ = NC_INT;
 19557    this->type_ = type;
 19558    mpz_init_set_ui(this->u_.int_val, val);
 19559  }
 19560  
 19561  // Set to an integer value.
 19562  
 19563  void
 19564  Numeric_constant::set_int(Type* type, const mpz_t val)
 19565  {
 19566    this->clear();
 19567    this->classification_ = NC_INT;
 19568    this->type_ = type;
 19569    mpz_init_set(this->u_.int_val, val);
 19570  }
 19571  
 19572  // Set to a rune value.
 19573  
 19574  void
 19575  Numeric_constant::set_rune(Type* type, const mpz_t val)
 19576  {
 19577    this->clear();
 19578    this->classification_ = NC_RUNE;
 19579    this->type_ = type;
 19580    mpz_init_set(this->u_.int_val, val);
 19581  }
 19582  
 19583  // Set to a floating point value.
 19584  
 19585  void
 19586  Numeric_constant::set_float(Type* type, const mpfr_t val)
 19587  {
 19588    this->clear();
 19589    this->classification_ = NC_FLOAT;
 19590    this->type_ = type;
 19591  
 19592    // Numeric constants do not have negative zero values, so remove
 19593    // them here.  They also don't have infinity or NaN values, but we
 19594    // should never see them here.
 19595    int bits = 0;
 19596    if (type != NULL
 19597        && type->float_type() != NULL
 19598        && !type->float_type()->is_abstract())
 19599      bits = type->float_type()->bits();
 19600    if (Numeric_constant::is_float_neg_zero(val, bits))
 19601      mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
 19602    else
 19603      mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
 19604  }
 19605  
 19606  // Set to a complex value.
 19607  
 19608  void
 19609  Numeric_constant::set_complex(Type* type, const mpc_t val)
 19610  {
 19611    this->clear();
 19612    this->classification_ = NC_COMPLEX;
 19613    this->type_ = type;
 19614  
 19615    // Avoid negative zero as in set_float.
 19616    int bits = 0;
 19617    if (type != NULL
 19618        && type->complex_type() != NULL
 19619        && !type->complex_type()->is_abstract())
 19620      bits = type->complex_type()->bits() / 2;
 19621  
 19622    mpfr_t real;
 19623    mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
 19624    if (Numeric_constant::is_float_neg_zero(real, bits))
 19625      mpfr_set_ui(real, 0, MPFR_RNDN);
 19626  
 19627    mpfr_t imag;
 19628    mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
 19629    if (Numeric_constant::is_float_neg_zero(imag, bits))
 19630      mpfr_set_ui(imag, 0, MPFR_RNDN);
 19631  
 19632    mpc_init2(this->u_.complex_val, mpc_precision);
 19633    mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
 19634  
 19635    mpfr_clear(real);
 19636    mpfr_clear(imag);
 19637  }
 19638  
 19639  // Return whether VAL, at a precision of BITS, is a negative zero.
 19640  // BITS may be zero in which case it is ignored.
 19641  
 19642  bool
 19643  Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
 19644  {
 19645    if (!mpfr_signbit(val))
 19646      return false;
 19647    if (mpfr_zero_p(val))
 19648      return true;
 19649    mpfr_exp_t min_exp;
 19650    switch (bits)
 19651      {
 19652      case 0:
 19653        return false;
 19654      case 32:
 19655        // In a denormalized float32 the exponent is -126, and there are
 19656        // 24 bits of which at least the last must be 1, so the smallest
 19657        // representable non-zero exponent is -126 - (24 - 1) == -149.
 19658        min_exp = -149;
 19659        break;
 19660      case 64:
 19661        // Minimum exponent is -1022, there are 53 bits.
 19662        min_exp = -1074;
 19663        break;
 19664      default:
 19665        go_unreachable();
 19666      }
 19667    return mpfr_get_exp(val) < min_exp;
 19668  }
 19669  
 19670  // Get an int value.
 19671  
 19672  void
 19673  Numeric_constant::get_int(mpz_t* val) const
 19674  {
 19675    go_assert(this->is_int());
 19676    mpz_init_set(*val, this->u_.int_val);
 19677  }
 19678  
 19679  // Get a rune value.
 19680  
 19681  void
 19682  Numeric_constant::get_rune(mpz_t* val) const
 19683  {
 19684    go_assert(this->is_rune());
 19685    mpz_init_set(*val, this->u_.int_val);
 19686  }
 19687  
 19688  // Get a floating point value.
 19689  
 19690  void
 19691  Numeric_constant::get_float(mpfr_t* val) const
 19692  {
 19693    go_assert(this->is_float());
 19694    mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
 19695  }
 19696  
 19697  // Get a complex value.
 19698  
 19699  void
 19700  Numeric_constant::get_complex(mpc_t* val) const
 19701  {
 19702    go_assert(this->is_complex());
 19703    mpc_init2(*val, mpc_precision);
 19704    mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
 19705  }
 19706  
 19707  // Express value as unsigned long if possible.
 19708  
 19709  Numeric_constant::To_unsigned_long
 19710  Numeric_constant::to_unsigned_long(unsigned long* val) const
 19711  {
 19712    switch (this->classification_)
 19713      {
 19714      case NC_INT:
 19715      case NC_RUNE:
 19716        return this->mpz_to_unsigned_long(this->u_.int_val, val);
 19717      case NC_FLOAT:
 19718        return this->mpfr_to_unsigned_long(this->u_.float_val, val);
 19719      case NC_COMPLEX:
 19720        if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
 19721  	return NC_UL_NOTINT;
 19722        return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
 19723  					 val);
 19724      default:
 19725        go_unreachable();
 19726      }
 19727  }
 19728  
 19729  // Express integer value as unsigned long if possible.
 19730  
 19731  Numeric_constant::To_unsigned_long
 19732  Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
 19733  				       unsigned long *val) const
 19734  {
 19735    if (mpz_sgn(ival) < 0)
 19736      return NC_UL_NEGATIVE;
 19737    unsigned long ui = mpz_get_ui(ival);
 19738    if (mpz_cmp_ui(ival, ui) != 0)
 19739      return NC_UL_BIG;
 19740    *val = ui;
 19741    return NC_UL_VALID;
 19742  }
 19743  
 19744  // Express floating point value as unsigned long if possible.
 19745  
 19746  Numeric_constant::To_unsigned_long
 19747  Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
 19748  					unsigned long *val) const
 19749  {
 19750    if (!mpfr_integer_p(fval))
 19751      return NC_UL_NOTINT;
 19752    mpz_t ival;
 19753    mpz_init(ival);
 19754    mpfr_get_z(ival, fval, MPFR_RNDN);
 19755    To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
 19756    mpz_clear(ival);
 19757    return ret;
 19758  }
 19759  
 19760  // Express value as memory size if possible.
 19761  
 19762  bool
 19763  Numeric_constant::to_memory_size(int64_t* val) const
 19764  {
 19765    switch (this->classification_)
 19766      {
 19767      case NC_INT:
 19768      case NC_RUNE:
 19769        return this->mpz_to_memory_size(this->u_.int_val, val);
 19770      case NC_FLOAT:
 19771        return this->mpfr_to_memory_size(this->u_.float_val, val);
 19772      case NC_COMPLEX:
 19773        if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
 19774  	return false;
 19775        return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
 19776      default:
 19777        go_unreachable();
 19778      }
 19779  }
 19780  
 19781  // Express integer as memory size if possible.
 19782  
 19783  bool
 19784  Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
 19785  {
 19786    if (mpz_sgn(ival) < 0)
 19787      return false;
 19788    if (mpz_fits_slong_p(ival))
 19789      {
 19790        *val = static_cast<int64_t>(mpz_get_si(ival));
 19791        return true;
 19792      }
 19793  
 19794    // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
 19795    // positive value.
 19796    if (mpz_sizeinbase(ival, 2) >= 64)
 19797      return false;
 19798  
 19799    mpz_t q, r;
 19800    mpz_init(q);
 19801    mpz_init(r);
 19802    mpz_tdiv_q_2exp(q, ival, 32);
 19803    mpz_tdiv_r_2exp(r, ival, 32);
 19804    go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
 19805    *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
 19806  	  + static_cast<int64_t>(mpz_get_ui(r)));
 19807    mpz_clear(r);
 19808    mpz_clear(q);
 19809    return true;
 19810  }
 19811  
 19812  // Express floating point value as memory size if possible.
 19813  
 19814  bool
 19815  Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
 19816  {
 19817    if (!mpfr_integer_p(fval))
 19818      return false;
 19819    mpz_t ival;
 19820    mpz_init(ival);
 19821    mpfr_get_z(ival, fval, MPFR_RNDN);
 19822    bool ret = this->mpz_to_memory_size(ival, val);
 19823    mpz_clear(ival);
 19824    return ret;
 19825  }
 19826  
 19827  // Convert value to integer if possible.
 19828  
 19829  bool
 19830  Numeric_constant::to_int(mpz_t* val) const
 19831  {
 19832    switch (this->classification_)
 19833      {
 19834      case NC_INT:
 19835      case NC_RUNE:
 19836        mpz_init_set(*val, this->u_.int_val);
 19837        return true;
 19838      case NC_FLOAT:
 19839        if (!mpfr_integer_p(this->u_.float_val))
 19840  	return false;
 19841        mpz_init(*val);
 19842        mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
 19843        return true;
 19844      case NC_COMPLEX:
 19845        if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
 19846  	  || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
 19847  	return false;
 19848        mpz_init(*val);
 19849        mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
 19850        return true;
 19851      default:
 19852        go_unreachable();
 19853      }
 19854  }
 19855  
 19856  // Convert value to floating point if possible.
 19857  
 19858  bool
 19859  Numeric_constant::to_float(mpfr_t* val) const
 19860  {
 19861    switch (this->classification_)
 19862      {
 19863      case NC_INT:
 19864      case NC_RUNE:
 19865        mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
 19866        return true;
 19867      case NC_FLOAT:
 19868        mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
 19869        return true;
 19870      case NC_COMPLEX:
 19871        if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
 19872  	return false;
 19873        mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
 19874        return true;
 19875      default:
 19876        go_unreachable();
 19877      }
 19878  }
 19879  
 19880  // Convert value to complex.
 19881  
 19882  bool
 19883  Numeric_constant::to_complex(mpc_t* val) const
 19884  {
 19885    mpc_init2(*val, mpc_precision);
 19886    switch (this->classification_)
 19887      {
 19888      case NC_INT:
 19889      case NC_RUNE:
 19890        mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
 19891        return true;
 19892      case NC_FLOAT:
 19893        mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
 19894        return true;
 19895      case NC_COMPLEX:
 19896        mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
 19897        return true;
 19898      default:
 19899        go_unreachable();
 19900      }
 19901  }
 19902  
 19903  // Get the type.
 19904  
 19905  Type*
 19906  Numeric_constant::type() const
 19907  {
 19908    if (this->type_ != NULL)
 19909      return this->type_;
 19910    switch (this->classification_)
 19911      {
 19912      case NC_INT:
 19913        return Type::make_abstract_integer_type();
 19914      case NC_RUNE:
 19915        return Type::make_abstract_character_type();
 19916      case NC_FLOAT:
 19917        return Type::make_abstract_float_type();
 19918      case NC_COMPLEX:
 19919        return Type::make_abstract_complex_type();
 19920      default:
 19921        go_unreachable();
 19922      }
 19923  }
 19924  
 19925  // If the constant can be expressed in TYPE, then set the type of the
 19926  // constant to TYPE and return true.  Otherwise return false, and, if
 19927  // ISSUE_ERROR is true, report an appropriate error message.
 19928  
 19929  bool
 19930  Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
 19931  {
 19932    bool ret;
 19933    if (type == NULL || type->is_error())
 19934      ret = true;
 19935    else if (type->integer_type() != NULL)
 19936      ret = this->check_int_type(type->integer_type(), issue_error, loc);
 19937    else if (type->float_type() != NULL)
 19938      ret = this->check_float_type(type->float_type(), issue_error, loc);
 19939    else if (type->complex_type() != NULL)
 19940      ret = this->check_complex_type(type->complex_type(), issue_error, loc);
 19941    else
 19942      {
 19943        ret = false;
 19944        if (issue_error)
 19945          go_assert(saw_errors());
 19946      }
 19947    if (ret)
 19948      this->type_ = type;
 19949    return ret;
 19950  }
 19951  
 19952  // Check whether the constant can be expressed in an integer type.
 19953  
 19954  bool
 19955  Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
 19956  				 Location location)
 19957  {
 19958    mpz_t val;
 19959    switch (this->classification_)
 19960      {
 19961      case NC_INT:
 19962      case NC_RUNE:
 19963        mpz_init_set(val, this->u_.int_val);
 19964        break;
 19965  
 19966      case NC_FLOAT:
 19967        if (!mpfr_integer_p(this->u_.float_val))
 19968  	{
 19969  	  if (issue_error)
 19970              {
 19971                go_error_at(location,
 19972                            "floating-point constant truncated to integer");
 19973                this->set_invalid();
 19974              }
 19975  	  return false;
 19976  	}
 19977        mpz_init(val);
 19978        mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
 19979        break;
 19980  
 19981      case NC_COMPLEX:
 19982        if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
 19983  	  || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
 19984  	{
 19985  	  if (issue_error)
 19986              {
 19987                go_error_at(location, "complex constant truncated to integer");
 19988                this->set_invalid();
 19989              }
 19990  	  return false;
 19991  	}
 19992        mpz_init(val);
 19993        mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
 19994        break;
 19995  
 19996      default:
 19997        go_unreachable();
 19998      }
 19999  
 20000    bool ret;
 20001    if (type->is_abstract())
 20002      ret = true;
 20003    else
 20004      {
 20005        int bits = mpz_sizeinbase(val, 2);
 20006        if (type->is_unsigned())
 20007  	{
 20008  	  // For an unsigned type we can only accept a nonnegative
 20009  	  // number, and we must be able to represents at least BITS.
 20010  	  ret = mpz_sgn(val) >= 0 && bits <= type->bits();
 20011  	}
 20012        else
 20013  	{
 20014  	  // For a signed type we need an extra bit to indicate the
 20015  	  // sign.  We have to handle the most negative integer
 20016  	  // specially.
 20017  	  ret = (bits + 1 <= type->bits()
 20018  		 || (bits <= type->bits()
 20019  		     && mpz_sgn(val) < 0
 20020  		     && (mpz_scan1(val, 0)
 20021  			 == static_cast<unsigned long>(type->bits() - 1))
 20022  		     && mpz_scan0(val, type->bits()) == ULONG_MAX));
 20023  	}
 20024      }
 20025  
 20026    if (!ret && issue_error)
 20027      {
 20028        go_error_at(location, "integer constant overflow");
 20029        this->set_invalid();
 20030      }
 20031  
 20032    return ret;
 20033  }
 20034  
 20035  // Check whether the constant can be expressed in a floating point
 20036  // type.
 20037  
 20038  bool
 20039  Numeric_constant::check_float_type(Float_type* type, bool issue_error,
 20040  				   Location location)
 20041  {
 20042    mpfr_t val;
 20043    switch (this->classification_)
 20044      {
 20045      case NC_INT:
 20046      case NC_RUNE:
 20047        mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
 20048        break;
 20049  
 20050      case NC_FLOAT:
 20051        mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
 20052        break;
 20053  
 20054      case NC_COMPLEX:
 20055        if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
 20056  	{
 20057  	  if (issue_error)
 20058              {
 20059                this->set_invalid();
 20060                go_error_at(location,
 20061  			  "complex constant truncated to floating-point");
 20062              }
 20063  	  return false;
 20064  	}
 20065        mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
 20066        break;
 20067  
 20068      default:
 20069        go_unreachable();
 20070      }
 20071  
 20072    bool ret;
 20073    if (type->is_abstract())
 20074      ret = true;
 20075    else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
 20076      {
 20077        // A NaN or Infinity always fits in the range of the type.
 20078        ret = true;
 20079      }
 20080    else
 20081      {
 20082        mpfr_exp_t exp = mpfr_get_exp(val);
 20083        mpfr_exp_t max_exp;
 20084        switch (type->bits())
 20085  	{
 20086  	case 32:
 20087  	  max_exp = 128;
 20088  	  break;
 20089  	case 64:
 20090  	  max_exp = 1024;
 20091  	  break;
 20092  	default:
 20093  	  go_unreachable();
 20094  	}
 20095  
 20096        ret = exp <= max_exp;
 20097  
 20098        if (ret)
 20099  	{
 20100  	  // Round the constant to the desired type.
 20101  	  mpfr_t t;
 20102  	  mpfr_init(t);
 20103  	  switch (type->bits())
 20104  	    {
 20105  	    case 32:
 20106  	      mpfr_set_prec(t, 24);
 20107  	      break;
 20108  	    case 64:
 20109  	      mpfr_set_prec(t, 53);
 20110  	      break;
 20111  	    default:
 20112  	      go_unreachable();
 20113  	    }
 20114  	  mpfr_set(t, val, MPFR_RNDN);
 20115  	  mpfr_set(val, t, MPFR_RNDN);
 20116  	  mpfr_clear(t);
 20117  
 20118  	  this->set_float(type, val);
 20119  	}
 20120      }
 20121  
 20122    mpfr_clear(val);
 20123  
 20124    if (!ret && issue_error)
 20125      {
 20126        go_error_at(location, "floating-point constant overflow");
 20127        this->set_invalid();
 20128      }
 20129  
 20130    return ret;
 20131  }
 20132  
 20133  // Check whether the constant can be expressed in a complex type.
 20134  
 20135  bool
 20136  Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
 20137  				     Location location)
 20138  {
 20139    if (type->is_abstract())
 20140      return true;
 20141  
 20142    mpfr_exp_t max_exp;
 20143    switch (type->bits())
 20144      {
 20145      case 64:
 20146        max_exp = 128;
 20147        break;
 20148      case 128:
 20149        max_exp = 1024;
 20150        break;
 20151      default:
 20152        go_unreachable();
 20153      }
 20154  
 20155    mpc_t val;
 20156    mpc_init2(val, mpc_precision);
 20157    switch (this->classification_)
 20158      {
 20159      case NC_INT:
 20160      case NC_RUNE:
 20161        mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
 20162        break;
 20163  
 20164      case NC_FLOAT:
 20165        mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
 20166        break;
 20167  
 20168      case NC_COMPLEX:
 20169        mpc_set(val, this->u_.complex_val, MPC_RNDNN);
 20170        break;
 20171  
 20172      default:
 20173        go_unreachable();
 20174      }
 20175  
 20176    bool ret = true;
 20177    if (!mpfr_nan_p(mpc_realref(val))
 20178        && !mpfr_inf_p(mpc_realref(val))
 20179        && !mpfr_zero_p(mpc_realref(val))
 20180        && mpfr_get_exp(mpc_realref(val)) > max_exp)
 20181      {
 20182        if (issue_error)
 20183          {
 20184            go_error_at(location, "complex real part overflow");
 20185            this->set_invalid();
 20186          }
 20187        ret = false;
 20188      }
 20189  
 20190    if (!mpfr_nan_p(mpc_imagref(val))
 20191        && !mpfr_inf_p(mpc_imagref(val))
 20192        && !mpfr_zero_p(mpc_imagref(val))
 20193        && mpfr_get_exp(mpc_imagref(val)) > max_exp)
 20194      {
 20195        if (issue_error)
 20196          {
 20197            go_error_at(location, "complex imaginary part overflow");
 20198            this->set_invalid();
 20199          }
 20200        ret = false;
 20201      }
 20202  
 20203    if (ret)
 20204      {
 20205        // Round the constant to the desired type.
 20206        mpc_t t;
 20207        switch (type->bits())
 20208  	{
 20209  	case 64:
 20210  	  mpc_init2(t, 24);
 20211  	  break;
 20212  	case 128:
 20213  	  mpc_init2(t, 53);
 20214  	  break;
 20215  	default:
 20216  	  go_unreachable();
 20217  	}
 20218        mpc_set(t, val, MPC_RNDNN);
 20219        mpc_set(val, t, MPC_RNDNN);
 20220        mpc_clear(t);
 20221  
 20222        this->set_complex(type, val);
 20223      }
 20224  
 20225    mpc_clear(val);
 20226  
 20227    return ret;
 20228  }
 20229  
 20230  // Return an Expression for this value.
 20231  
 20232  Expression*
 20233  Numeric_constant::expression(Location loc) const
 20234  {
 20235    switch (this->classification_)
 20236      {
 20237      case NC_INT:
 20238        return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
 20239      case NC_RUNE:
 20240        return Expression::make_character(&this->u_.int_val, this->type_, loc);
 20241      case NC_FLOAT:
 20242        return Expression::make_float(&this->u_.float_val, this->type_, loc);
 20243      case NC_COMPLEX:
 20244        return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
 20245      case NC_INVALID:
 20246        go_assert(saw_errors());
 20247        return Expression::make_error(loc);
 20248      default:
 20249        go_unreachable();
 20250      }
 20251  }
 20252  
 20253  // Calculate a hash code with a given seed.
 20254  
 20255  unsigned int
 20256  Numeric_constant::hash(unsigned int seed) const
 20257  {
 20258    unsigned long val;
 20259    const unsigned int PRIME = 97;
 20260    long e = 0;
 20261    double f = 1.0;
 20262    mpfr_t m;
 20263  
 20264    switch (this->classification_)
 20265      {
 20266      case NC_INVALID:
 20267        return PRIME;
 20268      case NC_INT:
 20269      case NC_RUNE:
 20270        val = mpz_get_ui(this->u_.int_val);
 20271        break;
 20272      case NC_COMPLEX:
 20273        mpfr_init(m);
 20274        mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
 20275        val = mpfr_get_ui(m, MPFR_RNDN);
 20276        mpfr_clear(m);
 20277        break;
 20278      case NC_FLOAT:
 20279        f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
 20280        val = static_cast<unsigned long>(e + static_cast<long>(f));
 20281        break;
 20282      default:
 20283        go_unreachable();
 20284      }
 20285  
 20286    return (static_cast<unsigned int>(val) + seed) * PRIME;
 20287  }