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 
Expression(Expression_classification classification,Location location)27 Expression::Expression(Expression_classification classification,
28 		       Location location)
29   : classification_(classification), location_(location)
30 {
31 }
32 
~Expression()33 Expression::~Expression()
34 {
35 }
36 
37 // Traverse the expressions.
38 
39 int
traverse(Expression ** pexpr,Traverse * traverse)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
traverse_subexpressions(Traverse * traverse)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:
Set_location(Location loc)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
expression(Expression ** pexpr)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
set_location(Location loc)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
do_traverse(Traverse *)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
do_discarding_value()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
do_export(Export_function_body *) const146 Expression::do_export(Export_function_body*) const
147 {
148   go_unreachable();
149 }
150 
151 // Write a name to the export data.
152 
153 void
export_name(Export_function_body * efb,const Named_object * no)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
unused_value_error()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
set_is_error()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
report_error(const char * msg)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
determine_type(const Type_context * context)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
determine_type_no_context()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
is_same_variable(Expression * a,Expression * b)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*
convert_for_assignment(Gogo * gogo,Type * lhs_type,Expression * rhs,Location location)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*
convert_type_to_interface(Type * lhs_type,Expression * rhs,bool on_stack,Location location)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*
unpack_direct_iface(Expression * rhs,Location loc)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*
pack_direct_iface(Type * t,Expression * rhs,Location loc)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*
get_interface_type_descriptor(Expression * rhs)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*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)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*
convert_interface_to_type(Gogo * gogo,Type * lhs_type,Expression * rhs,Location location)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*
get_backend(Translate_context * context)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*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)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
check_bounds(Expression * val,Operator op,Expression * bound,Runtime::Function code,Runtime::Function code_u,Runtime::Function code_extend,Runtime::Function code_extend_u,Statement_inserter * inserter,Location loc)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
dump_expression(Ast_dump_context * ast_dump_context) const810 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:
Error_expression(Location location)820   Error_expression(Location location)
821     : Expression(EXPRESSION_ERROR, location)
822   { }
823 
824  protected:
825   bool
do_is_constant() const826   do_is_constant() const
827   { return true; }
828 
829   bool
do_numeric_constant_value(Numeric_constant * nc) const830   do_numeric_constant_value(Numeric_constant* nc) const
831   {
832     nc->set_unsigned_long(NULL, 0);
833     return true;
834   }
835 
836   bool
do_discarding_value()837   do_discarding_value()
838   { return true; }
839 
840   Type*
do_type()841   do_type()
842   { return Type::make_error_type(); }
843 
844   void
do_determine_type(const Type_context *)845   do_determine_type(const Type_context*)
846   { }
847 
848   Expression*
do_copy()849   do_copy()
850   { return this; }
851 
852   bool
do_is_addressable() const853   do_is_addressable() const
854   { return true; }
855 
856   Bexpression*
do_get_backend(Translate_context * context)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
do_dump_expression(Ast_dump_context * ast_dump_context) const867 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
868 {
869   ast_dump_context->ostream() << "_Error_" ;
870 }
871 
872 Expression*
make_error(Location location)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:
Type_expression(Type * type,Location location)885   Type_expression(Type* type, Location location)
886     : Expression(EXPRESSION_TYPE, location),
887       type_(type)
888   { }
889 
890  protected:
891   int
do_traverse(Traverse * traverse)892   do_traverse(Traverse* traverse)
893   { return Type::traverse(this->type_, traverse); }
894 
895   Type*
do_type()896   do_type()
897   { return this->type_; }
898 
899   void
do_determine_type(const Type_context *)900   do_determine_type(const Type_context*)
901   { }
902 
903   void
904   do_check_types(Gogo*);
905 
906   Expression*
do_copy()907   do_copy()
908   { return this; }
909 
910   Bexpression*
do_get_backend(Translate_context *)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
do_check_types(Gogo *)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
do_dump_expression(Ast_dump_context * ast_dump_context) const934 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*
make_type(Type * type,Location location)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*
do_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*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)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*
do_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
do_determine_type(const Type_context *)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
do_address_taken(bool escapes)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
do_export(Export_function_body * efb) const1043 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*
do_get_backend(Translate_context * context)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
do_dump_expression(Ast_dump_context * ast_dump_context) const1086 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*
make_var_reference(Named_object * var,Location location)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
do_traverse(Traverse *)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*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)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*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)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
do_address_taken(bool escapes)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
do_dump_expression(Ast_dump_context * adc) const1162 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*
make_enclosing_var_reference(Expression * reference,Named_object * var,Location location)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*
do_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
do_address_taken(bool)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
do_export(Export_function_body * efb) const1200 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*
do_import(Import_function_body * ifb,Location loc)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*
do_get_backend(Translate_context * context)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
do_dump_expression(Ast_dump_context * ast_dump_context) const1276 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*
make_temporary_reference(Temporary_statement * statement,Location location)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*
do_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
do_determine_type(const Type_context * context)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
do_address_taken(bool)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*
do_get_backend(Translate_context * context)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
do_dump_expression(Ast_dump_context * ast_dump_context) const1343 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*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)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:
Sink_expression(Location location)1367   Sink_expression(Location location)
1368     : Expression(EXPRESSION_SINK, location),
1369       type_(NULL), bvar_(NULL)
1370   { }
1371 
1372  protected:
1373   bool
do_discarding_value()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*
do_copy()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*
do_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
do_determine_type(const Type_context * context)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*
do_get_backend(Translate_context * context)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       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1430       Named_object* fn = context->function();
1431       go_assert(fn != NULL);
1432       Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1433       Btype* bt = this->type_->get_backend(context->gogo());
1434       Bstatement* decl;
1435       this->bvar_ =
1436 	gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1437 					    0, loc, &decl);
1438       Bexpression* var_ref =
1439           gogo->backend()->var_expression(this->bvar_, loc);
1440       var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1441       return var_ref;
1442     }
1443   return gogo->backend()->var_expression(this->bvar_, loc);
1444 }
1445 
1446 // Ast dump for sink expression.
1447 
1448 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1449 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1450 {
1451   ast_dump_context->ostream() << "_" ;
1452 }
1453 
1454 // Make a sink expression.
1455 
1456 Expression*
make_sink(Location location)1457 Expression::make_sink(Location location)
1458 {
1459   return new Sink_expression(location);
1460 }
1461 
1462 // Class Func_expression.
1463 
1464 // FIXME: Can a function expression appear in a constant expression?
1465 // The value is unchanging.  Initializing a constant to the address of
1466 // a function seems like it could work, though there might be little
1467 // point to it.
1468 
1469 // Traversal.
1470 
1471 int
do_traverse(Traverse * traverse)1472 Func_expression::do_traverse(Traverse* traverse)
1473 {
1474   return (this->closure_ == NULL
1475 	  ? TRAVERSE_CONTINUE
1476 	  : Expression::traverse(&this->closure_, traverse));
1477 }
1478 
1479 // Return the type of a function expression.
1480 
1481 Type*
do_type()1482 Func_expression::do_type()
1483 {
1484   if (this->function_->is_function())
1485     return this->function_->func_value()->type();
1486   else if (this->function_->is_function_declaration())
1487     return this->function_->func_declaration_value()->type();
1488   else
1489     go_unreachable();
1490 }
1491 
1492 // Get the backend representation for the code of a function expression.
1493 
1494 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1495 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1496 {
1497   Function_type* fntype;
1498   if (no->is_function())
1499     fntype = no->func_value()->type();
1500   else if (no->is_function_declaration())
1501     fntype = no->func_declaration_value()->type();
1502   else
1503     go_unreachable();
1504 
1505   // Builtin functions are handled specially by Call_expression.  We
1506   // can't take their address.
1507   if (fntype->is_builtin())
1508     {
1509       go_error_at(loc,
1510 		  ("invalid use of special built-in function %qs; "
1511 		   "must be called"),
1512 		  no->message_name().c_str());
1513       return gogo->backend()->error_expression();
1514     }
1515 
1516   Bfunction* fndecl;
1517   if (no->is_function())
1518     fndecl = no->func_value()->get_or_make_decl(gogo, no);
1519   else if (no->is_function_declaration())
1520     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1521   else
1522     go_unreachable();
1523 
1524   return gogo->backend()->function_code_expression(fndecl, loc);
1525 }
1526 
1527 // Get the backend representation for a function expression.  This is used when
1528 // we take the address of a function rather than simply calling it.  A func
1529 // value is represented as a pointer to a block of memory.  The first
1530 // word of that memory is a pointer to the function code.  The
1531 // remaining parts of that memory are the addresses of variables that
1532 // the function closes over.
1533 
1534 Bexpression*
do_get_backend(Translate_context * context)1535 Func_expression::do_get_backend(Translate_context* context)
1536 {
1537   // If there is no closure, just use the function descriptor.
1538   if (this->closure_ == NULL)
1539     {
1540       Gogo* gogo = context->gogo();
1541       Named_object* no = this->function_;
1542       Expression* descriptor;
1543       if (no->is_function())
1544 	descriptor = no->func_value()->descriptor(gogo, no);
1545       else if (no->is_function_declaration())
1546 	{
1547 	  if (no->func_declaration_value()->type()->is_builtin())
1548 	    {
1549 	      go_error_at(this->location(),
1550 			  ("invalid use of special built-in function %qs; "
1551 			   "must be called"),
1552 			  no->message_name().c_str());
1553 	      return gogo->backend()->error_expression();
1554 	    }
1555 	  descriptor = no->func_declaration_value()->descriptor(gogo, no);
1556 	}
1557       else
1558 	go_unreachable();
1559 
1560       Bexpression* bdesc = descriptor->get_backend(context);
1561       return gogo->backend()->address_expression(bdesc, this->location());
1562     }
1563 
1564   go_assert(this->function_->func_value()->enclosing() != NULL);
1565 
1566   // If there is a closure, then the closure is itself the function
1567   // expression.  It is a pointer to a struct whose first field points
1568   // to the function code and whose remaining fields are the addresses
1569   // of the closed-over variables.
1570   Bexpression *bexpr = this->closure_->get_backend(context);
1571 
1572   // Introduce a backend type conversion, to account for any differences
1573   // between the argument type (function descriptor, struct with a
1574   // single field) and the closure (struct with multiple fields).
1575   Gogo* gogo = context->gogo();
1576   Btype *btype = this->type()->get_backend(gogo);
1577   return gogo->backend()->convert_expression(btype, bexpr, this->location());
1578 }
1579 
1580 // The cost of inlining a function reference.
1581 
1582 int
do_inlining_cost() const1583 Func_expression::do_inlining_cost() const
1584 {
1585   // FIXME: We don't inline references to nested functions.
1586   if (this->closure_ != NULL)
1587     return 0x100000;
1588   if (this->function_->is_function()
1589       && this->function_->func_value()->enclosing() != NULL)
1590     return 0x100000;
1591 
1592   return 1;
1593 }
1594 
1595 // Export a reference to a function.
1596 
1597 void
do_export(Export_function_body * efb) const1598 Func_expression::do_export(Export_function_body* efb) const
1599 {
1600   Expression::export_name(efb, this->function_);
1601 }
1602 
1603 // Ast dump for function.
1604 
1605 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1606 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1607 {
1608   ast_dump_context->ostream() << this->function_->name();
1609   if (this->closure_ != NULL)
1610     {
1611       ast_dump_context->ostream() << " {closure =  ";
1612       this->closure_->dump_expression(ast_dump_context);
1613       ast_dump_context->ostream() << "}";
1614     }
1615 }
1616 
1617 // Make a reference to a function in an expression.
1618 
1619 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1620 Expression::make_func_reference(Named_object* function, Expression* closure,
1621 				Location location)
1622 {
1623   Func_expression* fe = new Func_expression(function, closure, location);
1624 
1625   // Detect references to builtin functions and set the runtime code if
1626   // appropriate.
1627   if (function->is_function_declaration())
1628     fe->set_runtime_code(Runtime::name_to_code(function->name()));
1629   return fe;
1630 }
1631 
1632 // Class Func_descriptor_expression.
1633 
1634 // Constructor.
1635 
Func_descriptor_expression(Named_object * fn)1636 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1637   : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1638     fn_(fn), dvar_(NULL)
1639 {
1640   go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1641 }
1642 
1643 // Traversal.
1644 
1645 int
do_traverse(Traverse *)1646 Func_descriptor_expression::do_traverse(Traverse*)
1647 {
1648   return TRAVERSE_CONTINUE;
1649 }
1650 
1651 // All function descriptors have the same type.
1652 
1653 Type* Func_descriptor_expression::descriptor_type;
1654 
1655 void
make_func_descriptor_type()1656 Func_descriptor_expression::make_func_descriptor_type()
1657 {
1658   if (Func_descriptor_expression::descriptor_type != NULL)
1659     return;
1660   Type* uintptr_type = Type::lookup_integer_type("uintptr");
1661   Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1662   Func_descriptor_expression::descriptor_type =
1663     Type::make_builtin_named_type("functionDescriptor", struct_type);
1664 }
1665 
1666 Type*
do_type()1667 Func_descriptor_expression::do_type()
1668 {
1669   Func_descriptor_expression::make_func_descriptor_type();
1670   return Func_descriptor_expression::descriptor_type;
1671 }
1672 
1673 // The backend representation for a function descriptor.
1674 
1675 Bexpression*
do_get_backend(Translate_context * context)1676 Func_descriptor_expression::do_get_backend(Translate_context* context)
1677 {
1678   Named_object* no = this->fn_;
1679   Location loc = no->location();
1680   if (this->dvar_ != NULL)
1681     return context->backend()->var_expression(this->dvar_, loc);
1682 
1683   Gogo* gogo = context->gogo();
1684   Backend_name bname;
1685   gogo->function_descriptor_backend_name(no, &bname);
1686   bool is_descriptor = false;
1687   if (no->is_function_declaration()
1688       && !no->func_declaration_value()->asm_name().empty()
1689       && Linemap::is_predeclared_location(no->location()))
1690     is_descriptor = true;
1691 
1692   // The runtime package implements some functions defined in the
1693   // syscall package.  Let the syscall package define the descriptor
1694   // in this case.
1695   if (gogo->compiling_runtime()
1696       && gogo->package_name() == "runtime"
1697       && no->is_function()
1698       && !no->func_value()->asm_name().empty()
1699       && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1700     is_descriptor = true;
1701 
1702   Btype* btype = this->type()->get_backend(gogo);
1703 
1704   Bvariable* bvar;
1705   if (no->package() != NULL || is_descriptor)
1706     bvar =
1707       context->backend()->immutable_struct_reference(bname.name(),
1708 						     bname.optional_asm_name(),
1709 						     btype, loc);
1710   else
1711     {
1712       Location bloc = Linemap::predeclared_location();
1713 
1714       // The runtime package has hash/equality functions that are
1715       // referenced by type descriptors outside of the runtime, so the
1716       // function descriptors must be visible even though they are not
1717       // exported.
1718       bool is_exported_runtime = false;
1719       if (gogo->compiling_runtime()
1720 	  && gogo->package_name() == "runtime"
1721 	  && (no->name().find("hash") != std::string::npos
1722 	      || no->name().find("equal") != std::string::npos))
1723 	is_exported_runtime = true;
1724 
1725       bool is_hidden = ((no->is_function()
1726 			 && no->func_value()->enclosing() != NULL)
1727 			|| (Gogo::is_hidden_name(no->name())
1728 			    && !is_exported_runtime)
1729 			|| Gogo::is_thunk(no));
1730 
1731       if (no->is_function() && no->func_value()->is_referenced_by_inline())
1732 	is_hidden = false;
1733 
1734       unsigned int flags = 0;
1735       if (is_hidden)
1736 	flags |= Backend::variable_is_hidden;
1737       bvar = context->backend()->immutable_struct(bname.name(),
1738 						  bname.optional_asm_name(),
1739 						  flags, btype, bloc);
1740       Expression_list* vals = new Expression_list();
1741       vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1742       Expression* init =
1743 	Expression::make_struct_composite_literal(this->type(), vals, bloc);
1744       Translate_context bcontext(gogo, NULL, NULL, NULL);
1745       bcontext.set_is_const();
1746       Bexpression* binit = init->get_backend(&bcontext);
1747       context->backend()->immutable_struct_set_init(bvar, bname.name(),
1748 						    flags, btype, bloc, binit);
1749     }
1750 
1751   this->dvar_ = bvar;
1752   return gogo->backend()->var_expression(bvar, loc);
1753 }
1754 
1755 // Print a function descriptor expression.
1756 
1757 void
do_dump_expression(Ast_dump_context * context) const1758 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1759 {
1760   context->ostream() << "[descriptor " << this->fn_->name() << "]";
1761 }
1762 
1763 // Make a function descriptor expression.
1764 
1765 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1766 Expression::make_func_descriptor(Named_object* fn)
1767 {
1768   return new Func_descriptor_expression(fn);
1769 }
1770 
1771 // Make the function descriptor type, so that it can be converted.
1772 
1773 void
make_func_descriptor_type()1774 Expression::make_func_descriptor_type()
1775 {
1776   Func_descriptor_expression::make_func_descriptor_type();
1777 }
1778 
1779 // A reference to just the code of a function.
1780 
1781 class Func_code_reference_expression : public Expression
1782 {
1783  public:
Func_code_reference_expression(Named_object * function,Location location)1784   Func_code_reference_expression(Named_object* function, Location location)
1785     : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1786       function_(function)
1787   { }
1788 
1789  protected:
1790   int
do_traverse(Traverse *)1791   do_traverse(Traverse*)
1792   { return TRAVERSE_CONTINUE; }
1793 
1794   bool
do_is_static_initializer() const1795   do_is_static_initializer() const
1796   { return true; }
1797 
1798   Type*
do_type()1799   do_type()
1800   { return Type::make_pointer_type(Type::make_void_type()); }
1801 
1802   void
do_determine_type(const Type_context *)1803   do_determine_type(const Type_context*)
1804   { }
1805 
1806   Expression*
do_copy()1807   do_copy()
1808   {
1809     return Expression::make_func_code_reference(this->function_,
1810 						this->location());
1811   }
1812 
1813   Bexpression*
1814   do_get_backend(Translate_context*);
1815 
1816   void
do_dump_expression(Ast_dump_context * context) const1817   do_dump_expression(Ast_dump_context* context) const
1818   { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1819 
1820  private:
1821   // The function.
1822   Named_object* function_;
1823 };
1824 
1825 // Get the backend representation for a reference to function code.
1826 
1827 Bexpression*
do_get_backend(Translate_context * context)1828 Func_code_reference_expression::do_get_backend(Translate_context* context)
1829 {
1830   return Func_expression::get_code_pointer(context->gogo(), this->function_,
1831 					   this->location());
1832 }
1833 
1834 // Make a reference to the code of a function.
1835 
1836 Expression*
make_func_code_reference(Named_object * function,Location location)1837 Expression::make_func_code_reference(Named_object* function, Location location)
1838 {
1839   return new Func_code_reference_expression(function, location);
1840 }
1841 
1842 // Class Unknown_expression.
1843 
1844 // Return the name of an unknown expression.
1845 
1846 const std::string&
name() const1847 Unknown_expression::name() const
1848 {
1849   return this->named_object_->name();
1850 }
1851 
1852 // Lower a reference to an unknown name.
1853 
1854 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1855 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1856 {
1857   Location location = this->location();
1858   Named_object* no = this->named_object_;
1859   Named_object* real;
1860   if (!no->is_unknown())
1861     real = no;
1862   else
1863     {
1864       real = no->unknown_value()->real_named_object();
1865       if (real == NULL)
1866 	{
1867 	  if (!this->no_error_message_)
1868 	    go_error_at(location, "reference to undefined name %qs",
1869 			this->named_object_->message_name().c_str());
1870 	  return Expression::make_error(location);
1871 	}
1872     }
1873   switch (real->classification())
1874     {
1875     case Named_object::NAMED_OBJECT_CONST:
1876       return Expression::make_const_reference(real, location);
1877     case Named_object::NAMED_OBJECT_TYPE:
1878       return Expression::make_type(real->type_value(), location);
1879     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1880       if (!this->no_error_message_)
1881 	go_error_at(location, "reference to undefined type %qs",
1882 		    real->message_name().c_str());
1883       return Expression::make_error(location);
1884     case Named_object::NAMED_OBJECT_VAR:
1885       real->var_value()->set_is_used();
1886       return Expression::make_var_reference(real, location);
1887     case Named_object::NAMED_OBJECT_FUNC:
1888     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1889       return Expression::make_func_reference(real, NULL, location);
1890     case Named_object::NAMED_OBJECT_PACKAGE:
1891       if (!this->no_error_message_)
1892 	go_error_at(location, "unexpected reference to package");
1893       return Expression::make_error(location);
1894     default:
1895       go_unreachable();
1896     }
1897 }
1898 
1899 // Dump the ast representation for an unknown expression to a dump context.
1900 
1901 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1902 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1903 {
1904   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1905 			      << ")";
1906 }
1907 
1908 // Make a reference to an unknown name.
1909 
1910 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1911 Expression::make_unknown_reference(Named_object* no, Location location)
1912 {
1913   return new Unknown_expression(no, location);
1914 }
1915 
1916 // Start exporting a type conversion for a constant, if needed.  This
1917 // returns whether we need to export a closing parenthesis.
1918 
1919 bool
export_constant_type(Export_function_body * efb,Type * type)1920 Expression::export_constant_type(Export_function_body* efb, Type* type)
1921 {
1922   if (type == NULL
1923       || type->is_abstract()
1924       || type == efb->type_context())
1925     return false;
1926   efb->write_c_string("$convert(");
1927   efb->write_type(type);
1928   efb->write_c_string(", ");
1929   return true;
1930 }
1931 
1932 // Finish a type conversion for a constant.
1933 
1934 void
finish_export_constant_type(Export_function_body * efb,bool needed)1935 Expression::finish_export_constant_type(Export_function_body* efb, bool needed)
1936 {
1937   if (needed)
1938     efb->write_c_string(")");
1939 }
1940 
1941 // A boolean expression.
1942 
1943 class Boolean_expression : public Expression
1944 {
1945  public:
Boolean_expression(bool val,Location location)1946   Boolean_expression(bool val, Location location)
1947     : Expression(EXPRESSION_BOOLEAN, location),
1948       val_(val), type_(NULL)
1949   { }
1950 
1951   static Expression*
1952   do_import(Import_expression*, Location);
1953 
1954  protected:
1955   int
1956   do_traverse(Traverse*);
1957 
1958   bool
do_is_constant() const1959   do_is_constant() const
1960   { return true; }
1961 
1962   bool
do_is_zero_value() const1963   do_is_zero_value() const
1964   { return this->val_ == false; }
1965 
1966   bool
do_boolean_constant_value(bool * val) const1967   do_boolean_constant_value(bool* val) const
1968   {
1969     *val = this->val_;
1970     return true;
1971   }
1972 
1973   bool
do_is_static_initializer() const1974   do_is_static_initializer() const
1975   { return true; }
1976 
1977   Type*
1978   do_type();
1979 
1980   void
1981   do_determine_type(const Type_context*);
1982 
1983   Expression*
do_copy()1984   do_copy()
1985   { return this; }
1986 
1987   Bexpression*
do_get_backend(Translate_context * context)1988   do_get_backend(Translate_context* context)
1989   { return context->backend()->boolean_constant_expression(this->val_); }
1990 
1991   int
do_inlining_cost() const1992   do_inlining_cost() const
1993   { return 1; }
1994 
1995   void
1996   do_export(Export_function_body* efb) const;
1997 
1998   void
do_dump_expression(Ast_dump_context * ast_dump_context) const1999   do_dump_expression(Ast_dump_context* ast_dump_context) const
2000   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
2001 
2002  private:
2003   // The constant.
2004   bool val_;
2005   // The type as determined by context.
2006   Type* type_;
2007 };
2008 
2009 // Traverse a boolean expression.  We just need to traverse the type
2010 // if there is one.
2011 
2012 int
do_traverse(Traverse * traverse)2013 Boolean_expression::do_traverse(Traverse* traverse)
2014 {
2015   if (this->type_ != NULL)
2016     return Type::traverse(this->type_, traverse);
2017   return TRAVERSE_CONTINUE;
2018 }
2019 
2020 // Get the type.
2021 
2022 Type*
do_type()2023 Boolean_expression::do_type()
2024 {
2025   if (this->type_ == NULL)
2026     this->type_ = Type::make_boolean_type();
2027   return this->type_;
2028 }
2029 
2030 // Set the type from the context.
2031 
2032 void
do_determine_type(const Type_context * context)2033 Boolean_expression::do_determine_type(const Type_context* context)
2034 {
2035   if (this->type_ != NULL && !this->type_->is_abstract())
2036     ;
2037   else if (context->type != NULL && context->type->is_boolean_type())
2038     this->type_ = context->type;
2039   else if (!context->may_be_abstract)
2040     this->type_ = Type::lookup_bool_type();
2041 }
2042 
2043 // Export a boolean constant.
2044 
2045 void
do_export(Export_function_body * efb) const2046 Boolean_expression::do_export(Export_function_body* efb) const
2047 {
2048   bool exported_type = Expression::export_constant_type(efb, this->type_);
2049   efb->write_c_string(this->val_ ? "$true" : "$false");
2050   Expression::finish_export_constant_type(efb, exported_type);
2051 }
2052 
2053 // Import a boolean constant.
2054 
2055 Expression*
do_import(Import_expression * imp,Location loc)2056 Boolean_expression::do_import(Import_expression* imp, Location loc)
2057 {
2058   if (imp->version() >= EXPORT_FORMAT_V3)
2059     imp->require_c_string("$");
2060   if (imp->peek_char() == 't')
2061     {
2062       imp->require_c_string("true");
2063       return Expression::make_boolean(true, loc);
2064     }
2065   else
2066     {
2067       imp->require_c_string("false");
2068       return Expression::make_boolean(false, loc);
2069     }
2070 }
2071 
2072 // Make a boolean expression.
2073 
2074 Expression*
make_boolean(bool val,Location location)2075 Expression::make_boolean(bool val, Location location)
2076 {
2077   return new Boolean_expression(val, location);
2078 }
2079 
2080 // Class String_expression.
2081 
2082 // Traverse a string expression.  We just need to traverse the type
2083 // if there is one.
2084 
2085 int
do_traverse(Traverse * traverse)2086 String_expression::do_traverse(Traverse* traverse)
2087 {
2088   if (this->type_ != NULL)
2089     return Type::traverse(this->type_, traverse);
2090   return TRAVERSE_CONTINUE;
2091 }
2092 
2093 // Get the type.
2094 
2095 Type*
do_type()2096 String_expression::do_type()
2097 {
2098   if (this->type_ == NULL)
2099     this->type_ = Type::make_string_type();
2100   return this->type_;
2101 }
2102 
2103 // Set the type from the context.
2104 
2105 void
do_determine_type(const Type_context * context)2106 String_expression::do_determine_type(const Type_context* context)
2107 {
2108   if (this->type_ != NULL && !this->type_->is_abstract())
2109     ;
2110   else if (context->type != NULL && context->type->is_string_type())
2111     this->type_ = context->type;
2112   else if (!context->may_be_abstract)
2113     this->type_ = Type::lookup_string_type();
2114 }
2115 
2116 // Build a string constant.
2117 
2118 Bexpression*
do_get_backend(Translate_context * context)2119 String_expression::do_get_backend(Translate_context* context)
2120 {
2121   Gogo* gogo = context->gogo();
2122   Btype* btype = Type::make_string_type()->get_backend(gogo);
2123 
2124   Location loc = this->location();
2125   std::vector<Bexpression*> init(2);
2126   Bexpression* str_cst =
2127       gogo->backend()->string_constant_expression(this->val_);
2128   init[0] = gogo->backend()->address_expression(str_cst, loc);
2129 
2130   Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
2131   mpz_t lenval;
2132   mpz_init_set_ui(lenval, this->val_.length());
2133   init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
2134   mpz_clear(lenval);
2135 
2136   return gogo->backend()->constructor_expression(btype, init, loc);
2137 }
2138 
2139  // Write string literal to string dump.
2140 
2141 void
export_string(String_dump * exp,const String_expression * str)2142 String_expression::export_string(String_dump* exp,
2143 				 const String_expression* str)
2144 {
2145   std::string s;
2146   s.reserve(str->val_.length() * 4 + 2);
2147   s += '"';
2148   for (std::string::const_iterator p = str->val_.begin();
2149        p != str->val_.end();
2150        ++p)
2151     {
2152       if (*p == '\\' || *p == '"')
2153 	{
2154 	  s += '\\';
2155 	  s += *p;
2156 	}
2157       else if (*p >= 0x20 && *p < 0x7f)
2158 	s += *p;
2159       else if (*p == '\n')
2160 	s += "\\n";
2161       else if (*p == '\t')
2162 	s += "\\t";
2163       else
2164 	{
2165 	  s += "\\x";
2166 	  unsigned char c = *p;
2167 	  unsigned int dig = c >> 4;
2168 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2169 	  dig = c & 0xf;
2170 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2171 	}
2172     }
2173   s += '"';
2174   exp->write_string(s);
2175 }
2176 
2177 // Export a string expression.
2178 
2179 void
do_export(Export_function_body * efb) const2180 String_expression::do_export(Export_function_body* efb) const
2181 {
2182   bool exported_type = Expression::export_constant_type(efb, this->type_);
2183   String_expression::export_string(efb, this);
2184   Expression::finish_export_constant_type(efb, exported_type);
2185 }
2186 
2187 // Import a string expression.
2188 
2189 Expression*
do_import(Import_expression * imp,Location loc)2190 String_expression::do_import(Import_expression* imp, Location loc)
2191 {
2192   imp->require_c_string("\"");
2193   std::string val;
2194   while (true)
2195     {
2196       int c = imp->get_char();
2197       if (c == '"' || c == -1)
2198 	break;
2199       if (c != '\\')
2200 	val += static_cast<char>(c);
2201       else
2202 	{
2203 	  c = imp->get_char();
2204 	  if (c == '\\' || c == '"')
2205 	    val += static_cast<char>(c);
2206 	  else if (c == 'n')
2207 	    val += '\n';
2208 	  else if (c == 't')
2209 	    val += '\t';
2210 	  else if (c == 'x')
2211 	    {
2212 	      c = imp->get_char();
2213 	      unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2214 	      c = imp->get_char();
2215 	      unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2216 	      char v = (vh << 4) | vl;
2217 	      val += v;
2218 	    }
2219 	  else
2220 	    {
2221 	      go_error_at(imp->location(), "bad string constant");
2222 	      return Expression::make_error(loc);
2223 	    }
2224 	}
2225     }
2226   return Expression::make_string(val, loc);
2227 }
2228 
2229 // Ast dump for string expression.
2230 
2231 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2232 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2233 {
2234   String_expression::export_string(ast_dump_context, this);
2235 }
2236 
2237 // Make a string expression with abstract string type (common case).
2238 
2239 Expression*
make_string(const std::string & val,Location location)2240 Expression::make_string(const std::string& val, Location location)
2241 {
2242   return new String_expression(val, NULL, location);
2243 }
2244 
2245 // Make a string expression with a specific string type.
2246 
2247 Expression*
make_string_typed(const std::string & val,Type * type,Location location)2248 Expression::make_string_typed(const std::string& val, Type* type, Location location)
2249 {
2250   return new String_expression(val, type, location);
2251 }
2252 
2253 // An expression that evaluates to some characteristic of a string.
2254 // This is used when indexing, bound-checking, or nil checking a string.
2255 
2256 class String_info_expression : public Expression
2257 {
2258  public:
String_info_expression(Expression * string,String_info string_info,Location location)2259   String_info_expression(Expression* string, String_info string_info,
2260                         Location location)
2261     : Expression(EXPRESSION_STRING_INFO, location),
2262       string_(string), string_info_(string_info)
2263   { }
2264 
2265  protected:
2266   Type*
2267   do_type();
2268 
2269   void
do_determine_type(const Type_context *)2270   do_determine_type(const Type_context*)
2271   { go_unreachable(); }
2272 
2273   Expression*
do_copy()2274   do_copy()
2275   {
2276     return new String_info_expression(this->string_->copy(), this->string_info_,
2277 				      this->location());
2278   }
2279 
2280   Bexpression*
2281   do_get_backend(Translate_context* context);
2282 
2283   void
2284   do_dump_expression(Ast_dump_context*) const;
2285 
2286   void
do_issue_nil_check()2287   do_issue_nil_check()
2288   { this->string_->issue_nil_check(); }
2289 
2290  private:
2291   // The string for which we are getting information.
2292   Expression* string_;
2293   // What information we want.
2294   String_info string_info_;
2295 };
2296 
2297 // Return the type of the string info.
2298 
2299 Type*
do_type()2300 String_info_expression::do_type()
2301 {
2302   switch (this->string_info_)
2303     {
2304     case STRING_INFO_DATA:
2305       {
2306 	Type* byte_type = Type::lookup_integer_type("uint8");
2307 	return Type::make_pointer_type(byte_type);
2308       }
2309     case STRING_INFO_LENGTH:
2310         return Type::lookup_integer_type("int");
2311     default:
2312       go_unreachable();
2313     }
2314 }
2315 
2316 // Return string information in GENERIC.
2317 
2318 Bexpression*
do_get_backend(Translate_context * context)2319 String_info_expression::do_get_backend(Translate_context* context)
2320 {
2321   Gogo* gogo = context->gogo();
2322 
2323   Bexpression* bstring = this->string_->get_backend(context);
2324   switch (this->string_info_)
2325     {
2326     case STRING_INFO_DATA:
2327     case STRING_INFO_LENGTH:
2328       return gogo->backend()->struct_field_expression(bstring,
2329 						      this->string_info_,
2330 						      this->location());
2331       break;
2332     default:
2333       go_unreachable();
2334     }
2335 }
2336 
2337 // Dump ast representation for a type info expression.
2338 
2339 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2340 String_info_expression::do_dump_expression(
2341     Ast_dump_context* ast_dump_context) const
2342 {
2343   ast_dump_context->ostream() << "stringinfo(";
2344   this->string_->dump_expression(ast_dump_context);
2345   ast_dump_context->ostream() << ",";
2346   ast_dump_context->ostream() <<
2347       (this->string_info_ == STRING_INFO_DATA ? "data"
2348     : this->string_info_ == STRING_INFO_LENGTH ? "length"
2349     : "unknown");
2350   ast_dump_context->ostream() << ")";
2351 }
2352 
2353 // Make a string info expression.
2354 
2355 Expression*
make_string_info(Expression * string,String_info string_info,Location location)2356 Expression::make_string_info(Expression* string, String_info string_info,
2357                             Location location)
2358 {
2359   return new String_info_expression(string, string_info, location);
2360 }
2361 
2362 // An expression that represents an string value: a struct with value pointer
2363 // and length fields.
2364 
2365 class String_value_expression : public Expression
2366 {
2367  public:
String_value_expression(Expression * valptr,Expression * len,Location location)2368   String_value_expression(Expression* valptr, Expression* len, Location location)
2369       : Expression(EXPRESSION_STRING_VALUE, location),
2370         valptr_(valptr), len_(len)
2371   { }
2372 
2373  protected:
2374   int
2375   do_traverse(Traverse*);
2376 
2377   Type*
do_type()2378   do_type()
2379   { return Type::make_string_type(); }
2380 
2381   void
do_determine_type(const Type_context *)2382   do_determine_type(const Type_context*)
2383   { go_unreachable(); }
2384 
2385   Expression*
do_copy()2386   do_copy()
2387   {
2388     return new String_value_expression(this->valptr_->copy(),
2389                                        this->len_->copy(),
2390                                        this->location());
2391   }
2392 
2393   Bexpression*
2394   do_get_backend(Translate_context* context);
2395 
2396   void
2397   do_dump_expression(Ast_dump_context*) const;
2398 
2399  private:
2400   // The value pointer.
2401   Expression* valptr_;
2402   // The length.
2403   Expression* len_;
2404 };
2405 
2406 int
do_traverse(Traverse * traverse)2407 String_value_expression::do_traverse(Traverse* traverse)
2408 {
2409   if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2410       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
2411     return TRAVERSE_EXIT;
2412   return TRAVERSE_CONTINUE;
2413 }
2414 
2415 Bexpression*
do_get_backend(Translate_context * context)2416 String_value_expression::do_get_backend(Translate_context* context)
2417 {
2418   std::vector<Bexpression*> vals(2);
2419   vals[0] = this->valptr_->get_backend(context);
2420   vals[1] = this->len_->get_backend(context);
2421 
2422   Gogo* gogo = context->gogo();
2423   Btype* btype = Type::make_string_type()->get_backend(gogo);
2424   return gogo->backend()->constructor_expression(btype, vals, this->location());
2425 }
2426 
2427 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2428 String_value_expression::do_dump_expression(
2429     Ast_dump_context* ast_dump_context) const
2430 {
2431   ast_dump_context->ostream() << "stringvalue(";
2432   ast_dump_context->ostream() << "value: ";
2433   this->valptr_->dump_expression(ast_dump_context);
2434   ast_dump_context->ostream() << ", length: ";
2435   this->len_->dump_expression(ast_dump_context);
2436   ast_dump_context->ostream() << ")";
2437 }
2438 
2439 Expression*
make_string_value(Expression * valptr,Expression * len,Location location)2440 Expression::make_string_value(Expression* valptr, Expression* len,
2441                               Location location)
2442 {
2443   return new String_value_expression(valptr, len, location);
2444 }
2445 
2446 // Make an integer expression.
2447 
2448 class Integer_expression : public Expression
2449 {
2450  public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)2451   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
2452 		     Location location)
2453     : Expression(EXPRESSION_INTEGER, location),
2454       type_(type), is_character_constant_(is_character_constant)
2455   { mpz_init_set(this->val_, *val); }
2456 
2457   static Expression*
2458   do_import(Import_expression*, Location);
2459 
2460   // Write VAL to string dump.
2461   static void
2462   export_integer(String_dump* exp, const mpz_t val);
2463 
2464   // Write VAL to dump context.
2465   static void
2466   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
2467 
2468  protected:
2469   int
2470   do_traverse(Traverse*);
2471 
2472   bool
do_is_constant() const2473   do_is_constant() const
2474   { return true; }
2475 
2476   bool
do_is_zero_value() const2477   do_is_zero_value() const
2478   { return mpz_sgn(this->val_) == 0; }
2479 
2480   bool
do_is_static_initializer() const2481   do_is_static_initializer() const
2482   { return true; }
2483 
2484   bool
2485   do_numeric_constant_value(Numeric_constant* nc) const;
2486 
2487   Type*
2488   do_type();
2489 
2490   void
2491   do_determine_type(const Type_context* context);
2492 
2493   void
2494   do_check_types(Gogo*);
2495 
2496   Bexpression*
2497   do_get_backend(Translate_context*);
2498 
2499   Expression*
do_copy()2500   do_copy()
2501   {
2502     if (this->is_character_constant_)
2503       return Expression::make_character(&this->val_,
2504 					(this->type_ == NULL
2505 					 ? NULL
2506 					 : this->type_->copy_expressions()),
2507 					this->location());
2508     else
2509       return Expression::make_integer_z(&this->val_,
2510 					(this->type_ == NULL
2511 					 ? NULL
2512 					 : this->type_->copy_expressions()),
2513 					this->location());
2514   }
2515 
2516   int
do_inlining_cost() const2517   do_inlining_cost() const
2518   { return 1; }
2519 
2520   void
2521   do_export(Export_function_body*) const;
2522 
2523   void
2524   do_dump_expression(Ast_dump_context*) const;
2525 
2526  private:
2527   // The integer value.
2528   mpz_t val_;
2529   // The type so far.
2530   Type* type_;
2531   // Whether this is a character constant.
2532   bool is_character_constant_;
2533 };
2534 
2535 // Traverse an integer expression.  We just need to traverse the type
2536 // if there is one.
2537 
2538 int
do_traverse(Traverse * traverse)2539 Integer_expression::do_traverse(Traverse* traverse)
2540 {
2541   if (this->type_ != NULL)
2542     return Type::traverse(this->type_, traverse);
2543   return TRAVERSE_CONTINUE;
2544 }
2545 
2546 // Return a numeric constant for this expression.  We have to mark
2547 // this as a character when appropriate.
2548 
2549 bool
do_numeric_constant_value(Numeric_constant * nc) const2550 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
2551 {
2552   if (this->is_character_constant_)
2553     nc->set_rune(this->type_, this->val_);
2554   else
2555     nc->set_int(this->type_, this->val_);
2556   return true;
2557 }
2558 
2559 // Return the current type.  If we haven't set the type yet, we return
2560 // an abstract integer type.
2561 
2562 Type*
do_type()2563 Integer_expression::do_type()
2564 {
2565   if (this->type_ == NULL)
2566     {
2567       if (this->is_character_constant_)
2568 	this->type_ = Type::make_abstract_character_type();
2569       else
2570 	this->type_ = Type::make_abstract_integer_type();
2571     }
2572   return this->type_;
2573 }
2574 
2575 // Set the type of the integer value.  Here we may switch from an
2576 // abstract type to a real type.
2577 
2578 void
do_determine_type(const Type_context * context)2579 Integer_expression::do_determine_type(const Type_context* context)
2580 {
2581   if (this->type_ != NULL && !this->type_->is_abstract())
2582     ;
2583   else if (context->type != NULL && context->type->is_numeric_type())
2584     this->type_ = context->type;
2585   else if (!context->may_be_abstract)
2586     {
2587       if (this->is_character_constant_)
2588 	this->type_ = Type::lookup_integer_type("int32");
2589       else
2590 	this->type_ = Type::lookup_integer_type("int");
2591     }
2592 }
2593 
2594 // Check the type of an integer constant.
2595 
2596 void
do_check_types(Gogo *)2597 Integer_expression::do_check_types(Gogo*)
2598 {
2599   Type* type = this->type_;
2600   if (type == NULL)
2601     return;
2602   Numeric_constant nc;
2603   if (this->is_character_constant_)
2604     nc.set_rune(NULL, this->val_);
2605   else
2606     nc.set_int(NULL, this->val_);
2607   if (!nc.set_type(type, true, this->location()))
2608     this->set_is_error();
2609 }
2610 
2611 // Get the backend representation for an integer constant.
2612 
2613 Bexpression*
do_get_backend(Translate_context * context)2614 Integer_expression::do_get_backend(Translate_context* context)
2615 {
2616   if (this->is_error_expression()
2617       || (this->type_ != NULL && this->type_->is_error_type()))
2618     {
2619       go_assert(saw_errors());
2620       return context->gogo()->backend()->error_expression();
2621     }
2622 
2623   Type* resolved_type = NULL;
2624   if (this->type_ != NULL && !this->type_->is_abstract())
2625     resolved_type = this->type_;
2626   else if (this->type_ != NULL && this->type_->float_type() != NULL)
2627     {
2628       // We are converting to an abstract floating point type.
2629       resolved_type = Type::lookup_float_type("float64");
2630     }
2631   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2632     {
2633       // We are converting to an abstract complex type.
2634       resolved_type = Type::lookup_complex_type("complex128");
2635     }
2636   else
2637     {
2638       // If we still have an abstract type here, then this is being
2639       // used in a constant expression which didn't get reduced for
2640       // some reason.  Use a type which will fit the value.  We use <,
2641       // not <=, because we need an extra bit for the sign bit.
2642       int bits = mpz_sizeinbase(this->val_, 2);
2643       Type* int_type = Type::lookup_integer_type("int");
2644       if (bits < int_type->integer_type()->bits())
2645 	resolved_type = int_type;
2646       else if (bits < 64)
2647         resolved_type = Type::lookup_integer_type("int64");
2648       else
2649         {
2650           if (!saw_errors())
2651             go_error_at(this->location(),
2652                         "unknown type for large integer constant");
2653           return context->gogo()->backend()->error_expression();
2654         }
2655     }
2656   Numeric_constant nc;
2657   nc.set_int(resolved_type, this->val_);
2658   return Expression::backend_numeric_constant_expression(context, &nc);
2659 }
2660 
2661 // Write VAL to export data.
2662 
2663 void
export_integer(String_dump * exp,const mpz_t val)2664 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2665 {
2666   char* s = mpz_get_str(NULL, 10, val);
2667   exp->write_c_string(s);
2668   free(s);
2669 }
2670 
2671 // Export an integer in a constant expression.
2672 
2673 void
do_export(Export_function_body * efb) const2674 Integer_expression::do_export(Export_function_body* efb) const
2675 {
2676   bool exported_type = Expression::export_constant_type(efb, this->type_);
2677 
2678   Integer_expression::export_integer(efb, this->val_);
2679   if (this->is_character_constant_)
2680     efb->write_c_string("'");
2681   // A trailing space lets us reliably identify the end of the number.
2682   efb->write_c_string(" ");
2683 
2684   Expression::finish_export_constant_type(efb, exported_type);
2685 }
2686 
2687 // Import an integer, floating point, or complex value.  This handles
2688 // all these types because they all start with digits.
2689 
2690 Expression*
do_import(Import_expression * imp,Location loc)2691 Integer_expression::do_import(Import_expression* imp, Location loc)
2692 {
2693   std::string num = imp->read_identifier();
2694   imp->require_c_string(" ");
2695   if (!num.empty() && num[num.length() - 1] == 'i')
2696     {
2697       mpfr_t real;
2698       size_t plus_pos = num.find('+', 1);
2699       size_t minus_pos = num.find('-', 1);
2700       size_t pos;
2701       if (plus_pos == std::string::npos)
2702 	pos = minus_pos;
2703       else if (minus_pos == std::string::npos)
2704 	pos = plus_pos;
2705       else
2706 	{
2707 	  go_error_at(imp->location(), "bad number in import data: %qs",
2708 		      num.c_str());
2709 	  return Expression::make_error(loc);
2710 	}
2711       if (pos == std::string::npos)
2712 	mpfr_set_ui(real, 0, MPFR_RNDN);
2713       else
2714 	{
2715 	  std::string real_str = num.substr(0, pos);
2716 	  if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
2717 	    {
2718 	      go_error_at(imp->location(), "bad number in import data: %qs",
2719 			  real_str.c_str());
2720 	      return Expression::make_error(loc);
2721 	    }
2722 	}
2723 
2724       std::string imag_str;
2725       if (pos == std::string::npos)
2726 	imag_str = num;
2727       else
2728 	imag_str = num.substr(pos);
2729       imag_str = imag_str.substr(0, imag_str.size() - 1);
2730       mpfr_t imag;
2731       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
2732 	{
2733 	  go_error_at(imp->location(), "bad number in import data: %qs",
2734 		      imag_str.c_str());
2735 	  return Expression::make_error(loc);
2736 	}
2737       mpc_t cval;
2738       mpc_init2(cval, mpc_precision);
2739       mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2740       mpfr_clear(real);
2741       mpfr_clear(imag);
2742       Expression* ret = Expression::make_complex(&cval, NULL, loc);
2743       mpc_clear(cval);
2744       return ret;
2745     }
2746   else if (num.find('.') == std::string::npos
2747 	   && num.find('E') == std::string::npos)
2748     {
2749       bool is_character_constant = (!num.empty()
2750 				    && num[num.length() - 1] == '\'');
2751       if (is_character_constant)
2752 	num = num.substr(0, num.length() - 1);
2753       mpz_t val;
2754       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2755 	{
2756 	  go_error_at(imp->location(), "bad number in import data: %qs",
2757 		      num.c_str());
2758 	  return Expression::make_error(loc);
2759 	}
2760       Expression* ret;
2761       if (is_character_constant)
2762 	ret = Expression::make_character(&val, NULL, loc);
2763       else
2764 	ret = Expression::make_integer_z(&val, NULL, loc);
2765       mpz_clear(val);
2766       return ret;
2767     }
2768   else
2769     {
2770       mpfr_t val;
2771       if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
2772 	{
2773 	  go_error_at(imp->location(), "bad number in import data: %qs",
2774 		      num.c_str());
2775 	  return Expression::make_error(loc);
2776 	}
2777       Expression* ret = Expression::make_float(&val, NULL, loc);
2778       mpfr_clear(val);
2779       return ret;
2780     }
2781 }
2782 // Ast dump for integer expression.
2783 
2784 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2785 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2786 {
2787   if (this->is_character_constant_)
2788     ast_dump_context->ostream() << '\'';
2789   Integer_expression::export_integer(ast_dump_context, this->val_);
2790   if (this->is_character_constant_)
2791     ast_dump_context->ostream() << '\'';
2792 }
2793 
2794 // Build a new integer value from a multi-precision integer.
2795 
2796 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2797 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2798 {
2799   return new Integer_expression(val, type, false, location);
2800 }
2801 
2802 // Build a new integer value from an unsigned long.
2803 
2804 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2805 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2806 {
2807   mpz_t zval;
2808   mpz_init_set_ui(zval, val);
2809   Expression* ret = Expression::make_integer_z(&zval, type, location);
2810   mpz_clear(zval);
2811   return ret;
2812 }
2813 
2814 // Build a new integer value from a signed long.
2815 
2816 Expression*
make_integer_sl(long val,Type * type,Location location)2817 Expression::make_integer_sl(long val, Type *type, Location location)
2818 {
2819   mpz_t zval;
2820   mpz_init_set_si(zval, val);
2821   Expression* ret = Expression::make_integer_z(&zval, type, location);
2822   mpz_clear(zval);
2823   return ret;
2824 }
2825 
2826 // Store an int64_t in an uninitialized mpz_t.
2827 
2828 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2829 set_mpz_from_int64(mpz_t* zval, int64_t val)
2830 {
2831   if (val >= 0)
2832     {
2833       unsigned long ul = static_cast<unsigned long>(val);
2834       if (static_cast<int64_t>(ul) == val)
2835 	{
2836 	  mpz_init_set_ui(*zval, ul);
2837 	  return;
2838 	}
2839     }
2840   uint64_t uv;
2841   if (val >= 0)
2842     uv = static_cast<uint64_t>(val);
2843   else
2844     uv = static_cast<uint64_t>(- val);
2845   unsigned long ul = uv & 0xffffffffUL;
2846   mpz_init_set_ui(*zval, ul);
2847   mpz_t hval;
2848   mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2849   mpz_mul_2exp(hval, hval, 32);
2850   mpz_add(*zval, *zval, hval);
2851   mpz_clear(hval);
2852   if (val < 0)
2853     mpz_neg(*zval, *zval);
2854 }
2855 
2856 // Build a new integer value from an int64_t.
2857 
2858 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2859 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2860 {
2861   mpz_t zval;
2862   set_mpz_from_int64(&zval, val);
2863   Expression* ret = Expression::make_integer_z(&zval, type, location);
2864   mpz_clear(zval);
2865   return ret;
2866 }
2867 
2868 // Build a new character constant value.
2869 
2870 Expression*
make_character(const mpz_t * val,Type * type,Location location)2871 Expression::make_character(const mpz_t* val, Type* type, Location location)
2872 {
2873   return new Integer_expression(val, type, true, location);
2874 }
2875 
2876 // Floats.
2877 
2878 class Float_expression : public Expression
2879 {
2880  public:
Float_expression(const mpfr_t * val,Type * type,Location location)2881   Float_expression(const mpfr_t* val, Type* type, Location location)
2882     : Expression(EXPRESSION_FLOAT, location),
2883       type_(type)
2884   {
2885     mpfr_init_set(this->val_, *val, MPFR_RNDN);
2886   }
2887 
2888   // Write VAL to export data.
2889   static void
2890   export_float(String_dump* exp, const mpfr_t val);
2891 
2892   // Write VAL to dump file.
2893   static void
2894   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2895 
2896  protected:
2897   int
2898   do_traverse(Traverse*);
2899 
2900   bool
do_is_constant() const2901   do_is_constant() const
2902   { return true; }
2903 
2904   bool
do_is_zero_value() const2905   do_is_zero_value() const
2906   {
2907     return mpfr_zero_p(this->val_) != 0
2908            && mpfr_signbit(this->val_) == 0;
2909   }
2910 
2911   bool
do_is_static_initializer() const2912   do_is_static_initializer() const
2913   { return true; }
2914 
2915   bool
do_numeric_constant_value(Numeric_constant * nc) const2916   do_numeric_constant_value(Numeric_constant* nc) const
2917   {
2918     nc->set_float(this->type_, this->val_);
2919     return true;
2920   }
2921 
2922   Type*
2923   do_type();
2924 
2925   void
2926   do_determine_type(const Type_context*);
2927 
2928   void
2929   do_check_types(Gogo*);
2930 
2931   Expression*
do_copy()2932   do_copy()
2933   { return Expression::make_float(&this->val_,
2934 				  (this->type_ == NULL
2935 				   ? NULL
2936 				   : this->type_->copy_expressions()),
2937 				  this->location()); }
2938 
2939   Bexpression*
2940   do_get_backend(Translate_context*);
2941 
2942   int
do_inlining_cost() const2943   do_inlining_cost() const
2944   { return 1; }
2945 
2946   void
2947   do_export(Export_function_body*) const;
2948 
2949   void
2950   do_dump_expression(Ast_dump_context*) const;
2951 
2952  private:
2953   // The floating point value.
2954   mpfr_t val_;
2955   // The type so far.
2956   Type* type_;
2957 };
2958 
2959 // Traverse a float expression.  We just need to traverse the type if
2960 // there is one.
2961 
2962 int
do_traverse(Traverse * traverse)2963 Float_expression::do_traverse(Traverse* traverse)
2964 {
2965   if (this->type_ != NULL)
2966     return Type::traverse(this->type_, traverse);
2967   return TRAVERSE_CONTINUE;
2968 }
2969 
2970 // Return the current type.  If we haven't set the type yet, we return
2971 // an abstract float type.
2972 
2973 Type*
do_type()2974 Float_expression::do_type()
2975 {
2976   if (this->type_ == NULL)
2977     this->type_ = Type::make_abstract_float_type();
2978   return this->type_;
2979 }
2980 
2981 // Set the type of the float value.  Here we may switch from an
2982 // abstract type to a real type.
2983 
2984 void
do_determine_type(const Type_context * context)2985 Float_expression::do_determine_type(const Type_context* context)
2986 {
2987   if (this->type_ != NULL && !this->type_->is_abstract())
2988     ;
2989   else if (context->type != NULL
2990 	   && (context->type->integer_type() != NULL
2991 	       || context->type->float_type() != NULL
2992 	       || context->type->complex_type() != NULL))
2993     this->type_ = context->type;
2994   else if (!context->may_be_abstract)
2995     this->type_ = Type::lookup_float_type("float64");
2996 }
2997 
2998 // Check the type of a float value.
2999 
3000 void
do_check_types(Gogo *)3001 Float_expression::do_check_types(Gogo*)
3002 {
3003   Type* type = this->type_;
3004   if (type == NULL)
3005     return;
3006   Numeric_constant nc;
3007   nc.set_float(NULL, this->val_);
3008   if (!nc.set_type(this->type_, true, this->location()))
3009     this->set_is_error();
3010 }
3011 
3012 // Get the backend representation for a float constant.
3013 
3014 Bexpression*
do_get_backend(Translate_context * context)3015 Float_expression::do_get_backend(Translate_context* context)
3016 {
3017   if (this->is_error_expression()
3018       || (this->type_ != NULL && this->type_->is_error_type()))
3019     {
3020       go_assert(saw_errors());
3021       return context->gogo()->backend()->error_expression();
3022     }
3023 
3024   Type* resolved_type;
3025   if (this->type_ != NULL && !this->type_->is_abstract())
3026     resolved_type = this->type_;
3027   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3028     {
3029       // We have an abstract integer type.  We just hope for the best.
3030       resolved_type = Type::lookup_integer_type("int");
3031     }
3032   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
3033     {
3034       // We are converting to an abstract complex type.
3035       resolved_type = Type::lookup_complex_type("complex128");
3036     }
3037   else
3038     {
3039       // If we still have an abstract type here, then this is being
3040       // used in a constant expression which didn't get reduced.  We
3041       // just use float64 and hope for the best.
3042       resolved_type = Type::lookup_float_type("float64");
3043     }
3044 
3045   Numeric_constant nc;
3046   nc.set_float(resolved_type, this->val_);
3047   return Expression::backend_numeric_constant_expression(context, &nc);
3048 }
3049 
3050 // Write a floating point number to a string dump.
3051 
3052 void
export_float(String_dump * exp,const mpfr_t val)3053 Float_expression::export_float(String_dump *exp, const mpfr_t val)
3054 {
3055   mpfr_exp_t exponent;
3056   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
3057   if (*s == '-')
3058     exp->write_c_string("-");
3059   exp->write_c_string("0.");
3060   exp->write_c_string(*s == '-' ? s + 1 : s);
3061   mpfr_free_str(s);
3062   char buf[30];
3063   snprintf(buf, sizeof buf, "E%ld", exponent);
3064   exp->write_c_string(buf);
3065 }
3066 
3067 // Export a floating point number in a constant expression.
3068 
3069 void
do_export(Export_function_body * efb) const3070 Float_expression::do_export(Export_function_body* efb) const
3071 {
3072   bool exported_type = Expression::export_constant_type(efb, this->type_);
3073 
3074   Float_expression::export_float(efb, this->val_);
3075   // A trailing space lets us reliably identify the end of the number.
3076   efb->write_c_string(" ");
3077 
3078   Expression::finish_export_constant_type(efb, exported_type);
3079 }
3080 
3081 // Dump a floating point number to the dump file.
3082 
3083 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3084 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3085 {
3086   Float_expression::export_float(ast_dump_context, this->val_);
3087 }
3088 
3089 // Make a float expression.
3090 
3091 Expression*
make_float(const mpfr_t * val,Type * type,Location location)3092 Expression::make_float(const mpfr_t* val, Type* type, Location location)
3093 {
3094   return new Float_expression(val, type, location);
3095 }
3096 
3097 // Complex numbers.
3098 
3099 class Complex_expression : public Expression
3100 {
3101  public:
Complex_expression(const mpc_t * val,Type * type,Location location)3102   Complex_expression(const mpc_t* val, Type* type, Location location)
3103     : Expression(EXPRESSION_COMPLEX, location),
3104       type_(type)
3105   {
3106     mpc_init2(this->val_, mpc_precision);
3107     mpc_set(this->val_, *val, MPC_RNDNN);
3108   }
3109 
3110   // Write VAL to string dump.
3111   static void
3112   export_complex(String_dump* exp, const mpc_t val);
3113 
3114   // Write REAL/IMAG to dump context.
3115   static void
3116   dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
3117 
3118  protected:
3119   int
3120   do_traverse(Traverse*);
3121 
3122   bool
do_is_constant() const3123   do_is_constant() const
3124   { return true; }
3125 
3126   bool
do_is_zero_value() const3127   do_is_zero_value() const
3128   {
3129     return mpfr_zero_p(mpc_realref(this->val_)) != 0
3130            && mpfr_signbit(mpc_realref(this->val_)) == 0
3131            && mpfr_zero_p(mpc_imagref(this->val_)) != 0
3132            && mpfr_signbit(mpc_imagref(this->val_)) == 0;
3133   }
3134 
3135   bool
do_is_static_initializer() const3136   do_is_static_initializer() const
3137   { return true; }
3138 
3139   bool
do_numeric_constant_value(Numeric_constant * nc) const3140   do_numeric_constant_value(Numeric_constant* nc) const
3141   {
3142     nc->set_complex(this->type_, this->val_);
3143     return true;
3144   }
3145 
3146   Type*
3147   do_type();
3148 
3149   void
3150   do_determine_type(const Type_context*);
3151 
3152   void
3153   do_check_types(Gogo*);
3154 
3155   Expression*
do_copy()3156   do_copy()
3157   {
3158     return Expression::make_complex(&this->val_,
3159 				    (this->type_ == NULL
3160 				     ? NULL
3161 				     : this->type_->copy_expressions()),
3162 				    this->location());
3163   }
3164 
3165   Bexpression*
3166   do_get_backend(Translate_context*);
3167 
3168   int
do_inlining_cost() const3169   do_inlining_cost() const
3170   { return 2; }
3171 
3172   void
3173   do_export(Export_function_body*) const;
3174 
3175   void
3176   do_dump_expression(Ast_dump_context*) const;
3177 
3178  private:
3179   // The complex value.
3180   mpc_t val_;
3181   // The type if known.
3182   Type* type_;
3183 };
3184 
3185 // Traverse a complex expression.  We just need to traverse the type
3186 // if there is one.
3187 
3188 int
do_traverse(Traverse * traverse)3189 Complex_expression::do_traverse(Traverse* traverse)
3190 {
3191   if (this->type_ != NULL)
3192     return Type::traverse(this->type_, traverse);
3193   return TRAVERSE_CONTINUE;
3194 }
3195 
3196 // Return the current type.  If we haven't set the type yet, we return
3197 // an abstract complex type.
3198 
3199 Type*
do_type()3200 Complex_expression::do_type()
3201 {
3202   if (this->type_ == NULL)
3203     this->type_ = Type::make_abstract_complex_type();
3204   return this->type_;
3205 }
3206 
3207 // Set the type of the complex value.  Here we may switch from an
3208 // abstract type to a real type.
3209 
3210 void
do_determine_type(const Type_context * context)3211 Complex_expression::do_determine_type(const Type_context* context)
3212 {
3213   if (this->type_ != NULL && !this->type_->is_abstract())
3214     ;
3215   else if (context->type != NULL && context->type->is_numeric_type())
3216     this->type_ = context->type;
3217   else if (!context->may_be_abstract)
3218     this->type_ = Type::lookup_complex_type("complex128");
3219 }
3220 
3221 // Check the type of a complex value.
3222 
3223 void
do_check_types(Gogo *)3224 Complex_expression::do_check_types(Gogo*)
3225 {
3226   Type* type = this->type_;
3227   if (type == NULL)
3228     return;
3229   Numeric_constant nc;
3230   nc.set_complex(NULL, this->val_);
3231   if (!nc.set_type(this->type_, true, this->location()))
3232     this->set_is_error();
3233 }
3234 
3235 // Get the backend representation for a complex constant.
3236 
3237 Bexpression*
do_get_backend(Translate_context * context)3238 Complex_expression::do_get_backend(Translate_context* context)
3239 {
3240   if (this->is_error_expression()
3241       || (this->type_ != NULL && this->type_->is_error_type()))
3242     {
3243       go_assert(saw_errors());
3244       return context->gogo()->backend()->error_expression();
3245     }
3246 
3247   Type* resolved_type;
3248   if (this->type_ != NULL && !this->type_->is_abstract())
3249     resolved_type = this->type_;
3250   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3251     {
3252       // We are converting to an abstract integer type.
3253       resolved_type = Type::lookup_integer_type("int");
3254     }
3255   else if (this->type_ != NULL && this->type_->float_type() != NULL)
3256     {
3257       // We are converting to an abstract float type.
3258       resolved_type = Type::lookup_float_type("float64");
3259     }
3260   else
3261     {
3262       // If we still have an abstract type here, this is being
3263       // used in a constant expression which didn't get reduced.  We
3264       // just use complex128 and hope for the best.
3265       resolved_type = Type::lookup_complex_type("complex128");
3266     }
3267 
3268   Numeric_constant nc;
3269   nc.set_complex(resolved_type, this->val_);
3270   return Expression::backend_numeric_constant_expression(context, &nc);
3271 }
3272 
3273 // Write REAL/IMAG to export data.
3274 
3275 void
export_complex(String_dump * exp,const mpc_t val)3276 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
3277 {
3278   if (!mpfr_zero_p(mpc_realref(val)))
3279     {
3280       Float_expression::export_float(exp, mpc_realref(val));
3281       if (mpfr_sgn(mpc_imagref(val)) >= 0)
3282 	exp->write_c_string("+");
3283     }
3284   Float_expression::export_float(exp, mpc_imagref(val));
3285   exp->write_c_string("i");
3286 }
3287 
3288 // Export a complex number in a constant expression.
3289 
3290 void
do_export(Export_function_body * efb) const3291 Complex_expression::do_export(Export_function_body* efb) const
3292 {
3293   bool exported_type = Expression::export_constant_type(efb, this->type_);
3294 
3295   Complex_expression::export_complex(efb, this->val_);
3296   // A trailing space lets us reliably identify the end of the number.
3297   efb->write_c_string(" ");
3298 
3299   Expression::finish_export_constant_type(efb, exported_type);
3300 }
3301 
3302 // Dump a complex expression to the dump file.
3303 
3304 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3305 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3306 {
3307   Complex_expression::export_complex(ast_dump_context, this->val_);
3308 }
3309 
3310 // Make a complex expression.
3311 
3312 Expression*
make_complex(const mpc_t * val,Type * type,Location location)3313 Expression::make_complex(const mpc_t* val, Type* type, Location location)
3314 {
3315   return new Complex_expression(val, type, location);
3316 }
3317 
3318 // Find a named object in an expression.
3319 
3320 class Find_named_object : public Traverse
3321 {
3322  public:
Find_named_object(Named_object * no)3323   Find_named_object(Named_object* no)
3324     : Traverse(traverse_expressions),
3325       no_(no), found_(false)
3326   { }
3327 
3328   // Whether we found the object.
3329   bool
found() const3330   found() const
3331   { return this->found_; }
3332 
3333  protected:
3334   int
3335   expression(Expression**);
3336 
3337  private:
3338   // The object we are looking for.
3339   Named_object* no_;
3340   // Whether we found it.
3341   bool found_;
3342 };
3343 
3344 // A reference to a const in an expression.
3345 
3346 class Const_expression : public Expression
3347 {
3348  public:
Const_expression(Named_object * constant,Location location)3349   Const_expression(Named_object* constant, Location location)
3350     : Expression(EXPRESSION_CONST_REFERENCE, location),
3351       constant_(constant), type_(NULL), seen_(false)
3352   { }
3353 
3354   Named_object*
named_object()3355   named_object()
3356   { return this->constant_; }
3357 
3358   const Named_object*
named_object() const3359   named_object() const
3360   { return this->constant_; }
3361 
3362   // Check that the initializer does not refer to the constant itself.
3363   void
3364   check_for_init_loop();
3365 
3366  protected:
3367   int
3368   do_traverse(Traverse*);
3369 
3370   Expression*
3371   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3372 
3373   bool
do_is_constant() const3374   do_is_constant() const
3375   { return true; }
3376 
3377   bool
do_is_zero_value() const3378   do_is_zero_value() const
3379   { return this->constant_->const_value()->expr()->is_zero_value(); }
3380 
3381   bool
do_is_static_initializer() const3382   do_is_static_initializer() const
3383   { return true; }
3384 
3385   bool
3386   do_numeric_constant_value(Numeric_constant* nc) const;
3387 
3388   bool
3389   do_string_constant_value(std::string* val) const;
3390 
3391   bool
3392   do_boolean_constant_value(bool* val) const;
3393 
3394   Type*
3395   do_type();
3396 
3397   // The type of a const is set by the declaration, not the use.
3398   void
3399   do_determine_type(const Type_context*);
3400 
3401   void
3402   do_check_types(Gogo*);
3403 
3404   Expression*
do_copy()3405   do_copy()
3406   { return this; }
3407 
3408   Bexpression*
3409   do_get_backend(Translate_context* context);
3410 
3411   int
do_inlining_cost() const3412   do_inlining_cost() const
3413   { return 1; }
3414 
3415   // When exporting a reference to a const as part of a const
3416   // expression, we export the value.  We ignore the fact that it has
3417   // a name.
3418   void
do_export(Export_function_body * efb) const3419   do_export(Export_function_body* efb) const
3420   { this->constant_->const_value()->expr()->export_expression(efb); }
3421 
3422   void
3423   do_dump_expression(Ast_dump_context*) const;
3424 
3425  private:
3426   // The constant.
3427   Named_object* constant_;
3428   // The type of this reference.  This is used if the constant has an
3429   // abstract type.
3430   Type* type_;
3431   // Used to prevent infinite recursion when a constant incorrectly
3432   // refers to itself.
3433   mutable bool seen_;
3434 };
3435 
3436 // Traversal.
3437 
3438 int
do_traverse(Traverse * traverse)3439 Const_expression::do_traverse(Traverse* traverse)
3440 {
3441   if (this->type_ != NULL)
3442     return Type::traverse(this->type_, traverse);
3443   return TRAVERSE_CONTINUE;
3444 }
3445 
3446 // Lower a constant expression.  This is where we convert the
3447 // predeclared constant iota into an integer value.
3448 
3449 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)3450 Const_expression::do_lower(Gogo* gogo, Named_object*,
3451 			   Statement_inserter*, int iota_value)
3452 {
3453   if (this->constant_->const_value()->expr()->classification()
3454       == EXPRESSION_IOTA)
3455     {
3456       if (iota_value == -1)
3457 	{
3458 	  go_error_at(this->location(),
3459 		      "iota is only defined in const declarations");
3460 	  iota_value = 0;
3461 	}
3462       return Expression::make_integer_ul(iota_value, NULL, this->location());
3463     }
3464 
3465   // Make sure that the constant itself has been lowered.
3466   gogo->lower_constant(this->constant_);
3467 
3468   return this;
3469 }
3470 
3471 // Return a numeric constant value.
3472 
3473 bool
do_numeric_constant_value(Numeric_constant * nc) const3474 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
3475 {
3476   if (this->seen_)
3477     return false;
3478 
3479   Expression* e = this->constant_->const_value()->expr();
3480 
3481   this->seen_ = true;
3482 
3483   bool r = e->numeric_constant_value(nc);
3484 
3485   this->seen_ = false;
3486 
3487   Type* ctype;
3488   if (this->type_ != NULL)
3489     ctype = this->type_;
3490   else
3491     ctype = this->constant_->const_value()->type();
3492   if (r && ctype != NULL)
3493     {
3494       if (!nc->set_type(ctype, false, this->location()))
3495 	return false;
3496     }
3497 
3498   return r;
3499 }
3500 
3501 bool
do_string_constant_value(std::string * val) const3502 Const_expression::do_string_constant_value(std::string* val) const
3503 {
3504   if (this->seen_)
3505     return false;
3506 
3507   Expression* e = this->constant_->const_value()->expr();
3508 
3509   this->seen_ = true;
3510   bool ok = e->string_constant_value(val);
3511   this->seen_ = false;
3512 
3513   return ok;
3514 }
3515 
3516 bool
do_boolean_constant_value(bool * val) const3517 Const_expression::do_boolean_constant_value(bool* val) const
3518 {
3519   if (this->seen_)
3520     return false;
3521 
3522   Expression* e = this->constant_->const_value()->expr();
3523 
3524   this->seen_ = true;
3525   bool ok = e->boolean_constant_value(val);
3526   this->seen_ = false;
3527 
3528   return ok;
3529 }
3530 
3531 // Return the type of the const reference.
3532 
3533 Type*
do_type()3534 Const_expression::do_type()
3535 {
3536   if (this->type_ != NULL)
3537     return this->type_;
3538 
3539   Named_constant* nc = this->constant_->const_value();
3540 
3541   if (this->seen_ || nc->lowering())
3542     {
3543       if (nc->type() == NULL || !nc->type()->is_error_type())
3544 	{
3545 	  Location loc = this->location();
3546 	  if (!this->seen_)
3547 	    loc = nc->location();
3548 	  go_error_at(loc, "constant refers to itself");
3549 	}
3550       this->set_is_error();
3551       this->type_ = Type::make_error_type();
3552       nc->set_type(this->type_);
3553       return this->type_;
3554     }
3555 
3556   this->seen_ = true;
3557 
3558   Type* ret = nc->type();
3559 
3560   if (ret != NULL)
3561     {
3562       this->seen_ = false;
3563       return ret;
3564     }
3565 
3566   // During parsing, a named constant may have a NULL type, but we
3567   // must not return a NULL type here.
3568   ret = nc->expr()->type();
3569 
3570   this->seen_ = false;
3571 
3572   if (ret->is_error_type())
3573     nc->set_type(ret);
3574 
3575   return ret;
3576 }
3577 
3578 // Set the type of the const reference.
3579 
3580 void
do_determine_type(const Type_context * context)3581 Const_expression::do_determine_type(const Type_context* context)
3582 {
3583   Type* ctype = this->constant_->const_value()->type();
3584   Type* cetype = (ctype != NULL
3585 		  ? ctype
3586 		  : this->constant_->const_value()->expr()->type());
3587   if (ctype != NULL && !ctype->is_abstract())
3588     ;
3589   else if (context->type != NULL
3590 	   && context->type->is_numeric_type()
3591 	   && cetype->is_numeric_type())
3592     this->type_ = context->type;
3593   else if (context->type != NULL
3594 	   && context->type->is_string_type()
3595 	   && cetype->is_string_type())
3596     this->type_ = context->type;
3597   else if (context->type != NULL
3598 	   && context->type->is_boolean_type()
3599 	   && cetype->is_boolean_type())
3600     this->type_ = context->type;
3601   else if (!context->may_be_abstract)
3602     {
3603       if (cetype->is_abstract())
3604 	cetype = cetype->make_non_abstract_type();
3605       this->type_ = cetype;
3606     }
3607 }
3608 
3609 // Check for a loop in which the initializer of a constant refers to
3610 // the constant itself.
3611 
3612 void
check_for_init_loop()3613 Const_expression::check_for_init_loop()
3614 {
3615   if (this->type_ != NULL && this->type_->is_error())
3616     return;
3617 
3618   if (this->seen_)
3619     {
3620       this->report_error(_("constant refers to itself"));
3621       this->type_ = Type::make_error_type();
3622       return;
3623     }
3624 
3625   Expression* init = this->constant_->const_value()->expr();
3626   Find_named_object find_named_object(this->constant_);
3627 
3628   this->seen_ = true;
3629   Expression::traverse(&init, &find_named_object);
3630   this->seen_ = false;
3631 
3632   if (find_named_object.found())
3633     {
3634       if (this->type_ == NULL || !this->type_->is_error())
3635 	{
3636 	  this->report_error(_("constant refers to itself"));
3637 	  this->type_ = Type::make_error_type();
3638 	}
3639       return;
3640     }
3641 }
3642 
3643 // Check types of a const reference.
3644 
3645 void
do_check_types(Gogo *)3646 Const_expression::do_check_types(Gogo*)
3647 {
3648   if (this->type_ != NULL && this->type_->is_error())
3649     return;
3650 
3651   this->check_for_init_loop();
3652 
3653   // Check that numeric constant fits in type.
3654   if (this->type_ != NULL && this->type_->is_numeric_type())
3655     {
3656       Numeric_constant nc;
3657       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
3658 	{
3659 	  if (!nc.set_type(this->type_, true, this->location()))
3660 	    this->set_is_error();
3661 	}
3662     }
3663 }
3664 
3665 // Return the backend representation for a const reference.
3666 
3667 Bexpression*
do_get_backend(Translate_context * context)3668 Const_expression::do_get_backend(Translate_context* context)
3669 {
3670   if (this->is_error_expression()
3671       || (this->type_ != NULL && this->type_->is_error()))
3672     {
3673       go_assert(saw_errors());
3674       return context->backend()->error_expression();
3675     }
3676 
3677   // If the type has been set for this expression, but the underlying
3678   // object is an abstract int or float, we try to get the abstract
3679   // value.  Otherwise we may lose something in the conversion.
3680   Expression* expr = this->constant_->const_value()->expr();
3681   if (this->type_ != NULL
3682       && this->type_->is_numeric_type()
3683       && (this->constant_->const_value()->type() == NULL
3684 	  || this->constant_->const_value()->type()->is_abstract()))
3685     {
3686       Numeric_constant nc;
3687       if (expr->numeric_constant_value(&nc)
3688 	  && nc.set_type(this->type_, false, this->location()))
3689 	{
3690 	  Expression* e = nc.expression(this->location());
3691 	  return e->get_backend(context);
3692 	}
3693     }
3694 
3695   if (this->type_ != NULL)
3696     expr = Expression::make_cast(this->type_, expr, this->location());
3697   return expr->get_backend(context);
3698 }
3699 
3700 // Dump ast representation for constant expression.
3701 
3702 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3703 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3704 {
3705   ast_dump_context->ostream() << this->constant_->name();
3706 }
3707 
3708 // Make a reference to a constant in an expression.
3709 
3710 Expression*
make_const_reference(Named_object * constant,Location location)3711 Expression::make_const_reference(Named_object* constant,
3712 				 Location location)
3713 {
3714   return new Const_expression(constant, location);
3715 }
3716 
3717 // Find a named object in an expression.
3718 
3719 int
expression(Expression ** pexpr)3720 Find_named_object::expression(Expression** pexpr)
3721 {
3722   switch ((*pexpr)->classification())
3723     {
3724     case Expression::EXPRESSION_CONST_REFERENCE:
3725       {
3726 	Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3727 	if (ce->named_object() == this->no_)
3728 	  break;
3729 
3730 	// We need to check a constant initializer explicitly, as
3731 	// loops here will not be caught by the loop checking for
3732 	// variable initializers.
3733 	ce->check_for_init_loop();
3734 
3735 	return TRAVERSE_CONTINUE;
3736       }
3737 
3738     case Expression::EXPRESSION_VAR_REFERENCE:
3739       if ((*pexpr)->var_expression()->named_object() == this->no_)
3740 	break;
3741       return TRAVERSE_CONTINUE;
3742     case Expression::EXPRESSION_FUNC_REFERENCE:
3743       if ((*pexpr)->func_expression()->named_object() == this->no_)
3744 	break;
3745       return TRAVERSE_CONTINUE;
3746     default:
3747       return TRAVERSE_CONTINUE;
3748     }
3749   this->found_ = true;
3750   return TRAVERSE_EXIT;
3751 }
3752 
3753 // The nil value.
3754 
3755 class Nil_expression : public Expression
3756 {
3757  public:
Nil_expression(Location location)3758   Nil_expression(Location location)
3759     : Expression(EXPRESSION_NIL, location)
3760   { }
3761 
3762   static Expression*
3763   do_import(Import_expression*, Location);
3764 
3765  protected:
3766   bool
do_is_constant() const3767   do_is_constant() const
3768   { return true; }
3769 
3770   bool
do_is_zero_value() const3771   do_is_zero_value() const
3772   { return true; }
3773 
3774   bool
do_is_static_initializer() const3775   do_is_static_initializer() const
3776   { return true; }
3777 
3778   Type*
do_type()3779   do_type()
3780   { return Type::make_nil_type(); }
3781 
3782   void
do_determine_type(const Type_context *)3783   do_determine_type(const Type_context*)
3784   { }
3785 
3786   Expression*
do_copy()3787   do_copy()
3788   { return this; }
3789 
3790   Bexpression*
do_get_backend(Translate_context * context)3791   do_get_backend(Translate_context* context)
3792   { return context->backend()->nil_pointer_expression(); }
3793 
3794   int
do_inlining_cost() const3795   do_inlining_cost() const
3796   { return 1; }
3797 
3798   void
do_export(Export_function_body * efb) const3799   do_export(Export_function_body* efb) const
3800   { efb->write_c_string("$nil"); }
3801 
3802   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3803   do_dump_expression(Ast_dump_context* ast_dump_context) const
3804   { ast_dump_context->ostream() << "nil"; }
3805 };
3806 
3807 // Import a nil expression.
3808 
3809 Expression*
do_import(Import_expression * imp,Location loc)3810 Nil_expression::do_import(Import_expression* imp, Location loc)
3811 {
3812   if (imp->version() >= EXPORT_FORMAT_V3)
3813     imp->require_c_string("$");
3814   imp->require_c_string("nil");
3815   return Expression::make_nil(loc);
3816 }
3817 
3818 // Make a nil expression.
3819 
3820 Expression*
make_nil(Location location)3821 Expression::make_nil(Location location)
3822 {
3823   return new Nil_expression(location);
3824 }
3825 
3826 // The value of the predeclared constant iota.  This is little more
3827 // than a marker.  This will be lowered to an integer in
3828 // Const_expression::do_lower, which is where we know the value that
3829 // it should have.
3830 
3831 class Iota_expression : public Parser_expression
3832 {
3833  public:
Iota_expression(Location location)3834   Iota_expression(Location location)
3835     : Parser_expression(EXPRESSION_IOTA, location)
3836   { }
3837 
3838  protected:
3839   Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3840   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3841   { go_unreachable(); }
3842 
3843   // There should only ever be one of these.
3844   Expression*
do_copy()3845   do_copy()
3846   { go_unreachable(); }
3847 
3848   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3849   do_dump_expression(Ast_dump_context* ast_dump_context) const
3850   { ast_dump_context->ostream() << "iota"; }
3851 };
3852 
3853 // Make an iota expression.  This is only called for one case: the
3854 // value of the predeclared constant iota.
3855 
3856 Expression*
make_iota()3857 Expression::make_iota()
3858 {
3859   static Iota_expression iota_expression(Linemap::unknown_location());
3860   return &iota_expression;
3861 }
3862 
3863 // Class Type_conversion_expression.
3864 
3865 // Traversal.
3866 
3867 int
do_traverse(Traverse * traverse)3868 Type_conversion_expression::do_traverse(Traverse* traverse)
3869 {
3870   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3871       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3872     return TRAVERSE_EXIT;
3873   return TRAVERSE_CONTINUE;
3874 }
3875 
3876 // Convert to a constant at lowering time.  Also lower conversions
3877 // from slice to pointer-to-array, as they can panic.
3878 
3879 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter * inserter,int)3880 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3881 				     Statement_inserter* inserter, int)
3882 {
3883   Type* type = this->type_;
3884   Expression* val = this->expr_;
3885   Location location = this->location();
3886 
3887   if (type->is_numeric_type())
3888     {
3889       Numeric_constant nc;
3890       if (val->numeric_constant_value(&nc))
3891 	{
3892 	  if (!nc.set_type(type, true, location))
3893 	    return Expression::make_error(location);
3894 	  return nc.expression(location);
3895 	}
3896     }
3897 
3898   // According to the language specification on string conversions
3899   // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3900   // When converting an integer into a string, the string will be a UTF-8
3901   // representation of the integer and integers "outside the range of valid
3902   // Unicode code points are converted to '\uFFFD'."
3903   if (type->is_string_type())
3904     {
3905       Numeric_constant nc;
3906       if (val->numeric_constant_value(&nc) && nc.is_int())
3907         {
3908           // An integer value doesn't fit in the Unicode code point range if it
3909           // overflows the Go "int" type or is negative.
3910           unsigned long ul;
3911           if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3912               || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3913             return Expression::make_string("\ufffd", location);
3914         }
3915     }
3916 
3917   if (type->is_slice_type())
3918     {
3919       Type* element_type = type->array_type()->element_type()->forwarded();
3920       bool is_byte = (element_type->integer_type() != NULL
3921 		      && element_type->integer_type()->is_byte());
3922       bool is_rune = (element_type->integer_type() != NULL
3923 		      && element_type->integer_type()->is_rune());
3924       if (is_byte || is_rune)
3925 	{
3926 	  std::string s;
3927 	  if (val->string_constant_value(&s))
3928 	    {
3929 	      Expression_list* vals = new Expression_list();
3930 	      if (is_byte)
3931 		{
3932 		  for (std::string::const_iterator p = s.begin();
3933 		       p != s.end();
3934 		       p++)
3935 		    {
3936 		      unsigned char c = static_cast<unsigned char>(*p);
3937 		      vals->push_back(Expression::make_integer_ul(c,
3938 								  element_type,
3939 								  location));
3940 		    }
3941 		}
3942 	      else
3943 		{
3944 		  const char *p = s.data();
3945 		  const char *pend = s.data() + s.length();
3946 		  while (p < pend)
3947 		    {
3948 		      unsigned int c;
3949 		      int adv = Lex::fetch_char(p, &c);
3950 		      if (adv == 0)
3951 			{
3952 			  go_warning_at(this->location(), 0,
3953 				     "invalid UTF-8 encoding");
3954 			  adv = 1;
3955 			}
3956 		      p += adv;
3957 		      vals->push_back(Expression::make_integer_ul(c,
3958 								  element_type,
3959 								  location));
3960 		    }
3961 		}
3962 
3963 	      return Expression::make_slice_composite_literal(type, vals,
3964 							      location);
3965 	    }
3966 	}
3967     }
3968 
3969   if (type->points_to() != NULL
3970       && type->points_to()->array_type() != NULL
3971       && !type->points_to()->is_slice_type()
3972       && val->type()->is_slice_type()
3973       && Type::are_identical(type->points_to()->array_type()->element_type(),
3974 			     val->type()->array_type()->element_type(),
3975 			     0, NULL))
3976     {
3977       Temporary_statement* val_temp = NULL;
3978       if (!val->is_multi_eval_safe())
3979 	{
3980 	  val_temp = Statement::make_temporary(val->type(), NULL, location);
3981 	  inserter->insert(val_temp);
3982 	  val = Expression::make_set_and_use_temporary(val_temp, val,
3983 						       location);
3984 	}
3985 
3986       Type* int_type = Type::lookup_integer_type("int");
3987       Temporary_statement* vallen_temp =
3988 	Statement::make_temporary(int_type, NULL, location);
3989       inserter->insert(vallen_temp);
3990 
3991       Expression* arrlen = type->points_to()->array_type()->length();
3992       Expression* vallen =
3993 	Expression::make_slice_info(val, Expression::SLICE_INFO_LENGTH,
3994 				    location);
3995       vallen = Expression::make_set_and_use_temporary(vallen_temp, vallen,
3996 						      location);
3997       Expression* cond = Expression::make_binary(OPERATOR_GT, arrlen, vallen,
3998 						 location);
3999 
4000       vallen = Expression::make_temporary_reference(vallen_temp, location);
4001       Expression* panic = Runtime::make_call(Runtime::PANIC_SLICE_CONVERT,
4002 					     location, 2, arrlen, vallen);
4003 
4004       Expression* nil = Expression::make_nil(location);
4005       Expression* check = Expression::make_conditional(cond, panic, nil,
4006 						       location);
4007 
4008       if (val_temp == NULL)
4009 	val = val->copy();
4010       else
4011 	val = Expression::make_temporary_reference(val_temp, location);
4012       Expression* ptr =
4013 	Expression::make_slice_info(val, Expression::SLICE_INFO_VALUE_POINTER,
4014 				    location);
4015       ptr = Expression::make_unsafe_cast(type, ptr, location);
4016 
4017       return Expression::make_compound(check, ptr, location);
4018     }
4019 
4020   return this;
4021 }
4022 
4023 // Flatten a type conversion by using a temporary variable for the slice
4024 // in slice to string conversions.
4025 
4026 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)4027 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
4028                                        Statement_inserter* inserter)
4029 {
4030   if (this->type()->is_error_type() || this->expr_->is_error_expression())
4031     {
4032       go_assert(saw_errors());
4033       return Expression::make_error(this->location());
4034     }
4035 
4036   if (((this->type()->is_string_type()
4037         && this->expr_->type()->is_slice_type())
4038        || this->expr_->type()->interface_type() != NULL)
4039       && !this->expr_->is_multi_eval_safe())
4040     {
4041       Temporary_statement* temp =
4042           Statement::make_temporary(NULL, this->expr_, this->location());
4043       inserter->insert(temp);
4044       this->expr_ = Expression::make_temporary_reference(temp, this->location());
4045     }
4046 
4047   // For interface conversion and string to/from slice conversions,
4048   // decide if we can allocate on stack.
4049   if (this->type()->interface_type() != NULL
4050       || this->type()->is_string_type()
4051       || this->expr_->type()->is_string_type())
4052     {
4053       Node* n = Node::make_node(this);
4054       if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
4055         this->no_escape_ = true;
4056     }
4057   return this;
4058 }
4059 
4060 // Return whether a type conversion is a constant.
4061 
4062 bool
do_is_constant() const4063 Type_conversion_expression::do_is_constant() const
4064 {
4065   if (!this->expr_->is_constant())
4066     return false;
4067 
4068   // A conversion to a type that may not be used as a constant is not
4069   // a constant.  For example, []byte(nil).
4070   Type* type = this->type_;
4071   if (type->integer_type() == NULL
4072       && type->float_type() == NULL
4073       && type->complex_type() == NULL
4074       && !type->is_boolean_type()
4075       && !type->is_string_type())
4076     return false;
4077 
4078   return true;
4079 }
4080 
4081 // Return whether a type conversion is a zero value.
4082 
4083 bool
do_is_zero_value() const4084 Type_conversion_expression::do_is_zero_value() const
4085 {
4086   if (!this->expr_->is_zero_value())
4087     return false;
4088 
4089   // Some type conversion from zero value is still not zero value.
4090   // For example, []byte("") or interface{}(0).
4091   // Conservatively, only report true if the RHS is nil.
4092   Type* type = this->type_;
4093   if (type->integer_type() == NULL
4094       && type->float_type() == NULL
4095       && type->complex_type() == NULL
4096       && !type->is_boolean_type()
4097       && !type->is_string_type())
4098     return this->expr_->is_nil_expression();
4099 
4100   return true;
4101 }
4102 
4103 // Return whether a type conversion can be used in a constant
4104 // initializer.
4105 
4106 bool
do_is_static_initializer() const4107 Type_conversion_expression::do_is_static_initializer() const
4108 {
4109   Type* type = this->type_;
4110   Type* expr_type = this->expr_->type();
4111 
4112   if (type->interface_type() != NULL
4113       || expr_type->interface_type() != NULL)
4114     return false;
4115 
4116   if (!this->expr_->is_static_initializer())
4117     return false;
4118 
4119   if (Type::are_identical(type, expr_type,
4120 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4121 			  NULL))
4122     return true;
4123 
4124   if (type->is_string_type() && expr_type->is_string_type())
4125     return true;
4126 
4127   if ((type->is_numeric_type()
4128        || type->is_boolean_type()
4129        || type->points_to() != NULL)
4130       && (expr_type->is_numeric_type()
4131 	  || expr_type->is_boolean_type()
4132 	  || expr_type->points_to() != NULL))
4133     return true;
4134 
4135   return false;
4136 }
4137 
4138 // Return the constant numeric value if there is one.
4139 
4140 bool
do_numeric_constant_value(Numeric_constant * nc) const4141 Type_conversion_expression::do_numeric_constant_value(
4142     Numeric_constant* nc) const
4143 {
4144   if (!this->type_->is_numeric_type())
4145     return false;
4146   if (!this->expr_->numeric_constant_value(nc))
4147     return false;
4148   return nc->set_type(this->type_, false, this->location());
4149 }
4150 
4151 // Return the constant string value if there is one.
4152 
4153 bool
do_string_constant_value(std::string * val) const4154 Type_conversion_expression::do_string_constant_value(std::string* val) const
4155 {
4156   if (this->type_->is_string_type()
4157       && this->expr_->type()->integer_type() != NULL)
4158     {
4159       Numeric_constant nc;
4160       if (this->expr_->numeric_constant_value(&nc))
4161 	{
4162 	  unsigned long ival;
4163 	  if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
4164 	    {
4165 	      unsigned int cval = static_cast<unsigned int>(ival);
4166 	      if (static_cast<unsigned long>(cval) != ival)
4167 		{
4168 		  go_warning_at(this->location(), 0,
4169 				"unicode code point 0x%lx out of range",
4170 				ival);
4171 		  cval = 0xfffd; // Unicode "replacement character."
4172 		}
4173 	      val->clear();
4174 	      Lex::append_char(cval, true, val, this->location());
4175 	      return true;
4176 	    }
4177 	}
4178     }
4179 
4180   // FIXME: Could handle conversion from const []int here.
4181 
4182   return false;
4183 }
4184 
4185 // Return the constant boolean value if there is one.
4186 
4187 bool
do_boolean_constant_value(bool * val) const4188 Type_conversion_expression::do_boolean_constant_value(bool* val) const
4189 {
4190   if (!this->type_->is_boolean_type())
4191     return false;
4192   return this->expr_->boolean_constant_value(val);
4193 }
4194 
4195 // Determine the resulting type of the conversion.
4196 
4197 void
do_determine_type(const Type_context *)4198 Type_conversion_expression::do_determine_type(const Type_context*)
4199 {
4200   Type_context subcontext(this->type_, false);
4201   this->expr_->determine_type(&subcontext);
4202 }
4203 
4204 // Check that types are convertible.
4205 
4206 void
do_check_types(Gogo *)4207 Type_conversion_expression::do_check_types(Gogo*)
4208 {
4209   Type* type = this->type_;
4210   Type* expr_type = this->expr_->type();
4211   std::string reason;
4212 
4213   if (type->is_error() || expr_type->is_error())
4214     {
4215       this->set_is_error();
4216       return;
4217     }
4218 
4219   if (this->may_convert_function_types_
4220       && type->function_type() != NULL
4221       && expr_type->function_type() != NULL)
4222     return;
4223 
4224   if (Type::are_convertible(type, expr_type, &reason))
4225     return;
4226 
4227   go_error_at(this->location(), "%s", reason.c_str());
4228   this->set_is_error();
4229 }
4230 
4231 // Copy.
4232 
4233 Expression*
do_copy()4234 Type_conversion_expression::do_copy()
4235 {
4236   Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
4237                                                    this->expr_->copy(),
4238                                                    this->location());
4239   ret->conversion_expression()->set_no_copy(this->no_copy_);
4240   return ret;
4241 }
4242 
4243 // Get the backend representation for a type conversion.
4244 
4245 Bexpression*
do_get_backend(Translate_context * context)4246 Type_conversion_expression::do_get_backend(Translate_context* context)
4247 {
4248   Type* type = this->type_;
4249   Type* expr_type = this->expr_->type();
4250 
4251   Gogo* gogo = context->gogo();
4252   Btype* btype = type->get_backend(gogo);
4253   Location loc = this->location();
4254 
4255   if (Type::are_identical(type, expr_type,
4256 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4257 			  NULL))
4258     {
4259       Bexpression* bexpr = this->expr_->get_backend(context);
4260       return gogo->backend()->convert_expression(btype, bexpr, loc);
4261     }
4262   else if (type->interface_type() != NULL
4263            && expr_type->interface_type() == NULL)
4264     {
4265       Expression* conversion =
4266           Expression::convert_type_to_interface(type, this->expr_,
4267                                                 this->no_escape_, loc);
4268       return conversion->get_backend(context);
4269     }
4270   else if (type->interface_type() != NULL
4271 	   || expr_type->interface_type() != NULL)
4272     {
4273       Expression* conversion =
4274           Expression::convert_for_assignment(gogo, type, this->expr_,
4275                                              loc);
4276       return conversion->get_backend(context);
4277     }
4278   else if (type->is_string_type()
4279 	   && expr_type->integer_type() != NULL)
4280     {
4281       mpz_t intval;
4282       Numeric_constant nc;
4283       if (this->expr_->numeric_constant_value(&nc)
4284 	  && nc.to_int(&intval))
4285 	{
4286 	  std::string s;
4287           unsigned int x;
4288           if (mpz_fits_uint_p(intval))
4289             x = mpz_get_ui(intval);
4290           else
4291             {
4292               char* ms = mpz_get_str(NULL, 16, intval);
4293               go_warning_at(loc, 0,
4294                             "unicode code point 0x%s out of range in string",
4295                             ms);
4296               free(ms);
4297               x = 0xfffd;
4298             }
4299 	  Lex::append_char(x, true, &s, loc);
4300 	  mpz_clear(intval);
4301 	  Expression* se = Expression::make_string(s, loc);
4302 	  return se->get_backend(context);
4303 	}
4304 
4305       Expression* buf;
4306       if (this->no_escape_)
4307         {
4308           Type* byte_type = Type::lookup_integer_type("uint8");
4309           Expression* buflen =
4310             Expression::make_integer_ul(4, NULL, loc);
4311           Type* array_type = Type::make_array_type(byte_type, buflen);
4312           buf = Expression::make_allocation(array_type, loc);
4313           buf->allocation_expression()->set_allocate_on_stack();
4314           buf->allocation_expression()->set_no_zero();
4315         }
4316       else
4317         buf = Expression::make_nil(loc);
4318       Expression* i2s_expr =
4319         Runtime::make_call(Runtime::INTSTRING, loc, 2, buf, this->expr_);
4320       return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
4321     }
4322   else if (type->is_string_type() && expr_type->is_slice_type())
4323     {
4324       Array_type* a = expr_type->array_type();
4325       Type* e = a->element_type()->forwarded();
4326       go_assert(e->integer_type() != NULL);
4327       go_assert(this->expr_->is_multi_eval_safe());
4328 
4329       Expression* buf;
4330       if (this->no_escape_ && !this->no_copy_)
4331         {
4332           Type* byte_type = Type::lookup_integer_type("uint8");
4333           Expression* buflen =
4334             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4335           Type* array_type = Type::make_array_type(byte_type, buflen);
4336           buf = Expression::make_allocation(array_type, loc);
4337           buf->allocation_expression()->set_allocate_on_stack();
4338           buf->allocation_expression()->set_no_zero();
4339         }
4340       else
4341         buf = Expression::make_nil(loc);
4342 
4343       if (e->integer_type()->is_byte())
4344         {
4345 	  Expression* ptr =
4346 	    Expression::make_slice_info(this->expr_, SLICE_INFO_VALUE_POINTER,
4347 					loc);
4348 	  Expression* len =
4349 	    Expression::make_slice_info(this->expr_, SLICE_INFO_LENGTH, loc);
4350           if (this->no_copy_)
4351             {
4352               if (gogo->debug_optimization())
4353                 go_debug(loc, "no copy string([]byte)");
4354               Expression* str = Expression::make_string_value(ptr, len, loc);
4355               return str->get_backend(context);
4356             }
4357 	  return Runtime::make_call(Runtime::SLICEBYTETOSTRING, loc, 3, buf,
4358 				    ptr, len)->get_backend(context);
4359         }
4360       else
4361         {
4362           go_assert(e->integer_type()->is_rune());
4363 	  return Runtime::make_call(Runtime::SLICERUNETOSTRING, loc, 2, buf,
4364 				    this->expr_)->get_backend(context);
4365 	}
4366     }
4367   else if (type->is_slice_type() && expr_type->is_string_type())
4368     {
4369       Type* e = type->array_type()->element_type()->forwarded();
4370       go_assert(e->integer_type() != NULL);
4371 
4372       Runtime::Function code;
4373       if (e->integer_type()->is_byte())
4374 	code = Runtime::STRINGTOSLICEBYTE;
4375       else
4376 	{
4377 	  go_assert(e->integer_type()->is_rune());
4378 	  code = Runtime::STRINGTOSLICERUNE;
4379 	}
4380 
4381       Expression* buf;
4382       if (this->no_escape_)
4383         {
4384           Expression* buflen =
4385             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4386           Type* array_type = Type::make_array_type(e, buflen);
4387           buf = Expression::make_allocation(array_type, loc);
4388           buf->allocation_expression()->set_allocate_on_stack();
4389           buf->allocation_expression()->set_no_zero();
4390         }
4391       else
4392         buf = Expression::make_nil(loc);
4393       Expression* s2a = Runtime::make_call(code, loc, 2, buf, this->expr_);
4394       return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
4395     }
4396   else if (type->is_numeric_type())
4397     {
4398       go_assert(Type::are_convertible(type, expr_type, NULL));
4399       Bexpression* bexpr = this->expr_->get_backend(context);
4400       return gogo->backend()->convert_expression(btype, bexpr, loc);
4401     }
4402   else if ((type->is_unsafe_pointer_type()
4403 	    && (expr_type->points_to() != NULL
4404                 || expr_type->integer_type()))
4405            || (expr_type->is_unsafe_pointer_type()
4406 	       && type->points_to() != NULL)
4407            || (this->may_convert_function_types_
4408                && type->function_type() != NULL
4409                && expr_type->function_type() != NULL))
4410     {
4411       Bexpression* bexpr = this->expr_->get_backend(context);
4412       return gogo->backend()->convert_expression(btype, bexpr, loc);
4413     }
4414   else
4415     {
4416       Expression* conversion =
4417           Expression::convert_for_assignment(gogo, type, this->expr_, loc);
4418       return conversion->get_backend(context);
4419     }
4420 }
4421 
4422 // Cost of inlining a type conversion.
4423 
4424 int
do_inlining_cost() const4425 Type_conversion_expression::do_inlining_cost() const
4426 {
4427   Type* type = this->type_;
4428   Type* expr_type = this->expr_->type();
4429   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
4430     return 10;
4431   else if (type->is_string_type() && expr_type->integer_type() != NULL)
4432     return 10;
4433   else if (type->is_string_type() && expr_type->is_slice_type())
4434     return 10;
4435   else if (type->is_slice_type() && expr_type->is_string_type())
4436     return 10;
4437   else
4438     return 1;
4439 }
4440 
4441 // Output a type conversion in a constant expression.
4442 
4443 void
do_export(Export_function_body * efb) const4444 Type_conversion_expression::do_export(Export_function_body* efb) const
4445 {
4446   efb->write_c_string("$convert(");
4447   efb->write_type(this->type_);
4448   efb->write_c_string(", ");
4449 
4450   Type* old_context = efb->type_context();
4451   efb->set_type_context(this->type_);
4452 
4453   this->expr_->export_expression(efb);
4454 
4455   efb->set_type_context(old_context);
4456 
4457   efb->write_c_string(")");
4458 }
4459 
4460 // Import a type conversion or a struct construction.
4461 
4462 Expression*
do_import(Import_expression * imp,Location loc)4463 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
4464 {
4465   imp->require_c_string("$convert(");
4466   Type* type = imp->read_type();
4467   imp->require_c_string(", ");
4468   Expression* val = Expression::import_expression(imp, loc);
4469   imp->require_c_string(")");
4470   return Expression::make_cast(type, val, loc);
4471 }
4472 
4473 // Dump ast representation for a type conversion expression.
4474 
4475 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4476 Type_conversion_expression::do_dump_expression(
4477     Ast_dump_context* ast_dump_context) const
4478 {
4479   ast_dump_context->dump_type(this->type_);
4480   ast_dump_context->ostream() << "(";
4481   ast_dump_context->dump_expression(this->expr_);
4482   ast_dump_context->ostream() << ") ";
4483 }
4484 
4485 // Make a type cast expression.
4486 
4487 Expression*
make_cast(Type * type,Expression * val,Location location)4488 Expression::make_cast(Type* type, Expression* val, Location location)
4489 {
4490   if (type->is_error_type() || val->is_error_expression())
4491     return Expression::make_error(location);
4492   return new Type_conversion_expression(type, val, location);
4493 }
4494 
4495 // Class Unsafe_type_conversion_expression.
4496 
4497 // Traversal.
4498 
4499 int
do_traverse(Traverse * traverse)4500 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
4501 {
4502   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4503       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4504     return TRAVERSE_EXIT;
4505   return TRAVERSE_CONTINUE;
4506 }
4507 
4508 // Return whether an unsafe type conversion can be used as a constant
4509 // initializer.
4510 
4511 bool
do_is_static_initializer() const4512 Unsafe_type_conversion_expression::do_is_static_initializer() const
4513 {
4514   Type* type = this->type_;
4515   Type* expr_type = this->expr_->type();
4516 
4517   if (type->interface_type() != NULL
4518       || expr_type->interface_type() != NULL)
4519     return false;
4520 
4521   if (!this->expr_->is_static_initializer())
4522     return false;
4523 
4524   if (Type::are_convertible(type, expr_type, NULL))
4525     return true;
4526 
4527   if (type->is_string_type() && expr_type->is_string_type())
4528     return true;
4529 
4530   if ((type->is_numeric_type()
4531        || type->is_boolean_type()
4532        || type->points_to() != NULL)
4533       && (expr_type->is_numeric_type()
4534 	  || expr_type->is_boolean_type()
4535 	  || expr_type->points_to() != NULL))
4536     return true;
4537 
4538   return false;
4539 }
4540 
4541 // Copy.
4542 
4543 Expression*
do_copy()4544 Unsafe_type_conversion_expression::do_copy()
4545 {
4546   return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
4547 					       this->expr_->copy(),
4548 					       this->location());
4549 }
4550 
4551 // Convert to backend representation.
4552 
4553 Bexpression*
do_get_backend(Translate_context * context)4554 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
4555 {
4556   // We are only called for a limited number of cases.
4557 
4558   Type* t = this->type_;
4559   Type* et = this->expr_->type();
4560 
4561   if (t->is_error_type()
4562       || this->expr_->is_error_expression()
4563       || et->is_error_type())
4564     {
4565       go_assert(saw_errors());
4566       return context->backend()->error_expression();
4567     }
4568 
4569   if (t->array_type() != NULL)
4570     go_assert(et->array_type() != NULL
4571               && t->is_slice_type() == et->is_slice_type());
4572   else if (t->struct_type() != NULL)
4573     {
4574       if (t->named_type() != NULL
4575           && et->named_type() != NULL
4576           && !Type::are_convertible(t, et, NULL))
4577 	{
4578 	  go_assert(saw_errors());
4579 	  return context->backend()->error_expression();
4580 	}
4581 
4582       go_assert(et->struct_type() != NULL
4583                 && Type::are_convertible(t, et, NULL));
4584     }
4585   else if (t->map_type() != NULL)
4586     go_assert(et->map_type() != NULL || et->points_to() != NULL);
4587   else if (t->channel_type() != NULL)
4588     go_assert(et->channel_type() != NULL || et->points_to() != NULL);
4589   else if (t->points_to() != NULL)
4590     go_assert(et->points_to() != NULL
4591               || et->channel_type() != NULL
4592               || et->map_type() != NULL
4593               || et->function_type() != NULL
4594 	      || et->integer_type() != NULL
4595               || et->is_nil_type());
4596   else if (t->function_type() != NULL)
4597     go_assert(et->points_to() != NULL);
4598   else if (et->is_unsafe_pointer_type())
4599     go_assert(t->points_to() != NULL
4600 	      || (t->integer_type() != NULL
4601 		  && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
4602   else if (t->interface_type() != NULL)
4603     {
4604       bool empty_iface = t->interface_type()->is_empty();
4605       go_assert(et->interface_type() != NULL
4606                 && et->interface_type()->is_empty() == empty_iface);
4607     }
4608   else if (t->integer_type() != NULL)
4609     go_assert(et->is_boolean_type()
4610               || et->integer_type() != NULL
4611               || et->function_type() != NULL
4612               || et->points_to() != NULL
4613               || et->map_type() != NULL
4614               || et->channel_type() != NULL
4615 	      || et->is_nil_type());
4616   else
4617     go_unreachable();
4618 
4619   Gogo* gogo = context->gogo();
4620   Btype* btype = t->get_backend(gogo);
4621   Bexpression* bexpr = this->expr_->get_backend(context);
4622   Location loc = this->location();
4623   return gogo->backend()->convert_expression(btype, bexpr, loc);
4624 }
4625 
4626 // Dump ast representation for an unsafe type conversion expression.
4627 
4628 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4629 Unsafe_type_conversion_expression::do_dump_expression(
4630     Ast_dump_context* ast_dump_context) const
4631 {
4632   ast_dump_context->dump_type(this->type_);
4633   ast_dump_context->ostream() << "(";
4634   ast_dump_context->dump_expression(this->expr_);
4635   ast_dump_context->ostream() << ") ";
4636 }
4637 
4638 // Make an unsafe type conversion expression.
4639 
4640 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)4641 Expression::make_unsafe_cast(Type* type, Expression* expr,
4642 			     Location location)
4643 {
4644   return new Unsafe_type_conversion_expression(type, expr, location);
4645 }
4646 
4647 // Class Unary_expression.
4648 
4649 // Call the address_taken method of the operand if needed.  This is
4650 // called after escape analysis but before inserting write barriers.
4651 
4652 void
check_operand_address_taken(Gogo *)4653 Unary_expression::check_operand_address_taken(Gogo*)
4654 {
4655   if (this->op_ != OPERATOR_AND)
4656     return;
4657 
4658   // If this->escapes_ is false at this point, then it was set to
4659   // false by an explicit call to set_does_not_escape, and the value
4660   // does not escape.  If this->escapes_ is true, we may be able to
4661   // set it to false based on the escape analysis pass.
4662   if (this->escapes_)
4663     {
4664       Node* n = Node::make_node(this);
4665       if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
4666 	this->escapes_ = false;
4667     }
4668 
4669   this->expr_->address_taken(this->escapes_);
4670 }
4671 
4672 // If we are taking the address of a composite literal, and the
4673 // contents are not constant, then we want to make a heap expression
4674 // instead.
4675 
4676 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)4677 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4678 {
4679   Location loc = this->location();
4680   Operator op = this->op_;
4681   Expression* expr = this->expr_;
4682 
4683   if (op == OPERATOR_MULT && expr->is_type_expression())
4684     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4685 
4686   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
4687   // moving x to the heap.  FIXME: Is it worth doing a real escape
4688   // analysis here?  This case is found in math/unsafe.go and is
4689   // therefore worth special casing.
4690   if (op == OPERATOR_MULT)
4691     {
4692       Expression* e = expr;
4693       while (e->classification() == EXPRESSION_CONVERSION)
4694 	{
4695 	  Type_conversion_expression* te
4696 	    = static_cast<Type_conversion_expression*>(e);
4697 	  e = te->expr();
4698 	}
4699 
4700       if (e->classification() == EXPRESSION_UNARY)
4701 	{
4702 	  Unary_expression* ue = static_cast<Unary_expression*>(e);
4703 	  if (ue->op_ == OPERATOR_AND)
4704 	    {
4705 	      if (e == expr)
4706 		{
4707 		  // *&x == x.
4708 		  if (!ue->expr_->is_addressable() && !ue->create_temp_)
4709 		    {
4710 		      go_error_at(ue->location(),
4711 				  "invalid operand for unary %<&%>");
4712 		      this->set_is_error();
4713 		    }
4714 		  return ue->expr_;
4715 		}
4716 	      ue->set_does_not_escape();
4717 	    }
4718 	}
4719     }
4720 
4721   // Catching an invalid indirection of unsafe.Pointer here avoid
4722   // having to deal with TYPE_VOID in other places.
4723   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4724     {
4725       go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4726       return Expression::make_error(this->location());
4727     }
4728 
4729   // Check for an invalid pointer dereference.  We need to do this
4730   // here because Unary_expression::do_type will return an error type
4731   // in this case.  That can cause code to appear erroneous, and
4732   // therefore disappear at lowering time, without any error message.
4733   if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
4734     {
4735       this->report_error(_("expected pointer"));
4736       return Expression::make_error(this->location());
4737     }
4738 
4739   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
4740     {
4741       Numeric_constant nc;
4742       if (expr->numeric_constant_value(&nc))
4743 	{
4744 	  Numeric_constant result;
4745 	  bool issued_error;
4746 	  if (Unary_expression::eval_constant(op, &nc, loc, &result,
4747 					      &issued_error))
4748 	    return result.expression(loc);
4749 	  else if (issued_error)
4750 	    return Expression::make_error(this->location());
4751 	}
4752     }
4753 
4754   return this;
4755 }
4756 
4757 // Flatten expression if a nil check must be performed and create temporary
4758 // variables if necessary.
4759 
4760 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)4761 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
4762                              Statement_inserter* inserter)
4763 {
4764   if (this->is_error_expression()
4765       || this->expr_->is_error_expression()
4766       || this->expr_->type()->is_error_type())
4767     {
4768       go_assert(saw_errors());
4769       return Expression::make_error(this->location());
4770     }
4771 
4772   Location location = this->location();
4773   if (this->op_ == OPERATOR_MULT
4774       && !this->expr_->is_multi_eval_safe())
4775     {
4776       go_assert(this->expr_->type()->points_to() != NULL);
4777       switch (this->requires_nil_check(gogo))
4778         {
4779           case NIL_CHECK_ERROR_ENCOUNTERED:
4780             {
4781               go_assert(saw_errors());
4782               return Expression::make_error(this->location());
4783             }
4784           case NIL_CHECK_NOT_NEEDED:
4785             break;
4786           case NIL_CHECK_NEEDED:
4787             this->create_temp_ = true;
4788             break;
4789           case NIL_CHECK_DEFAULT:
4790             go_unreachable();
4791         }
4792     }
4793 
4794   if (this->create_temp_ && !this->expr_->is_multi_eval_safe())
4795     {
4796       Temporary_statement* temp =
4797           Statement::make_temporary(NULL, this->expr_, location);
4798       inserter->insert(temp);
4799       this->expr_ = Expression::make_temporary_reference(temp, location);
4800     }
4801 
4802   return this;
4803 }
4804 
4805 // Return whether a unary expression is a constant.
4806 
4807 bool
do_is_constant() const4808 Unary_expression::do_is_constant() const
4809 {
4810   if (this->op_ == OPERATOR_MULT)
4811     {
4812       // Indirecting through a pointer is only constant if the object
4813       // to which the expression points is constant, but we currently
4814       // have no way to determine that.
4815       return false;
4816     }
4817   else if (this->op_ == OPERATOR_AND)
4818     {
4819       // Taking the address of a variable is constant if it is a
4820       // global variable, not constant otherwise.  In other cases taking the
4821       // address is probably not a constant.
4822       Var_expression* ve = this->expr_->var_expression();
4823       if (ve != NULL)
4824 	{
4825 	  Named_object* no = ve->named_object();
4826 	  return no->is_variable() && no->var_value()->is_global();
4827 	}
4828       return false;
4829     }
4830   else
4831     return this->expr_->is_constant();
4832 }
4833 
4834 // Return whether a unary expression can be used as a constant
4835 // initializer.
4836 
4837 bool
do_is_static_initializer() const4838 Unary_expression::do_is_static_initializer() const
4839 {
4840   if (this->op_ == OPERATOR_MULT)
4841     return false;
4842   else if (this->op_ == OPERATOR_AND)
4843     return Unary_expression::base_is_static_initializer(this->expr_);
4844   else
4845     return this->expr_->is_static_initializer();
4846 }
4847 
4848 // Return whether the address of EXPR can be used as a static
4849 // initializer.
4850 
4851 bool
base_is_static_initializer(Expression * expr)4852 Unary_expression::base_is_static_initializer(Expression* expr)
4853 {
4854   // The address of a field reference can be a static initializer if
4855   // the base can be a static initializer.
4856   Field_reference_expression* fre = expr->field_reference_expression();
4857   if (fre != NULL)
4858     return Unary_expression::base_is_static_initializer(fre->expr());
4859 
4860   // The address of an index expression can be a static initializer if
4861   // the base can be a static initializer and the index is constant.
4862   Array_index_expression* aind = expr->array_index_expression();
4863   if (aind != NULL)
4864     return (aind->end() == NULL
4865 	    && aind->start()->is_constant()
4866 	    && Unary_expression::base_is_static_initializer(aind->array()));
4867 
4868   // The address of a global variable can be a static initializer.
4869   Var_expression* ve = expr->var_expression();
4870   if (ve != NULL)
4871     {
4872       Named_object* no = ve->named_object();
4873       return no->is_variable() && no->var_value()->is_global();
4874     }
4875 
4876   // The address of a composite literal can be used as a static
4877   // initializer if the composite literal is itself usable as a
4878   // static initializer.
4879   if (expr->is_composite_literal() && expr->is_static_initializer())
4880     return true;
4881 
4882   // The address of a string constant can be used as a static
4883   // initializer.  This can not be written in Go itself but this is
4884   // used when building a type descriptor.
4885   if (expr->string_expression() != NULL)
4886     return true;
4887 
4888   return false;
4889 }
4890 
4891 // Return whether this dereference expression requires an explicit nil
4892 // check. If we are dereferencing the pointer to a large struct
4893 // (greater than the specified size threshold), we need to check for
4894 // nil. We don't bother to check for small structs because we expect
4895 // the system to crash on a nil pointer dereference. However, if we
4896 // know the address of this expression is being taken, we must always
4897 // check for nil.
4898 Unary_expression::Nil_check_classification
requires_nil_check(Gogo * gogo)4899 Unary_expression::requires_nil_check(Gogo* gogo)
4900 {
4901   go_assert(this->op_ == OPERATOR_MULT);
4902   go_assert(this->expr_->type()->points_to() != NULL);
4903 
4904   if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4905     return NIL_CHECK_NEEDED;
4906   else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4907     return NIL_CHECK_NOT_NEEDED;
4908 
4909   Type* ptype = this->expr_->type()->points_to();
4910   int64_t type_size = -1;
4911   if (!ptype->is_void_type())
4912     {
4913       bool ok = ptype->backend_type_size(gogo, &type_size);
4914       if (!ok)
4915         return NIL_CHECK_ERROR_ENCOUNTERED;
4916     }
4917 
4918   int64_t size_cutoff = gogo->nil_check_size_threshold();
4919   if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4920     this->issue_nil_check_ = NIL_CHECK_NEEDED;
4921   else
4922     this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4923   return this->issue_nil_check_;
4924 }
4925 
4926 // Apply unary opcode OP to UNC, setting NC.  Return true if this
4927 // could be done, false if not.  On overflow, issues an error and sets
4928 // *ISSUED_ERROR.
4929 
4930 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)4931 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4932 				Location location, Numeric_constant* nc,
4933 				bool* issued_error)
4934 {
4935   *issued_error = false;
4936   switch (op)
4937     {
4938     case OPERATOR_PLUS:
4939       *nc = *unc;
4940       return true;
4941 
4942     case OPERATOR_MINUS:
4943       if (unc->is_int() || unc->is_rune())
4944 	break;
4945       else if (unc->is_float())
4946 	{
4947 	  mpfr_t uval;
4948 	  unc->get_float(&uval);
4949 	  mpfr_t val;
4950 	  mpfr_init(val);
4951 	  mpfr_neg(val, uval, MPFR_RNDN);
4952 	  nc->set_float(unc->type(), val);
4953 	  mpfr_clear(uval);
4954 	  mpfr_clear(val);
4955 	  return true;
4956 	}
4957       else if (unc->is_complex())
4958 	{
4959 	  mpc_t uval;
4960 	  unc->get_complex(&uval);
4961 	  mpc_t val;
4962 	  mpc_init2(val, mpc_precision);
4963 	  mpc_neg(val, uval, MPC_RNDNN);
4964 	  nc->set_complex(unc->type(), val);
4965 	  mpc_clear(uval);
4966 	  mpc_clear(val);
4967 	  return true;
4968 	}
4969       else
4970 	go_unreachable();
4971 
4972     case OPERATOR_XOR:
4973       break;
4974 
4975     case OPERATOR_NOT:
4976     case OPERATOR_AND:
4977     case OPERATOR_MULT:
4978       return false;
4979 
4980     default:
4981       go_unreachable();
4982     }
4983 
4984   if (!unc->is_int() && !unc->is_rune())
4985     return false;
4986 
4987   mpz_t uval;
4988   if (unc->is_rune())
4989     unc->get_rune(&uval);
4990   else
4991     unc->get_int(&uval);
4992   mpz_t val;
4993   mpz_init(val);
4994 
4995   switch (op)
4996     {
4997     case OPERATOR_MINUS:
4998       mpz_neg(val, uval);
4999       break;
5000 
5001     case OPERATOR_NOT:
5002       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
5003       break;
5004 
5005     case OPERATOR_XOR:
5006       {
5007 	Type* utype = unc->type();
5008 	if (utype->integer_type() == NULL
5009 	    || utype->integer_type()->is_abstract())
5010 	  mpz_com(val, uval);
5011 	else
5012 	  {
5013 	    // The number of HOST_WIDE_INTs that it takes to represent
5014 	    // UVAL.
5015 	    size_t count = ((mpz_sizeinbase(uval, 2)
5016 			     + HOST_BITS_PER_WIDE_INT
5017 			     - 1)
5018 			    / HOST_BITS_PER_WIDE_INT);
5019 
5020 	    unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
5021 	    memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
5022 
5023 	    size_t obits = utype->integer_type()->bits();
5024 
5025 	    if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
5026 	      {
5027 		mpz_t adj;
5028 		mpz_init_set_ui(adj, 1);
5029 		mpz_mul_2exp(adj, adj, obits);
5030 		mpz_add(uval, uval, adj);
5031 		mpz_clear(adj);
5032 	      }
5033 
5034 	    size_t ecount;
5035 	    mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
5036 	    go_assert(ecount <= count);
5037 
5038 	    // Trim down to the number of words required by the type.
5039 	    size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
5040 			     / HOST_BITS_PER_WIDE_INT);
5041 	    go_assert(ocount <= count);
5042 
5043 	    for (size_t i = 0; i < ocount; ++i)
5044 	      phwi[i] = ~phwi[i];
5045 
5046 	    size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
5047 	    if (clearbits != 0)
5048 	      phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
5049 				   >> clearbits);
5050 
5051 	    mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
5052 
5053 	    if (!utype->integer_type()->is_unsigned()
5054 		&& mpz_tstbit(val, obits - 1))
5055 	      {
5056 		mpz_t adj;
5057 		mpz_init_set_ui(adj, 1);
5058 		mpz_mul_2exp(adj, adj, obits);
5059 		mpz_sub(val, val, adj);
5060 		mpz_clear(adj);
5061 	      }
5062 
5063 	    delete[] phwi;
5064 	  }
5065       }
5066       break;
5067 
5068     default:
5069       go_unreachable();
5070     }
5071 
5072   if (unc->is_rune())
5073     nc->set_rune(NULL, val);
5074   else
5075     nc->set_int(NULL, val);
5076 
5077   mpz_clear(uval);
5078   mpz_clear(val);
5079 
5080   if (!nc->set_type(unc->type(), true, location))
5081     {
5082       *issued_error = true;
5083       return false;
5084     }
5085   return true;
5086 }
5087 
5088 // Return the integral constant value of a unary expression, if it has one.
5089 
5090 bool
do_numeric_constant_value(Numeric_constant * nc) const5091 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5092 {
5093   Numeric_constant unc;
5094   if (!this->expr_->numeric_constant_value(&unc))
5095     return false;
5096   bool issued_error;
5097   return Unary_expression::eval_constant(this->op_, &unc, this->location(),
5098 					 nc, &issued_error);
5099 }
5100 
5101 // Return the boolean constant value of a unary expression, if it has one.
5102 
5103 bool
do_boolean_constant_value(bool * val) const5104 Unary_expression::do_boolean_constant_value(bool* val) const
5105 {
5106   if (this->op_ == OPERATOR_NOT
5107       && this->expr_->boolean_constant_value(val))
5108     {
5109       *val = !*val;
5110       return true;
5111     }
5112   return false;
5113 }
5114 
5115 // Return the type of a unary expression.
5116 
5117 Type*
do_type()5118 Unary_expression::do_type()
5119 {
5120   switch (this->op_)
5121     {
5122     case OPERATOR_PLUS:
5123     case OPERATOR_MINUS:
5124     case OPERATOR_NOT:
5125     case OPERATOR_XOR:
5126       return this->expr_->type();
5127 
5128     case OPERATOR_AND:
5129       return Type::make_pointer_type(this->expr_->type());
5130 
5131     case OPERATOR_MULT:
5132       {
5133 	Type* subtype = this->expr_->type();
5134 	Type* points_to = subtype->points_to();
5135 	if (points_to == NULL)
5136 	  return Type::make_error_type();
5137 	return points_to;
5138       }
5139 
5140     default:
5141       go_unreachable();
5142     }
5143 }
5144 
5145 // Determine abstract types for a unary expression.
5146 
5147 void
do_determine_type(const Type_context * context)5148 Unary_expression::do_determine_type(const Type_context* context)
5149 {
5150   switch (this->op_)
5151     {
5152     case OPERATOR_PLUS:
5153     case OPERATOR_MINUS:
5154     case OPERATOR_NOT:
5155     case OPERATOR_XOR:
5156       this->expr_->determine_type(context);
5157       break;
5158 
5159     case OPERATOR_AND:
5160       // Taking the address of something.
5161       {
5162 	Type* subtype = (context->type == NULL
5163 			 ? NULL
5164 			 : context->type->points_to());
5165 	Type_context subcontext(subtype, false);
5166 	this->expr_->determine_type(&subcontext);
5167       }
5168       break;
5169 
5170     case OPERATOR_MULT:
5171       // Indirecting through a pointer.
5172       {
5173 	Type* subtype = (context->type == NULL
5174 			 ? NULL
5175 			 : Type::make_pointer_type(context->type));
5176 	Type_context subcontext(subtype, false);
5177 	this->expr_->determine_type(&subcontext);
5178       }
5179       break;
5180 
5181     default:
5182       go_unreachable();
5183     }
5184 }
5185 
5186 // Check types for a unary expression.
5187 
5188 void
do_check_types(Gogo *)5189 Unary_expression::do_check_types(Gogo*)
5190 {
5191   Type* type = this->expr_->type();
5192   if (type->is_error())
5193     {
5194       this->set_is_error();
5195       return;
5196     }
5197 
5198   switch (this->op_)
5199     {
5200     case OPERATOR_PLUS:
5201     case OPERATOR_MINUS:
5202       if (type->integer_type() == NULL
5203 	  && type->float_type() == NULL
5204 	  && type->complex_type() == NULL)
5205 	this->report_error(_("expected numeric type"));
5206       break;
5207 
5208     case OPERATOR_NOT:
5209       if (!type->is_boolean_type())
5210 	this->report_error(_("expected boolean type"));
5211       break;
5212 
5213     case OPERATOR_XOR:
5214       if (type->integer_type() == NULL)
5215 	this->report_error(_("expected integer"));
5216       break;
5217 
5218     case OPERATOR_AND:
5219       if (!this->expr_->is_addressable())
5220 	{
5221 	  if (!this->create_temp_)
5222 	    {
5223 	      go_error_at(this->location(), "invalid operand for unary %<&%>");
5224 	      this->set_is_error();
5225 	    }
5226 	}
5227       else
5228 	this->expr_->issue_nil_check();
5229       break;
5230 
5231     case OPERATOR_MULT:
5232       // Indirecting through a pointer.
5233       if (type->points_to() == NULL)
5234 	this->report_error(_("expected pointer"));
5235       if (type->points_to()->is_error())
5236 	this->set_is_error();
5237       break;
5238 
5239     default:
5240       go_unreachable();
5241     }
5242 }
5243 
5244 // Get the backend representation for a unary expression.
5245 
5246 Bexpression*
do_get_backend(Translate_context * context)5247 Unary_expression::do_get_backend(Translate_context* context)
5248 {
5249   Gogo* gogo = context->gogo();
5250   Location loc = this->location();
5251 
5252   // Taking the address of a set-and-use-temporary expression requires
5253   // setting the temporary and then taking the address.
5254   if (this->op_ == OPERATOR_AND)
5255     {
5256       Set_and_use_temporary_expression* sut =
5257 	this->expr_->set_and_use_temporary_expression();
5258       if (sut != NULL)
5259 	{
5260 	  Temporary_statement* temp = sut->temporary();
5261 	  Bvariable* bvar = temp->get_backend_variable(context);
5262           Bexpression* bvar_expr =
5263               gogo->backend()->var_expression(bvar, loc);
5264           Bexpression* bval = sut->expression()->get_backend(context);
5265 
5266           Named_object* fn = context->function();
5267           go_assert(fn != NULL);
5268           Bfunction* bfn =
5269               fn->func_value()->get_or_make_decl(gogo, fn);
5270           Bstatement* bassign =
5271               gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
5272           Bexpression* bvar_addr =
5273               gogo->backend()->address_expression(bvar_expr, loc);
5274 	  return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
5275 	}
5276     }
5277 
5278   Bexpression* ret;
5279   Bexpression* bexpr = this->expr_->get_backend(context);
5280   Btype* btype = this->expr_->type()->get_backend(gogo);
5281   switch (this->op_)
5282     {
5283     case OPERATOR_PLUS:
5284       ret = bexpr;
5285       break;
5286 
5287     case OPERATOR_MINUS:
5288       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5289       ret = gogo->backend()->convert_expression(btype, ret, loc);
5290       break;
5291 
5292     case OPERATOR_NOT:
5293     case OPERATOR_XOR:
5294       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5295       break;
5296 
5297     case OPERATOR_AND:
5298       if (!this->create_temp_)
5299 	{
5300 	  // We should not see a non-constant constructor here; cases
5301 	  // where we would see one should have been moved onto the
5302 	  // heap at parse time.  Taking the address of a nonconstant
5303 	  // constructor will not do what the programmer expects.
5304 
5305           go_assert(!this->expr_->is_composite_literal()
5306                     || this->expr_->is_static_initializer());
5307 	  if (this->expr_->classification() == EXPRESSION_UNARY)
5308 	    {
5309 	      Unary_expression* ue =
5310 		static_cast<Unary_expression*>(this->expr_);
5311 	      go_assert(ue->op() != OPERATOR_AND);
5312 	    }
5313 	}
5314 
5315       if (this->is_gc_root_ || this->is_slice_init_)
5316 	{
5317 	  std::string var_name;
5318 	  bool copy_to_heap = false;
5319 	  if (this->is_gc_root_)
5320 	    {
5321 	      // Build a decl for a GC root variable.  GC roots are mutable, so
5322 	      // they cannot be represented as an immutable_struct in the
5323 	      // backend.
5324 	      var_name = gogo->gc_root_name();
5325 	    }
5326 	  else
5327 	    {
5328 	      // Build a decl for a slice value initializer.  An immutable slice
5329 	      // value initializer may have to be copied to the heap if it
5330 	      // contains pointers in a non-constant context.
5331 	      var_name = gogo->initializer_name();
5332 
5333 	      Array_type* at = this->expr_->type()->array_type();
5334 	      go_assert(at != NULL);
5335 
5336 	      // If we are not copying the value to the heap, we will only
5337 	      // initialize the value once, so we can use this directly
5338 	      // rather than copying it.  In that case we can't make it
5339 	      // read-only, because the program is permitted to change it.
5340 	      copy_to_heap = (context->function() != NULL
5341                               || context->is_const());
5342 	    }
5343 	  unsigned int flags = (Backend::variable_is_hidden
5344 				| Backend::variable_address_is_taken);
5345 	  if (copy_to_heap)
5346 	    flags |= Backend::variable_is_constant;
5347 	  Bvariable* implicit =
5348 	    gogo->backend()->implicit_variable(var_name, "", btype, flags, 0);
5349 	  gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
5350 						      flags, bexpr);
5351 	  bexpr = gogo->backend()->var_expression(implicit, loc);
5352 
5353 	  // If we are not copying a slice initializer to the heap,
5354 	  // then it can be changed by the program, so if it can
5355 	  // contain pointers we must register it as a GC root.
5356 	  if (this->is_slice_init_
5357 	      && !copy_to_heap
5358 	      && this->expr_->type()->has_pointer())
5359 	    {
5360 	      Bexpression* root =
5361                   gogo->backend()->var_expression(implicit, loc);
5362 	      root = gogo->backend()->address_expression(root, loc);
5363 	      Type* type = Type::make_pointer_type(this->expr_->type());
5364 	      gogo->add_gc_root(Expression::make_backend(root, type, loc));
5365 	    }
5366 	}
5367       else if ((this->expr_->is_composite_literal()
5368 		|| this->expr_->string_expression() != NULL)
5369 	       && this->expr_->is_static_initializer())
5370         {
5371 	  std::string var_name(gogo->initializer_name());
5372 	  unsigned int flags = (Backend::variable_is_hidden
5373 				| Backend::variable_address_is_taken);
5374           Bvariable* decl =
5375 	    gogo->backend()->immutable_struct(var_name, "", flags, btype, loc);
5376           gogo->backend()->immutable_struct_set_init(decl, var_name, flags,
5377 						     btype, loc, bexpr);
5378           bexpr = gogo->backend()->var_expression(decl, loc);
5379         }
5380       else if (this->expr_->is_constant())
5381         {
5382           std::string var_name(gogo->initializer_name());
5383 	  unsigned int flags = (Backend::variable_is_hidden
5384 				| Backend::variable_is_constant
5385 				| Backend::variable_address_is_taken);
5386           Bvariable* decl =
5387 	    gogo->backend()->implicit_variable(var_name, "", btype, flags, 0);
5388           gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
5389 						      flags, bexpr);
5390           bexpr = gogo->backend()->var_expression(decl, loc);
5391         }
5392 
5393       go_assert(!this->create_temp_ || this->expr_->is_multi_eval_safe());
5394       ret = gogo->backend()->address_expression(bexpr, loc);
5395       break;
5396 
5397     case OPERATOR_MULT:
5398       {
5399         go_assert(this->expr_->type()->points_to() != NULL);
5400 
5401         Type* ptype = this->expr_->type()->points_to();
5402         Btype* pbtype = ptype->get_backend(gogo);
5403         switch (this->requires_nil_check(gogo))
5404           {
5405             case NIL_CHECK_NOT_NEEDED:
5406               break;
5407             case NIL_CHECK_ERROR_ENCOUNTERED:
5408               {
5409                 go_assert(saw_errors());
5410                 return gogo->backend()->error_expression();
5411               }
5412             case NIL_CHECK_NEEDED:
5413               {
5414                 go_assert(this->expr_->is_multi_eval_safe());
5415 
5416                 // If we're nil-checking the result of a set-and-use-temporary
5417                 // expression, then pick out the target temp and use that
5418                 // for the final result of the conditional.
5419                 Bexpression* tbexpr = bexpr;
5420                 Bexpression* ubexpr = bexpr;
5421                 Set_and_use_temporary_expression* sut =
5422                     this->expr_->set_and_use_temporary_expression();
5423                 if (sut != NULL) {
5424                   Temporary_statement* temp = sut->temporary();
5425                   Bvariable* bvar = temp->get_backend_variable(context);
5426                   ubexpr = gogo->backend()->var_expression(bvar, loc);
5427                 }
5428                 Bexpression* nil =
5429                     Expression::make_nil(loc)->get_backend(context);
5430                 Bexpression* compare =
5431                     gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
5432                                                        nil, loc);
5433 		Expression* crash = Runtime::make_call(Runtime::PANIC_MEM,
5434 						       loc, 0);
5435 		Bexpression* bcrash = crash->get_backend(context);
5436                 Bfunction* bfn = context->function()->func_value()->get_decl();
5437                 bexpr = gogo->backend()->conditional_expression(bfn, btype,
5438                                                                 compare,
5439                                                                 bcrash, ubexpr,
5440                                                                 loc);
5441                 break;
5442               }
5443             case NIL_CHECK_DEFAULT:
5444               go_unreachable();
5445           }
5446         ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
5447       }
5448       break;
5449 
5450     default:
5451       go_unreachable();
5452     }
5453 
5454   return ret;
5455 }
5456 
5457 // Export a unary expression.
5458 
5459 void
do_export(Export_function_body * efb) const5460 Unary_expression::do_export(Export_function_body* efb) const
5461 {
5462   switch (this->op_)
5463     {
5464     case OPERATOR_PLUS:
5465       efb->write_c_string("+");
5466       break;
5467     case OPERATOR_MINUS:
5468       efb->write_c_string("-");
5469       break;
5470     case OPERATOR_NOT:
5471       efb->write_c_string("!");
5472       break;
5473     case OPERATOR_XOR:
5474       efb->write_c_string("^");
5475       break;
5476     case OPERATOR_AND:
5477       efb->write_c_string("&");
5478       break;
5479     case OPERATOR_MULT:
5480       efb->write_c_string("*");
5481       break;
5482     default:
5483       go_unreachable();
5484     }
5485   this->expr_->export_expression(efb);
5486 }
5487 
5488 // Import a unary expression.
5489 
5490 Expression*
do_import(Import_expression * imp,Location loc)5491 Unary_expression::do_import(Import_expression* imp, Location loc)
5492 {
5493   Operator op;
5494   switch (imp->get_char())
5495     {
5496     case '+':
5497       op = OPERATOR_PLUS;
5498       break;
5499     case '-':
5500       op = OPERATOR_MINUS;
5501       break;
5502     case '!':
5503       op = OPERATOR_NOT;
5504       break;
5505     case '^':
5506       op = OPERATOR_XOR;
5507       break;
5508     case '&':
5509       op = OPERATOR_AND;
5510       break;
5511     case '*':
5512       op = OPERATOR_MULT;
5513       break;
5514     default:
5515       go_unreachable();
5516     }
5517   if (imp->version() < EXPORT_FORMAT_V3)
5518     imp->require_c_string(" ");
5519   Expression* expr = Expression::import_expression(imp, loc);
5520   return Expression::make_unary(op, expr, loc);
5521 }
5522 
5523 // Dump ast representation of an unary expression.
5524 
5525 void
do_dump_expression(Ast_dump_context * ast_dump_context) const5526 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5527 {
5528   ast_dump_context->dump_operator(this->op_);
5529   ast_dump_context->ostream() << "(";
5530   ast_dump_context->dump_expression(this->expr_);
5531   ast_dump_context->ostream() << ") ";
5532 }
5533 
5534 // Make a unary expression.
5535 
5536 Expression*
make_unary(Operator op,Expression * expr,Location location)5537 Expression::make_unary(Operator op, Expression* expr, Location location)
5538 {
5539   return new Unary_expression(op, expr, location);
5540 }
5541 
5542 Expression*
make_dereference(Expression * ptr,Nil_check_classification docheck,Location location)5543 Expression::make_dereference(Expression* ptr,
5544                              Nil_check_classification docheck,
5545                              Location location)
5546 {
5547   Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
5548   if (docheck == NIL_CHECK_NEEDED)
5549     deref->unary_expression()->set_requires_nil_check(true);
5550   else if (docheck == NIL_CHECK_NOT_NEEDED)
5551     deref->unary_expression()->set_requires_nil_check(false);
5552   return deref;
5553 }
5554 
5555 // If this is an indirection through a pointer, return the expression
5556 // being pointed through.  Otherwise return this.
5557 
5558 Expression*
deref()5559 Expression::deref()
5560 {
5561   if (this->classification_ == EXPRESSION_UNARY)
5562     {
5563       Unary_expression* ue = static_cast<Unary_expression*>(this);
5564       if (ue->op() == OPERATOR_MULT)
5565 	return ue->operand();
5566     }
5567   return this;
5568 }
5569 
5570 // Class Binary_expression.
5571 
5572 // Traversal.
5573 
5574 int
do_traverse(Traverse * traverse)5575 Binary_expression::do_traverse(Traverse* traverse)
5576 {
5577   int t = Expression::traverse(&this->left_, traverse);
5578   if (t == TRAVERSE_EXIT)
5579     return TRAVERSE_EXIT;
5580   return Expression::traverse(&this->right_, traverse);
5581 }
5582 
5583 // Return whether this expression may be used as a static initializer.
5584 
5585 bool
do_is_static_initializer() const5586 Binary_expression::do_is_static_initializer() const
5587 {
5588   if (!this->left_->is_static_initializer()
5589       || !this->right_->is_static_initializer())
5590     return false;
5591 
5592   // Addresses can be static initializers, but we can't implement
5593   // arbitray binary expressions of them.
5594   Unary_expression* lu = this->left_->unary_expression();
5595   Unary_expression* ru = this->right_->unary_expression();
5596   if (lu != NULL && lu->op() == OPERATOR_AND)
5597     {
5598       if (ru != NULL && ru->op() == OPERATOR_AND)
5599 	return this->op_ == OPERATOR_MINUS;
5600       else
5601 	return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5602     }
5603   else if (ru != NULL && ru->op() == OPERATOR_AND)
5604     return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5605 
5606   // Other cases should resolve in the backend.
5607   return true;
5608 }
5609 
5610 // Return the type to use for a binary operation on operands of
5611 // LEFT_TYPE and RIGHT_TYPE.  These are the types of constants and as
5612 // such may be NULL or abstract.
5613 
5614 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)5615 Binary_expression::operation_type(Operator op, Type* left_type,
5616 				  Type* right_type, Type** result_type)
5617 {
5618   if (left_type != right_type
5619       && !left_type->is_abstract()
5620       && !right_type->is_abstract()
5621       && left_type->base() != right_type->base()
5622       && op != OPERATOR_LSHIFT
5623       && op != OPERATOR_RSHIFT)
5624     {
5625       // May be a type error--let it be diagnosed elsewhere.
5626       return false;
5627     }
5628 
5629   if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5630     {
5631       if (left_type->integer_type() != NULL)
5632 	*result_type = left_type;
5633       else
5634 	*result_type = Type::make_abstract_integer_type();
5635     }
5636   else if (!left_type->is_abstract() && left_type->named_type() != NULL)
5637     *result_type = left_type;
5638   else if (!right_type->is_abstract() && right_type->named_type() != NULL)
5639     *result_type = right_type;
5640   else if (!left_type->is_abstract())
5641     *result_type = left_type;
5642   else if (!right_type->is_abstract())
5643     *result_type = right_type;
5644   else if (left_type->complex_type() != NULL)
5645     *result_type = left_type;
5646   else if (right_type->complex_type() != NULL)
5647     *result_type = right_type;
5648   else if (left_type->float_type() != NULL)
5649     *result_type = left_type;
5650   else if (right_type->float_type() != NULL)
5651     *result_type = right_type;
5652   else if (left_type->integer_type() != NULL
5653 	   && left_type->integer_type()->is_rune())
5654     *result_type = left_type;
5655   else if (right_type->integer_type() != NULL
5656 	   && right_type->integer_type()->is_rune())
5657     *result_type = right_type;
5658   else
5659     *result_type = left_type;
5660 
5661   return true;
5662 }
5663 
5664 // Convert an integer comparison code and an operator to a boolean
5665 // value.
5666 
5667 bool
cmp_to_bool(Operator op,int cmp)5668 Binary_expression::cmp_to_bool(Operator op, int cmp)
5669 {
5670   switch (op)
5671     {
5672     case OPERATOR_EQEQ:
5673       return cmp == 0;
5674       break;
5675     case OPERATOR_NOTEQ:
5676       return cmp != 0;
5677       break;
5678     case OPERATOR_LT:
5679       return cmp < 0;
5680       break;
5681     case OPERATOR_LE:
5682       return cmp <= 0;
5683     case OPERATOR_GT:
5684       return cmp > 0;
5685     case OPERATOR_GE:
5686       return cmp >= 0;
5687     default:
5688       go_unreachable();
5689     }
5690 }
5691 
5692 // Compare constants according to OP.
5693 
5694 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)5695 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
5696 				    Numeric_constant* right_nc,
5697 				    Location location, bool* result)
5698 {
5699   Type* left_type = left_nc->type();
5700   Type* right_type = right_nc->type();
5701 
5702   Type* type;
5703   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5704     return false;
5705 
5706   // When comparing an untyped operand to a typed operand, we are
5707   // effectively coercing the untyped operand to the other operand's
5708   // type, so make sure that is valid.
5709   if (!left_nc->set_type(type, true, location)
5710       || !right_nc->set_type(type, true, location))
5711     return false;
5712 
5713   bool ret;
5714   int cmp;
5715   if (type->complex_type() != NULL)
5716     {
5717       if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
5718 	return false;
5719       ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
5720     }
5721   else if (type->float_type() != NULL)
5722     ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
5723   else
5724     ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
5725 
5726   if (ret)
5727     *result = Binary_expression::cmp_to_bool(op, cmp);
5728 
5729   return ret;
5730 }
5731 
5732 // Compare integer constants.
5733 
5734 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5735 Binary_expression::compare_integer(const Numeric_constant* left_nc,
5736 				   const Numeric_constant* right_nc,
5737 				   int* cmp)
5738 {
5739   mpz_t left_val;
5740   if (!left_nc->to_int(&left_val))
5741     return false;
5742   mpz_t right_val;
5743   if (!right_nc->to_int(&right_val))
5744     {
5745       mpz_clear(left_val);
5746       return false;
5747     }
5748 
5749   *cmp = mpz_cmp(left_val, right_val);
5750 
5751   mpz_clear(left_val);
5752   mpz_clear(right_val);
5753 
5754   return true;
5755 }
5756 
5757 // Compare floating point constants.
5758 
5759 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5760 Binary_expression::compare_float(const Numeric_constant* left_nc,
5761 				 const Numeric_constant* right_nc,
5762 				 int* cmp)
5763 {
5764   mpfr_t left_val;
5765   if (!left_nc->to_float(&left_val))
5766     return false;
5767   mpfr_t right_val;
5768   if (!right_nc->to_float(&right_val))
5769     {
5770       mpfr_clear(left_val);
5771       return false;
5772     }
5773 
5774   // We already coerced both operands to the same type.  If that type
5775   // is not an abstract type, we need to round the values accordingly.
5776   Type* type = left_nc->type();
5777   if (!type->is_abstract() && type->float_type() != NULL)
5778     {
5779       int bits = type->float_type()->bits();
5780       mpfr_prec_round(left_val, bits, MPFR_RNDN);
5781       mpfr_prec_round(right_val, bits, MPFR_RNDN);
5782     }
5783 
5784   *cmp = mpfr_cmp(left_val, right_val);
5785 
5786   mpfr_clear(left_val);
5787   mpfr_clear(right_val);
5788 
5789   return true;
5790 }
5791 
5792 // Compare complex constants.  Complex numbers may only be compared
5793 // for equality.
5794 
5795 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5796 Binary_expression::compare_complex(const Numeric_constant* left_nc,
5797 				   const Numeric_constant* right_nc,
5798 				   int* cmp)
5799 {
5800   mpc_t left_val;
5801   if (!left_nc->to_complex(&left_val))
5802     return false;
5803   mpc_t right_val;
5804   if (!right_nc->to_complex(&right_val))
5805     {
5806       mpc_clear(left_val);
5807       return false;
5808     }
5809 
5810   // We already coerced both operands to the same type.  If that type
5811   // is not an abstract type, we need to round the values accordingly.
5812   Type* type = left_nc->type();
5813   if (!type->is_abstract() && type->complex_type() != NULL)
5814     {
5815       int bits = type->complex_type()->bits();
5816       mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
5817       mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
5818       mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
5819       mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
5820     }
5821 
5822   *cmp = mpc_cmp(left_val, right_val) != 0;
5823 
5824   mpc_clear(left_val);
5825   mpc_clear(right_val);
5826 
5827   return true;
5828 }
5829 
5830 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC.  Return
5831 // true if this could be done, false if not.  Issue errors at LOCATION
5832 // as appropriate, and sets *ISSUED_ERROR if it did.
5833 
5834 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)5835 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
5836 				 Numeric_constant* right_nc,
5837 				 Location location, Numeric_constant* nc,
5838 				 bool* issued_error)
5839 {
5840   *issued_error = false;
5841   switch (op)
5842     {
5843     case OPERATOR_OROR:
5844     case OPERATOR_ANDAND:
5845     case OPERATOR_EQEQ:
5846     case OPERATOR_NOTEQ:
5847     case OPERATOR_LT:
5848     case OPERATOR_LE:
5849     case OPERATOR_GT:
5850     case OPERATOR_GE:
5851       // These return boolean values, not numeric.
5852       return false;
5853     default:
5854       break;
5855     }
5856 
5857   Type* left_type = left_nc->type();
5858   Type* right_type = right_nc->type();
5859 
5860   Type* type;
5861   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5862     return false;
5863 
5864   bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
5865 
5866   // When combining an untyped operand with a typed operand, we are
5867   // effectively coercing the untyped operand to the other operand's
5868   // type, so make sure that is valid.
5869   if (!left_nc->set_type(type, true, location))
5870     return false;
5871   if (!is_shift && !right_nc->set_type(type, true, location))
5872     return false;
5873   if (is_shift
5874       && ((left_type->integer_type() == NULL
5875            && !left_type->is_abstract())
5876           || (right_type->integer_type() == NULL
5877               && !right_type->is_abstract())))
5878     return false;
5879 
5880   bool r;
5881   if (type->complex_type() != NULL)
5882     r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
5883   else if (type->float_type() != NULL)
5884     r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
5885   else
5886     r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
5887 
5888   if (r)
5889     {
5890       r = nc->set_type(type, true, location);
5891       if (!r)
5892 	*issued_error = true;
5893     }
5894 
5895   return r;
5896 }
5897 
5898 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5899 // integer operations.  Return true if this could be done, false if
5900 // not.
5901 
5902 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5903 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
5904 				const Numeric_constant* right_nc,
5905 				Location location, Numeric_constant* nc)
5906 {
5907   mpz_t left_val;
5908   if (!left_nc->to_int(&left_val))
5909     return false;
5910   mpz_t right_val;
5911   if (!right_nc->to_int(&right_val))
5912     {
5913       mpz_clear(left_val);
5914       return false;
5915     }
5916 
5917   mpz_t val;
5918   mpz_init(val);
5919 
5920   switch (op)
5921     {
5922     case OPERATOR_PLUS:
5923       mpz_add(val, left_val, right_val);
5924       if (mpz_sizeinbase(val, 2) > 0x100000)
5925 	{
5926 	  go_error_at(location, "constant addition overflow");
5927           nc->set_invalid();
5928 	  mpz_set_ui(val, 1);
5929 	}
5930       break;
5931     case OPERATOR_MINUS:
5932       mpz_sub(val, left_val, right_val);
5933       if (mpz_sizeinbase(val, 2) > 0x100000)
5934 	{
5935 	  go_error_at(location, "constant subtraction overflow");
5936           nc->set_invalid();
5937 	  mpz_set_ui(val, 1);
5938 	}
5939       break;
5940     case OPERATOR_OR:
5941       mpz_ior(val, left_val, right_val);
5942       break;
5943     case OPERATOR_XOR:
5944       mpz_xor(val, left_val, right_val);
5945       break;
5946     case OPERATOR_MULT:
5947       mpz_mul(val, left_val, right_val);
5948       if (mpz_sizeinbase(val, 2) > 0x100000)
5949 	{
5950 	  go_error_at(location, "constant multiplication overflow");
5951           nc->set_invalid();
5952 	  mpz_set_ui(val, 1);
5953 	}
5954       break;
5955     case OPERATOR_DIV:
5956       if (mpz_sgn(right_val) != 0)
5957 	mpz_tdiv_q(val, left_val, right_val);
5958       else
5959 	{
5960 	  go_error_at(location, "division by zero");
5961           nc->set_invalid();
5962 	  mpz_set_ui(val, 0);
5963 	}
5964       break;
5965     case OPERATOR_MOD:
5966       if (mpz_sgn(right_val) != 0)
5967 	mpz_tdiv_r(val, left_val, right_val);
5968       else
5969 	{
5970 	  go_error_at(location, "division by zero");
5971           nc->set_invalid();
5972 	  mpz_set_ui(val, 0);
5973 	}
5974       break;
5975     case OPERATOR_LSHIFT:
5976       {
5977 	unsigned long shift = mpz_get_ui(right_val);
5978 	if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5979 	  mpz_mul_2exp(val, left_val, shift);
5980 	else
5981 	  {
5982 	    go_error_at(location, "shift count overflow");
5983             nc->set_invalid();
5984 	    mpz_set_ui(val, 1);
5985 	  }
5986 	break;
5987       }
5988       break;
5989     case OPERATOR_RSHIFT:
5990       {
5991 	unsigned long shift = mpz_get_ui(right_val);
5992 	if (mpz_cmp_ui(right_val, shift) != 0)
5993 	  {
5994 	    go_error_at(location, "shift count overflow");
5995             nc->set_invalid();
5996 	    mpz_set_ui(val, 1);
5997 	  }
5998 	else
5999 	  {
6000 	    if (mpz_cmp_ui(left_val, 0) >= 0)
6001 	      mpz_tdiv_q_2exp(val, left_val, shift);
6002 	    else
6003 	      mpz_fdiv_q_2exp(val, left_val, shift);
6004 	  }
6005 	break;
6006       }
6007       break;
6008     case OPERATOR_AND:
6009       mpz_and(val, left_val, right_val);
6010       break;
6011     case OPERATOR_BITCLEAR:
6012       {
6013 	mpz_t tval;
6014 	mpz_init(tval);
6015 	mpz_com(tval, right_val);
6016 	mpz_and(val, left_val, tval);
6017 	mpz_clear(tval);
6018       }
6019       break;
6020     default:
6021       go_unreachable();
6022     }
6023 
6024   mpz_clear(left_val);
6025   mpz_clear(right_val);
6026 
6027   if (left_nc->is_rune()
6028       || (op != OPERATOR_LSHIFT
6029 	  && op != OPERATOR_RSHIFT
6030 	  && right_nc->is_rune()))
6031     nc->set_rune(NULL, val);
6032   else
6033     nc->set_int(NULL, val);
6034 
6035   mpz_clear(val);
6036 
6037   return true;
6038 }
6039 
6040 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6041 // floating point operations.  Return true if this could be done,
6042 // false if not.
6043 
6044 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)6045 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
6046 			      const Numeric_constant* right_nc,
6047 			      Location location, Numeric_constant* nc)
6048 {
6049   mpfr_t left_val;
6050   if (!left_nc->to_float(&left_val))
6051     return false;
6052   mpfr_t right_val;
6053   if (!right_nc->to_float(&right_val))
6054     {
6055       mpfr_clear(left_val);
6056       return false;
6057     }
6058 
6059   mpfr_t val;
6060   mpfr_init(val);
6061 
6062   bool ret = true;
6063   switch (op)
6064     {
6065     case OPERATOR_PLUS:
6066       mpfr_add(val, left_val, right_val, MPFR_RNDN);
6067       break;
6068     case OPERATOR_MINUS:
6069       mpfr_sub(val, left_val, right_val, MPFR_RNDN);
6070       break;
6071     case OPERATOR_OR:
6072     case OPERATOR_XOR:
6073     case OPERATOR_AND:
6074     case OPERATOR_BITCLEAR:
6075     case OPERATOR_MOD:
6076     case OPERATOR_LSHIFT:
6077     case OPERATOR_RSHIFT:
6078       mpfr_set_ui(val, 0, MPFR_RNDN);
6079       ret = false;
6080       break;
6081     case OPERATOR_MULT:
6082       mpfr_mul(val, left_val, right_val, MPFR_RNDN);
6083       break;
6084     case OPERATOR_DIV:
6085       if (!mpfr_zero_p(right_val))
6086 	mpfr_div(val, left_val, right_val, MPFR_RNDN);
6087       else
6088 	{
6089 	  go_error_at(location, "division by zero");
6090           nc->set_invalid();
6091 	  mpfr_set_ui(val, 0, MPFR_RNDN);
6092 	}
6093       break;
6094     default:
6095       go_unreachable();
6096     }
6097 
6098   mpfr_clear(left_val);
6099   mpfr_clear(right_val);
6100 
6101   nc->set_float(NULL, val);
6102   mpfr_clear(val);
6103 
6104   return ret;
6105 }
6106 
6107 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6108 // complex operations.  Return true if this could be done, false if
6109 // not.
6110 
6111 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)6112 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
6113 				const Numeric_constant* right_nc,
6114 				Location location, Numeric_constant* nc)
6115 {
6116   mpc_t left_val;
6117   if (!left_nc->to_complex(&left_val))
6118     return false;
6119   mpc_t right_val;
6120   if (!right_nc->to_complex(&right_val))
6121     {
6122       mpc_clear(left_val);
6123       return false;
6124     }
6125 
6126   mpc_t val;
6127   mpc_init2(val, mpc_precision);
6128 
6129   bool ret = true;
6130   switch (op)
6131     {
6132     case OPERATOR_PLUS:
6133       mpc_add(val, left_val, right_val, MPC_RNDNN);
6134       break;
6135     case OPERATOR_MINUS:
6136       mpc_sub(val, left_val, right_val, MPC_RNDNN);
6137       break;
6138     case OPERATOR_OR:
6139     case OPERATOR_XOR:
6140     case OPERATOR_AND:
6141     case OPERATOR_BITCLEAR:
6142     case OPERATOR_MOD:
6143     case OPERATOR_LSHIFT:
6144     case OPERATOR_RSHIFT:
6145       mpc_set_ui(val, 0, MPC_RNDNN);
6146       ret = false;
6147       break;
6148     case OPERATOR_MULT:
6149       mpc_mul(val, left_val, right_val, MPC_RNDNN);
6150       break;
6151     case OPERATOR_DIV:
6152       if (mpc_cmp_si(right_val, 0) == 0)
6153 	{
6154 	  go_error_at(location, "division by zero");
6155           nc->set_invalid();
6156 	  mpc_set_ui(val, 0, MPC_RNDNN);
6157 	  break;
6158 	}
6159       mpc_div(val, left_val, right_val, MPC_RNDNN);
6160       break;
6161     default:
6162       go_unreachable();
6163     }
6164 
6165   mpc_clear(left_val);
6166   mpc_clear(right_val);
6167 
6168   nc->set_complex(NULL, val);
6169   mpc_clear(val);
6170 
6171   return ret;
6172 }
6173 
6174 // Lower a binary expression.  We have to evaluate constant
6175 // expressions now, in order to implement Go's unlimited precision
6176 // constants.
6177 
6178 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)6179 Binary_expression::do_lower(Gogo* gogo, Named_object*,
6180 			    Statement_inserter* inserter, int)
6181 {
6182   Location location = this->location();
6183   Operator op = this->op_;
6184   Expression* left = this->left_;
6185   Expression* right = this->right_;
6186 
6187   const bool is_comparison = (op == OPERATOR_EQEQ
6188 			      || op == OPERATOR_NOTEQ
6189 			      || op == OPERATOR_LT
6190 			      || op == OPERATOR_LE
6191 			      || op == OPERATOR_GT
6192 			      || op == OPERATOR_GE);
6193 
6194   // Numeric constant expressions.
6195   {
6196     Numeric_constant left_nc;
6197     Numeric_constant right_nc;
6198     if (left->numeric_constant_value(&left_nc)
6199 	&& right->numeric_constant_value(&right_nc))
6200       {
6201 	if (is_comparison)
6202 	  {
6203 	    bool result;
6204 	    if (!Binary_expression::compare_constant(op, &left_nc,
6205 						     &right_nc, location,
6206 						     &result))
6207 	      return this;
6208 	    return Expression::make_boolean(result, location);
6209 	  }
6210 	else
6211 	  {
6212 	    Numeric_constant nc;
6213 	    bool issued_error;
6214 	    if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
6215 						  location, &nc,
6216 						  &issued_error))
6217 	      {
6218 		if (issued_error)
6219 		  return Expression::make_error(location);
6220                 return this;
6221 	      }
6222 	    return nc.expression(location);
6223 	  }
6224       }
6225   }
6226 
6227   // String constant expressions.
6228   //
6229   // Avoid constant folding here if the left and right types are incompatible
6230   // (leave the operation intact so that the type checker can complain about it
6231   // later on). If concatenating an abstract string with a named string type,
6232   // result type needs to be of the named type (see issue 31412).
6233   if (left->type()->is_string_type()
6234       && right->type()->is_string_type()
6235       && (left->type()->named_type() == NULL
6236           || right->type()->named_type() == NULL
6237           || left->type()->named_type() == right->type()->named_type()))
6238     {
6239       std::string left_string;
6240       std::string right_string;
6241       if (left->string_constant_value(&left_string)
6242 	  && right->string_constant_value(&right_string))
6243 	{
6244 	  if (op == OPERATOR_PLUS)
6245             {
6246               Type* result_type = (left->type()->named_type() != NULL
6247                                    ? left->type()
6248                                    : right->type());
6249 	      delete left;
6250 	      delete right;
6251               return Expression::make_string_typed(left_string + right_string,
6252                                                    result_type, location);
6253             }
6254 	  else if (is_comparison)
6255 	    {
6256 	      int cmp = left_string.compare(right_string);
6257 	      bool r = Binary_expression::cmp_to_bool(op, cmp);
6258 	      delete left;
6259 	      delete right;
6260 	      return Expression::make_boolean(r, location);
6261 	    }
6262 	}
6263     }
6264 
6265   // Lower struct, array, and some interface comparisons.
6266   if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6267     {
6268       if (left->type()->struct_type() != NULL
6269 	  && right->type()->struct_type() != NULL)
6270 	return this->lower_struct_comparison(gogo, inserter);
6271       else if (left->type()->array_type() != NULL
6272 	       && !left->type()->is_slice_type()
6273 	       && right->type()->array_type() != NULL
6274 	       && !right->type()->is_slice_type())
6275 	return this->lower_array_comparison(gogo, inserter);
6276       else if ((left->type()->interface_type() != NULL
6277                 && right->type()->interface_type() == NULL)
6278                || (left->type()->interface_type() == NULL
6279                    && right->type()->interface_type() != NULL))
6280 	return this->lower_interface_value_comparison(gogo, inserter);
6281     }
6282 
6283   // Lower string concatenation to String_concat_expression, so that
6284   // we can group sequences of string additions.
6285   if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
6286     {
6287       Expression_list* exprs;
6288       String_concat_expression* left_sce =
6289 	this->left_->string_concat_expression();
6290       if (left_sce != NULL)
6291 	exprs = left_sce->exprs();
6292       else
6293 	{
6294 	  exprs = new Expression_list();
6295 	  exprs->push_back(this->left_);
6296 	}
6297 
6298       String_concat_expression* right_sce =
6299 	this->right_->string_concat_expression();
6300       if (right_sce != NULL)
6301 	exprs->append(right_sce->exprs());
6302       else
6303 	exprs->push_back(this->right_);
6304 
6305       return Expression::make_string_concat(exprs);
6306     }
6307 
6308   return this;
6309 }
6310 
6311 // Lower a struct comparison.
6312 
6313 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)6314 Binary_expression::lower_struct_comparison(Gogo* gogo,
6315 					   Statement_inserter* inserter)
6316 {
6317   Struct_type* st = this->left_->type()->struct_type();
6318   Struct_type* st2 = this->right_->type()->struct_type();
6319   if (st2 == NULL)
6320     return this;
6321   if (st != st2
6322       && !Type::are_identical(st, st2,
6323 			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6324 			      NULL))
6325     return this;
6326   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6327 					   this->right_->type(), NULL))
6328     return this;
6329 
6330   // See if we can compare using memcmp.  As a heuristic, we use
6331   // memcmp rather than field references and comparisons if there are
6332   // more than two fields.
6333   if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
6334     return this->lower_compare_to_memcmp(gogo, inserter);
6335 
6336   Location loc = this->location();
6337 
6338   Expression* left = this->left_;
6339   Temporary_statement* left_temp = NULL;
6340   if (left->var_expression() == NULL
6341       && left->temporary_reference_expression() == NULL)
6342     {
6343       left_temp = Statement::make_temporary(left->type(), NULL, loc);
6344       inserter->insert(left_temp);
6345       left = Expression::make_set_and_use_temporary(left_temp, left, loc);
6346     }
6347 
6348   Expression* right = this->right_;
6349   Temporary_statement* right_temp = NULL;
6350   if (right->var_expression() == NULL
6351       && right->temporary_reference_expression() == NULL)
6352     {
6353       right_temp = Statement::make_temporary(right->type(), NULL, loc);
6354       inserter->insert(right_temp);
6355       right = Expression::make_set_and_use_temporary(right_temp, right, loc);
6356     }
6357 
6358   Expression* ret = Expression::make_boolean(true, loc);
6359   const Struct_field_list* fields = st->fields();
6360   unsigned int field_index = 0;
6361   for (Struct_field_list::const_iterator pf = fields->begin();
6362        pf != fields->end();
6363        ++pf, ++field_index)
6364     {
6365       if (Gogo::is_sink_name(pf->field_name()))
6366 	continue;
6367 
6368       if (field_index > 0)
6369 	{
6370 	  if (left_temp == NULL)
6371 	    left = left->copy();
6372 	  else
6373 	    left = Expression::make_temporary_reference(left_temp, loc);
6374 	  if (right_temp == NULL)
6375 	    right = right->copy();
6376 	  else
6377 	    right = Expression::make_temporary_reference(right_temp, loc);
6378 	}
6379       Expression* f1 = Expression::make_field_reference(left, field_index,
6380 							loc);
6381       Expression* f2 = Expression::make_field_reference(right, field_index,
6382 							loc);
6383       Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6384       ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6385     }
6386 
6387   if (this->op_ == OPERATOR_NOTEQ)
6388     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6389 
6390   return ret;
6391 }
6392 
6393 // Lower an array comparison.
6394 
6395 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)6396 Binary_expression::lower_array_comparison(Gogo* gogo,
6397 					  Statement_inserter* inserter)
6398 {
6399   Array_type* at = this->left_->type()->array_type();
6400   Array_type* at2 = this->right_->type()->array_type();
6401   if (at2 == NULL)
6402     return this;
6403   if (at != at2
6404       && !Type::are_identical(at, at2,
6405 			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6406 			      NULL))
6407     return this;
6408   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6409 					   this->right_->type(), NULL))
6410     return this;
6411 
6412   // Call memcmp directly if possible.  This may let the middle-end
6413   // optimize the call.
6414   if (at->compare_is_identity(gogo))
6415     return this->lower_compare_to_memcmp(gogo, inserter);
6416 
6417   // Call the array comparison function.
6418   Named_object* equal_fn =
6419     at->equal_function(gogo, this->left_->type()->named_type(), NULL);
6420 
6421   Location loc = this->location();
6422 
6423   Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6424 
6425   Expression_list* args = new Expression_list();
6426   args->push_back(this->operand_address(inserter, this->left_));
6427   args->push_back(this->operand_address(inserter, this->right_));
6428 
6429   Call_expression* ce = Expression::make_call(func, args, false, loc);
6430 
6431   // Record that this is a call to a generated equality function.  We
6432   // need to do this because a comparison returns an abstract boolean
6433   // type, but the function necessarily returns "bool".  The
6434   // difference shows up in code like
6435   //     type mybool bool
6436   //     var b mybool = [10]string{} == [10]string{}
6437   // The comparison function returns "bool", but since a comparison
6438   // has an abstract boolean type we need an implicit conversion to
6439   // "mybool".  The implicit conversion is inserted in
6440   // Call_expression::do_flatten.
6441   ce->set_is_equal_function();
6442 
6443   Expression* ret = ce;
6444   if (this->op_ == OPERATOR_NOTEQ)
6445     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6446 
6447   return ret;
6448 }
6449 
6450 // Lower an interface to value comparison.
6451 
6452 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)6453 Binary_expression::lower_interface_value_comparison(Gogo*,
6454                                                     Statement_inserter* inserter)
6455 {
6456   Type* left_type = this->left_->type();
6457   Type* right_type = this->right_->type();
6458   Interface_type* ift;
6459   if (left_type->interface_type() != NULL)
6460     {
6461       ift = left_type->interface_type();
6462       if (!ift->implements_interface(right_type, NULL))
6463         return this;
6464     }
6465   else
6466     {
6467       ift = right_type->interface_type();
6468       if (!ift->implements_interface(left_type, NULL))
6469         return this;
6470     }
6471   if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
6472     return this;
6473 
6474   Location loc = this->location();
6475 
6476   if (left_type->interface_type() == NULL
6477       && left_type->points_to() == NULL
6478       && !this->left_->is_addressable())
6479     {
6480       Temporary_statement* temp =
6481           Statement::make_temporary(left_type, NULL, loc);
6482       inserter->insert(temp);
6483       this->left_ =
6484           Expression::make_set_and_use_temporary(temp, this->left_, loc);
6485     }
6486 
6487   if (right_type->interface_type() == NULL
6488       && right_type->points_to() == NULL
6489       && !this->right_->is_addressable())
6490     {
6491       Temporary_statement* temp =
6492           Statement::make_temporary(right_type, NULL, loc);
6493       inserter->insert(temp);
6494       this->right_ =
6495           Expression::make_set_and_use_temporary(temp, this->right_, loc);
6496     }
6497 
6498   return this;
6499 }
6500 
6501 // Lower a struct or array comparison to a call to memcmp.
6502 
6503 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)6504 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6505 {
6506   Location loc = this->location();
6507 
6508   Expression* a1 = this->operand_address(inserter, this->left_);
6509   Expression* a2 = this->operand_address(inserter, this->right_);
6510   Expression* len = Expression::make_type_info(this->left_->type(),
6511 					       TYPE_INFO_SIZE);
6512 
6513   Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6514   Type* int32_type = Type::lookup_integer_type("int32");
6515   Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
6516   return Expression::make_binary(this->op_, call, zero, loc);
6517 }
6518 
6519 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)6520 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
6521                               Statement_inserter* inserter)
6522 {
6523   Location loc = this->location();
6524   if (this->left_->type()->is_error_type()
6525       || this->right_->type()->is_error_type()
6526       || this->left_->is_error_expression()
6527       || this->right_->is_error_expression())
6528     {
6529       go_assert(saw_errors());
6530       return Expression::make_error(loc);
6531     }
6532 
6533   Temporary_statement* temp;
6534 
6535   Type* left_type = this->left_->type();
6536   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6537                       || this->op_ == OPERATOR_RSHIFT);
6538   bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
6539                       left_type->integer_type() != NULL)
6540                      || this->op_ == OPERATOR_MOD);
6541   bool is_string_op = (left_type->is_string_type()
6542                        && this->right_->type()->is_string_type());
6543 
6544   if (is_string_op)
6545     {
6546       // Mark string([]byte) operands to reuse the backing store.
6547       // String comparison does not keep the reference, so it is safe.
6548       Type_conversion_expression* lce =
6549         this->left_->conversion_expression();
6550       if (lce != NULL && lce->expr()->type()->is_slice_type())
6551         lce->set_no_copy(true);
6552       Type_conversion_expression* rce =
6553         this->right_->conversion_expression();
6554       if (rce != NULL && rce->expr()->type()->is_slice_type())
6555         rce->set_no_copy(true);
6556     }
6557 
6558   if (is_shift_op
6559       || (is_idiv_op
6560 	  && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
6561       || is_string_op)
6562     {
6563       if (!this->left_->is_multi_eval_safe())
6564         {
6565           temp = Statement::make_temporary(NULL, this->left_, loc);
6566           inserter->insert(temp);
6567           this->left_ = Expression::make_temporary_reference(temp, loc);
6568         }
6569       if (!this->right_->is_multi_eval_safe())
6570         {
6571           temp =
6572               Statement::make_temporary(NULL, this->right_, loc);
6573           this->right_ = Expression::make_temporary_reference(temp, loc);
6574           inserter->insert(temp);
6575         }
6576     }
6577   return this;
6578 }
6579 
6580 
6581 // Return the address of EXPR, cast to unsafe.Pointer.
6582 
6583 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)6584 Binary_expression::operand_address(Statement_inserter* inserter,
6585 				   Expression* expr)
6586 {
6587   Location loc = this->location();
6588 
6589   if (!expr->is_addressable())
6590     {
6591       Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6592 							    loc);
6593       inserter->insert(temp);
6594       expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6595     }
6596   expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6597   static_cast<Unary_expression*>(expr)->set_does_not_escape();
6598   Type* void_type = Type::make_void_type();
6599   Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6600   return Expression::make_cast(unsafe_pointer_type, expr, loc);
6601 }
6602 
6603 // Return the numeric constant value, if it has one.
6604 
6605 bool
do_numeric_constant_value(Numeric_constant * nc) const6606 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
6607 {
6608   Numeric_constant left_nc;
6609   if (!this->left_->numeric_constant_value(&left_nc))
6610     return false;
6611   Numeric_constant right_nc;
6612   if (!this->right_->numeric_constant_value(&right_nc))
6613     return false;
6614   bool issued_error;
6615   return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
6616 					  this->location(), nc, &issued_error);
6617 }
6618 
6619 // Return the boolean constant value, if it has one.
6620 
6621 bool
do_boolean_constant_value(bool * val) const6622 Binary_expression::do_boolean_constant_value(bool* val) const
6623 {
6624   bool is_comparison = false;
6625   switch (this->op_)
6626     {
6627     case OPERATOR_EQEQ:
6628     case OPERATOR_NOTEQ:
6629     case OPERATOR_LT:
6630     case OPERATOR_LE:
6631     case OPERATOR_GT:
6632     case OPERATOR_GE:
6633       is_comparison = true;
6634       break;
6635     case OPERATOR_ANDAND:
6636     case OPERATOR_OROR:
6637       break;
6638     default:
6639       return false;
6640     }
6641 
6642   Numeric_constant left_nc, right_nc;
6643   if (is_comparison
6644       && this->left_->numeric_constant_value(&left_nc)
6645       && this->right_->numeric_constant_value(&right_nc))
6646     return Binary_expression::compare_constant(this->op_, &left_nc,
6647                                                &right_nc,
6648                                                this->location(),
6649                                                val);
6650 
6651   std::string left_str, right_str;
6652   if (is_comparison
6653       && this->left_->string_constant_value(&left_str)
6654       && this->right_->string_constant_value(&right_str))
6655     {
6656       *val = Binary_expression::cmp_to_bool(this->op_,
6657                                             left_str.compare(right_str));
6658       return true;
6659     }
6660 
6661   bool left_bval;
6662   if (this->left_->boolean_constant_value(&left_bval))
6663     {
6664       if (this->op_ == OPERATOR_ANDAND && !left_bval)
6665         {
6666           *val = false;
6667           return true;
6668         }
6669       else if (this->op_ == OPERATOR_OROR && left_bval)
6670         {
6671           *val = true;
6672           return true;
6673         }
6674 
6675       bool right_bval;
6676       if (this->right_->boolean_constant_value(&right_bval))
6677         {
6678           switch (this->op_)
6679             {
6680             case OPERATOR_EQEQ:
6681               *val = (left_bval == right_bval);
6682               return true;
6683             case OPERATOR_NOTEQ:
6684               *val = (left_bval != right_bval);
6685               return true;
6686             case OPERATOR_ANDAND:
6687             case OPERATOR_OROR:
6688               *val = right_bval;
6689               return true;
6690             default:
6691               go_unreachable();
6692             }
6693         }
6694     }
6695 
6696   return false;
6697 }
6698 
6699 // Note that the value is being discarded.
6700 
6701 bool
do_discarding_value()6702 Binary_expression::do_discarding_value()
6703 {
6704   if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6705     return this->right_->discarding_value();
6706   else
6707     {
6708       this->unused_value_error();
6709       return false;
6710     }
6711 }
6712 
6713 // Get type.
6714 
6715 Type*
do_type()6716 Binary_expression::do_type()
6717 {
6718   if (this->classification() == EXPRESSION_ERROR)
6719     return Type::make_error_type();
6720 
6721   switch (this->op_)
6722     {
6723     case OPERATOR_EQEQ:
6724     case OPERATOR_NOTEQ:
6725     case OPERATOR_LT:
6726     case OPERATOR_LE:
6727     case OPERATOR_GT:
6728     case OPERATOR_GE:
6729       if (this->type_ == NULL)
6730 	this->type_ = Type::make_boolean_type();
6731       return this->type_;
6732 
6733     case OPERATOR_PLUS:
6734     case OPERATOR_MINUS:
6735     case OPERATOR_OR:
6736     case OPERATOR_XOR:
6737     case OPERATOR_MULT:
6738     case OPERATOR_DIV:
6739     case OPERATOR_MOD:
6740     case OPERATOR_AND:
6741     case OPERATOR_BITCLEAR:
6742     case OPERATOR_OROR:
6743     case OPERATOR_ANDAND:
6744       {
6745 	Type* type;
6746 	if (!Binary_expression::operation_type(this->op_,
6747 					       this->left_->type(),
6748 					       this->right_->type(),
6749 					       &type))
6750 	  return Type::make_error_type();
6751 	return type;
6752       }
6753 
6754     case OPERATOR_LSHIFT:
6755     case OPERATOR_RSHIFT:
6756       return this->left_->type();
6757 
6758     default:
6759       go_unreachable();
6760     }
6761 }
6762 
6763 // Set type for a binary expression.
6764 
6765 void
do_determine_type(const Type_context * context)6766 Binary_expression::do_determine_type(const Type_context* context)
6767 {
6768   Type* tleft = this->left_->type();
6769   Type* tright = this->right_->type();
6770 
6771   // Both sides should have the same type, except for the shift
6772   // operations.  For a comparison, we should ignore the incoming
6773   // type.
6774 
6775   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6776 		      || this->op_ == OPERATOR_RSHIFT);
6777 
6778   bool is_comparison = (this->op_ == OPERATOR_EQEQ
6779 			|| this->op_ == OPERATOR_NOTEQ
6780 			|| this->op_ == OPERATOR_LT
6781 			|| this->op_ == OPERATOR_LE
6782 			|| this->op_ == OPERATOR_GT
6783 			|| this->op_ == OPERATOR_GE);
6784 
6785   // For constant expressions, the context of the result is not useful in
6786   // determining the types of the operands.  It is only legal to use abstract
6787   // boolean, numeric, and string constants as operands where it is legal to
6788   // use non-abstract boolean, numeric, and string constants, respectively.
6789   // Any issues with the operation will be resolved in the check_types pass.
6790   bool is_constant_expr = (this->left_->is_constant()
6791                            && this->right_->is_constant());
6792 
6793   Type_context subcontext(*context);
6794 
6795   if (is_constant_expr && !is_shift_op)
6796     {
6797       subcontext.type = NULL;
6798       subcontext.may_be_abstract = true;
6799     }
6800   else if (is_comparison)
6801     {
6802       // In a comparison, the context does not determine the types of
6803       // the operands.
6804       subcontext.type = NULL;
6805     }
6806 
6807   // Set the context for the left hand operand.
6808   if (is_shift_op)
6809     {
6810       // The right hand operand of a shift plays no role in
6811       // determining the type of the left hand operand.
6812     }
6813   else if (!tleft->is_abstract())
6814     subcontext.type = tleft;
6815   else if (!tright->is_abstract())
6816     subcontext.type = tright;
6817   else if (subcontext.type == NULL)
6818     {
6819       if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6820 	  || (tleft->float_type() != NULL && tright->float_type() != NULL)
6821 	  || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6822 	{
6823 	  // Both sides have an abstract integer, abstract float, or
6824 	  // abstract complex type.  Just let CONTEXT determine
6825 	  // whether they may remain abstract or not.
6826 	}
6827       else if (tleft->complex_type() != NULL)
6828 	subcontext.type = tleft;
6829       else if (tright->complex_type() != NULL)
6830 	subcontext.type = tright;
6831       else if (tleft->float_type() != NULL)
6832 	subcontext.type = tleft;
6833       else if (tright->float_type() != NULL)
6834 	subcontext.type = tright;
6835       else
6836 	subcontext.type = tleft;
6837 
6838       if (subcontext.type != NULL && !context->may_be_abstract)
6839 	subcontext.type = subcontext.type->make_non_abstract_type();
6840     }
6841 
6842   this->left_->determine_type(&subcontext);
6843 
6844   if (is_shift_op)
6845     {
6846       // We may have inherited an unusable type for the shift operand.
6847       // Give a useful error if that happened.
6848       if (tleft->is_abstract()
6849 	  && subcontext.type != NULL
6850 	  && !subcontext.may_be_abstract
6851 	  && subcontext.type->interface_type() == NULL
6852 	  && subcontext.type->integer_type() == NULL)
6853 	this->report_error(("invalid context-determined non-integer type "
6854 			    "for left operand of shift"));
6855 
6856       // The context for the right hand operand is the same as for the
6857       // left hand operand, except for a shift operator.
6858       subcontext.type = Type::lookup_integer_type("uint");
6859       subcontext.may_be_abstract = false;
6860     }
6861 
6862   this->right_->determine_type(&subcontext);
6863 
6864   if (is_comparison)
6865     {
6866       if (this->type_ != NULL && !this->type_->is_abstract())
6867 	;
6868       else if (context->type != NULL && context->type->is_boolean_type())
6869 	this->type_ = context->type;
6870       else if (!context->may_be_abstract)
6871 	this->type_ = Type::lookup_bool_type();
6872     }
6873 }
6874 
6875 // Report an error if the binary operator OP does not support TYPE.
6876 // OTYPE is the type of the other operand.  Return whether the
6877 // operation is OK.  This should not be used for shift.
6878 
6879 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)6880 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6881 				       Location location)
6882 {
6883   switch (op)
6884     {
6885     case OPERATOR_OROR:
6886     case OPERATOR_ANDAND:
6887       if (!type->is_boolean_type()
6888           || !otype->is_boolean_type())
6889 	{
6890 	  go_error_at(location, "expected boolean type");
6891 	  return false;
6892 	}
6893       break;
6894 
6895     case OPERATOR_EQEQ:
6896     case OPERATOR_NOTEQ:
6897       {
6898 	std::string reason;
6899 	if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6900 	  {
6901 	    go_error_at(location, "%s", reason.c_str());
6902 	    return false;
6903 	  }
6904       }
6905       break;
6906 
6907     case OPERATOR_LT:
6908     case OPERATOR_LE:
6909     case OPERATOR_GT:
6910     case OPERATOR_GE:
6911       {
6912 	std::string reason;
6913 	if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6914 	  {
6915 	    go_error_at(location, "%s", reason.c_str());
6916 	    return false;
6917 	  }
6918       }
6919       break;
6920 
6921     case OPERATOR_PLUS:
6922     case OPERATOR_PLUSEQ:
6923       if ((!type->is_numeric_type() && !type->is_string_type())
6924           || (!otype->is_numeric_type() && !otype->is_string_type()))
6925 	{
6926 	  go_error_at(location,
6927 		   "expected integer, floating, complex, or string type");
6928 	  return false;
6929 	}
6930       break;
6931 
6932     case OPERATOR_MINUS:
6933     case OPERATOR_MINUSEQ:
6934     case OPERATOR_MULT:
6935     case OPERATOR_MULTEQ:
6936     case OPERATOR_DIV:
6937     case OPERATOR_DIVEQ:
6938       if (!type->is_numeric_type() || !otype->is_numeric_type())
6939 	{
6940 	  go_error_at(location, "expected integer, floating, or complex type");
6941 	  return false;
6942 	}
6943       break;
6944 
6945     case OPERATOR_MOD:
6946     case OPERATOR_MODEQ:
6947     case OPERATOR_OR:
6948     case OPERATOR_OREQ:
6949     case OPERATOR_AND:
6950     case OPERATOR_ANDEQ:
6951     case OPERATOR_XOR:
6952     case OPERATOR_XOREQ:
6953     case OPERATOR_BITCLEAR:
6954     case OPERATOR_BITCLEAREQ:
6955       if (type->integer_type() == NULL || otype->integer_type() == NULL)
6956 	{
6957 	  go_error_at(location, "expected integer type");
6958 	  return false;
6959 	}
6960       break;
6961 
6962     default:
6963       go_unreachable();
6964     }
6965 
6966   return true;
6967 }
6968 
6969 // Check types.
6970 
6971 void
do_check_types(Gogo *)6972 Binary_expression::do_check_types(Gogo*)
6973 {
6974   if (this->classification() == EXPRESSION_ERROR)
6975     return;
6976 
6977   Type* left_type = this->left_->type();
6978   Type* right_type = this->right_->type();
6979   if (left_type->is_error() || right_type->is_error())
6980     {
6981       this->set_is_error();
6982       return;
6983     }
6984 
6985   if (this->op_ == OPERATOR_EQEQ
6986       || this->op_ == OPERATOR_NOTEQ
6987       || this->op_ == OPERATOR_LT
6988       || this->op_ == OPERATOR_LE
6989       || this->op_ == OPERATOR_GT
6990       || this->op_ == OPERATOR_GE)
6991     {
6992       if (left_type->is_nil_type() && right_type->is_nil_type())
6993 	{
6994 	  this->report_error(_("invalid comparison of nil with nil"));
6995 	  return;
6996 	}
6997       if (!Type::are_assignable(left_type, right_type, NULL)
6998 	  && !Type::are_assignable(right_type, left_type, NULL))
6999 	{
7000 	  this->report_error(_("incompatible types in binary expression"));
7001 	  return;
7002 	}
7003       if (!Binary_expression::check_operator_type(this->op_, left_type,
7004 						  right_type,
7005 						  this->location())
7006 	  || !Binary_expression::check_operator_type(this->op_, right_type,
7007 						     left_type,
7008 						     this->location()))
7009 	{
7010 	  this->set_is_error();
7011 	  return;
7012 	}
7013     }
7014   else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
7015     {
7016       if (!Type::are_compatible_for_binop(left_type, right_type))
7017 	{
7018 	  this->report_error(_("incompatible types in binary expression"));
7019 	  return;
7020 	}
7021       if (!Binary_expression::check_operator_type(this->op_, left_type,
7022 						  right_type,
7023 						  this->location()))
7024 	{
7025 	  this->set_is_error();
7026 	  return;
7027 	}
7028       if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
7029 	{
7030 	  // Division by a zero integer constant is an error.
7031 	  Numeric_constant rconst;
7032 	  unsigned long rval;
7033 	  if (left_type->integer_type() != NULL
7034 	      && this->right_->numeric_constant_value(&rconst)
7035 	      && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
7036 	      && rval == 0)
7037 	    {
7038 	      this->report_error(_("integer division by zero"));
7039 	      return;
7040 	    }
7041 	}
7042     }
7043   else
7044     {
7045       if (left_type->integer_type() == NULL)
7046 	this->report_error(_("shift of non-integer operand"));
7047 
7048       if (right_type->is_string_type())
7049         this->report_error(_("shift count not integer"));
7050       else if (!right_type->is_abstract()
7051 	       && right_type->integer_type() == NULL)
7052 	this->report_error(_("shift count not integer"));
7053       else
7054 	{
7055 	  Numeric_constant nc;
7056 	  if (this->right_->numeric_constant_value(&nc))
7057 	    {
7058 	      mpz_t val;
7059 	      if (!nc.to_int(&val))
7060 		this->report_error(_("shift count not integer"));
7061 	      else
7062 		{
7063 		  if (mpz_sgn(val) < 0)
7064 		    {
7065 		      this->report_error(_("negative shift count"));
7066 		      Location rloc = this->right_->location();
7067 		      this->right_ = Expression::make_integer_ul(0, right_type,
7068 								 rloc);
7069 		    }
7070 		  mpz_clear(val);
7071 		}
7072 	    }
7073 	}
7074     }
7075 }
7076 
7077 // Get the backend representation for a binary expression.
7078 
7079 Bexpression*
do_get_backend(Translate_context * context)7080 Binary_expression::do_get_backend(Translate_context* context)
7081 {
7082   Gogo* gogo = context->gogo();
7083   Location loc = this->location();
7084   Type* left_type = this->left_->type();
7085   Type* right_type = this->right_->type();
7086 
7087   bool use_left_type = true;
7088   bool is_shift_op = false;
7089   bool is_idiv_op = false;
7090   switch (this->op_)
7091     {
7092     case OPERATOR_EQEQ:
7093     case OPERATOR_NOTEQ:
7094     case OPERATOR_LT:
7095     case OPERATOR_LE:
7096     case OPERATOR_GT:
7097     case OPERATOR_GE:
7098       return Expression::comparison(context, this->type_, this->op_,
7099 				    this->left_, this->right_, loc);
7100 
7101     case OPERATOR_OROR:
7102     case OPERATOR_ANDAND:
7103       use_left_type = false;
7104       break;
7105     case OPERATOR_PLUS:
7106     case OPERATOR_MINUS:
7107     case OPERATOR_OR:
7108     case OPERATOR_XOR:
7109     case OPERATOR_MULT:
7110       break;
7111     case OPERATOR_DIV:
7112       if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
7113         break;
7114       // Fall through.
7115     case OPERATOR_MOD:
7116       is_idiv_op = true;
7117       break;
7118     case OPERATOR_LSHIFT:
7119     case OPERATOR_RSHIFT:
7120       is_shift_op = true;
7121       break;
7122     case OPERATOR_BITCLEAR:
7123       this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
7124     case OPERATOR_AND:
7125       break;
7126     default:
7127       go_unreachable();
7128     }
7129 
7130   // The only binary operation for string is +, and that should have
7131   // been converted to a String_concat_expression in do_lower.
7132   go_assert(!left_type->is_string_type());
7133 
7134   Bexpression* left = this->left_->get_backend(context);
7135   Bexpression* right = this->right_->get_backend(context);
7136 
7137   Type* type = use_left_type ? left_type : right_type;
7138   Btype* btype = type->get_backend(gogo);
7139 
7140   Bexpression* ret =
7141       gogo->backend()->binary_expression(this->op_, left, right, loc);
7142   ret = gogo->backend()->convert_expression(btype, ret, loc);
7143 
7144   // Initialize overflow constants.
7145   Bexpression* overflow;
7146   mpz_t zero;
7147   mpz_init_set_ui(zero, 0UL);
7148   mpz_t one;
7149   mpz_init_set_ui(one, 1UL);
7150   mpz_t neg_one;
7151   mpz_init_set_si(neg_one, -1);
7152 
7153   Btype* left_btype = left_type->get_backend(gogo);
7154   Btype* right_btype = right_type->get_backend(gogo);
7155 
7156   // In Go, a shift larger than the size of the type is well-defined.
7157   // This is not true in C, so we need to insert a conditional.
7158   // We also need to check for a negative shift count.
7159   if (is_shift_op)
7160     {
7161       go_assert(left_type->integer_type() != NULL);
7162       go_assert(right_type->integer_type() != NULL);
7163 
7164       int bits = left_type->integer_type()->bits();
7165 
7166       Numeric_constant nc;
7167       unsigned long ul;
7168       if (!this->right_->numeric_constant_value(&nc)
7169 	  || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
7170 	  || ul >= static_cast<unsigned long>(bits))
7171 	{
7172 	  mpz_t bitsval;
7173 	  mpz_init_set_ui(bitsval, bits);
7174 	  Bexpression* bits_expr =
7175 	    gogo->backend()->integer_constant_expression(right_btype, bitsval);
7176 	  Bexpression* compare =
7177 	    gogo->backend()->binary_expression(OPERATOR_LT,
7178 					       right, bits_expr, loc);
7179 
7180 	  Bexpression* zero_expr =
7181 	    gogo->backend()->integer_constant_expression(left_btype, zero);
7182 	  overflow = zero_expr;
7183 	  Bfunction* bfn = context->function()->func_value()->get_decl();
7184 	  if (this->op_ == OPERATOR_RSHIFT
7185 	      && !left_type->integer_type()->is_unsigned())
7186 	    {
7187 	      Bexpression* neg_expr =
7188 		gogo->backend()->binary_expression(OPERATOR_LT, left,
7189 						   zero_expr, loc);
7190 	      Bexpression* neg_one_expr =
7191 		gogo->backend()->integer_constant_expression(left_btype,
7192 							     neg_one);
7193 	      overflow = gogo->backend()->conditional_expression(bfn,
7194 								 btype,
7195 								 neg_expr,
7196 								 neg_one_expr,
7197 								 zero_expr,
7198 								 loc);
7199 	    }
7200 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7201 							ret, overflow, loc);
7202 	  mpz_clear(bitsval);
7203 	}
7204 
7205       if (!right_type->integer_type()->is_unsigned()
7206 	  && (!this->right_->numeric_constant_value(&nc)
7207 	      || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
7208 	{
7209 	  Bexpression* zero_expr =
7210 	    gogo->backend()->integer_constant_expression(right_btype, zero);
7211 	  Bexpression* compare =
7212 	    gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
7213 					       loc);
7214 	  Expression* crash = Runtime::make_call(Runtime::PANIC_SHIFT,
7215 						 loc, 0);
7216 	  Bexpression* bcrash = crash->get_backend(context);
7217 	  Bfunction* bfn = context->function()->func_value()->get_decl();
7218 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7219 							bcrash, ret, loc);
7220 	}
7221     }
7222 
7223   // Add checks for division by zero and division overflow as needed.
7224   if (is_idiv_op)
7225     {
7226       if (gogo->check_divide_by_zero())
7227 	{
7228 	  // right == 0
7229           Bexpression* zero_expr =
7230               gogo->backend()->integer_constant_expression(right_btype, zero);
7231           Bexpression* check =
7232               gogo->backend()->binary_expression(OPERATOR_EQEQ,
7233                                                  right, zero_expr, loc);
7234 
7235 	  Expression* crash = Runtime::make_call(Runtime::PANIC_DIVIDE,
7236 						 loc, 0);
7237 	  Bexpression* bcrash = crash->get_backend(context);
7238 
7239 	  // right == 0 ? (panicdivide(), 0) : ret
7240           Bfunction* bfn = context->function()->func_value()->get_decl();
7241           ret = gogo->backend()->conditional_expression(bfn, btype,
7242                                                         check, bcrash,
7243 							ret, loc);
7244 	}
7245 
7246       if (gogo->check_divide_overflow())
7247 	{
7248 	  // right == -1
7249 	  // FIXME: It would be nice to say that this test is expected
7250 	  // to return false.
7251 
7252           Bexpression* neg_one_expr =
7253               gogo->backend()->integer_constant_expression(right_btype, neg_one);
7254           Bexpression* check =
7255               gogo->backend()->binary_expression(OPERATOR_EQEQ,
7256                                                  right, neg_one_expr, loc);
7257 
7258           Bexpression* zero_expr =
7259               gogo->backend()->integer_constant_expression(btype, zero);
7260           Bexpression* one_expr =
7261               gogo->backend()->integer_constant_expression(btype, one);
7262           Bfunction* bfn = context->function()->func_value()->get_decl();
7263 
7264 	  if (type->integer_type()->is_unsigned())
7265 	    {
7266 	      // An unsigned -1 is the largest possible number, so
7267 	      // dividing is always 1 or 0.
7268 
7269               Bexpression* cmp =
7270                   gogo->backend()->binary_expression(OPERATOR_EQEQ,
7271                                                      left, right, loc);
7272 	      if (this->op_ == OPERATOR_DIV)
7273                 overflow =
7274                     gogo->backend()->conditional_expression(bfn, btype, cmp,
7275                                                             one_expr, zero_expr,
7276                                                             loc);
7277 	      else
7278                 overflow =
7279                     gogo->backend()->conditional_expression(bfn, btype, cmp,
7280                                                             zero_expr, left,
7281                                                             loc);
7282 	    }
7283 	  else
7284 	    {
7285 	      // Computing left / -1 is the same as computing - left,
7286 	      // which does not overflow since Go sets -fwrapv.
7287 	      if (this->op_ == OPERATOR_DIV)
7288                 {
7289                   Expression* negate_expr =
7290                       Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
7291                   overflow = negate_expr->get_backend(context);
7292                 }
7293 	      else
7294                 overflow = zero_expr;
7295 	    }
7296           overflow = gogo->backend()->convert_expression(btype, overflow, loc);
7297 
7298 	  // right == -1 ? - left : ret
7299           ret = gogo->backend()->conditional_expression(bfn, btype,
7300                                                         check, overflow,
7301                                                         ret, loc);
7302 	}
7303     }
7304 
7305   mpz_clear(zero);
7306   mpz_clear(one);
7307   mpz_clear(neg_one);
7308   return ret;
7309 }
7310 
7311 // Export a binary expression.
7312 
7313 void
do_export(Export_function_body * efb) const7314 Binary_expression::do_export(Export_function_body* efb) const
7315 {
7316   efb->write_c_string("(");
7317   this->left_->export_expression(efb);
7318   switch (this->op_)
7319     {
7320     case OPERATOR_OROR:
7321       efb->write_c_string(" || ");
7322       break;
7323     case OPERATOR_ANDAND:
7324       efb->write_c_string(" && ");
7325       break;
7326     case OPERATOR_EQEQ:
7327       efb->write_c_string(" == ");
7328       break;
7329     case OPERATOR_NOTEQ:
7330       efb->write_c_string(" != ");
7331       break;
7332     case OPERATOR_LT:
7333       efb->write_c_string(" < ");
7334       break;
7335     case OPERATOR_LE:
7336       efb->write_c_string(" <= ");
7337       break;
7338     case OPERATOR_GT:
7339       efb->write_c_string(" > ");
7340       break;
7341     case OPERATOR_GE:
7342       efb->write_c_string(" >= ");
7343       break;
7344     case OPERATOR_PLUS:
7345       efb->write_c_string(" + ");
7346       break;
7347     case OPERATOR_MINUS:
7348       efb->write_c_string(" - ");
7349       break;
7350     case OPERATOR_OR:
7351       efb->write_c_string(" | ");
7352       break;
7353     case OPERATOR_XOR:
7354       efb->write_c_string(" ^ ");
7355       break;
7356     case OPERATOR_MULT:
7357       efb->write_c_string(" * ");
7358       break;
7359     case OPERATOR_DIV:
7360       efb->write_c_string(" / ");
7361       break;
7362     case OPERATOR_MOD:
7363       efb->write_c_string(" % ");
7364       break;
7365     case OPERATOR_LSHIFT:
7366       efb->write_c_string(" << ");
7367       break;
7368     case OPERATOR_RSHIFT:
7369       efb->write_c_string(" >> ");
7370       break;
7371     case OPERATOR_AND:
7372       efb->write_c_string(" & ");
7373       break;
7374     case OPERATOR_BITCLEAR:
7375       efb->write_c_string(" &^ ");
7376       break;
7377     default:
7378       go_unreachable();
7379     }
7380   this->right_->export_expression(efb);
7381   efb->write_c_string(")");
7382 }
7383 
7384 // Import a binary expression.
7385 
7386 Expression*
do_import(Import_expression * imp,Location loc)7387 Binary_expression::do_import(Import_expression* imp, Location loc)
7388 {
7389   imp->require_c_string("(");
7390 
7391   Expression* left = Expression::import_expression(imp, loc);
7392 
7393   Operator op;
7394   if (imp->match_c_string(" || "))
7395     {
7396       op = OPERATOR_OROR;
7397       imp->advance(4);
7398     }
7399   else if (imp->match_c_string(" && "))
7400     {
7401       op = OPERATOR_ANDAND;
7402       imp->advance(4);
7403     }
7404   else if (imp->match_c_string(" == "))
7405     {
7406       op = OPERATOR_EQEQ;
7407       imp->advance(4);
7408     }
7409   else if (imp->match_c_string(" != "))
7410     {
7411       op = OPERATOR_NOTEQ;
7412       imp->advance(4);
7413     }
7414   else if (imp->match_c_string(" < "))
7415     {
7416       op = OPERATOR_LT;
7417       imp->advance(3);
7418     }
7419   else if (imp->match_c_string(" <= "))
7420     {
7421       op = OPERATOR_LE;
7422       imp->advance(4);
7423     }
7424   else if (imp->match_c_string(" > "))
7425     {
7426       op = OPERATOR_GT;
7427       imp->advance(3);
7428     }
7429   else if (imp->match_c_string(" >= "))
7430     {
7431       op = OPERATOR_GE;
7432       imp->advance(4);
7433     }
7434   else if (imp->match_c_string(" + "))
7435     {
7436       op = OPERATOR_PLUS;
7437       imp->advance(3);
7438     }
7439   else if (imp->match_c_string(" - "))
7440     {
7441       op = OPERATOR_MINUS;
7442       imp->advance(3);
7443     }
7444   else if (imp->match_c_string(" | "))
7445     {
7446       op = OPERATOR_OR;
7447       imp->advance(3);
7448     }
7449   else if (imp->match_c_string(" ^ "))
7450     {
7451       op = OPERATOR_XOR;
7452       imp->advance(3);
7453     }
7454   else if (imp->match_c_string(" * "))
7455     {
7456       op = OPERATOR_MULT;
7457       imp->advance(3);
7458     }
7459   else if (imp->match_c_string(" / "))
7460     {
7461       op = OPERATOR_DIV;
7462       imp->advance(3);
7463     }
7464   else if (imp->match_c_string(" % "))
7465     {
7466       op = OPERATOR_MOD;
7467       imp->advance(3);
7468     }
7469   else if (imp->match_c_string(" << "))
7470     {
7471       op = OPERATOR_LSHIFT;
7472       imp->advance(4);
7473     }
7474   else if (imp->match_c_string(" >> "))
7475     {
7476       op = OPERATOR_RSHIFT;
7477       imp->advance(4);
7478     }
7479   else if (imp->match_c_string(" & "))
7480     {
7481       op = OPERATOR_AND;
7482       imp->advance(3);
7483     }
7484   else if (imp->match_c_string(" &^ "))
7485     {
7486       op = OPERATOR_BITCLEAR;
7487       imp->advance(4);
7488     }
7489   else if (imp->match_c_string(")"))
7490     {
7491       // Not a binary operator after all.
7492       imp->advance(1);
7493       return left;
7494     }
7495   else
7496     {
7497       go_error_at(imp->location(), "unrecognized binary operator");
7498       return Expression::make_error(loc);
7499     }
7500 
7501   Expression* right = Expression::import_expression(imp, loc);
7502 
7503   imp->require_c_string(")");
7504 
7505   return Expression::make_binary(op, left, right, loc);
7506 }
7507 
7508 // Dump ast representation of a binary expression.
7509 
7510 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7511 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
7512 {
7513   ast_dump_context->ostream() << "(";
7514   ast_dump_context->dump_expression(this->left_);
7515   ast_dump_context->ostream() << " ";
7516   ast_dump_context->dump_operator(this->op_);
7517   ast_dump_context->ostream() << " ";
7518   ast_dump_context->dump_expression(this->right_);
7519   ast_dump_context->ostream() << ") ";
7520 }
7521 
7522 // Make a binary expression.
7523 
7524 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)7525 Expression::make_binary(Operator op, Expression* left, Expression* right,
7526 			Location location)
7527 {
7528   return new Binary_expression(op, left, right, location);
7529 }
7530 
7531 // Implement a comparison.
7532 
7533 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)7534 Expression::comparison(Translate_context* context, Type* result_type,
7535 		       Operator op, Expression* left, Expression* right,
7536 		       Location location)
7537 {
7538   Type* left_type = left->type();
7539   Type* right_type = right->type();
7540 
7541   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
7542 
7543   if (left_type->is_string_type() && right_type->is_string_type())
7544     {
7545       go_assert(left->is_multi_eval_safe());
7546       go_assert(right->is_multi_eval_safe());
7547 
7548       if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
7549 	{
7550           // (l.len == r.len
7551           //  ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
7552           //  : false)
7553           Expression* llen = Expression::make_string_info(left,
7554                                                           STRING_INFO_LENGTH,
7555                                                           location);
7556           Expression* rlen = Expression::make_string_info(right,
7557                                                           STRING_INFO_LENGTH,
7558                                                           location);
7559           Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
7560                                                       location);
7561           Expression* lptr = Expression::make_string_info(left->copy(),
7562                                                           STRING_INFO_DATA,
7563                                                           location);
7564           Expression* rptr = Expression::make_string_info(right->copy(),
7565                                                           STRING_INFO_DATA,
7566                                                           location);
7567           Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
7568                                                       location);
7569           Expression* btrue = Expression::make_boolean(true, location);
7570           Expression* call = Runtime::make_call(Runtime::MEMCMP, location, 3,
7571                                                 lptr->copy(), rptr->copy(),
7572                                                 rlen->copy());
7573           Type* int32_type = Type::lookup_integer_type("int32");
7574           Expression* zero = Expression::make_integer_ul(0, int32_type, location);
7575           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
7576                                                     location);
7577           Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
7578                                                           location);
7579           Expression* bfalse = Expression::make_boolean(false, location);
7580           left = Expression::make_conditional(leneq, cond, bfalse, location);
7581 	  right = Expression::make_boolean(true, location);
7582 	}
7583       else
7584 	{
7585 	  left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
7586 				    left, right);
7587 	  right = zexpr;
7588 	}
7589     }
7590   else if ((left_type->interface_type() != NULL
7591 	    && right_type->interface_type() == NULL
7592 	    && !right_type->is_nil_type())
7593 	   || (left_type->interface_type() == NULL
7594 	       && !left_type->is_nil_type()
7595 	       && right_type->interface_type() != NULL))
7596     {
7597       // Comparing an interface value to a non-interface value.
7598       if (left_type->interface_type() == NULL)
7599 	{
7600 	  std::swap(left_type, right_type);
7601 	  std::swap(left, right);
7602 	}
7603 
7604       // The right operand is not an interface.  We need to take its
7605       // address if it is not a direct interface type.
7606       Expression* pointer_arg = NULL;
7607       if (right_type->is_direct_iface_type())
7608         pointer_arg = Expression::unpack_direct_iface(right, location);
7609       else
7610 	{
7611           go_assert(right->is_addressable());
7612           pointer_arg = Expression::make_unary(OPERATOR_AND, right,
7613                                                location);
7614 	}
7615 
7616       Expression* descriptor =
7617           Expression::make_type_descriptor(right_type, location);
7618       left =
7619           Runtime::make_call((left_type->interface_type()->is_empty()
7620                               ? Runtime::EFACEVALEQ
7621                               : Runtime::IFACEVALEQ),
7622                              location, 3, left, descriptor,
7623                              pointer_arg);
7624       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7625       right = Expression::make_boolean(true, location);
7626     }
7627   else if (left_type->interface_type() != NULL
7628 	   && right_type->interface_type() != NULL)
7629     {
7630       Runtime::Function compare_function;
7631       if (left_type->interface_type()->is_empty()
7632 	  && right_type->interface_type()->is_empty())
7633 	compare_function = Runtime::EFACEEQ;
7634       else if (!left_type->interface_type()->is_empty()
7635 	       && !right_type->interface_type()->is_empty())
7636 	compare_function = Runtime::IFACEEQ;
7637       else
7638 	{
7639 	  if (left_type->interface_type()->is_empty())
7640 	    {
7641 	      std::swap(left_type, right_type);
7642 	      std::swap(left, right);
7643 	    }
7644 	  go_assert(!left_type->interface_type()->is_empty());
7645 	  go_assert(right_type->interface_type()->is_empty());
7646 	  compare_function = Runtime::IFACEEFACEEQ;
7647 	}
7648 
7649       left = Runtime::make_call(compare_function, location, 2, left, right);
7650       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7651       right = Expression::make_boolean(true, location);
7652     }
7653 
7654   if (left_type->is_nil_type()
7655       && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7656     {
7657       std::swap(left_type, right_type);
7658       std::swap(left, right);
7659     }
7660 
7661   if (right_type->is_nil_type())
7662     {
7663       right = Expression::make_nil(location);
7664       if (left_type->array_type() != NULL
7665 	  && left_type->array_type()->length() == NULL)
7666 	{
7667 	  Array_type* at = left_type->array_type();
7668           bool is_lvalue = false;
7669           left = at->get_value_pointer(context->gogo(), left, is_lvalue);
7670 	}
7671       else if (left_type->interface_type() != NULL)
7672 	{
7673 	  // An interface is nil if the first field is nil.
7674           left = Expression::make_field_reference(left, 0, location);
7675 	}
7676     }
7677 
7678   Bexpression* left_bexpr = left->get_backend(context);
7679   Bexpression* right_bexpr = right->get_backend(context);
7680 
7681   Gogo* gogo = context->gogo();
7682   Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
7683                                                         right_bexpr, location);
7684   if (result_type != NULL)
7685     ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
7686                                               ret, location);
7687   return ret;
7688 }
7689 
7690 // Class String_concat_expression.
7691 
7692 bool
do_is_constant() const7693 String_concat_expression::do_is_constant() const
7694 {
7695   for (Expression_list::const_iterator pe = this->exprs_->begin();
7696        pe != this->exprs_->end();
7697        ++pe)
7698     {
7699       if (!(*pe)->is_constant())
7700 	return false;
7701     }
7702   return true;
7703 }
7704 
7705 bool
do_is_zero_value() const7706 String_concat_expression::do_is_zero_value() const
7707 {
7708   for (Expression_list::const_iterator pe = this->exprs_->begin();
7709        pe != this->exprs_->end();
7710        ++pe)
7711     {
7712       if (!(*pe)->is_zero_value())
7713 	return false;
7714     }
7715   return true;
7716 }
7717 
7718 bool
do_is_static_initializer() const7719 String_concat_expression::do_is_static_initializer() const
7720 {
7721   for (Expression_list::const_iterator pe = this->exprs_->begin();
7722        pe != this->exprs_->end();
7723        ++pe)
7724     {
7725       if (!(*pe)->is_static_initializer())
7726 	return false;
7727     }
7728   return true;
7729 }
7730 
7731 Type*
do_type()7732 String_concat_expression::do_type()
7733 {
7734   Type* t = this->exprs_->front()->type();
7735   Expression_list::iterator pe = this->exprs_->begin();
7736   ++pe;
7737   for (; pe != this->exprs_->end(); ++pe)
7738     {
7739       Type* t1;
7740       if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
7741 					     (*pe)->type(),
7742 					     &t1))
7743 	return Type::make_error_type();
7744       t = t1;
7745     }
7746   return t;
7747 }
7748 
7749 void
do_determine_type(const Type_context * context)7750 String_concat_expression::do_determine_type(const Type_context* context)
7751 {
7752   Type_context subcontext(*context);
7753   for (Expression_list::iterator pe = this->exprs_->begin();
7754        pe != this->exprs_->end();
7755        ++pe)
7756     {
7757       Type* t = (*pe)->type();
7758       if (!t->is_abstract())
7759 	{
7760 	  subcontext.type = t;
7761 	  break;
7762 	}
7763     }
7764   if (subcontext.type == NULL)
7765     subcontext.type = this->exprs_->front()->type();
7766   for (Expression_list::iterator pe = this->exprs_->begin();
7767        pe != this->exprs_->end();
7768        ++pe)
7769     (*pe)->determine_type(&subcontext);
7770 }
7771 
7772 void
do_check_types(Gogo *)7773 String_concat_expression::do_check_types(Gogo*)
7774 {
7775   if (this->is_error_expression())
7776     return;
7777   Type* t = this->exprs_->front()->type();
7778   if (t->is_error())
7779     {
7780       this->set_is_error();
7781       return;
7782     }
7783   Expression_list::iterator pe = this->exprs_->begin();
7784   ++pe;
7785   for (; pe != this->exprs_->end(); ++pe)
7786     {
7787       Type* t1 = (*pe)->type();
7788       if (!Type::are_compatible_for_binop(t, t1))
7789 	{
7790 	  this->report_error("incompatible types in binary expression");
7791 	  return;
7792 	}
7793       if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
7794 						  this->location()))
7795 	{
7796 	  this->set_is_error();
7797 	  return;
7798 	}
7799     }
7800 }
7801 
7802 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)7803 String_concat_expression::do_flatten(Gogo*, Named_object*,
7804 				     Statement_inserter* inserter)
7805 {
7806   if (this->is_error_expression())
7807     return this;
7808   Location loc = this->location();
7809   Type* type = this->type();
7810 
7811   // Mark string([]byte) operands to reuse the backing store.
7812   // runtime.concatstrings does not keep the reference.
7813   //
7814   // Note: in the gc runtime, if all but one inputs are empty,
7815   // concatstrings returns the only nonempty input without copy.
7816   // So it is not safe to reuse the backing store if it is a
7817   // string([]byte) conversion. So the gc compiler does the
7818   // no-copy optimization only when there is at least one
7819   // constant nonempty input. Currently the gccgo runtime
7820   // doesn't do this, so we don't do the check.
7821   for (Expression_list::iterator p = this->exprs_->begin();
7822        p != this->exprs_->end();
7823        ++p)
7824     {
7825       Type_conversion_expression* tce = (*p)->conversion_expression();
7826       if (tce != NULL)
7827         tce->set_no_copy(true);
7828     }
7829 
7830   Expression* buf = NULL;
7831   Node* n = Node::make_node(this);
7832   if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7833     {
7834       size_t size = 0;
7835       for (Expression_list::iterator p = this->exprs_->begin();
7836            p != this->exprs_->end();
7837            ++p)
7838         {
7839           std::string s;
7840           if ((*p)->string_constant_value(&s))
7841             size += s.length();
7842         }
7843       // Make a buffer on stack if the result does not escape.
7844       // But don't do this if we know it won't fit.
7845       if (size < (size_t)tmp_string_buf_size)
7846         {
7847           Type* byte_type = Type::lookup_integer_type("uint8");
7848           Expression* buflen =
7849             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7850           Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7851           Type* array_type = Type::make_array_type(byte_type, buflen);
7852           buf = Expression::make_allocation(array_type, loc);
7853           buf->allocation_expression()->set_allocate_on_stack();
7854           buf->allocation_expression()->set_no_zero();
7855         }
7856     }
7857   if (buf == NULL)
7858     buf = Expression::make_nil(loc);
7859   go_assert(this->exprs_->size() > 1);
7860   Expression* len =
7861     Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
7862   Array_type* array_type = Type::make_array_type(type, len);
7863   array_type->set_is_array_incomparable();
7864   Expression* array =
7865     Expression::make_array_composite_literal(array_type, this->exprs_,
7866                                              loc);
7867   Temporary_statement* ts =
7868     Statement::make_temporary(array_type, array, loc);
7869   inserter->insert(ts);
7870   Expression* ref = Expression::make_temporary_reference(ts, loc);
7871   ref = Expression::make_unary(OPERATOR_AND, ref, loc);
7872 	Expression* call =
7873     Runtime::make_call(Runtime::CONCATSTRINGS, loc, 3, buf,
7874                        ref, len->copy());
7875   return Expression::make_cast(type, call, loc);
7876 }
7877 
7878 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7879 String_concat_expression::do_dump_expression(
7880     Ast_dump_context* ast_dump_context) const
7881 {
7882   ast_dump_context->ostream() << "concat(";
7883   ast_dump_context->dump_expression_list(this->exprs_, false);
7884   ast_dump_context->ostream() << ")";
7885 }
7886 
7887 Expression*
make_string_concat(Expression_list * exprs)7888 Expression::make_string_concat(Expression_list* exprs)
7889 {
7890   return new String_concat_expression(exprs);
7891 }
7892 
7893 // Class Bound_method_expression.
7894 
7895 // Traversal.
7896 
7897 int
do_traverse(Traverse * traverse)7898 Bound_method_expression::do_traverse(Traverse* traverse)
7899 {
7900   return Expression::traverse(&this->expr_, traverse);
7901 }
7902 
7903 // Return the type of a bound method expression.  The type of this
7904 // object is simply the type of the method with no receiver.
7905 
7906 Type*
do_type()7907 Bound_method_expression::do_type()
7908 {
7909   Named_object* fn = this->method_->named_object();
7910   Function_type* fntype;
7911   if (fn->is_function())
7912     fntype = fn->func_value()->type();
7913   else if (fn->is_function_declaration())
7914     fntype = fn->func_declaration_value()->type();
7915   else
7916     return Type::make_error_type();
7917   return fntype->copy_without_receiver();
7918 }
7919 
7920 // Determine the types of a method expression.
7921 
7922 void
do_determine_type(const Type_context *)7923 Bound_method_expression::do_determine_type(const Type_context*)
7924 {
7925   Named_object* fn = this->method_->named_object();
7926   Function_type* fntype;
7927   if (fn->is_function())
7928     fntype = fn->func_value()->type();
7929   else if (fn->is_function_declaration())
7930     fntype = fn->func_declaration_value()->type();
7931   else
7932     fntype = NULL;
7933   if (fntype == NULL || !fntype->is_method())
7934     this->expr_->determine_type_no_context();
7935   else
7936     {
7937       Type_context subcontext(fntype->receiver()->type(), false);
7938       this->expr_->determine_type(&subcontext);
7939     }
7940 }
7941 
7942 // Check the types of a method expression.
7943 
7944 void
do_check_types(Gogo *)7945 Bound_method_expression::do_check_types(Gogo*)
7946 {
7947   Named_object* fn = this->method_->named_object();
7948   if (!fn->is_function() && !fn->is_function_declaration())
7949     {
7950       this->report_error(_("object is not a method"));
7951       return;
7952     }
7953 
7954   Function_type* fntype;
7955   if (fn->is_function())
7956     fntype = fn->func_value()->type();
7957   else if (fn->is_function_declaration())
7958     fntype = fn->func_declaration_value()->type();
7959   else
7960     go_unreachable();
7961   Type* rtype = fntype->receiver()->type()->deref();
7962   Type* etype = (this->expr_type_ != NULL
7963 		 ? this->expr_type_
7964 		 : this->expr_->type());
7965   etype = etype->deref();
7966   if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
7967     this->report_error(_("method type does not match object type"));
7968 }
7969 
7970 // If a bound method expression is not simply called, then it is
7971 // represented as a closure.  The closure will hold a single variable,
7972 // the receiver to pass to the method.  The function will be a simple
7973 // thunk that pulls that value from the closure and calls the method
7974 // with the remaining arguments.
7975 //
7976 // Because method values are not common, we don't build all thunks for
7977 // every methods, but instead only build them as we need them.  In
7978 // particular, we even build them on demand for methods defined in
7979 // other packages.
7980 
7981 Bound_method_expression::Method_value_thunks
7982   Bound_method_expression::method_value_thunks;
7983 
7984 // Find or create the thunk for FN.
7985 
7986 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)7987 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
7988 				      Named_object* fn)
7989 {
7990   std::pair<Named_object*, Named_object*> val(fn, NULL);
7991   std::pair<Method_value_thunks::iterator, bool> ins =
7992     Bound_method_expression::method_value_thunks.insert(val);
7993   if (!ins.second)
7994     {
7995       // We have seen this method before.
7996       go_assert(ins.first->second != NULL);
7997       return ins.first->second;
7998     }
7999 
8000   Location loc = fn->location();
8001 
8002   Function_type* orig_fntype;
8003   if (fn->is_function())
8004     orig_fntype = fn->func_value()->type();
8005   else if (fn->is_function_declaration())
8006     orig_fntype = fn->func_declaration_value()->type();
8007   else
8008     orig_fntype = NULL;
8009 
8010   if (orig_fntype == NULL || !orig_fntype->is_method())
8011     {
8012       ins.first->second =
8013 	Named_object::make_erroneous_name(gogo->thunk_name());
8014       return ins.first->second;
8015     }
8016 
8017   Struct_field_list* sfl = new Struct_field_list();
8018   // The type here is wrong--it should be the C function type.  But it
8019   // doesn't really matter.
8020   Type* vt = Type::make_pointer_type(Type::make_void_type());
8021   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
8022   sfl->push_back(Struct_field(Typed_identifier("val",
8023 					       orig_fntype->receiver()->type(),
8024 					       loc)));
8025   Struct_type* st = Type::make_struct_type(sfl, loc);
8026   st->set_is_struct_incomparable();
8027   Type* closure_type = Type::make_pointer_type(st);
8028 
8029   Function_type* new_fntype = orig_fntype->copy_with_names();
8030 
8031   std::string thunk_name = gogo->thunk_name();
8032   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
8033 					      false, loc);
8034 
8035   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
8036   cvar->set_is_used();
8037   cvar->set_is_closure();
8038   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
8039 						 NULL, cvar);
8040   new_no->func_value()->set_closure_var(cp);
8041 
8042   gogo->start_block(loc);
8043 
8044   // Field 0 of the closure is the function code pointer, field 1 is
8045   // the value on which to invoke the method.
8046   Expression* arg = Expression::make_var_reference(cp, loc);
8047   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
8048   arg = Expression::make_field_reference(arg, 1, loc);
8049 
8050   Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
8051 
8052   const Typed_identifier_list* orig_params = orig_fntype->parameters();
8053   Expression_list* args;
8054   if (orig_params == NULL || orig_params->empty())
8055     args = NULL;
8056   else
8057     {
8058       const Typed_identifier_list* new_params = new_fntype->parameters();
8059       args = new Expression_list();
8060       for (Typed_identifier_list::const_iterator p = new_params->begin();
8061 	   p != new_params->end();
8062 	   ++p)
8063 	{
8064 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
8065 	  go_assert(p_no != NULL
8066 		    && p_no->is_variable()
8067 		    && p_no->var_value()->is_parameter());
8068 	  args->push_back(Expression::make_var_reference(p_no, loc));
8069 	}
8070     }
8071 
8072   Call_expression* call = Expression::make_call(bme, args,
8073 						orig_fntype->is_varargs(),
8074 						loc);
8075   call->set_varargs_are_lowered();
8076 
8077   Statement* s = Statement::make_return_from_call(call, loc);
8078   gogo->add_statement(s);
8079   Block* b = gogo->finish_block(loc);
8080   gogo->add_block(b, loc);
8081 
8082   // This is called after lowering but before determine_types.
8083   gogo->lower_block(new_no, b);
8084 
8085   gogo->finish_function(loc);
8086 
8087   ins.first->second = new_no;
8088   return new_no;
8089 }
8090 
8091 // Look up a thunk for FN.
8092 
8093 Named_object*
lookup_thunk(Named_object * fn)8094 Bound_method_expression::lookup_thunk(Named_object* fn)
8095 {
8096   Method_value_thunks::const_iterator p =
8097     Bound_method_expression::method_value_thunks.find(fn);
8098   if (p == Bound_method_expression::method_value_thunks.end())
8099     return NULL;
8100   return p->second;
8101 }
8102 
8103 // Return an expression to check *REF for nil while dereferencing
8104 // according to FIELD_INDEXES.  Update *REF to build up the field
8105 // reference.  This is a static function so that we don't have to
8106 // worry about declaring Field_indexes in expressions.h.
8107 
8108 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)8109 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
8110 	      Expression** ref)
8111 {
8112   if (field_indexes == NULL)
8113     return Expression::make_boolean(false, loc);
8114   Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
8115   Struct_type* stype = (*ref)->type()->deref()->struct_type();
8116   go_assert(stype != NULL
8117 	    && field_indexes->field_index < stype->field_count());
8118   if ((*ref)->type()->struct_type() == NULL)
8119     {
8120       go_assert((*ref)->type()->points_to() != NULL);
8121       Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
8122 					      Expression::make_nil(loc),
8123 					      loc);
8124       cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
8125       *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
8126                                           loc);
8127       go_assert((*ref)->type()->struct_type() == stype);
8128     }
8129   *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
8130 					  loc);
8131   return cond;
8132 }
8133 
8134 // Flatten a method value into a struct with nil checks.  We can't do
8135 // this in the lowering phase, because if the method value is called
8136 // directly we don't need a thunk.  That case will have been handled
8137 // by Call_expression::do_lower, so if we get here then we do need a
8138 // thunk.
8139 
8140 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)8141 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
8142 				    Statement_inserter* inserter)
8143 {
8144   Location loc = this->location();
8145 
8146   Named_object* thunk = Bound_method_expression::lookup_thunk(this->function_);
8147 
8148   // The thunk should have been created during the
8149   // create_function_descriptors pass.
8150   if (thunk == NULL || thunk->is_erroneous())
8151     {
8152       go_assert(saw_errors());
8153       return Expression::make_error(loc);
8154     }
8155 
8156   // Force the expression into a variable.  This is only necessary if
8157   // we are going to do nil checks below, but it's easy enough to
8158   // always do it.
8159   Expression* expr = this->expr_;
8160   if (!expr->is_multi_eval_safe())
8161     {
8162       Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
8163       inserter->insert(etemp);
8164       expr = Expression::make_temporary_reference(etemp, loc);
8165     }
8166 
8167   // If the method expects a value, and we have a pointer, we need to
8168   // dereference the pointer.
8169 
8170   Named_object* fn = this->method_->named_object();
8171   Function_type *fntype;
8172   if (fn->is_function())
8173     fntype = fn->func_value()->type();
8174   else if (fn->is_function_declaration())
8175     fntype = fn->func_declaration_value()->type();
8176   else
8177     go_unreachable();
8178 
8179   Expression* val = expr;
8180   if (fntype->receiver()->type()->points_to() == NULL
8181       && val->type()->points_to() != NULL)
8182     val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
8183 
8184   // Note that we are ignoring this->expr_type_ here.  The thunk will
8185   // expect a closure whose second field has type this->expr_type_ (if
8186   // that is not NULL).  We are going to pass it a closure whose
8187   // second field has type this->expr_->type().  Since
8188   // this->expr_type_ is only not-NULL for pointer types, we can get
8189   // away with this.
8190 
8191   Struct_field_list* fields = new Struct_field_list();
8192   fields->push_back(Struct_field(Typed_identifier("fn",
8193 						  thunk->func_value()->type(),
8194 						  loc)));
8195   fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
8196   Struct_type* st = Type::make_struct_type(fields, loc);
8197   st->set_is_struct_incomparable();
8198 
8199   Expression_list* vals = new Expression_list();
8200   vals->push_back(Expression::make_func_code_reference(thunk, loc));
8201   vals->push_back(val);
8202 
8203   Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
8204   ret = Expression::make_heap_expression(ret, loc);
8205 
8206   Node* node = Node::make_node(this);
8207   if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8208     ret->heap_expression()->set_allocate_on_stack();
8209   else if (gogo->compiling_runtime()
8210 	   && gogo->package_name() == "runtime"
8211 	   && !saw_errors())
8212     go_error_at(loc, "%s escapes to heap, not allowed in runtime",
8213                 node->ast_format(gogo).c_str());
8214 
8215   // If necessary, check whether the expression or any embedded
8216   // pointers are nil.
8217 
8218   Expression* nil_check = NULL;
8219   if (this->method_->field_indexes() != NULL)
8220     {
8221       Expression* ref = expr;
8222       nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
8223       expr = ref;
8224     }
8225 
8226   if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
8227     {
8228       Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
8229 					      Expression::make_nil(loc),
8230 					      loc);
8231       if (nil_check == NULL)
8232 	nil_check = n;
8233       else
8234 	nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
8235     }
8236 
8237   if (nil_check != NULL)
8238     {
8239       Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
8240       // Fix the type of the conditional expression by pretending to
8241       // evaluate to RET either way through the conditional.
8242       crash = Expression::make_compound(crash, ret, loc);
8243       ret = Expression::make_conditional(nil_check, crash, ret, loc);
8244     }
8245 
8246   // RET is a pointer to a struct, but we want a function type.
8247   ret = Expression::make_unsafe_cast(this->type(), ret, loc);
8248 
8249   return ret;
8250 }
8251 
8252 // Dump ast representation of a bound method expression.
8253 
8254 void
do_dump_expression(Ast_dump_context * ast_dump_context) const8255 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
8256     const
8257 {
8258   if (this->expr_type_ != NULL)
8259     ast_dump_context->ostream() << "(";
8260   ast_dump_context->dump_expression(this->expr_);
8261   if (this->expr_type_ != NULL)
8262     {
8263       ast_dump_context->ostream() << ":";
8264       ast_dump_context->dump_type(this->expr_type_);
8265       ast_dump_context->ostream() << ")";
8266     }
8267 
8268   ast_dump_context->ostream() << "." << this->function_->name();
8269 }
8270 
8271 // Make a method expression.
8272 
8273 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)8274 Expression::make_bound_method(Expression* expr, const Method* method,
8275 			      Named_object* function, Location location)
8276 {
8277   return new Bound_method_expression(expr, method, function, location);
8278 }
8279 
8280 // Class Builtin_call_expression.  This is used for a call to a
8281 // builtin function.
8282 
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)8283 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
8284 						 Expression* fn,
8285 						 Expression_list* args,
8286 						 bool is_varargs,
8287 						 Location location)
8288   : Call_expression(fn, args, is_varargs, location),
8289     gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
8290     recover_arg_is_set_(false)
8291 {
8292   Func_expression* fnexp = this->fn()->func_expression();
8293   if (fnexp == NULL)
8294     {
8295       this->code_ = BUILTIN_INVALID;
8296       return;
8297     }
8298   const std::string& name(fnexp->named_object()->name());
8299   if (name == "append")
8300     this->code_ = BUILTIN_APPEND;
8301   else if (name == "cap")
8302     this->code_ = BUILTIN_CAP;
8303   else if (name == "close")
8304     this->code_ = BUILTIN_CLOSE;
8305   else if (name == "complex")
8306     this->code_ = BUILTIN_COMPLEX;
8307   else if (name == "copy")
8308     this->code_ = BUILTIN_COPY;
8309   else if (name == "delete")
8310     this->code_ = BUILTIN_DELETE;
8311   else if (name == "imag")
8312     this->code_ = BUILTIN_IMAG;
8313   else if (name == "len")
8314     this->code_ = BUILTIN_LEN;
8315   else if (name == "make")
8316     this->code_ = BUILTIN_MAKE;
8317   else if (name == "new")
8318     this->code_ = BUILTIN_NEW;
8319   else if (name == "panic")
8320     this->code_ = BUILTIN_PANIC;
8321   else if (name == "print")
8322     this->code_ = BUILTIN_PRINT;
8323   else if (name == "println")
8324     this->code_ = BUILTIN_PRINTLN;
8325   else if (name == "real")
8326     this->code_ = BUILTIN_REAL;
8327   else if (name == "recover")
8328     this->code_ = BUILTIN_RECOVER;
8329   else if (name == "Add")
8330     this->code_ = BUILTIN_ADD;
8331   else if (name == "Alignof")
8332     this->code_ = BUILTIN_ALIGNOF;
8333   else if (name == "Offsetof")
8334     this->code_ = BUILTIN_OFFSETOF;
8335   else if (name == "Sizeof")
8336     this->code_ = BUILTIN_SIZEOF;
8337   else if (name == "Slice")
8338     this->code_ = BUILTIN_SLICE;
8339   else
8340     go_unreachable();
8341 }
8342 
8343 // Return whether this is a call to recover.  This is a virtual
8344 // function called from the parent class.
8345 
8346 bool
do_is_recover_call() const8347 Builtin_call_expression::do_is_recover_call() const
8348 {
8349   if (this->classification() == EXPRESSION_ERROR)
8350     return false;
8351   return this->code_ == BUILTIN_RECOVER;
8352 }
8353 
8354 // Set the argument for a call to recover.
8355 
8356 void
do_set_recover_arg(Expression * arg)8357 Builtin_call_expression::do_set_recover_arg(Expression* arg)
8358 {
8359   const Expression_list* args = this->args();
8360   go_assert(args == NULL || args->empty());
8361   Expression_list* new_args = new Expression_list();
8362   new_args->push_back(arg);
8363   this->set_args(new_args);
8364   this->recover_arg_is_set_ = true;
8365 }
8366 
8367 // Lower a builtin call expression.  This turns new and make into
8368 // specific expressions.  We also convert to a constant if we can.
8369 
8370 Expression*
do_lower(Gogo *,Named_object * function,Statement_inserter * inserter,int)8371 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
8372 				  Statement_inserter* inserter, int)
8373 {
8374   if (this->is_error_expression())
8375     return this;
8376 
8377   Location loc = this->location();
8378 
8379   if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
8380     {
8381       this->report_error(_("invalid use of %<...%> with builtin function"));
8382       return Expression::make_error(loc);
8383     }
8384 
8385   if (this->code_ == BUILTIN_OFFSETOF)
8386     {
8387       Expression* arg = this->one_arg();
8388 
8389       if (arg->bound_method_expression() != NULL
8390 	  || arg->interface_field_reference_expression() != NULL)
8391 	{
8392 	  this->report_error(_("invalid use of method value as argument "
8393 			       "of Offsetof"));
8394 	  return this;
8395 	}
8396 
8397       Field_reference_expression* farg = arg->field_reference_expression();
8398       while (farg != NULL)
8399 	{
8400 	  if (!farg->implicit())
8401 	    break;
8402 	  // When the selector refers to an embedded field,
8403 	  // it must not be reached through pointer indirections.
8404 	  if (farg->expr()->deref() != farg->expr())
8405 	    {
8406 	      this->report_error(_("argument of Offsetof implies "
8407 				   "indirection of an embedded field"));
8408 	      return this;
8409 	    }
8410 	  // Go up until we reach the original base.
8411 	  farg = farg->expr()->field_reference_expression();
8412 	}
8413     }
8414 
8415   if (this->is_constant())
8416     {
8417       Numeric_constant nc;
8418       if (this->numeric_constant_value(&nc))
8419 	return nc.expression(loc);
8420     }
8421 
8422   switch (this->code_)
8423     {
8424     default:
8425       break;
8426 
8427     case BUILTIN_NEW:
8428       {
8429 	const Expression_list* args = this->args();
8430 	if (args == NULL || args->size() < 1)
8431 	  this->report_error(_("not enough arguments"));
8432 	else if (args->size() > 1)
8433 	  this->report_error(_("too many arguments"));
8434 	else
8435 	  {
8436 	    Expression* arg = args->front();
8437 	    if (!arg->is_type_expression())
8438 	      {
8439 		go_error_at(arg->location(), "expected type");
8440 		this->set_is_error();
8441 	      }
8442 	    else
8443 	      return Expression::make_allocation(arg->type(), loc);
8444 	  }
8445       }
8446       break;
8447 
8448     case BUILTIN_MAKE:
8449       return this->lower_make(inserter);
8450 
8451     case BUILTIN_RECOVER:
8452       if (function != NULL)
8453 	function->func_value()->set_calls_recover();
8454       else
8455 	{
8456 	  // Calling recover outside of a function always returns the
8457 	  // nil empty interface.
8458 	  Type* eface = Type::make_empty_interface_type(loc);
8459 	  return Expression::make_cast(eface, Expression::make_nil(loc), loc);
8460 	}
8461       break;
8462 
8463     case BUILTIN_DELETE:
8464       {
8465         const Expression_list* args = this->args();
8466         if (args == NULL || args->size() < 2)
8467           this->report_error(_("not enough arguments"));
8468         else if (args->size() > 2)
8469           this->report_error(_("too many arguments"));
8470         else if (args->front()->type()->map_type() == NULL)
8471           this->report_error(_("argument 1 must be a map"));
8472         else
8473           {
8474             Type* key_type =
8475               args->front()->type()->map_type()->key_type();
8476             Expression_list::iterator pa = this->args()->begin();
8477             pa++;
8478             Type* arg_type = (*pa)->type();
8479             std::string reason;
8480             if (!Type::are_assignable(key_type, arg_type, &reason))
8481               {
8482                 if (reason.empty())
8483                   go_error_at(loc, "argument 2 has incompatible type");
8484                 else
8485                   go_error_at(loc, "argument 2 has incompatible type (%s)",
8486                               reason.c_str());
8487                 this->set_is_error();
8488               }
8489             else if (!Type::are_identical(key_type, arg_type, 0, NULL))
8490               *pa = Expression::make_cast(key_type, *pa, loc);
8491           }
8492       }
8493       break;
8494 
8495     case BUILTIN_PRINT:
8496     case BUILTIN_PRINTLN:
8497       // Force all the arguments into temporary variables, so that we
8498       // don't try to evaluate something while holding the print lock.
8499       if (this->args() == NULL)
8500 	break;
8501       for (Expression_list::iterator pa = this->args()->begin();
8502 	   pa != this->args()->end();
8503 	   ++pa)
8504 	{
8505 	  if (!(*pa)->is_multi_eval_safe())
8506 	    {
8507 	      Temporary_statement* temp =
8508 		Statement::make_temporary(NULL, *pa, loc);
8509 	      inserter->insert(temp);
8510 	      *pa = Expression::make_temporary_reference(temp, loc);
8511 	    }
8512 	}
8513       break;
8514     }
8515 
8516   return this;
8517 }
8518 
8519 // Flatten a builtin call expression.  This turns the arguments of some
8520 // builtin calls into temporary expressions.  Also expand copy and append
8521 // to runtime calls.
8522 
8523 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)8524 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
8525                                     Statement_inserter* inserter)
8526 {
8527   if (this->is_error_expression())
8528     {
8529       go_assert(saw_errors());
8530       return this;
8531     }
8532 
8533   Location loc = this->location();
8534 
8535   switch (this->code_)
8536     {
8537     default:
8538       break;
8539 
8540     case BUILTIN_APPEND:
8541       return this->flatten_append(gogo, function, inserter, NULL, NULL);
8542 
8543     case BUILTIN_COPY:
8544       {
8545 	Type* at = this->args()->front()->type();
8546 	for (Expression_list::iterator pa = this->args()->begin();
8547 	     pa != this->args()->end();
8548 	     ++pa)
8549 	  {
8550 	    if ((*pa)->is_nil_expression())
8551 	      {
8552 		Expression* nil = Expression::make_nil(loc);
8553 		Expression* zero = Expression::make_integer_ul(0, NULL, loc);
8554 		*pa = Expression::make_slice_value(at, nil, zero, zero, loc);
8555 	      }
8556 	    if (!(*pa)->is_multi_eval_safe())
8557 	      {
8558 		Temporary_statement* temp =
8559                   Statement::make_temporary(NULL, *pa, loc);
8560 		inserter->insert(temp);
8561 		*pa = Expression::make_temporary_reference(temp, loc);
8562 	      }
8563 	  }
8564 
8565         // Lower to runtime call.
8566         const Expression_list* args = this->args();
8567         go_assert(args != NULL && args->size() == 2);
8568         Expression* arg1 = args->front();
8569         Expression* arg2 = args->back();
8570 	go_assert(arg1->is_multi_eval_safe());
8571 	go_assert(arg2->is_multi_eval_safe());
8572         bool arg2_is_string = arg2->type()->is_string_type();
8573 
8574         Expression* ret;
8575         Type* et = at->array_type()->element_type();
8576         if (et->has_pointer())
8577           {
8578             Expression* td = Expression::make_type_descriptor(et, loc);
8579 	    Expression* pd =
8580 	      Expression::make_slice_info(arg1, SLICE_INFO_VALUE_POINTER, loc);
8581 	    Expression* ld =
8582 	      Expression::make_slice_info(arg1, SLICE_INFO_LENGTH, loc);
8583 	    Expression* ps =
8584 	      Expression::make_slice_info(arg2, SLICE_INFO_VALUE_POINTER, loc);
8585 	    Expression* ls =
8586 	      Expression::make_slice_info(arg2, SLICE_INFO_LENGTH, loc);
8587             ret = Runtime::make_call(Runtime::TYPEDSLICECOPY, loc,
8588                                      5, td, pd, ld, ps, ls);
8589           }
8590         else
8591           {
8592             Type* int_type = Type::lookup_integer_type("int");
8593             Type* uintptr_type = Type::lookup_integer_type("uintptr");
8594 
8595             // l1 = len(arg1)
8596             Named_object* lenfn = gogo->lookup_global("len");
8597             Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8598             Expression_list* len_args = new Expression_list();
8599             len_args->push_back(arg1->copy());
8600             Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
8601             gogo->lower_expression(function, inserter, &len1);
8602             gogo->flatten_expression(function, inserter, &len1);
8603             Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
8604             inserter->insert(l1tmp);
8605 
8606             // l2 = len(arg2)
8607             len_args = new Expression_list();
8608             len_args->push_back(arg2->copy());
8609             Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
8610             gogo->lower_expression(function, inserter, &len2);
8611             gogo->flatten_expression(function, inserter, &len2);
8612             Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
8613             inserter->insert(l2tmp);
8614 
8615             // n = (l1 < l2 ? l1 : l2)
8616             Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
8617             Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
8618             Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
8619             Expression* n = Expression::make_conditional(cond,
8620                                                          l1ref->copy(),
8621                                                          l2ref->copy(),
8622                                                          loc);
8623             Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
8624             inserter->insert(ntmp);
8625 
8626             // sz = n * sizeof(elem_type)
8627             Expression* nref = Expression::make_temporary_reference(ntmp, loc);
8628             nref = Expression::make_cast(uintptr_type, nref, loc);
8629             Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
8630             sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
8631 
8632             // memmove(arg1.ptr, arg2.ptr, sz)
8633             Expression* p1 = Expression::make_slice_info(arg1,
8634                                                          SLICE_INFO_VALUE_POINTER,
8635                                                          loc);
8636             Expression* p2 = (arg2_is_string
8637                               ? Expression::make_string_info(arg2,
8638                                                              STRING_INFO_DATA,
8639                                                              loc)
8640                               : Expression::make_slice_info(arg2,
8641                                                             SLICE_INFO_VALUE_POINTER,
8642                                                             loc));
8643             Expression* call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
8644                                                   p1, p2, sz);
8645 
8646             // n is the return value of copy
8647             nref = Expression::make_temporary_reference(ntmp, loc);
8648             ret = Expression::make_compound(call, nref, loc);
8649           }
8650         return ret;
8651       }
8652       break;
8653 
8654     case BUILTIN_PANIC:
8655       for (Expression_list::iterator pa = this->args()->begin();
8656 	   pa != this->args()->end();
8657 	   ++pa)
8658 	{
8659 	  if (!(*pa)->is_multi_eval_safe()
8660 	      && (*pa)->type()->interface_type() != NULL)
8661 	    {
8662 	      Temporary_statement* temp =
8663 		Statement::make_temporary(NULL, *pa, loc);
8664 	      inserter->insert(temp);
8665 	      *pa = Expression::make_temporary_reference(temp, loc);
8666 	    }
8667 	}
8668       break;
8669 
8670     case BUILTIN_LEN:
8671     case BUILTIN_CAP:
8672       {
8673 	Expression_list::iterator pa = this->args()->begin();
8674 	if (!(*pa)->is_multi_eval_safe()
8675 	    && ((*pa)->type()->map_type() != NULL
8676 		|| (*pa)->type()->channel_type() != NULL))
8677 	  {
8678 	    Temporary_statement* temp =
8679 	      Statement::make_temporary(NULL, *pa, loc);
8680 	    inserter->insert(temp);
8681 	    *pa = Expression::make_temporary_reference(temp, loc);
8682 	  }
8683       }
8684       break;
8685 
8686     case BUILTIN_DELETE:
8687       {
8688         // Lower to a runtime function call.
8689         const Expression_list* args = this->args();
8690 
8691         // Since this function returns no value it must appear in
8692         // a statement by itself, so we don't have to worry about
8693         // order of evaluation of values around it.  Evaluate the
8694         // map first to get order of evaluation right.
8695         Map_type* mt = args->front()->type()->map_type();
8696         Temporary_statement* map_temp =
8697           Statement::make_temporary(mt, args->front(), loc);
8698         inserter->insert(map_temp);
8699 
8700         Temporary_statement* key_temp =
8701           Statement::make_temporary(mt->key_type(), args->back(), loc);
8702         inserter->insert(key_temp);
8703 
8704         Expression* e1 = Expression::make_type_descriptor(mt, loc);
8705         Expression* e2 = Expression::make_temporary_reference(map_temp,
8706                                                               loc);
8707         Expression* e3 = Expression::make_temporary_reference(key_temp,
8708                                                               loc);
8709 
8710         Runtime::Function code;
8711         switch (mt->algorithm(gogo))
8712           {
8713             case Map_type::MAP_ALG_FAST32:
8714             case Map_type::MAP_ALG_FAST32PTR:
8715               {
8716                 code = Runtime::MAPDELETE_FAST32;
8717                 Type* uint32_type = Type::lookup_integer_type("uint32");
8718                 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
8719                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8720                 e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
8721                                                   loc);
8722                 e3 = Expression::make_dereference(e3,
8723                                                   Expression::NIL_CHECK_NOT_NEEDED,
8724                                                   loc);
8725                 break;
8726               }
8727             case Map_type::MAP_ALG_FAST64:
8728             case Map_type::MAP_ALG_FAST64PTR:
8729               {
8730                 code = Runtime::MAPDELETE_FAST64;
8731                 Type* uint64_type = Type::lookup_integer_type("uint64");
8732                 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
8733                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8734                 e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
8735                                                   loc);
8736                 e3 = Expression::make_dereference(e3,
8737                                                   Expression::NIL_CHECK_NOT_NEEDED,
8738                                                   loc);
8739                 break;
8740               }
8741             case Map_type::MAP_ALG_FASTSTR:
8742               code = Runtime::MAPDELETE_FASTSTR;
8743               break;
8744             default:
8745               code = Runtime::MAPDELETE;
8746 
8747               // If the call to delete is deferred, and is in a loop,
8748               // then the loop will only have a single instance of the
8749               // temporary variable.  Passing the address of the
8750               // temporary variable here means that the deferred call
8751               // will see the last value in the loop, not the current
8752               // value.  So for this unusual case copy the value into
8753               // the heap.
8754               if (!this->is_deferred())
8755                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8756               else
8757                 {
8758                   Expression* a = Expression::make_allocation(mt->key_type(),
8759                                                               loc);
8760                   Temporary_statement* atemp =
8761                     Statement::make_temporary(NULL, a, loc);
8762                   inserter->insert(atemp);
8763 
8764                   a = Expression::make_temporary_reference(atemp, loc);
8765                   a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
8766                   Statement* s = Statement::make_assignment(a, e3, loc);
8767                   inserter->insert(s);
8768 
8769                   e3 = Expression::make_temporary_reference(atemp, loc);
8770                 }
8771           }
8772 
8773         return Runtime::make_call(code, loc, 3, e1, e2, e3);
8774       }
8775 
8776     case BUILTIN_ADD:
8777       {
8778 	Expression* ptr = this->args()->front();
8779 	Type* uintptr_type = Type::lookup_integer_type("uintptr");
8780 	ptr = Expression::make_cast(uintptr_type, ptr, loc);
8781 	Expression* len = this->args()->back();
8782 	len = Expression::make_cast(uintptr_type, len, loc);
8783 	Expression* add = Expression::make_binary(OPERATOR_PLUS, ptr, len,
8784 						  loc);
8785 	return Expression::make_cast(this->args()->front()->type(), add, loc);
8786       }
8787 
8788     case BUILTIN_SLICE:
8789       {
8790 	Expression* ptr = this->args()->front();
8791 	Temporary_statement* ptr_temp = NULL;
8792 	if (!ptr->is_multi_eval_safe())
8793 	  {
8794 	    ptr_temp = Statement::make_temporary(NULL, ptr, loc);
8795 	    inserter->insert(ptr_temp);
8796 	    ptr = Expression::make_temporary_reference(ptr_temp, loc);
8797 	  }
8798 
8799 	Expression* len = this->args()->back();
8800 	Temporary_statement* len_temp = NULL;
8801 	if (!len->is_multi_eval_safe())
8802 	  {
8803 	    len_temp = Statement::make_temporary(NULL, len, loc);
8804 	    inserter->insert(len_temp);
8805 	    len = Expression::make_temporary_reference(len_temp, loc);
8806 	  }
8807 
8808 	bool fits_in_int;
8809 	Numeric_constant nc;
8810 	if (this->args()->back()->numeric_constant_value(&nc))
8811 	  {
8812 	    // We gave an error for constants that don't fit in int in
8813 	    // check_types.
8814 	    fits_in_int = true;
8815 	  }
8816 	else
8817 	  {
8818 	    Integer_type* itype = this->args()->back()->type()->integer_type();
8819 	    go_assert(itype != NULL);
8820 	    int ebits = itype->bits();
8821 	    int intbits =
8822 	      Type::lookup_integer_type("int")->integer_type()->bits();
8823 
8824 	    // We can treat ebits == intbits as small even for an
8825 	    // unsigned integer type, because we will convert the
8826 	    // value to int and then reject it in the runtime if it is
8827 	    // negative.
8828 
8829 	    fits_in_int = ebits <= intbits;
8830 	  }
8831 
8832 	Runtime::Function code = (fits_in_int
8833 				  ? Runtime::UNSAFESLICE
8834 				  : Runtime::UNSAFESLICE64);
8835 	Expression* td =
8836 	  Expression::make_type_descriptor(ptr->type()->points_to(), loc);
8837 	Expression* check = Runtime::make_call(code, loc, 3,
8838 					       td, ptr, len);
8839 
8840 	if (ptr_temp == NULL)
8841 	  ptr = ptr->copy();
8842 	else
8843 	  ptr = Expression::make_temporary_reference(ptr_temp, loc);
8844 	Expression* nil = Expression::make_nil(loc);
8845 	nil = Expression::make_cast(ptr->type(), nil, loc);
8846 	Expression* is_nil = Expression::make_binary(OPERATOR_EQEQ, ptr, nil,
8847 						     loc);
8848 
8849 	if (len_temp == NULL)
8850 	  len = len->copy();
8851 	else
8852 	  len = Expression::make_temporary_reference(len_temp, loc);
8853 	Expression* zero = Expression::make_integer_ul(0, len->type(), loc);
8854 	Expression* is_zero = Expression::make_binary(OPERATOR_EQEQ, len, zero,
8855 						      loc);
8856 
8857 	Expression* cond = Expression::make_binary(OPERATOR_ANDAND, is_nil,
8858 						   is_zero, loc);
8859 
8860 	Type* slice_type = Type::make_array_type(ptr->type()->points_to(),
8861 						 NULL);
8862 	nil = Expression::make_nil(loc);
8863 	Expression* nil_slice = Expression::make_cast(slice_type, nil, loc);
8864 
8865 	if (ptr_temp == NULL)
8866 	  ptr = ptr->copy();
8867 	else
8868 	  ptr = Expression::make_temporary_reference(ptr_temp, loc);
8869 
8870 	if (len_temp == NULL)
8871 	  len = len->copy();
8872 	else
8873 	  len = Expression::make_temporary_reference(len_temp, loc);
8874 
8875 	Expression* cap;
8876 	if (len_temp == NULL)
8877 	  cap = len->copy();
8878 	else
8879 	  cap = Expression::make_temporary_reference(len_temp, loc);
8880 
8881 	Expression* slice = Expression::make_slice_value(slice_type, ptr,
8882 							 len, cap, loc);
8883 
8884 	slice = Expression::make_conditional(cond, nil_slice, slice, loc);
8885 
8886 	return Expression::make_compound(check, slice, loc);
8887       }
8888     }
8889 
8890   return this;
8891 }
8892 
8893 // Lower a make expression.
8894 
8895 Expression*
lower_make(Statement_inserter * inserter)8896 Builtin_call_expression::lower_make(Statement_inserter* inserter)
8897 {
8898   Location loc = this->location();
8899 
8900   const Expression_list* args = this->args();
8901   if (args == NULL || args->size() < 1)
8902     {
8903       this->report_error(_("not enough arguments"));
8904       return Expression::make_error(this->location());
8905     }
8906 
8907   Expression_list::const_iterator parg = args->begin();
8908 
8909   Expression* first_arg = *parg;
8910   if (!first_arg->is_type_expression())
8911     {
8912       go_error_at(first_arg->location(), "expected type");
8913       this->set_is_error();
8914       return Expression::make_error(this->location());
8915     }
8916   Type* type = first_arg->type();
8917 
8918   if (!type->in_heap())
8919     go_error_at(first_arg->location(),
8920 		"cannot make slice of go:notinheap type");
8921 
8922   bool is_slice = false;
8923   bool is_map = false;
8924   bool is_chan = false;
8925   if (type->is_slice_type())
8926     is_slice = true;
8927   else if (type->map_type() != NULL)
8928     is_map = true;
8929   else if (type->channel_type() != NULL)
8930     is_chan = true;
8931   else
8932     {
8933       this->report_error(_("invalid type for make function"));
8934       return Expression::make_error(this->location());
8935     }
8936 
8937   Type_context int_context(Type::lookup_integer_type("int"), false);
8938 
8939   ++parg;
8940   Expression* len_arg;
8941   bool len_small = false;
8942   if (parg == args->end())
8943     {
8944       if (is_slice)
8945 	{
8946 	  this->report_error(_("length required when allocating a slice"));
8947 	  return Expression::make_error(this->location());
8948 	}
8949       len_arg = Expression::make_integer_ul(0, NULL, loc);
8950       len_small = true;
8951     }
8952   else
8953     {
8954       len_arg = *parg;
8955       len_arg->determine_type(&int_context);
8956       if (len_arg->type()->integer_type() == NULL)
8957 	{
8958 	  go_error_at(len_arg->location(), "non-integer len argument in make");
8959 	  return Expression::make_error(this->location());
8960 	}
8961       if (!this->check_int_value(len_arg, true, &len_small))
8962 	return Expression::make_error(this->location());
8963       ++parg;
8964     }
8965 
8966   Expression* cap_arg = NULL;
8967   bool cap_small = false;
8968   Numeric_constant nclen;
8969   Numeric_constant nccap;
8970   unsigned long vlen;
8971   unsigned long vcap;
8972   if (is_slice && parg != args->end())
8973     {
8974       cap_arg = *parg;
8975       cap_arg->determine_type(&int_context);
8976       if (cap_arg->type()->integer_type() == NULL)
8977 	{
8978 	  go_error_at(cap_arg->location(), "non-integer cap argument in make");
8979 	  return Expression::make_error(this->location());
8980 	}
8981       if (!this->check_int_value(cap_arg, false, &cap_small))
8982 	return Expression::make_error(this->location());
8983 
8984       if (len_arg->numeric_constant_value(&nclen)
8985 	  && cap_arg->numeric_constant_value(&nccap)
8986 	  && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8987 	  && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
8988 	  && vlen > vcap)
8989 	{
8990 	  this->report_error(_("len larger than cap"));
8991 	  return Expression::make_error(this->location());
8992 	}
8993 
8994       ++parg;
8995     }
8996 
8997   if (parg != args->end())
8998     {
8999       this->report_error(_("too many arguments to make"));
9000       return Expression::make_error(this->location());
9001     }
9002 
9003   Location type_loc = first_arg->location();
9004 
9005   Expression* call;
9006   if (is_slice)
9007     {
9008       Temporary_statement* len_temp = NULL;
9009       if (!len_arg->is_constant())
9010 	{
9011 	  len_temp = Statement::make_temporary(NULL, len_arg, loc);
9012 	  inserter->insert(len_temp);
9013 	  len_arg = Expression::make_temporary_reference(len_temp, loc);
9014 	}
9015 
9016       if (cap_arg == NULL)
9017 	{
9018           cap_small = len_small;
9019 	  if (len_temp == NULL)
9020 	    cap_arg = len_arg->copy();
9021 	  else
9022 	    cap_arg = Expression::make_temporary_reference(len_temp, loc);
9023 	}
9024       else if (!cap_arg->is_constant())
9025 	{
9026 	  Temporary_statement* cap_temp = Statement::make_temporary(NULL,
9027 								    cap_arg,
9028 								    loc);
9029 	  inserter->insert(cap_temp);
9030 	  cap_arg = Expression::make_temporary_reference(cap_temp, loc);
9031 	}
9032 
9033       Type* et = type->array_type()->element_type();
9034       Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
9035       Runtime::Function code = Runtime::MAKESLICE;
9036       if (!len_small || !cap_small)
9037 	code = Runtime::MAKESLICE64;
9038       Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
9039 					   cap_arg);
9040       mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
9041 					 loc);
9042       Type* int_type = Type::lookup_integer_type("int");
9043       len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
9044       cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
9045       call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
9046     }
9047   else if (is_map)
9048     {
9049       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
9050       if (!len_small)
9051 	call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
9052 				  len_arg,
9053 				  Expression::make_nil(loc));
9054       else
9055 	{
9056 	  if (len_arg->numeric_constant_value(&nclen)
9057 	      && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
9058 	      && vlen <= Map_type::bucket_size)
9059 	    call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
9060 	  else
9061 	    call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
9062 				      len_arg,
9063 				      Expression::make_nil(loc));
9064 	}
9065     }
9066   else if (is_chan)
9067     {
9068       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
9069       Runtime::Function code = Runtime::MAKECHAN;
9070       if (!len_small)
9071 	code = Runtime::MAKECHAN64;
9072       call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
9073     }
9074   else
9075     go_unreachable();
9076 
9077   return Expression::make_unsafe_cast(type, call, loc);
9078 }
9079 
9080 // Flatten a call to the predeclared append function.  We do this in
9081 // the flatten phase, not the lowering phase, so that we run after
9082 // type checking and after order_evaluations.  If ASSIGN_LHS is not
9083 // NULL, this append is the right-hand-side of an assignment and
9084 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
9085 // rather than returning a slice.  This lets us omit a write barrier
9086 // in common cases like a = append(a, ...) when the slice does not
9087 // need to grow.  ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
9088 
9089 Expression*
flatten_append(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Expression * assign_lhs,Block * enclosing)9090 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
9091 					Statement_inserter* inserter,
9092 					Expression* assign_lhs,
9093 					Block* enclosing)
9094 {
9095   if (this->is_error_expression())
9096     return this;
9097 
9098   Location loc = this->location();
9099 
9100   const Expression_list* args = this->args();
9101   go_assert(args != NULL && !args->empty());
9102 
9103   Type* slice_type = args->front()->type();
9104   go_assert(slice_type->is_slice_type());
9105   Type* element_type = slice_type->array_type()->element_type();
9106 
9107   if (args->size() == 1)
9108     {
9109       // append(s) evaluates to s.
9110       if (assign_lhs != NULL)
9111 	return NULL;
9112       return args->front();
9113     }
9114 
9115   Type* int_type = Type::lookup_integer_type("int");
9116   Type* uint_type = Type::lookup_integer_type("uint");
9117 
9118   // Implementing
9119   //   append(s1, s2...)
9120   // or
9121   //   append(s1, a1, a2, a3, ...)
9122 
9123   // s1tmp := s1
9124   Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
9125 							 loc);
9126   inserter->insert(s1tmp);
9127 
9128   // l1tmp := len(s1tmp)
9129   Named_object* lenfn = gogo->lookup_global("len");
9130   Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
9131   Expression_list* call_args = new Expression_list();
9132   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
9133   Expression* len = Expression::make_call(lenref, call_args, false, loc);
9134   gogo->lower_expression(function, inserter, &len);
9135   gogo->flatten_expression(function, inserter, &len);
9136   Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
9137   inserter->insert(l1tmp);
9138 
9139   Temporary_statement* s2tmp = NULL;
9140   Temporary_statement* l2tmp = NULL;
9141   Expression_list* add = NULL;
9142   Expression* len2;
9143   Call_expression* makecall = NULL;
9144   if (this->is_varargs())
9145     {
9146       go_assert(args->size() == 2);
9147 
9148       std::pair<Call_expression*, Temporary_statement*> p =
9149         Expression::find_makeslice_call(args->back());
9150       makecall = p.first;
9151       if (makecall != NULL)
9152         {
9153           // We are handling
9154           // 	append(s, make([]T, len[, cap])...))
9155           // which has already been lowered to
9156           // 	append(s, runtime.makeslice(T, len, cap)).
9157           // We will optimize this to directly zeroing the tail,
9158           // instead of allocating a new slice then copy.
9159 
9160           // Retrieve the length and capacity. Cannot reference s2 as
9161           // we will remove the makeslice call.
9162           Expression* len_arg = makecall->args()->at(1);
9163           len_arg = Expression::make_cast(int_type, len_arg, loc);
9164           l2tmp = Statement::make_temporary(int_type, len_arg, loc);
9165           inserter->insert(l2tmp);
9166 
9167           Expression* cap_arg = makecall->args()->at(2);
9168           cap_arg = Expression::make_cast(int_type, cap_arg, loc);
9169           Temporary_statement* c2tmp =
9170             Statement::make_temporary(int_type, cap_arg, loc);
9171           inserter->insert(c2tmp);
9172 
9173           // Check bad len/cap here.
9174 	  // checkmakeslice(type, len, cap)
9175 	  // (Note that if len and cap are constants, we won't see a
9176 	  // makeslice call here, as it will be rewritten to a stack
9177 	  // allocated array by Mark_address_taken::expression.)
9178 	  Expression* elem = Expression::make_type_descriptor(element_type,
9179 							      loc);
9180           len2 = Expression::make_temporary_reference(l2tmp, loc);
9181           Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
9182 	  Expression* check = Runtime::make_call(Runtime::CHECK_MAKE_SLICE,
9183 						 loc, 3, elem, len2, cap2);
9184           gogo->lower_expression(function, inserter, &check);
9185           gogo->flatten_expression(function, inserter, &check);
9186           Statement* s = Statement::make_statement(check, false);
9187           inserter->insert(s);
9188 
9189           // Remove the original makeslice call.
9190           Temporary_statement* ts = p.second;
9191           if (ts != NULL && ts->uses() == 1)
9192             ts->set_init(Expression::make_nil(loc));
9193         }
9194       else
9195         {
9196           // s2tmp := s2
9197           s2tmp = Statement::make_temporary(NULL, args->back(), loc);
9198           inserter->insert(s2tmp);
9199 
9200           // l2tmp := len(s2tmp)
9201           lenref = Expression::make_func_reference(lenfn, NULL, loc);
9202           call_args = new Expression_list();
9203           call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
9204           len = Expression::make_call(lenref, call_args, false, loc);
9205           gogo->lower_expression(function, inserter, &len);
9206           gogo->flatten_expression(function, inserter, &len);
9207           l2tmp = Statement::make_temporary(int_type, len, loc);
9208           inserter->insert(l2tmp);
9209         }
9210 
9211       // len2 = l2tmp
9212       len2 = Expression::make_temporary_reference(l2tmp, loc);
9213     }
9214   else
9215     {
9216       // We have to ensure that all the arguments are in variables
9217       // now, because otherwise if one of them is an index expression
9218       // into the current slice we could overwrite it before we fetch
9219       // it.
9220       add = new Expression_list();
9221       Expression_list::const_iterator pa = args->begin();
9222       for (++pa; pa != args->end(); ++pa)
9223 	{
9224 	  if ((*pa)->is_multi_eval_safe())
9225 	    add->push_back(*pa);
9226 	  else
9227 	    {
9228 	      Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
9229 								   loc);
9230 	      inserter->insert(tmp);
9231 	      add->push_back(Expression::make_temporary_reference(tmp, loc));
9232 	    }
9233 	}
9234 
9235       // len2 = len(add)
9236       len2 = Expression::make_integer_ul(add->size(), int_type, loc);
9237     }
9238 
9239   // ntmp := l1tmp + len2
9240   Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
9241   Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
9242   gogo->lower_expression(function, inserter, &sum);
9243   gogo->flatten_expression(function, inserter, &sum);
9244   Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
9245   inserter->insert(ntmp);
9246 
9247   // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
9248   //   growslice(type, s1tmp, ntmp) :
9249   //   s1tmp[:ntmp]
9250   // Using uint here means that if the computation of ntmp overflowed,
9251   // we will call growslice which will panic.
9252 
9253   Named_object* capfn = gogo->lookup_global("cap");
9254   Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
9255   call_args = new Expression_list();
9256   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
9257   Expression* cap = Expression::make_call(capref, call_args, false, loc);
9258   gogo->lower_expression(function, inserter, &cap);
9259   gogo->flatten_expression(function, inserter, &cap);
9260   Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
9261   inserter->insert(c1tmp);
9262 
9263   Expression* left = Expression::make_temporary_reference(ntmp, loc);
9264   left = Expression::make_cast(uint_type, left, loc);
9265   Expression* right = Expression::make_temporary_reference(c1tmp, loc);
9266   right = Expression::make_cast(uint_type, right, loc);
9267 
9268   Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
9269 
9270   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
9271   Expression* a1 = Expression::make_type_descriptor(element_type, loc);
9272   Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
9273   a2 = slice_type->array_type()->get_value_pointer(gogo, a2, false);
9274   a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
9275   Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
9276   Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
9277   Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
9278   Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
9279 					a1, a2, a3, a4, a5);
9280   call = Expression::make_unsafe_cast(slice_type, call, loc);
9281 
9282   ref = Expression::make_temporary_reference(s1tmp, loc);
9283   Expression* zero = Expression::make_integer_ul(0, int_type, loc);
9284   Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
9285   ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
9286   ref->array_index_expression()->set_needs_bounds_check(false);
9287 
9288   if (assign_lhs == NULL)
9289     {
9290       Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
9291 
9292       gogo->lower_expression(function, inserter, &rhs);
9293       gogo->flatten_expression(function, inserter, &rhs);
9294 
9295       ref = Expression::make_temporary_reference(s1tmp, loc);
9296       Statement* assign = Statement::make_assignment(ref, rhs, loc);
9297       inserter->insert(assign);
9298     }
9299   else
9300     {
9301       gogo->lower_expression(function, inserter, &cond);
9302       gogo->flatten_expression(function, inserter, &cond);
9303       gogo->lower_expression(function, inserter, &call);
9304       gogo->flatten_expression(function, inserter, &call);
9305       gogo->lower_expression(function, inserter, &ref);
9306       gogo->flatten_expression(function, inserter, &ref);
9307 
9308       Block* then_block = new Block(enclosing, loc);
9309       Assignment_statement* assign =
9310 	Statement::make_assignment(assign_lhs, call, loc);
9311       then_block->add_statement(assign);
9312 
9313       Block* else_block = new Block(enclosing, loc);
9314       assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
9315       // This assignment will not change the pointer value, so it does
9316       // not need a write barrier.
9317       assign->set_omit_write_barrier();
9318       else_block->add_statement(assign);
9319 
9320       Statement* s = Statement::make_if_statement(cond, then_block,
9321 						  else_block, loc);
9322       inserter->insert(s);
9323 
9324       ref = Expression::make_temporary_reference(s1tmp, loc);
9325       assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
9326       inserter->insert(assign);
9327     }
9328 
9329   Type* uintptr_type = Type::lookup_integer_type("uintptr");
9330 
9331   if (this->is_varargs())
9332     {
9333       if (makecall != NULL)
9334         {
9335           // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
9336           a1 = Expression::make_temporary_reference(s1tmp, loc);
9337           ref = Expression::make_temporary_reference(l1tmp, loc);
9338           a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9339           a1->array_index_expression()->set_needs_bounds_check(false);
9340           a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9341 
9342           ref = Expression::make_temporary_reference(l2tmp, loc);
9343           ref = Expression::make_cast(uintptr_type, ref, loc);
9344           a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9345           a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
9346 
9347           if (element_type->has_pointer())
9348             call = Runtime::make_call(Runtime::MEMCLRHASPTR, loc, 2, a1, a2);
9349           else
9350             {
9351               Type* int32_type = Type::lookup_integer_type("int32");
9352               zero = Expression::make_integer_ul(0, int32_type, loc);
9353               call = Runtime::make_call(Runtime::BUILTIN_MEMSET, loc, 3, a1,
9354                                         zero, a2);
9355             }
9356 
9357           if (element_type->has_pointer())
9358             {
9359               // For a slice containing pointers, growslice already zeroed
9360               // the memory. We only need to zero in non-growing case.
9361               // Note: growslice does not zero the memory in non-pointer case.
9362               ref = Expression::make_temporary_reference(ntmp, loc);
9363               ref = Expression::make_cast(uint_type, ref, loc);
9364               ref2 = Expression::make_temporary_reference(c1tmp, loc);
9365               ref2 = Expression::make_cast(uint_type, ref2, loc);
9366               cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
9367               zero = Expression::make_integer_ul(0, int_type, loc);
9368               call = Expression::make_conditional(cond, zero, call, loc);
9369             }
9370         }
9371       else
9372         {
9373           if (element_type->has_pointer())
9374             {
9375               // copy(s1tmp[l1tmp:], s2tmp)
9376               a1 = Expression::make_temporary_reference(s1tmp, loc);
9377               ref = Expression::make_temporary_reference(l1tmp, loc);
9378               Expression* nil = Expression::make_nil(loc);
9379               a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
9380               a1->array_index_expression()->set_needs_bounds_check(false);
9381 
9382               a2 = Expression::make_temporary_reference(s2tmp, loc);
9383 
9384               Named_object* copyfn = gogo->lookup_global("copy");
9385               Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
9386               call_args = new Expression_list();
9387               call_args->push_back(a1);
9388               call_args->push_back(a2);
9389               call = Expression::make_call(copyref, call_args, false, loc);
9390             }
9391           else
9392             {
9393               // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
9394               a1 = Expression::make_temporary_reference(s1tmp, loc);
9395               ref = Expression::make_temporary_reference(l1tmp, loc);
9396               a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9397               a1->array_index_expression()->set_needs_bounds_check(false);
9398               a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9399 
9400               a2 = Expression::make_temporary_reference(s2tmp, loc);
9401               a2 = (a2->type()->is_string_type()
9402                     ? Expression::make_string_info(a2,
9403                                                    STRING_INFO_DATA,
9404                                                    loc)
9405                     : Expression::make_slice_info(a2,
9406                                                   SLICE_INFO_VALUE_POINTER,
9407                                                   loc));
9408 
9409               ref = Expression::make_temporary_reference(l2tmp, loc);
9410               ref = Expression::make_cast(uintptr_type, ref, loc);
9411               a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9412               a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
9413 
9414               call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
9415                                         a1, a2, a3);
9416             }
9417         }
9418       gogo->lower_expression(function, inserter, &call);
9419       gogo->flatten_expression(function, inserter, &call);
9420       inserter->insert(Statement::make_statement(call, false));
9421     }
9422   else
9423     {
9424       // For each argument:
9425       //  s1tmp[l1tmp+i] = a
9426       unsigned long i = 0;
9427       for (Expression_list::const_iterator pa = add->begin();
9428 	   pa != add->end();
9429 	   ++pa, ++i)
9430 	{
9431 	  ref = Expression::make_temporary_reference(s1tmp, loc);
9432 	  ref2 = Expression::make_temporary_reference(l1tmp, loc);
9433 	  Expression* off = Expression::make_integer_ul(i, int_type, loc);
9434 	  ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
9435 	  Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
9436                                                          NULL, loc);
9437           lhs->array_index_expression()->set_needs_bounds_check(false);
9438 	  gogo->lower_expression(function, inserter, &lhs);
9439 	  gogo->flatten_expression(function, inserter, &lhs);
9440       Expression* elem = *pa;
9441       if (!Type::are_identical(element_type, elem->type(), 0, NULL)
9442           && element_type->interface_type() != NULL)
9443         elem = Expression::make_cast(element_type, elem, loc);
9444 	  // The flatten pass runs after the write barrier pass, so we
9445 	  // need to insert a write barrier here if necessary.
9446 	  // However, if ASSIGN_LHS is not NULL, we have been called
9447 	  // directly before the write barrier pass.
9448 	  Statement* assign;
9449 	  if (assign_lhs != NULL
9450 	      || !gogo->assign_needs_write_barrier(lhs, NULL))
9451 	    assign = Statement::make_assignment(lhs, elem, loc);
9452 	  else
9453 	    {
9454 	      Function* f = function == NULL ? NULL : function->func_value();
9455 	      assign = gogo->assign_with_write_barrier(f, NULL, inserter,
9456 						       lhs, elem, loc);
9457 	    }
9458 	  inserter->insert(assign);
9459 	}
9460     }
9461 
9462   if (assign_lhs != NULL)
9463     return NULL;
9464 
9465   return Expression::make_temporary_reference(s1tmp, loc);
9466 }
9467 
9468 // Return whether an expression has an integer value.  Report an error
9469 // if not.  This is used when handling calls to the predeclared make
9470 // function.  Set *SMALL if the value is known to fit in type "int".
9471 
9472 bool
check_int_value(Expression * e,bool is_length,bool * small)9473 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
9474 					 bool *small)
9475 {
9476   *small = false;
9477 
9478   Numeric_constant nc;
9479   if (e->numeric_constant_value(&nc))
9480     {
9481       unsigned long v;
9482       switch (nc.to_unsigned_long(&v))
9483 	{
9484 	case Numeric_constant::NC_UL_VALID:
9485 	  break;
9486 	case Numeric_constant::NC_UL_NOTINT:
9487 	  go_error_at(e->location(), "non-integer %s argument to make",
9488 		      is_length ? "len" : "cap");
9489 	  return false;
9490 	case Numeric_constant::NC_UL_NEGATIVE:
9491 	  go_error_at(e->location(), "negative %s argument to make",
9492 		      is_length ? "len" : "cap");
9493 	  return false;
9494 	case Numeric_constant::NC_UL_BIG:
9495 	  // We don't want to give a compile-time error for a 64-bit
9496 	  // value on a 32-bit target.
9497 	  break;
9498 	}
9499 
9500       mpz_t val;
9501       if (!nc.to_int(&val))
9502 	go_unreachable();
9503       int bits = mpz_sizeinbase(val, 2);
9504       mpz_clear(val);
9505       Type* int_type = Type::lookup_integer_type("int");
9506       if (bits >= int_type->integer_type()->bits())
9507 	{
9508 	  go_error_at(e->location(), "%s argument too large for make",
9509 		      is_length ? "len" : "cap");
9510 	  return false;
9511 	}
9512 
9513       *small = true;
9514       return true;
9515     }
9516 
9517   if (e->type()->integer_type() != NULL)
9518     {
9519       int ebits = e->type()->integer_type()->bits();
9520       int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
9521 
9522       // We can treat ebits == intbits as small even for an unsigned
9523       // integer type, because we will convert the value to int and
9524       // then reject it in the runtime if it is negative.
9525       *small = ebits <= intbits;
9526 
9527       return true;
9528     }
9529 
9530   go_error_at(e->location(), "non-integer %s argument to make",
9531 	      is_length ? "len" : "cap");
9532   return false;
9533 }
9534 
9535 // Return the type of the real or imag functions, given the type of
9536 // the argument.  We need to map complex64 to float32 and complex128
9537 // to float64, so it has to be done by name.  This returns NULL if it
9538 // can't figure out the type.
9539 
9540 Type*
real_imag_type(Type * arg_type)9541 Builtin_call_expression::real_imag_type(Type* arg_type)
9542 {
9543   if (arg_type == NULL || arg_type->is_abstract())
9544     return NULL;
9545   Named_type* nt = arg_type->named_type();
9546   if (nt == NULL)
9547     return NULL;
9548   while (nt->real_type()->named_type() != NULL)
9549     nt = nt->real_type()->named_type();
9550   if (nt->name() == "complex64")
9551     return Type::lookup_float_type("float32");
9552   else if (nt->name() == "complex128")
9553     return Type::lookup_float_type("float64");
9554   else
9555     return NULL;
9556 }
9557 
9558 // Return the type of the complex function, given the type of one of the
9559 // argments.  Like real_imag_type, we have to map by name.
9560 
9561 Type*
complex_type(Type * arg_type)9562 Builtin_call_expression::complex_type(Type* arg_type)
9563 {
9564   if (arg_type == NULL || arg_type->is_abstract())
9565     return NULL;
9566   Named_type* nt = arg_type->named_type();
9567   if (nt == NULL)
9568     return NULL;
9569   while (nt->real_type()->named_type() != NULL)
9570     nt = nt->real_type()->named_type();
9571   if (nt->name() == "float32")
9572     return Type::lookup_complex_type("complex64");
9573   else if (nt->name() == "float64")
9574     return Type::lookup_complex_type("complex128");
9575   else
9576     return NULL;
9577 }
9578 
9579 // Return a single argument, or NULL if there isn't one.
9580 
9581 Expression*
one_arg() const9582 Builtin_call_expression::one_arg() const
9583 {
9584   const Expression_list* args = this->args();
9585   if (args == NULL || args->size() != 1)
9586     return NULL;
9587   return args->front();
9588 }
9589 
9590 // A traversal class which looks for a call or receive expression.
9591 
9592 class Find_call_expression : public Traverse
9593 {
9594  public:
Find_call_expression()9595   Find_call_expression()
9596     : Traverse(traverse_expressions),
9597       found_(false)
9598   { }
9599 
9600   int
9601   expression(Expression**);
9602 
9603   bool
found()9604   found()
9605   { return this->found_; }
9606 
9607  private:
9608   bool found_;
9609 };
9610 
9611 int
expression(Expression ** pexpr)9612 Find_call_expression::expression(Expression** pexpr)
9613 {
9614   Expression* expr = *pexpr;
9615   if (!expr->is_constant()
9616       && (expr->call_expression() != NULL
9617 	  || expr->receive_expression() != NULL))
9618     {
9619       this->found_ = true;
9620       return TRAVERSE_EXIT;
9621     }
9622   return TRAVERSE_CONTINUE;
9623 }
9624 
9625 // Return whether calling len or cap on EXPR, of array type, is a
9626 // constant.  The language spec says "the expressions len(s) and
9627 // cap(s) are constants if the type of s is an array or pointer to an
9628 // array and the expression s does not contain channel receives or
9629 // (non-constant) function calls."
9630 
9631 bool
array_len_is_constant(Expression * expr)9632 Builtin_call_expression::array_len_is_constant(Expression* expr)
9633 {
9634   go_assert(expr->type()->deref()->array_type() != NULL
9635 	    && !expr->type()->deref()->is_slice_type());
9636   if (expr->is_constant())
9637     return true;
9638   Find_call_expression find_call;
9639   Expression::traverse(&expr, &find_call);
9640   return !find_call.found();
9641 }
9642 
9643 // Return whether this is constant: len of a string constant, or len
9644 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
9645 // unsafe.Alignof.
9646 
9647 bool
do_is_constant() const9648 Builtin_call_expression::do_is_constant() const
9649 {
9650   if (this->is_error_expression())
9651     return true;
9652   switch (this->code_)
9653     {
9654     case BUILTIN_LEN:
9655     case BUILTIN_CAP:
9656       {
9657 	if (this->seen_)
9658 	  return false;
9659 
9660 	Expression* arg = this->one_arg();
9661 	if (arg == NULL)
9662 	  return false;
9663 	Type* arg_type = arg->type();
9664 	if (arg_type->is_error())
9665 	  return true;
9666 
9667 	if (arg_type->points_to() != NULL
9668 	    && arg_type->points_to()->array_type() != NULL
9669 	    && !arg_type->points_to()->is_slice_type())
9670 	  arg_type = arg_type->points_to();
9671 
9672 	if (arg_type->array_type() != NULL
9673 	    && arg_type->array_type()->length() != NULL)
9674           {
9675 	    this->seen_ = true;
9676 	    bool ret = Builtin_call_expression::array_len_is_constant(arg);
9677 	    this->seen_ = false;
9678 	    return ret;
9679           }
9680 
9681 	if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9682 	  {
9683 	    this->seen_ = true;
9684 	    bool ret = arg->is_constant();
9685 	    this->seen_ = false;
9686 	    return ret;
9687 	  }
9688       }
9689       break;
9690 
9691     case BUILTIN_SIZEOF:
9692     case BUILTIN_ALIGNOF:
9693       return this->one_arg() != NULL;
9694 
9695     case BUILTIN_OFFSETOF:
9696       {
9697 	Expression* arg = this->one_arg();
9698 	if (arg == NULL)
9699 	  return false;
9700 	return arg->field_reference_expression() != NULL;
9701       }
9702 
9703     case BUILTIN_COMPLEX:
9704       {
9705 	const Expression_list* args = this->args();
9706 	if (args != NULL && args->size() == 2)
9707 	  return args->front()->is_constant() && args->back()->is_constant();
9708       }
9709       break;
9710 
9711     case BUILTIN_REAL:
9712     case BUILTIN_IMAG:
9713       {
9714 	Expression* arg = this->one_arg();
9715 	return arg != NULL && arg->is_constant();
9716       }
9717 
9718     default:
9719       break;
9720     }
9721 
9722   return false;
9723 }
9724 
9725 // Return a numeric constant if possible.
9726 
9727 bool
do_numeric_constant_value(Numeric_constant * nc) const9728 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
9729 {
9730   if (this->code_ == BUILTIN_LEN
9731       || this->code_ == BUILTIN_CAP)
9732     {
9733       Expression* arg = this->one_arg();
9734       if (arg == NULL)
9735 	return false;
9736       Type* arg_type = arg->type();
9737       if (arg_type->is_error())
9738 	return false;
9739 
9740       if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9741 	{
9742 	  std::string sval;
9743 	  if (arg->string_constant_value(&sval))
9744 	    {
9745 	      nc->set_unsigned_long(Type::lookup_integer_type("int"),
9746 				    sval.length());
9747 	      return true;
9748 	    }
9749 	}
9750 
9751       if (arg_type->points_to() != NULL
9752 	  && arg_type->points_to()->array_type() != NULL
9753 	  && !arg_type->points_to()->is_slice_type())
9754 	arg_type = arg_type->points_to();
9755 
9756       if (arg_type->array_type() != NULL
9757 	  && arg_type->array_type()->length() != NULL)
9758 	{
9759 	  if (this->seen_)
9760 	    return false;
9761 
9762 	  // We may be replacing this expression with a constant
9763 	  // during lowering, so verify the type to report any errors.
9764 	  // It's OK to verify an array type more than once.
9765 	  arg_type->verify();
9766 	  if (!arg_type->is_error())
9767 	    {
9768 	      Expression* e = arg_type->array_type()->length();
9769 	      this->seen_ = true;
9770 	      bool r = e->numeric_constant_value(nc);
9771 	      this->seen_ = false;
9772 	      if (r)
9773 		{
9774 		  if (!nc->set_type(Type::lookup_integer_type("int"), false,
9775 				    this->location()))
9776 		    r = false;
9777 		}
9778 	      return r;
9779 	    }
9780 	}
9781     }
9782   else if (this->code_ == BUILTIN_SIZEOF
9783 	   || this->code_ == BUILTIN_ALIGNOF)
9784     {
9785       Expression* arg = this->one_arg();
9786       if (arg == NULL)
9787 	return false;
9788       Type* arg_type = arg->type();
9789       if (arg_type->is_error())
9790 	return false;
9791       if (arg_type->is_abstract())
9792 	arg_type = arg_type->make_non_abstract_type();
9793       if (this->seen_)
9794         return false;
9795 
9796       int64_t ret;
9797       if (this->code_ == BUILTIN_SIZEOF)
9798 	{
9799           this->seen_ = true;
9800 	  bool ok = arg_type->backend_type_size(this->gogo_, &ret);
9801           this->seen_ = false;
9802 	  if (!ok)
9803 	    return false;
9804 	}
9805       else if (this->code_ == BUILTIN_ALIGNOF)
9806 	{
9807 	  bool ok;
9808           this->seen_ = true;
9809 	  if (arg->field_reference_expression() == NULL)
9810 	    ok = arg_type->backend_type_align(this->gogo_, &ret);
9811 	  else
9812 	    {
9813 	      // Calling unsafe.Alignof(s.f) returns the alignment of
9814 	      // the type of f when it is used as a field in a struct.
9815 	      ok = arg_type->backend_type_field_align(this->gogo_, &ret);
9816 	    }
9817           this->seen_ = false;
9818 	  if (!ok)
9819 	    return false;
9820 	}
9821       else
9822 	go_unreachable();
9823 
9824       mpz_t zval;
9825       set_mpz_from_int64(&zval, ret);
9826       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9827       mpz_clear(zval);
9828       return true;
9829     }
9830   else if (this->code_ == BUILTIN_OFFSETOF)
9831     {
9832       Expression* arg = this->one_arg();
9833       if (arg == NULL)
9834 	return false;
9835       Field_reference_expression* farg = arg->field_reference_expression();
9836       if (farg == NULL)
9837 	return false;
9838       if (this->seen_)
9839         return false;
9840 
9841       int64_t total_offset = 0;
9842       while (true)
9843         {
9844           Expression* struct_expr = farg->expr();
9845           Type* st = struct_expr->type();
9846           if (st->struct_type() == NULL)
9847             return false;
9848           if (st->named_type() != NULL)
9849             st->named_type()->convert(this->gogo_);
9850           if (st->is_error_type())
9851             {
9852               go_assert(saw_errors());
9853               return false;
9854             }
9855           int64_t offset;
9856           this->seen_ = true;
9857           bool ok = st->struct_type()->backend_field_offset(this->gogo_,
9858 							    farg->field_index(),
9859 							    &offset);
9860           this->seen_ = false;
9861 	  if (!ok)
9862 	    return false;
9863           total_offset += offset;
9864           if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
9865             {
9866               // Go up until we reach the original base.
9867               farg = struct_expr->field_reference_expression();
9868               continue;
9869             }
9870           break;
9871         }
9872       mpz_t zval;
9873       set_mpz_from_int64(&zval, total_offset);
9874       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9875       mpz_clear(zval);
9876       return true;
9877     }
9878   else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
9879     {
9880       Expression* arg = this->one_arg();
9881       if (arg == NULL)
9882 	return false;
9883 
9884       Numeric_constant argnc;
9885       if (!arg->numeric_constant_value(&argnc))
9886 	return false;
9887 
9888       mpc_t val;
9889       if (!argnc.to_complex(&val))
9890 	return false;
9891 
9892       Type* type = Builtin_call_expression::real_imag_type(argnc.type());
9893       if (this->code_ == BUILTIN_REAL)
9894 	nc->set_float(type, mpc_realref(val));
9895       else
9896 	nc->set_float(type, mpc_imagref(val));
9897       mpc_clear(val);
9898       return true;
9899     }
9900   else if (this->code_ == BUILTIN_COMPLEX)
9901     {
9902       const Expression_list* args = this->args();
9903       if (args == NULL || args->size() != 2)
9904 	return false;
9905 
9906       Numeric_constant rnc;
9907       if (!args->front()->numeric_constant_value(&rnc))
9908 	return false;
9909       Numeric_constant inc;
9910       if (!args->back()->numeric_constant_value(&inc))
9911 	return false;
9912 
9913       if (rnc.type() != NULL
9914 	  && !rnc.type()->is_abstract()
9915 	  && inc.type() != NULL
9916 	  && !inc.type()->is_abstract()
9917 	  && !Type::are_identical(rnc.type(), inc.type(),
9918 				  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
9919 				  NULL))
9920 	return false;
9921 
9922       mpfr_t r;
9923       if (!rnc.to_float(&r))
9924 	return false;
9925       mpfr_t i;
9926       if (!inc.to_float(&i))
9927 	{
9928 	  mpfr_clear(r);
9929 	  return false;
9930 	}
9931 
9932       Type* arg_type = rnc.type();
9933       if (arg_type == NULL || arg_type->is_abstract())
9934 	arg_type = inc.type();
9935 
9936       mpc_t val;
9937       mpc_init2(val, mpc_precision);
9938       mpc_set_fr_fr(val, r, i, MPC_RNDNN);
9939       mpfr_clear(r);
9940       mpfr_clear(i);
9941 
9942       Type* type = Builtin_call_expression::complex_type(arg_type);
9943       nc->set_complex(type, val);
9944 
9945       mpc_clear(val);
9946 
9947       return true;
9948     }
9949 
9950   return false;
9951 }
9952 
9953 // Give an error if we are discarding the value of an expression which
9954 // should not normally be discarded.  We don't give an error for
9955 // discarding the value of an ordinary function call, but we do for
9956 // builtin functions, purely for consistency with the gc compiler.
9957 
9958 bool
do_discarding_value()9959 Builtin_call_expression::do_discarding_value()
9960 {
9961   switch (this->code_)
9962     {
9963     case BUILTIN_INVALID:
9964     default:
9965       go_unreachable();
9966 
9967     case BUILTIN_APPEND:
9968     case BUILTIN_CAP:
9969     case BUILTIN_COMPLEX:
9970     case BUILTIN_IMAG:
9971     case BUILTIN_LEN:
9972     case BUILTIN_MAKE:
9973     case BUILTIN_NEW:
9974     case BUILTIN_REAL:
9975     case BUILTIN_ADD:
9976     case BUILTIN_ALIGNOF:
9977     case BUILTIN_OFFSETOF:
9978     case BUILTIN_SIZEOF:
9979     case BUILTIN_SLICE:
9980       this->unused_value_error();
9981       return false;
9982 
9983     case BUILTIN_CLOSE:
9984     case BUILTIN_COPY:
9985     case BUILTIN_DELETE:
9986     case BUILTIN_PANIC:
9987     case BUILTIN_PRINT:
9988     case BUILTIN_PRINTLN:
9989     case BUILTIN_RECOVER:
9990       return true;
9991     }
9992 }
9993 
9994 // Return the type.
9995 
9996 Type*
do_type()9997 Builtin_call_expression::do_type()
9998 {
9999   if (this->is_error_expression())
10000     return Type::make_error_type();
10001   switch (this->code_)
10002     {
10003     case BUILTIN_INVALID:
10004     default:
10005       return Type::make_error_type();
10006 
10007     case BUILTIN_NEW:
10008       {
10009 	const Expression_list* args = this->args();
10010 	if (args == NULL || args->empty())
10011 	  return Type::make_error_type();
10012 	return Type::make_pointer_type(args->front()->type());
10013       }
10014 
10015     case BUILTIN_MAKE:
10016       {
10017 	const Expression_list* args = this->args();
10018 	if (args == NULL || args->empty())
10019 	  return Type::make_error_type();
10020 	return args->front()->type();
10021       }
10022 
10023     case BUILTIN_CAP:
10024     case BUILTIN_COPY:
10025     case BUILTIN_LEN:
10026       return Type::lookup_integer_type("int");
10027 
10028     case BUILTIN_ALIGNOF:
10029     case BUILTIN_OFFSETOF:
10030     case BUILTIN_SIZEOF:
10031       return Type::lookup_integer_type("uintptr");
10032 
10033     case BUILTIN_CLOSE:
10034     case BUILTIN_DELETE:
10035     case BUILTIN_PANIC:
10036     case BUILTIN_PRINT:
10037     case BUILTIN_PRINTLN:
10038       return Type::make_void_type();
10039 
10040     case BUILTIN_RECOVER:
10041       return Type::make_empty_interface_type(Linemap::predeclared_location());
10042 
10043     case BUILTIN_APPEND:
10044       {
10045 	const Expression_list* args = this->args();
10046 	if (args == NULL || args->empty())
10047 	  return Type::make_error_type();
10048 	Type *ret = args->front()->type();
10049 	if (!ret->is_slice_type())
10050 	  return Type::make_error_type();
10051 	return ret;
10052       }
10053 
10054     case BUILTIN_REAL:
10055     case BUILTIN_IMAG:
10056       {
10057 	Expression* arg = this->one_arg();
10058 	if (arg == NULL)
10059 	  return Type::make_error_type();
10060 	Type* t = arg->type();
10061 	if (t->is_abstract())
10062 	  t = t->make_non_abstract_type();
10063 	t = Builtin_call_expression::real_imag_type(t);
10064 	if (t == NULL)
10065 	  t = Type::make_error_type();
10066 	return t;
10067       }
10068 
10069     case BUILTIN_COMPLEX:
10070       {
10071 	const Expression_list* args = this->args();
10072 	if (args == NULL || args->size() != 2)
10073 	  return Type::make_error_type();
10074 	Type* t = args->front()->type();
10075 	if (t->is_abstract())
10076 	  {
10077 	    t = args->back()->type();
10078 	    if (t->is_abstract())
10079 	      t = t->make_non_abstract_type();
10080 	  }
10081 	t = Builtin_call_expression::complex_type(t);
10082 	if (t == NULL)
10083 	  t = Type::make_error_type();
10084 	return t;
10085       }
10086 
10087     case BUILTIN_ADD:
10088       return Type::make_pointer_type(Type::make_void_type());
10089 
10090     case BUILTIN_SLICE:
10091       const Expression_list* args = this->args();
10092       if (args == NULL || args->size() != 2)
10093 	return Type::make_error_type();
10094       Type* pt = args->front()->type()->points_to();
10095       if (pt == NULL)
10096 	return Type::make_error_type();
10097       return Type::make_array_type(pt, NULL);
10098     }
10099 }
10100 
10101 // Determine the type.
10102 
10103 void
do_determine_type(const Type_context * context)10104 Builtin_call_expression::do_determine_type(const Type_context* context)
10105 {
10106   if (!this->determining_types())
10107     return;
10108 
10109   this->fn()->determine_type_no_context();
10110 
10111   const Expression_list* args = this->args();
10112 
10113   bool is_print;
10114   Type* arg_type = NULL;
10115   Type* trailing_arg_types = NULL;
10116   switch (this->code_)
10117     {
10118     case BUILTIN_PRINT:
10119     case BUILTIN_PRINTLN:
10120       // Do not force a large integer constant to "int".
10121       is_print = true;
10122       break;
10123 
10124     case BUILTIN_REAL:
10125     case BUILTIN_IMAG:
10126       arg_type = Builtin_call_expression::complex_type(context->type);
10127       if (arg_type == NULL)
10128 	arg_type = Type::lookup_complex_type("complex128");
10129       is_print = false;
10130       break;
10131 
10132     case BUILTIN_COMPLEX:
10133       {
10134 	// For the complex function the type of one operand can
10135 	// determine the type of the other, as in a binary expression.
10136 	arg_type = Builtin_call_expression::real_imag_type(context->type);
10137 	if (arg_type == NULL)
10138 	  arg_type = Type::lookup_float_type("float64");
10139 	if (args != NULL && args->size() == 2)
10140 	  {
10141 	    Type* t1 = args->front()->type();
10142 	    Type* t2 = args->back()->type();
10143 	    if (!t1->is_abstract())
10144 	      arg_type = t1;
10145 	    else if (!t2->is_abstract())
10146 	      arg_type = t2;
10147 	  }
10148 	is_print = false;
10149       }
10150       break;
10151 
10152     case BUILTIN_APPEND:
10153       if (!this->is_varargs()
10154 	  && args != NULL
10155 	  && !args->empty()
10156 	  && args->front()->type()->is_slice_type())
10157 	trailing_arg_types =
10158 	  args->front()->type()->array_type()->element_type();
10159       is_print = false;
10160       break;
10161 
10162     case BUILTIN_ADD:
10163     case BUILTIN_SLICE:
10164       // Both unsafe.Add and unsafe.Slice take two arguments, and the
10165       // second arguments defaults to "int".
10166       if (args != NULL && args->size() == 2)
10167 	{
10168 	  if (this->code_ == BUILTIN_SLICE)
10169 	    args->front()->determine_type_no_context();
10170 	  else
10171 	    {
10172 	      Type* pointer = Type::make_pointer_type(Type::make_void_type());
10173 	      Type_context subcontext(pointer, false);
10174 	      args->front()->determine_type(&subcontext);
10175 	    }
10176 	  Type* int_type = Type::lookup_integer_type("int");
10177 	  Type_context subcontext(int_type, false);
10178 	  args->back()->determine_type(&subcontext);
10179 	  return;
10180 	}
10181       is_print = false;
10182       break;
10183 
10184     default:
10185       is_print = false;
10186       break;
10187     }
10188 
10189   if (args != NULL)
10190     {
10191       for (Expression_list::const_iterator pa = args->begin();
10192 	   pa != args->end();
10193 	   ++pa)
10194 	{
10195 	  Type_context subcontext;
10196 	  subcontext.type = arg_type;
10197 
10198 	  if (is_print)
10199 	    {
10200 	      // We want to print large constants, we so can't just
10201 	      // use the appropriate nonabstract type.  Use uint64 for
10202 	      // an integer if we know it is nonnegative, otherwise
10203 	      // use int64 for a integer, otherwise use float64 for a
10204 	      // float or complex128 for a complex.
10205 	      Type* want_type = NULL;
10206 	      Type* atype = (*pa)->type();
10207 	      if (atype->is_abstract())
10208 		{
10209 		  if (atype->integer_type() != NULL)
10210 		    {
10211 		      Numeric_constant nc;
10212 		      if (this->numeric_constant_value(&nc))
10213 			{
10214 			  mpz_t val;
10215 			  if (nc.to_int(&val))
10216 			    {
10217 			      if (mpz_sgn(val) >= 0)
10218 				want_type = Type::lookup_integer_type("uint64");
10219 			      mpz_clear(val);
10220 			    }
10221 			}
10222 		      if (want_type == NULL)
10223 			want_type = Type::lookup_integer_type("int64");
10224 		    }
10225 		  else if (atype->float_type() != NULL)
10226 		    want_type = Type::lookup_float_type("float64");
10227 		  else if (atype->complex_type() != NULL)
10228 		    want_type = Type::lookup_complex_type("complex128");
10229 		  else if (atype->is_abstract_string_type())
10230 		    want_type = Type::lookup_string_type();
10231 		  else if (atype->is_abstract_boolean_type())
10232 		    want_type = Type::lookup_bool_type();
10233 		  else
10234 		    go_unreachable();
10235 		  subcontext.type = want_type;
10236 		}
10237 	    }
10238 
10239 	  (*pa)->determine_type(&subcontext);
10240 
10241 	  if (trailing_arg_types != NULL)
10242 	    {
10243 	      arg_type = trailing_arg_types;
10244 	      trailing_arg_types = NULL;
10245 	    }
10246 	}
10247     }
10248 }
10249 
10250 // If there is exactly one argument, return true.  Otherwise give an
10251 // error message and return false.
10252 
10253 bool
check_one_arg()10254 Builtin_call_expression::check_one_arg()
10255 {
10256   const Expression_list* args = this->args();
10257   if (args == NULL || args->size() < 1)
10258     {
10259       this->report_error(_("not enough arguments"));
10260       return false;
10261     }
10262   else if (args->size() > 1)
10263     {
10264       this->report_error(_("too many arguments"));
10265       return false;
10266     }
10267   if (args->front()->is_error_expression()
10268       || args->front()->type()->is_error())
10269     {
10270       this->set_is_error();
10271       return false;
10272     }
10273   return true;
10274 }
10275 
10276 // Check argument types for a builtin function.
10277 
10278 void
do_check_types(Gogo *)10279 Builtin_call_expression::do_check_types(Gogo*)
10280 {
10281   if (this->is_error_expression())
10282     return;
10283   switch (this->code_)
10284     {
10285     case BUILTIN_INVALID:
10286     case BUILTIN_NEW:
10287     case BUILTIN_MAKE:
10288     case BUILTIN_DELETE:
10289       return;
10290 
10291     case BUILTIN_LEN:
10292     case BUILTIN_CAP:
10293       {
10294 	// The single argument may be either a string or an array or a
10295 	// map or a channel, or a pointer to a closed array.
10296 	if (this->check_one_arg())
10297 	  {
10298 	    Type* arg_type = this->one_arg()->type();
10299 	    if (arg_type->points_to() != NULL
10300 		&& arg_type->points_to()->array_type() != NULL
10301 		&& !arg_type->points_to()->is_slice_type())
10302 	      arg_type = arg_type->points_to();
10303 	    if (this->code_ == BUILTIN_CAP)
10304 	      {
10305 		if (!arg_type->is_error()
10306 		    && arg_type->array_type() == NULL
10307 		    && arg_type->channel_type() == NULL)
10308 		  this->report_error(_("argument must be array or slice "
10309 				       "or channel"));
10310 	      }
10311 	    else
10312 	      {
10313 		if (!arg_type->is_error()
10314 		    && !arg_type->is_string_type()
10315 		    && arg_type->array_type() == NULL
10316 		    && arg_type->map_type() == NULL
10317 		    && arg_type->channel_type() == NULL)
10318 		  this->report_error(_("argument must be string or "
10319 				       "array or slice or map or channel"));
10320 	      }
10321 	  }
10322       }
10323       break;
10324 
10325     case BUILTIN_PRINT:
10326     case BUILTIN_PRINTLN:
10327       {
10328 	const Expression_list* args = this->args();
10329 	if (args == NULL)
10330 	  {
10331 	    if (this->code_ == BUILTIN_PRINT)
10332 	      go_warning_at(this->location(), 0,
10333 			 "no arguments for built-in function %<%s%>",
10334 			 (this->code_ == BUILTIN_PRINT
10335 			  ? "print"
10336 			  : "println"));
10337 	  }
10338 	else
10339 	  {
10340 	    for (Expression_list::const_iterator p = args->begin();
10341 		 p != args->end();
10342 		 ++p)
10343 	      {
10344 		Type* type = (*p)->type();
10345 		if (type->is_error()
10346 		    || type->is_string_type()
10347 		    || type->integer_type() != NULL
10348 		    || type->float_type() != NULL
10349 		    || type->complex_type() != NULL
10350 		    || type->is_boolean_type()
10351 		    || type->points_to() != NULL
10352 		    || type->interface_type() != NULL
10353 		    || type->channel_type() != NULL
10354 		    || type->map_type() != NULL
10355 		    || type->function_type() != NULL
10356 		    || type->is_slice_type())
10357 		  ;
10358 		else if ((*p)->is_type_expression())
10359 		  {
10360 		    // If this is a type expression it's going to give
10361 		    // an error anyhow, so we don't need one here.
10362 		  }
10363 		else
10364 		  this->report_error(_("unsupported argument type to "
10365 				       "builtin function"));
10366 	      }
10367 	  }
10368       }
10369       break;
10370 
10371     case BUILTIN_CLOSE:
10372       if (this->check_one_arg())
10373 	{
10374 	  if (this->one_arg()->type()->channel_type() == NULL)
10375 	    this->report_error(_("argument must be channel"));
10376 	  else if (!this->one_arg()->type()->channel_type()->may_send())
10377 	    this->report_error(_("cannot close receive-only channel"));
10378 	}
10379       break;
10380 
10381     case BUILTIN_PANIC:
10382     case BUILTIN_SIZEOF:
10383     case BUILTIN_ALIGNOF:
10384       this->check_one_arg();
10385       break;
10386 
10387     case BUILTIN_RECOVER:
10388       if (this->args() != NULL
10389 	  && !this->args()->empty()
10390 	  && !this->recover_arg_is_set_)
10391 	this->report_error(_("too many arguments"));
10392       break;
10393 
10394     case BUILTIN_OFFSETOF:
10395       if (this->check_one_arg())
10396 	{
10397 	  Expression* arg = this->one_arg();
10398 	  if (arg->field_reference_expression() == NULL)
10399 	    this->report_error(_("argument must be a field reference"));
10400 	}
10401       break;
10402 
10403     case BUILTIN_COPY:
10404       {
10405 	const Expression_list* args = this->args();
10406 	if (args == NULL || args->size() < 2)
10407 	  {
10408 	    this->report_error(_("not enough arguments"));
10409 	    break;
10410 	  }
10411 	else if (args->size() > 2)
10412 	  {
10413 	    this->report_error(_("too many arguments"));
10414 	    break;
10415 	  }
10416 	Type* arg1_type = args->front()->type();
10417 	Type* arg2_type = args->back()->type();
10418 	if (arg1_type->is_error() || arg2_type->is_error())
10419 	  {
10420 	    this->set_is_error();
10421 	    break;
10422 	  }
10423 
10424 	Type* e1;
10425 	if (arg1_type->is_slice_type())
10426 	  e1 = arg1_type->array_type()->element_type();
10427 	else
10428 	  {
10429 	    this->report_error(_("left argument must be a slice"));
10430 	    break;
10431 	  }
10432 
10433 	if (arg2_type->is_slice_type())
10434 	  {
10435 	    Type* e2 = arg2_type->array_type()->element_type();
10436 	    if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
10437 	      this->report_error(_("element types must be the same"));
10438 	  }
10439 	else if (arg2_type->is_string_type())
10440 	  {
10441 	    if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
10442 	      this->report_error(_("first argument must be []byte"));
10443 	  }
10444 	else
10445 	    this->report_error(_("second argument must be slice or string"));
10446       }
10447       break;
10448 
10449     case BUILTIN_APPEND:
10450       {
10451 	const Expression_list* args = this->args();
10452 	if (args == NULL || args->empty())
10453 	  {
10454 	    this->report_error(_("not enough arguments"));
10455 	    break;
10456 	  }
10457 
10458 	Type* slice_type = args->front()->type();
10459 	if (!slice_type->is_slice_type())
10460 	  {
10461 	    if (slice_type->is_error_type())
10462 	      break;
10463 	    if (slice_type->is_nil_type())
10464 	      go_error_at(args->front()->location(), "use of untyped nil");
10465 	    else
10466 	      go_error_at(args->front()->location(),
10467 			  "argument 1 must be a slice");
10468 	    this->set_is_error();
10469 	    break;
10470 	  }
10471 
10472 	Type* element_type = slice_type->array_type()->element_type();
10473 	if (!element_type->in_heap())
10474 	  go_error_at(args->front()->location(),
10475 		      "cannot append to slice of go:notinheap type");
10476 	if (this->is_varargs())
10477 	  {
10478 	    if (!args->back()->type()->is_slice_type()
10479 		&& !args->back()->type()->is_string_type())
10480 	      {
10481 		go_error_at(args->back()->location(),
10482 			    "invalid use of %<...%> with non-slice/non-string");
10483 		this->set_is_error();
10484 		break;
10485 	      }
10486 
10487 	    if (args->size() < 2)
10488 	      {
10489 		this->report_error(_("not enough arguments"));
10490 		break;
10491 	      }
10492 	    if (args->size() > 2)
10493 	      {
10494 		this->report_error(_("too many arguments"));
10495 		break;
10496 	      }
10497 
10498 	    if (args->back()->type()->is_string_type()
10499 		&& element_type->integer_type() != NULL
10500 		&& element_type->integer_type()->is_byte())
10501 	      {
10502 		// Permit append(s1, s2...) when s1 is a slice of
10503 		// bytes and s2 is a string type.
10504 	      }
10505 	    else
10506 	      {
10507 		// We have to test for assignment compatibility to a
10508 		// slice of the element type, which is not necessarily
10509 		// the same as the type of the first argument: the
10510 		// first argument might have a named type.
10511 		Type* check_type = Type::make_array_type(element_type, NULL);
10512 		std::string reason;
10513 		if (!Type::are_assignable(check_type, args->back()->type(),
10514 					  &reason))
10515 		  {
10516 		    if (reason.empty())
10517 		      go_error_at(args->back()->location(),
10518 				  "argument 2 has invalid type");
10519 		    else
10520 		      go_error_at(args->back()->location(),
10521 				  "argument 2 has invalid type (%s)",
10522 				  reason.c_str());
10523 		    this->set_is_error();
10524 		    break;
10525 		  }
10526 	      }
10527 	  }
10528 	else
10529 	  {
10530 	    Expression_list::const_iterator pa = args->begin();
10531 	    int i = 2;
10532 	    for (++pa; pa != args->end(); ++pa, ++i)
10533 	      {
10534 		std::string reason;
10535 		if (!Type::are_assignable(element_type, (*pa)->type(),
10536 					  &reason))
10537 		  {
10538 		    if (reason.empty())
10539 		      go_error_at((*pa)->location(),
10540 				  "argument %d has incompatible type", i);
10541 		    else
10542 		      go_error_at((*pa)->location(),
10543 				  "argument %d has incompatible type (%s)",
10544 				  i, reason.c_str());
10545 		    this->set_is_error();
10546 		  }
10547 	      }
10548 	  }
10549       }
10550       break;
10551 
10552     case BUILTIN_REAL:
10553     case BUILTIN_IMAG:
10554       if (this->check_one_arg())
10555 	{
10556 	  if (this->one_arg()->type()->complex_type() == NULL)
10557 	    this->report_error(_("argument must have complex type"));
10558 	}
10559       break;
10560 
10561     case BUILTIN_COMPLEX:
10562       {
10563 	const Expression_list* args = this->args();
10564 	if (args == NULL || args->size() < 2)
10565 	  this->report_error(_("not enough arguments"));
10566 	else if (args->size() > 2)
10567 	  this->report_error(_("too many arguments"));
10568 	else if (args->front()->is_error_expression()
10569 		 || args->front()->type()->is_error()
10570 		 || args->back()->is_error_expression()
10571 		 || args->back()->type()->is_error())
10572 	  this->set_is_error();
10573 	else if (!Type::are_identical(args->front()->type(),
10574 				      args->back()->type(),
10575 				      Type::COMPARE_TAGS, NULL))
10576 	  this->report_error(_("complex arguments must have identical types"));
10577 	else if (args->front()->type()->float_type() == NULL)
10578 	  this->report_error(_("complex arguments must have "
10579 			       "floating-point type"));
10580       }
10581       break;
10582 
10583     case BUILTIN_ADD:
10584     case BUILTIN_SLICE:
10585       {
10586 	Numeric_constant nc;
10587 	unsigned long v;
10588 	const Expression_list* args = this->args();
10589 	if (args == NULL || args->size() < 2)
10590 	  this->report_error(_("not enough arguments"));
10591 	else if (args->size() > 2)
10592 	  this->report_error(_("too many arguments"));
10593 	else if (args->front()->is_error_expression()
10594 		 || args->front()->type()->is_error()
10595 		 || args->back()->is_error_expression()
10596 		 || args->back()->type()->is_error())
10597 	  this->set_is_error();
10598 	else if (args->back()->type()->integer_type() == NULL
10599 		 && (!args->back()->type()->is_abstract()
10600 		     || !args->back()->numeric_constant_value(&nc)
10601 		     || (nc.to_unsigned_long(&v)
10602 			 == Numeric_constant::NC_UL_NOTINT)))
10603 	  {
10604 	    if (this->code_ == BUILTIN_ADD)
10605 	      go_error_at(args->back()->location(), "non-integer offset");
10606 	    else
10607 	      go_error_at(args->back()->location(), "non-integer size");
10608 	  }
10609 	else if (this->code_ == BUILTIN_ADD)
10610 	  {
10611 	    Type* pointer_type =
10612 	      Type::make_pointer_type(Type::make_void_type());
10613 	    std::string reason;
10614 	    if (!Type::are_assignable(pointer_type, args->front()->type(),
10615 				      &reason))
10616 	      {
10617 		if (reason.empty())
10618 		  go_error_at(args->front()->location(),
10619 			      "argument 1 has incompatible type");
10620 		else
10621 		  go_error_at(args->front()->location(),
10622 			      "argument 1 has incompatible type (%s)",
10623 			      reason.c_str());
10624 		this->set_is_error();
10625 	      }
10626 	  }
10627 	else
10628 	  {
10629 	    if (args->front()->type()->points_to() == NULL)
10630 	      {
10631 		go_error_at(args->front()->location(),
10632 			    "argument 1 must be a pointer");
10633 		this->set_is_error();
10634 	      }
10635 
10636 	    unsigned int int_bits =
10637 	      Type::lookup_integer_type("int")->integer_type()->bits();
10638 
10639 	    mpz_t ival;
10640 	    if (args->back()->numeric_constant_value(&nc) && nc.to_int(&ival))
10641 	      {
10642 		if (mpz_sgn(ival) < 0
10643 		    || mpz_sizeinbase(ival, 2) >= int_bits)
10644 		  {
10645 		    go_error_at(args->back()->location(),
10646 				"slice length out of range");
10647 		    this->set_is_error();
10648 		  }
10649 		mpz_clear(ival);
10650 	      }
10651 	  }
10652       }
10653       break;
10654 
10655     default:
10656       go_unreachable();
10657     }
10658 }
10659 
10660 Expression*
do_copy()10661 Builtin_call_expression::do_copy()
10662 {
10663   Call_expression* bce =
10664     new Builtin_call_expression(this->gogo_, this->fn()->copy(),
10665 				(this->args() == NULL
10666 				 ? NULL
10667 				 : this->args()->copy()),
10668 				this->is_varargs(),
10669 				this->location());
10670 
10671   if (this->varargs_are_lowered())
10672     bce->set_varargs_are_lowered();
10673   if (this->is_deferred())
10674     bce->set_is_deferred();
10675   if (this->is_concurrent())
10676     bce->set_is_concurrent();
10677   return bce;
10678 }
10679 
10680 // Return the backend representation for a builtin function.
10681 
10682 Bexpression*
do_get_backend(Translate_context * context)10683 Builtin_call_expression::do_get_backend(Translate_context* context)
10684 {
10685   Gogo* gogo = context->gogo();
10686   Location location = this->location();
10687 
10688   if (this->is_erroneous_call())
10689     {
10690       go_assert(saw_errors());
10691       return gogo->backend()->error_expression();
10692     }
10693 
10694   switch (this->code_)
10695     {
10696     case BUILTIN_INVALID:
10697     case BUILTIN_NEW:
10698     case BUILTIN_MAKE:
10699     case BUILTIN_ADD:
10700     case BUILTIN_SLICE:
10701       go_unreachable();
10702 
10703     case BUILTIN_LEN:
10704     case BUILTIN_CAP:
10705       {
10706 	const Expression_list* args = this->args();
10707 	go_assert(args != NULL && args->size() == 1);
10708 	Expression* arg = args->front();
10709 	Type* arg_type = arg->type();
10710 
10711 	if (this->seen_)
10712 	  {
10713 	    go_assert(saw_errors());
10714 	    return context->backend()->error_expression();
10715 	  }
10716 	this->seen_ = true;
10717 	this->seen_ = false;
10718 	if (arg_type->points_to() != NULL)
10719 	  {
10720 	    arg_type = arg_type->points_to();
10721 	    go_assert(arg_type->array_type() != NULL
10722 		       && !arg_type->is_slice_type());
10723             arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
10724                                                location);
10725 	  }
10726 
10727 	Type* int_type = Type::lookup_integer_type("int");
10728         Expression* val;
10729 	if (this->code_ == BUILTIN_LEN)
10730 	  {
10731 	    if (arg_type->is_string_type())
10732 	      val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
10733 						 location);
10734 	    else if (arg_type->array_type() != NULL)
10735 	      {
10736 		if (this->seen_)
10737 		  {
10738 		    go_assert(saw_errors());
10739 		    return context->backend()->error_expression();
10740 		  }
10741 		this->seen_ = true;
10742 	        val = arg_type->array_type()->get_length(gogo, arg);
10743 		this->seen_ = false;
10744 	      }
10745 	    else if (arg_type->map_type() != NULL
10746 		     || arg_type->channel_type() != NULL)
10747 	      {
10748 		// The first field is the length.  If the pointer is
10749 		// nil, the length is zero.
10750 		Type* pint_type = Type::make_pointer_type(int_type);
10751 		arg = Expression::make_unsafe_cast(pint_type, arg, location);
10752 		Expression* nil = Expression::make_nil(location);
10753 		nil = Expression::make_cast(pint_type, nil, location);
10754 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10755 							  arg, nil, location);
10756 		Expression* zero = Expression::make_integer_ul(0, int_type,
10757 							       location);
10758                 Expression* indir =
10759                     Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
10760                                                  location);
10761 		val = Expression::make_conditional(cmp, zero, indir, location);
10762 	      }
10763 	    else
10764 	      go_unreachable();
10765 	  }
10766 	else
10767 	  {
10768 	    if (arg_type->array_type() != NULL)
10769 	      {
10770 		if (this->seen_)
10771 		  {
10772 		    go_assert(saw_errors());
10773 		    return context->backend()->error_expression();
10774 		  }
10775 		this->seen_ = true;
10776                 val = arg_type->array_type()->get_capacity(gogo, arg);
10777 		this->seen_ = false;
10778 	      }
10779 	    else if (arg_type->channel_type() != NULL)
10780 	      {
10781 		// The second field is the capacity.  If the pointer
10782 		// is nil, the capacity is zero.
10783 		Type* uintptr_type = Type::lookup_integer_type("uintptr");
10784 		Type* pint_type = Type::make_pointer_type(int_type);
10785 		Expression* parg = Expression::make_unsafe_cast(uintptr_type,
10786 								arg,
10787 								location);
10788 		int off = int_type->integer_type()->bits() / 8;
10789 		Expression* eoff = Expression::make_integer_ul(off,
10790 							       uintptr_type,
10791 							       location);
10792 		parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
10793 					       location);
10794 		parg = Expression::make_unsafe_cast(pint_type, parg, location);
10795 		Expression* nil = Expression::make_nil(location);
10796 		nil = Expression::make_cast(pint_type, nil, location);
10797 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10798 							  arg, nil, location);
10799 		Expression* zero = Expression::make_integer_ul(0, int_type,
10800 							       location);
10801                 Expression* indir =
10802                     Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
10803                                                  location);
10804 		val = Expression::make_conditional(cmp, zero, indir, location);
10805 	      }
10806 	    else
10807 	      go_unreachable();
10808 	  }
10809 
10810 	return Expression::make_cast(int_type, val,
10811 				     location)->get_backend(context);
10812       }
10813 
10814     case BUILTIN_PRINT:
10815     case BUILTIN_PRINTLN:
10816       {
10817 	const bool is_ln = this->code_ == BUILTIN_PRINTLN;
10818 
10819 	Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
10820 						     location, 0);
10821 
10822 	const Expression_list* call_args = this->args();
10823 	if (call_args != NULL)
10824 	  {
10825 	    for (Expression_list::const_iterator p = call_args->begin();
10826 		 p != call_args->end();
10827 		 ++p)
10828 	      {
10829 		if (is_ln && p != call_args->begin())
10830 		  {
10831                     Expression* print_space =
10832 		      Runtime::make_call(Runtime::PRINTSP, location, 0);
10833 
10834                     print_stmts =
10835                         Expression::make_compound(print_stmts, print_space,
10836                                                   location);
10837 		  }
10838 
10839                 Expression* arg = *p;
10840 		Type* type = arg->type();
10841                 Runtime::Function code;
10842 		if (type->is_string_type())
10843                   code = Runtime::PRINTSTRING;
10844 		else if (type->integer_type() != NULL
10845 			 && type->integer_type()->is_unsigned())
10846 		  {
10847 		    Type* itype = Type::lookup_integer_type("uint64");
10848 		    arg = Expression::make_cast(itype, arg, location);
10849                     if (gogo->compiling_runtime()
10850                         && type->named_type() != NULL
10851                         && gogo->unpack_hidden_name(type->named_type()->name())
10852                            == "hex")
10853                       code = Runtime::PRINTHEX;
10854                     else
10855                       code = Runtime::PRINTUINT;
10856 		  }
10857 		else if (type->integer_type() != NULL)
10858 		  {
10859 		    Type* itype = Type::lookup_integer_type("int64");
10860 		    arg = Expression::make_cast(itype, arg, location);
10861                     code = Runtime::PRINTINT;
10862 		  }
10863 		else if (type->float_type() != NULL)
10864 		  {
10865                     Type* dtype = Type::lookup_float_type("float64");
10866                     arg = Expression::make_cast(dtype, arg, location);
10867                     code = Runtime::PRINTFLOAT;
10868 		  }
10869 		else if (type->complex_type() != NULL)
10870 		  {
10871                     Type* ctype = Type::lookup_complex_type("complex128");
10872                     arg = Expression::make_cast(ctype, arg, location);
10873                     code = Runtime::PRINTCOMPLEX;
10874 		  }
10875 		else if (type->is_boolean_type())
10876                   code = Runtime::PRINTBOOL;
10877 		else if (type->points_to() != NULL
10878 			 || type->channel_type() != NULL
10879 			 || type->map_type() != NULL
10880 			 || type->function_type() != NULL)
10881 		  {
10882                     arg = Expression::make_cast(type, arg, location);
10883                     code = Runtime::PRINTPOINTER;
10884 		  }
10885 		else if (type->interface_type() != NULL)
10886 		  {
10887 		    if (type->interface_type()->is_empty())
10888                       code = Runtime::PRINTEFACE;
10889 		    else
10890                       code = Runtime::PRINTIFACE;
10891 		  }
10892 		else if (type->is_slice_type())
10893                   code = Runtime::PRINTSLICE;
10894 		else
10895 		  {
10896 		    go_assert(saw_errors());
10897 		    return context->backend()->error_expression();
10898 		  }
10899 
10900                 Expression* call = Runtime::make_call(code, location, 1, arg);
10901 		print_stmts = Expression::make_compound(print_stmts, call,
10902 							location);
10903 	      }
10904 	  }
10905 
10906 	if (is_ln)
10907 	  {
10908             Expression* print_nl =
10909                 Runtime::make_call(Runtime::PRINTNL, location, 0);
10910 	    print_stmts = Expression::make_compound(print_stmts, print_nl,
10911 						    location);
10912 	  }
10913 
10914 	Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
10915 						location, 0);
10916 	print_stmts = Expression::make_compound(print_stmts, unlock, location);
10917 
10918         return print_stmts->get_backend(context);
10919       }
10920 
10921     case BUILTIN_PANIC:
10922       {
10923 	const Expression_list* args = this->args();
10924 	go_assert(args != NULL && args->size() == 1);
10925 	Expression* arg = args->front();
10926 	Type *empty =
10927 	  Type::make_empty_interface_type(Linemap::predeclared_location());
10928         arg = Expression::convert_for_assignment(gogo, empty, arg, location);
10929 
10930         Expression* panic =
10931             Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
10932         return panic->get_backend(context);
10933       }
10934 
10935     case BUILTIN_RECOVER:
10936       {
10937 	// The argument is set when building recover thunks.  It's a
10938 	// boolean value which is true if we can recover a value now.
10939 	const Expression_list* args = this->args();
10940 	go_assert(args != NULL && args->size() == 1);
10941 	Expression* arg = args->front();
10942 	Type *empty =
10943 	  Type::make_empty_interface_type(Linemap::predeclared_location());
10944 
10945 	Expression* nil = Expression::make_nil(location);
10946         nil = Expression::make_interface_value(empty, nil, nil, location);
10947 
10948 	// We need to handle a deferred call to recover specially,
10949 	// because it changes whether it can recover a panic or not.
10950 	// See test7 in test/recover1.go.
10951         Expression* recover = Runtime::make_call((this->is_deferred()
10952                                                   ? Runtime::DEFERREDRECOVER
10953                                                   : Runtime::GORECOVER),
10954                                                  location, 0);
10955         Expression* cond =
10956             Expression::make_conditional(arg, recover, nil, location);
10957         return cond->get_backend(context);
10958       }
10959 
10960     case BUILTIN_CLOSE:
10961       {
10962 	const Expression_list* args = this->args();
10963 	go_assert(args != NULL && args->size() == 1);
10964 	Expression* arg = args->front();
10965         Expression* close = Runtime::make_call(Runtime::CLOSE, location,
10966 					       1, arg);
10967         return close->get_backend(context);
10968       }
10969 
10970     case BUILTIN_SIZEOF:
10971     case BUILTIN_OFFSETOF:
10972     case BUILTIN_ALIGNOF:
10973       {
10974 	Numeric_constant nc;
10975 	unsigned long val;
10976 	if (!this->numeric_constant_value(&nc)
10977 	    || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
10978 	  {
10979 	    go_assert(saw_errors());
10980 	    return context->backend()->error_expression();
10981 	  }
10982 	Type* uintptr_type = Type::lookup_integer_type("uintptr");
10983         mpz_t ival;
10984         nc.get_int(&ival);
10985         Expression* int_cst =
10986             Expression::make_integer_z(&ival, uintptr_type, location);
10987         mpz_clear(ival);
10988         return int_cst->get_backend(context);
10989       }
10990 
10991     case BUILTIN_COPY:
10992       // Handled in Builtin_call_expression::do_flatten.
10993       go_unreachable();
10994 
10995     case BUILTIN_APPEND:
10996       // Handled in Builtin_call_expression::flatten_append.
10997       go_unreachable();
10998 
10999     case BUILTIN_REAL:
11000     case BUILTIN_IMAG:
11001       {
11002 	const Expression_list* args = this->args();
11003 	go_assert(args != NULL && args->size() == 1);
11004 
11005         Bexpression* ret;
11006         Bexpression* bcomplex = args->front()->get_backend(context);
11007         if (this->code_ == BUILTIN_REAL)
11008           ret = gogo->backend()->real_part_expression(bcomplex, location);
11009         else
11010           ret = gogo->backend()->imag_part_expression(bcomplex, location);
11011         return ret;
11012       }
11013 
11014     case BUILTIN_COMPLEX:
11015       {
11016 	const Expression_list* args = this->args();
11017 	go_assert(args != NULL && args->size() == 2);
11018 	Bexpression* breal = args->front()->get_backend(context);
11019 	Bexpression* bimag = args->back()->get_backend(context);
11020 	return gogo->backend()->complex_expression(breal, bimag, location);
11021       }
11022 
11023     default:
11024       go_unreachable();
11025     }
11026 }
11027 
11028 // We have to support exporting a builtin call expression, because
11029 // code can set a constant to the result of a builtin expression.
11030 
11031 void
do_export(Export_function_body * efb) const11032 Builtin_call_expression::do_export(Export_function_body* efb) const
11033 {
11034   Numeric_constant nc;
11035   if (this->numeric_constant_value(&nc))
11036     {
11037       if (nc.is_int())
11038 	{
11039 	  mpz_t val;
11040 	  nc.get_int(&val);
11041 	  Integer_expression::export_integer(efb, val);
11042 	  mpz_clear(val);
11043 	}
11044       else if (nc.is_float())
11045 	{
11046 	  mpfr_t fval;
11047 	  nc.get_float(&fval);
11048 	  Float_expression::export_float(efb, fval);
11049 	  mpfr_clear(fval);
11050 	}
11051       else if (nc.is_complex())
11052 	{
11053 	  mpc_t cval;
11054 	  nc.get_complex(&cval);
11055 	  Complex_expression::export_complex(efb, cval);
11056 	  mpc_clear(cval);
11057 	}
11058       else
11059 	go_unreachable();
11060 
11061       // A trailing space lets us reliably identify the end of the number.
11062       efb->write_c_string(" ");
11063     }
11064   else if (this->code_ == BUILTIN_ADD || this->code_ == BUILTIN_SLICE)
11065     {
11066       char buf[50];
11067       snprintf(buf, sizeof buf, "<p%d>%s", efb->unsafe_package_index(),
11068 	       (this->code_ == BUILTIN_ADD ? "Add" : "Slice"));
11069       efb->write_c_string(buf);
11070       this->export_arguments(efb);
11071     }
11072   else
11073     {
11074       const char *s = NULL;
11075       switch (this->code_)
11076 	{
11077 	default:
11078 	  go_unreachable();
11079 	case BUILTIN_APPEND:
11080 	  s = "append";
11081 	  break;
11082 	case BUILTIN_COPY:
11083 	  s = "copy";
11084 	  break;
11085 	case BUILTIN_LEN:
11086 	  s = "len";
11087 	  break;
11088 	case BUILTIN_CAP:
11089 	  s = "cap";
11090 	  break;
11091 	case BUILTIN_DELETE:
11092 	  s = "delete";
11093 	  break;
11094 	case BUILTIN_PRINT:
11095 	  s = "print";
11096 	  break;
11097 	case BUILTIN_PRINTLN:
11098 	  s = "println";
11099 	  break;
11100 	case BUILTIN_PANIC:
11101 	  s = "panic";
11102 	  break;
11103 	case BUILTIN_RECOVER:
11104 	  s = "recover";
11105 	  break;
11106 	case BUILTIN_CLOSE:
11107 	  s = "close";
11108 	  break;
11109 	case BUILTIN_REAL:
11110 	  s = "real";
11111 	  break;
11112 	case BUILTIN_IMAG:
11113 	  s = "imag";
11114 	  break;
11115 	case BUILTIN_COMPLEX:
11116 	  s = "complex";
11117 	  break;
11118 	}
11119       efb->write_c_string(s);
11120       this->export_arguments(efb);
11121     }
11122 }
11123 
11124 // Class Call_expression.
11125 
11126 // A Go function can be viewed in a couple of different ways.  The
11127 // code of a Go function becomes a backend function with parameters
11128 // whose types are simply the backend representation of the Go types.
11129 // If there are multiple results, they are returned as a backend
11130 // struct.
11131 
11132 // However, when Go code refers to a function other than simply
11133 // calling it, the backend type of that function is actually a struct.
11134 // The first field of the struct points to the Go function code
11135 // (sometimes a wrapper as described below).  The remaining fields
11136 // hold addresses of closed-over variables.  This struct is called a
11137 // closure.
11138 
11139 // There are a few cases to consider.
11140 
11141 // A direct function call of a known function in package scope.  In
11142 // this case there are no closed-over variables, and we know the name
11143 // of the function code.  We can simply produce a backend call to the
11144 // function directly, and not worry about the closure.
11145 
11146 // A direct function call of a known function literal.  In this case
11147 // we know the function code and we know the closure.  We generate the
11148 // function code such that it expects an additional final argument of
11149 // the closure type.  We pass the closure as the last argument, after
11150 // the other arguments.
11151 
11152 // An indirect function call.  In this case we have a closure.  We
11153 // load the pointer to the function code from the first field of the
11154 // closure.  We pass the address of the closure as the last argument.
11155 
11156 // A call to a method of an interface.  Type methods are always at
11157 // package scope, so we call the function directly, and don't worry
11158 // about the closure.
11159 
11160 // This means that for a function at package scope we have two cases.
11161 // One is the direct call, which has no closure.  The other is the
11162 // indirect call, which does have a closure.  We can't simply ignore
11163 // the closure, even though it is the last argument, because that will
11164 // fail on targets where the function pops its arguments.  So when
11165 // generating a closure for a package-scope function we set the
11166 // function code pointer in the closure to point to a wrapper
11167 // function.  This wrapper function accepts a final argument that
11168 // points to the closure, ignores it, and calls the real function as a
11169 // direct function call.  This wrapper will normally be efficient, and
11170 // can often simply be a tail call to the real function.
11171 
11172 // We don't use GCC's static chain pointer because 1) we don't need
11173 // it; 2) GCC only permits using a static chain to call a known
11174 // function, so we can't use it for an indirect call anyhow.  Since we
11175 // can't use it for an indirect call, we may as well not worry about
11176 // using it for a direct call either.
11177 
11178 // We pass the closure last rather than first because it means that
11179 // the function wrapper we put into a closure for a package-scope
11180 // function can normally just be a tail call to the real function.
11181 
11182 // For method expressions we generate a wrapper that loads the
11183 // receiver from the closure and then calls the method.  This
11184 // unfortunately forces reshuffling the arguments, since there is a
11185 // new first argument, but we can't avoid reshuffling either for
11186 // method expressions or for indirect calls of package-scope
11187 // functions, and since the latter are more common we reshuffle for
11188 // method expressions.
11189 
11190 // Note that the Go code retains the Go types.  The extra final
11191 // argument only appears when we convert to the backend
11192 // representation.
11193 
11194 // Traversal.
11195 
11196 int
do_traverse(Traverse * traverse)11197 Call_expression::do_traverse(Traverse* traverse)
11198 {
11199   // If we are calling a function in a different package that returns
11200   // an unnamed type, this may be the only chance we get to traverse
11201   // that type.  We don't traverse this->type_ because it may be a
11202   // Call_multiple_result_type that will just lead back here.
11203   if (this->type_ != NULL && !this->type_->is_error_type())
11204     {
11205       Function_type *fntype = this->get_function_type();
11206       if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
11207 	return TRAVERSE_EXIT;
11208     }
11209   if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
11210     return TRAVERSE_EXIT;
11211   if (this->args_ != NULL)
11212     {
11213       if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
11214 	return TRAVERSE_EXIT;
11215     }
11216   return TRAVERSE_CONTINUE;
11217 }
11218 
11219 // Lower a call statement.
11220 
11221 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)11222 Call_expression::do_lower(Gogo* gogo, Named_object* function,
11223 			  Statement_inserter* inserter, int)
11224 {
11225   Location loc = this->location();
11226 
11227   if (this->is_error_expression())
11228     return Expression::make_error(loc);
11229 
11230   // A type cast can look like a function call.
11231   if (this->fn_->is_type_expression()
11232       && this->args_ != NULL
11233       && this->args_->size() == 1)
11234     {
11235       if (this->expected_result_count_ != 0
11236 	  && this->expected_result_count_ != 1)
11237 	{
11238 	  this->report_error(_("type conversion result count mismatch"));
11239 	  return Expression::make_error(loc);
11240 	}
11241       return Expression::make_cast(this->fn_->type(), this->args_->front(),
11242 				   loc);
11243     }
11244 
11245   // Because do_type will return an error type and thus prevent future
11246   // errors, check for that case now to ensure that the error gets
11247   // reported.
11248   Function_type* fntype = this->get_function_type();
11249   if (fntype == NULL)
11250     {
11251       if (!this->fn_->type()->is_error())
11252 	this->report_error(_("expected function"));
11253       this->set_is_error();
11254       return this;
11255     }
11256 
11257   // Handle an argument which is a call to a function which returns
11258   // multiple results.
11259   if (this->args_ != NULL
11260       && this->args_->size() == 1
11261       && this->args_->front()->call_expression() != NULL)
11262     {
11263       size_t rc = this->args_->front()->call_expression()->result_count();
11264       if (rc > 1
11265 	  && ((fntype->parameters() != NULL
11266                && (fntype->parameters()->size() == rc
11267                    || (fntype->is_varargs()
11268                        && fntype->parameters()->size() - 1 <= rc)))
11269               || fntype->is_builtin()))
11270 	{
11271 	  Call_expression* call = this->args_->front()->call_expression();
11272 	  call->set_is_multi_value_arg();
11273 	  if (this->is_varargs_)
11274 	    {
11275 	      // It is not clear which result of a multiple result call
11276 	      // the ellipsis operator should be applied to.  If we unpack the
11277 	      // the call into its individual results here, the ellipsis will be
11278 	      // applied to the last result.
11279 	      go_error_at(call->location(),
11280 			  _("multiple-value argument in single-value context"));
11281 	      return Expression::make_error(call->location());
11282 	    }
11283 
11284 	  Expression_list* args = new Expression_list;
11285 	  for (size_t i = 0; i < rc; ++i)
11286 	    args->push_back(Expression::make_call_result(call, i));
11287 	  // We can't return a new call expression here, because this
11288 	  // one may be referenced by Call_result expressions.  We
11289 	  // also can't delete the old arguments, because we may still
11290 	  // traverse them somewhere up the call stack.  FIXME.
11291 	  this->args_ = args;
11292 	}
11293     }
11294 
11295   // Recognize a call to a builtin function.
11296   if (fntype->is_builtin())
11297     {
11298       Builtin_call_expression* bce =
11299 	new Builtin_call_expression(gogo, this->fn_, this->args_,
11300 				    this->is_varargs_, loc);
11301       if (this->is_deferred_)
11302 	bce->set_is_deferred();
11303       if (this->is_concurrent_)
11304 	bce->set_is_concurrent();
11305       return bce;
11306     }
11307 
11308   // If this call returns multiple results, create a temporary
11309   // variable to hold them.
11310   if (this->result_count() > 1 && this->call_temp_ == NULL)
11311     {
11312       Struct_field_list* sfl = new Struct_field_list();
11313       const Typed_identifier_list* results = fntype->results();
11314 
11315       int i = 0;
11316       char buf[20];
11317       for (Typed_identifier_list::const_iterator p = results->begin();
11318            p != results->end();
11319            ++p, ++i)
11320         {
11321           snprintf(buf, sizeof buf, "res%d", i);
11322           sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
11323         }
11324 
11325       Struct_type* st = Type::make_struct_type(sfl, loc);
11326       st->set_is_struct_incomparable();
11327       this->call_temp_ = Statement::make_temporary(st, NULL, loc);
11328       inserter->insert(this->call_temp_);
11329     }
11330 
11331   // Handle a call to a varargs function by packaging up the extra
11332   // parameters.
11333   if (fntype->is_varargs())
11334     {
11335       const Typed_identifier_list* parameters = fntype->parameters();
11336       go_assert(parameters != NULL && !parameters->empty());
11337       Type* varargs_type = parameters->back().type();
11338       this->lower_varargs(gogo, function, inserter, varargs_type,
11339 			  parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
11340     }
11341 
11342   // If this is call to a method, call the method directly passing the
11343   // object as the first parameter.
11344   Bound_method_expression* bme = this->fn_->bound_method_expression();
11345   if (bme != NULL && !this->is_deferred_ && !this->is_concurrent_)
11346     {
11347       Named_object* methodfn = bme->function();
11348       Function_type* mft = (methodfn->is_function()
11349                             ? methodfn->func_value()->type()
11350                             : methodfn->func_declaration_value()->type());
11351       Expression* first_arg = bme->first_argument();
11352 
11353       // We always pass a pointer when calling a method, except for
11354       // direct interface types when calling a value method.
11355       if (!first_arg->type()->is_error()
11356           && first_arg->type()->points_to() == NULL
11357           && !first_arg->type()->is_direct_iface_type())
11358 	{
11359 	  first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
11360 	  // We may need to create a temporary variable so that we can
11361 	  // take the address.  We can't do that here because it will
11362 	  // mess up the order of evaluation.
11363 	  Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
11364 	  ue->set_create_temp();
11365 	}
11366       else if (mft->receiver()->type()->points_to() == NULL
11367                && first_arg->type()->points_to() != NULL
11368                && first_arg->type()->points_to()->is_direct_iface_type())
11369         first_arg = Expression::make_dereference(first_arg,
11370                                                  Expression::NIL_CHECK_DEFAULT,
11371                                                  loc);
11372 
11373       // If we are calling a method which was inherited from an
11374       // embedded struct, and the method did not get a stub, then the
11375       // first type may be wrong.
11376       Type* fatype = bme->first_argument_type();
11377       if (fatype != NULL)
11378 	{
11379 	  if (fatype->points_to() == NULL)
11380 	    fatype = Type::make_pointer_type(fatype);
11381 	  first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
11382 	}
11383 
11384       Expression_list* new_args = new Expression_list();
11385       new_args->push_back(first_arg);
11386       if (this->args_ != NULL)
11387 	{
11388 	  for (Expression_list::const_iterator p = this->args_->begin();
11389 	       p != this->args_->end();
11390 	       ++p)
11391 	    new_args->push_back(*p);
11392 	}
11393 
11394       // We have to change in place because this structure may be
11395       // referenced by Call_result_expressions.  We can't delete the
11396       // old arguments, because we may be traversing them up in some
11397       // caller.  FIXME.
11398       this->args_ = new_args;
11399       this->fn_ = Expression::make_func_reference(methodfn, NULL,
11400 						  bme->location());
11401     }
11402 
11403   // If this is a call to an imported function for which we have an
11404   // inlinable function body, add it to the list of functions to give
11405   // to the backend as inlining opportunities.
11406   Func_expression* fe = this->fn_->func_expression();
11407   if (fe != NULL
11408       && fe->named_object()->is_function_declaration()
11409       && fe->named_object()->func_declaration_value()->has_imported_body())
11410     gogo->add_imported_inlinable_function(fe->named_object());
11411 
11412   return this;
11413 }
11414 
11415 // Lower a call to a varargs function.  FUNCTION is the function in
11416 // which the call occurs--it's not the function we are calling.
11417 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
11418 // PARAM_COUNT is the number of parameters of the function we are
11419 // calling; the last of these parameters will be the varargs
11420 // parameter.
11421 
11422 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count,Slice_storage_escape_disp escape_disp)11423 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
11424 			       Statement_inserter* inserter,
11425 			       Type* varargs_type, size_t param_count,
11426                                Slice_storage_escape_disp escape_disp)
11427 {
11428   if (this->varargs_are_lowered_)
11429     return;
11430 
11431   Location loc = this->location();
11432 
11433   go_assert(param_count > 0);
11434   go_assert(varargs_type->is_slice_type());
11435 
11436   size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
11437   if (arg_count < param_count - 1)
11438     {
11439       // Not enough arguments; will be caught in check_types.
11440       return;
11441     }
11442 
11443   Expression_list* old_args = this->args_;
11444   Expression_list* new_args = new Expression_list();
11445   bool push_empty_arg = false;
11446   if (old_args == NULL || old_args->empty())
11447     {
11448       go_assert(param_count == 1);
11449       push_empty_arg = true;
11450     }
11451   else
11452     {
11453       Expression_list::const_iterator pa;
11454       int i = 1;
11455       for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
11456 	{
11457 	  if (static_cast<size_t>(i) == param_count)
11458 	    break;
11459 	  new_args->push_back(*pa);
11460 	}
11461 
11462       // We have reached the varargs parameter.
11463 
11464       bool issued_error = false;
11465       if (pa == old_args->end())
11466 	push_empty_arg = true;
11467       else if (pa + 1 == old_args->end() && this->is_varargs_)
11468 	new_args->push_back(*pa);
11469       else if (this->is_varargs_)
11470 	{
11471 	  if ((*pa)->type()->is_slice_type())
11472 	    this->report_error(_("too many arguments"));
11473 	  else
11474 	    {
11475 	      go_error_at(this->location(),
11476 			  _("invalid use of %<...%> with non-slice"));
11477 	      this->set_is_error();
11478 	    }
11479 	  return;
11480 	}
11481       else
11482 	{
11483 	  Type* element_type = varargs_type->array_type()->element_type();
11484 	  Expression_list* vals = new Expression_list;
11485 	  for (; pa != old_args->end(); ++pa, ++i)
11486 	    {
11487 	      // Check types here so that we get a better message.
11488 	      Type* patype = (*pa)->type();
11489 	      Location paloc = (*pa)->location();
11490 	      if (!this->check_argument_type(i, element_type, patype,
11491 					     paloc, issued_error))
11492 		continue;
11493 	      vals->push_back(*pa);
11494 	    }
11495 	  Slice_construction_expression* sce =
11496 	    Expression::make_slice_composite_literal(varargs_type, vals, loc);
11497 	  if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
11498 	      sce->set_storage_does_not_escape();
11499           Expression* val = sce;
11500 	  gogo->lower_expression(function, inserter, &val);
11501 	  new_args->push_back(val);
11502 	}
11503     }
11504 
11505   if (push_empty_arg)
11506     new_args->push_back(Expression::make_nil(loc));
11507 
11508   // We can't return a new call expression here, because this one may
11509   // be referenced by Call_result expressions.  FIXME.  We can't
11510   // delete OLD_ARGS because we may have both a Call_expression and a
11511   // Builtin_call_expression which refer to them.  FIXME.
11512   this->args_ = new_args;
11513   this->varargs_are_lowered_ = true;
11514 }
11515 
11516 // Flatten a call with multiple results into a temporary.
11517 
11518 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)11519 Call_expression::do_flatten(Gogo* gogo, Named_object*,
11520 			    Statement_inserter* inserter)
11521 {
11522   if (this->is_erroneous_call())
11523     {
11524       go_assert(saw_errors());
11525       return Expression::make_error(this->location());
11526     }
11527 
11528   if (this->is_flattened_)
11529     return this;
11530   this->is_flattened_ = true;
11531 
11532   // Add temporary variables for all arguments that require type
11533   // conversion.
11534   Function_type* fntype = this->get_function_type();
11535   if (fntype == NULL)
11536     {
11537       go_assert(saw_errors());
11538       return this;
11539     }
11540   if (this->args_ != NULL && !this->args_->empty()
11541       && fntype->parameters() != NULL && !fntype->parameters()->empty())
11542     {
11543       bool is_interface_method =
11544 	this->fn_->interface_field_reference_expression() != NULL;
11545 
11546       Expression_list *args = new Expression_list();
11547       Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11548       Expression_list::const_iterator pa = this->args_->begin();
11549       if (!is_interface_method && fntype->is_method())
11550 	{
11551 	  // The receiver argument.
11552 	  args->push_back(*pa);
11553 	  ++pa;
11554 	}
11555       for (; pa != this->args_->end(); ++pa, ++pp)
11556 	{
11557 	  go_assert(pp != fntype->parameters()->end());
11558 	  if (Type::are_identical(pp->type(), (*pa)->type(),
11559 				  Type::COMPARE_TAGS, NULL))
11560 	    args->push_back(*pa);
11561 	  else
11562 	    {
11563 	      Location loc = (*pa)->location();
11564 	      Expression* arg = *pa;
11565 	      if (!arg->is_multi_eval_safe())
11566 		{
11567 		  Temporary_statement *temp =
11568 		    Statement::make_temporary(NULL, arg, loc);
11569 		  inserter->insert(temp);
11570 		  arg = Expression::make_temporary_reference(temp, loc);
11571 		}
11572 	      arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
11573 						       loc);
11574 	      args->push_back(arg);
11575 	    }
11576 	}
11577       delete this->args_;
11578       this->args_ = args;
11579     }
11580 
11581   // Lower to compiler intrinsic if possible.
11582   Func_expression* fe = this->fn_->func_expression();
11583   if (!this->is_concurrent_ && !this->is_deferred_
11584       && fe != NULL
11585       && (fe->named_object()->is_function_declaration()
11586           || fe->named_object()->is_function()))
11587     {
11588       Expression* ret = this->intrinsify(gogo, inserter);
11589       if (ret != NULL)
11590         return ret;
11591     }
11592 
11593   // Add an implicit conversion to a boolean type, if needed.  See the
11594   // comment in Binary_expression::lower_array_comparison.
11595   if (this->is_equal_function_
11596       && this->type_ != NULL
11597       && this->type_ != Type::lookup_bool_type())
11598     return Expression::make_cast(this->type_, this, this->location());
11599 
11600   return this;
11601 }
11602 
11603 // Lower a call to a compiler intrinsic if possible.
11604 // Returns NULL if it is not an intrinsic.
11605 
11606 Expression*
intrinsify(Gogo * gogo,Statement_inserter * inserter)11607 Call_expression::intrinsify(Gogo* gogo,
11608                             Statement_inserter* inserter)
11609 {
11610   Func_expression* fe = this->fn_->func_expression();
11611   Named_object* no = fe->named_object();
11612   std::string name = Gogo::unpack_hidden_name(no->name());
11613   std::string package = (no->package() != NULL
11614                          ? no->package()->pkgpath()
11615                          : gogo->pkgpath());
11616   Location loc = this->location();
11617 
11618   Type* int_type = Type::lookup_integer_type("int");
11619   Type* int32_type = Type::lookup_integer_type("int32");
11620   Type* int64_type = Type::lookup_integer_type("int64");
11621   Type* uint_type = Type::lookup_integer_type("uint");
11622   Type* uint32_type = Type::lookup_integer_type("uint32");
11623   Type* uint64_type = Type::lookup_integer_type("uint64");
11624   Type* uintptr_type = Type::lookup_integer_type("uintptr");
11625   Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
11626 
11627   int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
11628   int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
11629 
11630   if (package == "sync/atomic")
11631     {
11632       // sync/atomic functions and runtime/internal/atomic functions
11633       // are very similar. In order not to duplicate code, we just
11634       // redirect to the latter and let the code below to handle them.
11635       // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
11636       // as they need write barriers.
11637       if (name == "LoadInt32")
11638         name = "Loadint32";
11639       else if (name == "LoadInt64")
11640         name = "Loadint64";
11641       else if (name == "LoadUint32")
11642         name = "Load";
11643       else if (name == "LoadUint64")
11644         name = "Load64";
11645       else if (name == "LoadUintptr")
11646         name = "Loaduintptr";
11647       else if (name == "LoadPointer")
11648         name = "Loadp";
11649       else if (name == "StoreInt32")
11650         name = "Storeint32";
11651       else if (name == "StoreInt64")
11652         name = "Storeint64";
11653       else if (name == "StoreUint32")
11654         name = "Store";
11655       else if (name == "StoreUint64")
11656         name = "Store64";
11657       else if (name == "StoreUintptr")
11658         name = "Storeuintptr";
11659       else if (name == "AddInt32")
11660         name = "Xaddint32";
11661       else if (name == "AddInt64")
11662         name = "Xaddint64";
11663       else if (name == "AddUint32")
11664         name = "Xadd";
11665       else if (name == "AddUint64")
11666         name = "Xadd64";
11667       else if (name == "AddUintptr")
11668         name = "Xadduintptr";
11669       else if (name == "SwapInt32")
11670         name = "Xchgint32";
11671       else if (name == "SwapInt64")
11672         name = "Xchgint64";
11673       else if (name == "SwapUint32")
11674         name = "Xchg";
11675       else if (name == "SwapUint64")
11676         name = "Xchg64";
11677       else if (name == "SwapUintptr")
11678         name = "Xchguintptr";
11679       else if (name == "CompareAndSwapInt32")
11680         name = "Casint32";
11681       else if (name == "CompareAndSwapInt64")
11682         name = "Casint64";
11683       else if (name == "CompareAndSwapUint32")
11684         name = "Cas";
11685       else if (name == "CompareAndSwapUint64")
11686         name = "Cas64";
11687       else if (name == "CompareAndSwapUintptr")
11688         name = "Casuintptr";
11689       else
11690         return NULL;
11691 
11692       package = "runtime/internal/atomic";
11693     }
11694 
11695   if (package == "runtime/internal/sys")
11696     {
11697       // runtime/internal/sys functions and math/bits functions
11698       // are very similar. In order not to duplicate code, we just
11699       // redirect to the latter and let the code below to handle them.
11700       if (name == "Bswap32")
11701         name = "ReverseBytes32";
11702       else if (name == "Bswap64")
11703         name = "ReverseBytes64";
11704       else if (name == "Ctz32")
11705         name = "TrailingZeros32";
11706       else if (name == "Ctz64")
11707         name = "TrailingZeros64";
11708       else
11709         return NULL;
11710 
11711       package = "math/bits";
11712     }
11713 
11714   if (package == "runtime")
11715     {
11716       // Handle a couple of special runtime functions.  In the runtime
11717       // package, getcallerpc returns the PC of the caller, and
11718       // getcallersp returns the frame pointer of the caller.  Implement
11719       // these by turning them into calls to GCC builtin functions.  We
11720       // could implement them in normal code, but then we would have to
11721       // explicitly unwind the stack.  These functions are intended to be
11722       // efficient.  Note that this technique obviously only works for
11723       // direct calls, but that is the only way they are used.
11724       if (name == "getcallerpc"
11725           && (this->args_ == NULL || this->args_->size() == 0))
11726         {
11727           Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
11728           Expression* call =
11729             Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, loc,
11730                                1, arg);
11731           // The builtin functions return void*, but the Go functions return uintptr.
11732           return Expression::make_cast(uintptr_type, call, loc);
11733         }
11734       else if (name == "getcallersp"
11735                && (this->args_ == NULL || this->args_->size() == 0))
11736 
11737         {
11738           Expression* call =
11739             Runtime::make_call(Runtime::BUILTIN_DWARF_CFA, loc, 0);
11740           // The builtin functions return void*, but the Go functions return uintptr.
11741           return Expression::make_cast(uintptr_type, call, loc);
11742         }
11743     }
11744   else if (package == "math/bits")
11745     {
11746       if ((name == "ReverseBytes16" || name == "ReverseBytes32"
11747            || name == "ReverseBytes64" || name == "ReverseBytes")
11748           && this->args_ != NULL && this->args_->size() == 1)
11749         {
11750           Runtime::Function code;
11751           if (name == "ReverseBytes16")
11752             code = Runtime::BUILTIN_BSWAP16;
11753           else if (name == "ReverseBytes32")
11754             code = Runtime::BUILTIN_BSWAP32;
11755           else if (name == "ReverseBytes64")
11756             code = Runtime::BUILTIN_BSWAP64;
11757           else if (name == "ReverseBytes")
11758             code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
11759           else
11760             go_unreachable();
11761           Expression* arg = this->args_->front();
11762           Expression* call = Runtime::make_call(code, loc, 1, arg);
11763           if (name == "ReverseBytes")
11764             return Expression::make_cast(uint_type, call, loc);
11765           return call;
11766         }
11767       else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
11768                && this->args_ != NULL && this->args_->size() == 1)
11769         {
11770           // GCC does not have a ctz8 or ctz16 intrinsic. We do
11771           // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
11772           Expression* arg = this->args_->front();
11773           arg = Expression::make_cast(uint32_type, arg, loc);
11774           unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
11775           Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
11776           arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11777           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg);
11778           return Expression::make_cast(int_type, call, loc);
11779         }
11780       else if ((name == "TrailingZeros32"
11781                 || (name == "TrailingZeros" && int_size == 4))
11782                && this->args_ != NULL && this->args_->size() == 1)
11783         {
11784           Expression* arg = this->args_->front();
11785           if (!arg->is_multi_eval_safe())
11786             {
11787               Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11788               inserter->insert(ts);
11789               arg = Expression::make_temporary_reference(ts, loc);
11790             }
11791           // arg == 0 ? 32 : __builtin_ctz(arg)
11792           Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11793           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11794           Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11795           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg->copy());
11796           call = Expression::make_cast(int_type, call, loc);
11797           return Expression::make_conditional(cmp, c32, call, loc);
11798         }
11799       else if ((name == "TrailingZeros64"
11800                 || (name == "TrailingZeros" && int_size == 8))
11801                && this->args_ != NULL && this->args_->size() == 1)
11802         {
11803           Expression* arg = this->args_->front();
11804           if (!arg->is_multi_eval_safe())
11805             {
11806               Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11807               inserter->insert(ts);
11808               arg = Expression::make_temporary_reference(ts, loc);
11809             }
11810           // arg == 0 ? 64 : __builtin_ctzll(arg)
11811           Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11812           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11813           Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11814           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZLL, loc, 1, arg->copy());
11815           call = Expression::make_cast(int_type, call, loc);
11816           return Expression::make_conditional(cmp, c64, call, loc);
11817         }
11818       else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
11819                 || name == "Len8" || name == "Len16")
11820                && this->args_ != NULL && this->args_->size() == 1)
11821         {
11822           // GCC does not have a clz8 ir clz16 intrinsic. We do
11823           // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
11824           Expression* arg = this->args_->front();
11825           arg = Expression::make_cast(uint32_type, arg, loc);
11826           unsigned long shift =
11827             ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
11828           Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
11829           arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
11830           unsigned long mask =
11831             ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
11832           c = Expression::make_integer_ul(mask, uint32_type, loc);
11833           arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11834           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg);
11835           call = Expression::make_cast(int_type, call, loc);
11836           // len = width - clz
11837           if (name == "Len8")
11838             {
11839               c = Expression::make_integer_ul(8, int_type, loc);
11840               return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11841             }
11842           else if (name == "Len16")
11843             {
11844               c = Expression::make_integer_ul(16, int_type, loc);
11845               return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11846             }
11847           return call;
11848         }
11849       else if ((name == "LeadingZeros32" || name == "Len32"
11850                 || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
11851                && this->args_ != NULL && this->args_->size() == 1)
11852         {
11853           Expression* arg = this->args_->front();
11854           if (!arg->is_multi_eval_safe())
11855             {
11856               Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11857               inserter->insert(ts);
11858               arg = Expression::make_temporary_reference(ts, loc);
11859             }
11860           // arg == 0 ? 32 : __builtin_clz(arg)
11861           Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11862           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11863           Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11864           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg->copy());
11865           call = Expression::make_cast(int_type, call, loc);
11866           Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
11867           // len = 32 - clz
11868           if (name == "Len32" || name == "Len")
11869             return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
11870           return cond;
11871         }
11872       else if ((name == "LeadingZeros64" || name == "Len64"
11873                 || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
11874                && this->args_ != NULL && this->args_->size() == 1)
11875         {
11876           Expression* arg = this->args_->front();
11877           if (!arg->is_multi_eval_safe())
11878             {
11879               Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11880               inserter->insert(ts);
11881               arg = Expression::make_temporary_reference(ts, loc);
11882             }
11883           // arg == 0 ? 64 : __builtin_clzll(arg)
11884           Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11885           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11886           Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11887           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZLL, loc, 1, arg->copy());
11888           call = Expression::make_cast(int_type, call, loc);
11889           Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
11890           // len = 64 - clz
11891           if (name == "Len64" || name == "Len")
11892             return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
11893           return cond;
11894         }
11895       else if ((name == "OnesCount8" || name == "OnesCount16"
11896            || name == "OnesCount32" || name == "OnesCount64"
11897            || name == "OnesCount")
11898           && this->args_ != NULL && this->args_->size() == 1)
11899         {
11900           Runtime::Function code;
11901           if (name == "OnesCount64")
11902             code = Runtime::BUILTIN_POPCOUNTLL;
11903           else if (name == "OnesCount")
11904             code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
11905           else
11906             code = Runtime::BUILTIN_POPCOUNT;
11907           Expression* arg = this->args_->front();
11908           Expression* call = Runtime::make_call(code, loc, 1, arg);
11909           return Expression::make_cast(int_type, call, loc);
11910         }
11911     }
11912   else if (package == "runtime/internal/atomic")
11913     {
11914       int memorder = __ATOMIC_SEQ_CST;
11915 
11916       if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
11917            || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
11918            || name == "Loadint32")
11919           && this->args_ != NULL && this->args_->size() == 1)
11920         {
11921           if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
11922             // On 32-bit architectures we need to check alignment.
11923             // Not intrinsify for now.
11924             return NULL;
11925 
11926           Runtime::Function code;
11927           Type* res_type;
11928           if (name == "Load")
11929             {
11930               code = Runtime::ATOMIC_LOAD_4;
11931               res_type = uint32_type;
11932             }
11933           else if (name == "Load64")
11934             {
11935               code = Runtime::ATOMIC_LOAD_8;
11936               res_type = uint64_type;
11937             }
11938           else if (name == "Loadint32")
11939             {
11940               code = Runtime::ATOMIC_LOAD_4;
11941               res_type = int32_type;
11942             }
11943           else if (name == "Loadint64")
11944             {
11945               code = Runtime::ATOMIC_LOAD_8;
11946               res_type = int64_type;
11947             }
11948           else if (name == "Loaduint")
11949             {
11950               code = (int_size == 8
11951                       ? Runtime::ATOMIC_LOAD_8
11952                       : Runtime::ATOMIC_LOAD_4);
11953               res_type = uint_type;
11954             }
11955           else if (name == "Loaduintptr")
11956             {
11957               code = (ptr_size == 8
11958                       ? Runtime::ATOMIC_LOAD_8
11959                       : Runtime::ATOMIC_LOAD_4);
11960               res_type = uintptr_type;
11961             }
11962           else if (name == "Loadp")
11963             {
11964               code = (ptr_size == 8
11965                       ? Runtime::ATOMIC_LOAD_8
11966                       : Runtime::ATOMIC_LOAD_4);
11967               res_type = pointer_type;
11968             }
11969           else if (name == "LoadAcq")
11970             {
11971               code = Runtime::ATOMIC_LOAD_4;
11972               res_type = uint32_type;
11973               memorder = __ATOMIC_ACQUIRE;
11974             }
11975           else
11976             go_unreachable();
11977           Expression* a1 = this->args_->front();
11978           Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
11979           Expression* call = Runtime::make_call(code, loc, 2, a1, a2);
11980           return Expression::make_unsafe_cast(res_type, call, loc);
11981         }
11982 
11983       if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
11984            || name == "Storeuintptr" || name == "StoreRel"
11985            || name == "Storeint32" || name == "Storeint64")
11986           && this->args_ != NULL && this->args_->size() == 2)
11987         {
11988           if (int_size < 8 && (name == "Store64" || name == "Storeint64"))
11989             return NULL;
11990 
11991           Runtime::Function code;
11992           Expression* a1 = this->args_->at(0);
11993           Expression* a2 = this->args_->at(1);
11994           if (name == "Store")
11995             code = Runtime::ATOMIC_STORE_4;
11996           else if (name == "Store64")
11997             code = Runtime::ATOMIC_STORE_8;
11998           else if (name == "Storeint32")
11999             code = Runtime::ATOMIC_STORE_4;
12000           else if (name == "Storeint64")
12001             code = Runtime::ATOMIC_STORE_8;
12002           else if (name == "Storeuintptr")
12003             code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
12004           else if (name == "StorepNoWB")
12005             {
12006               code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
12007               a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
12008               a2 = Expression::make_cast(uint64_type, a2, loc);
12009             }
12010           else if (name == "StoreRel")
12011             {
12012               code = Runtime::ATOMIC_STORE_4;
12013               memorder = __ATOMIC_RELEASE;
12014             }
12015           else
12016             go_unreachable();
12017           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
12018           return Runtime::make_call(code, loc, 3, a1, a2, a3);
12019         }
12020 
12021       if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
12022            || name == "Xchgint32" || name == "Xchgint64")
12023           && this->args_ != NULL && this->args_->size() == 2)
12024         {
12025           if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
12026             return NULL;
12027 
12028           Runtime::Function code;
12029           Type* res_type;
12030           if (name == "Xchg")
12031             {
12032               code = Runtime::ATOMIC_EXCHANGE_4;
12033               res_type = uint32_type;
12034             }
12035           else if (name == "Xchg64")
12036             {
12037               code = Runtime::ATOMIC_EXCHANGE_8;
12038               res_type = uint64_type;
12039             }
12040           else if (name == "Xchgint32")
12041             {
12042               code = Runtime::ATOMIC_EXCHANGE_4;
12043               res_type = int32_type;
12044             }
12045           else if (name == "Xchgint64")
12046             {
12047               code = Runtime::ATOMIC_EXCHANGE_8;
12048               res_type = int64_type;
12049             }
12050           else if (name == "Xchguintptr")
12051             {
12052               code = (ptr_size == 8
12053                       ? Runtime::ATOMIC_EXCHANGE_8
12054                       : Runtime::ATOMIC_EXCHANGE_4);
12055               res_type = uintptr_type;
12056             }
12057           else
12058             go_unreachable();
12059           Expression* a1 = this->args_->at(0);
12060           Expression* a2 = this->args_->at(1);
12061           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
12062           Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
12063           return Expression::make_cast(res_type, call, loc);
12064         }
12065 
12066       if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
12067            || name == "Casp1" || name == "CasRel"
12068            || name == "Casint32" || name == "Casint64")
12069           && this->args_ != NULL && this->args_->size() == 3)
12070         {
12071           if (int_size < 8 && (name == "Cas64" || name == "Casint64"))
12072             return NULL;
12073 
12074           Runtime::Function code;
12075           Expression* a1 = this->args_->at(0);
12076 
12077           // Builtin cas takes a pointer to the old value.
12078           // Store it in a temporary and take the address.
12079           Expression* a2 = this->args_->at(1);
12080           Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
12081           inserter->insert(ts);
12082           a2 = Expression::make_temporary_reference(ts, loc);
12083           a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
12084 
12085           Expression* a3 = this->args_->at(2);
12086           if (name == "Cas")
12087             code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
12088           else if (name == "Cas64")
12089             code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
12090           else if (name == "Casint32")
12091             code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
12092           else if (name == "Casint64")
12093             code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
12094           else if (name == "Casuintptr")
12095             code = (ptr_size == 8
12096                     ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
12097                     : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
12098           else if (name == "Casp1")
12099             {
12100               code = (ptr_size == 8
12101                       ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
12102                       : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
12103               a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
12104               a3 = Expression::make_cast(uint64_type, a3, loc);
12105             }
12106           else if (name == "CasRel")
12107             {
12108               code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
12109               memorder = __ATOMIC_RELEASE;
12110             }
12111           else
12112             go_unreachable();
12113           Expression* a4 = Expression::make_boolean(false, loc);
12114           Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
12115           Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
12116           return Runtime::make_call(code, loc, 6, a1, a2, a3, a4, a5, a6);
12117         }
12118 
12119       if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
12120            || name == "Xadduintptr" || name == "Xaddint32")
12121           && this->args_ != NULL && this->args_->size() == 2)
12122         {
12123           if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
12124             return NULL;
12125 
12126           Runtime::Function code;
12127           Type* res_type;
12128           if (name == "Xadd")
12129             {
12130               code = Runtime::ATOMIC_ADD_FETCH_4;
12131               res_type = uint32_type;
12132             }
12133           else if (name == "Xadd64")
12134             {
12135               code = Runtime::ATOMIC_ADD_FETCH_8;
12136               res_type = uint64_type;
12137             }
12138           else if (name == "Xaddint32")
12139             {
12140               code = Runtime::ATOMIC_ADD_FETCH_4;
12141               res_type = int32_type;
12142             }
12143           else if (name == "Xaddint64")
12144             {
12145               code = Runtime::ATOMIC_ADD_FETCH_8;
12146               res_type = int64_type;
12147             }
12148           else if (name == "Xadduintptr")
12149             {
12150               code = (ptr_size == 8
12151                       ? Runtime::ATOMIC_ADD_FETCH_8
12152                       : Runtime::ATOMIC_ADD_FETCH_4);
12153               res_type = uintptr_type;
12154             }
12155           else
12156             go_unreachable();
12157           Expression* a1 = this->args_->at(0);
12158           Expression* a2 = this->args_->at(1);
12159           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
12160           Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
12161           return Expression::make_cast(res_type, call, loc);
12162         }
12163 
12164       if ((name == "And8" || name == "Or8")
12165           && this->args_ != NULL && this->args_->size() == 2)
12166         {
12167           Runtime::Function code;
12168           if (name == "And8")
12169             code = Runtime::ATOMIC_AND_FETCH_1;
12170           else if (name == "Or8")
12171             code = Runtime::ATOMIC_OR_FETCH_1;
12172           else
12173             go_unreachable();
12174           Expression* a1 = this->args_->at(0);
12175           Expression* a2 = this->args_->at(1);
12176           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
12177           return Runtime::make_call(code, loc, 3, a1, a2, a3);
12178         }
12179     }
12180 
12181   return NULL;
12182 }
12183 
12184 // Make implicit type conversions explicit.
12185 
12186 void
do_add_conversions()12187 Call_expression::do_add_conversions()
12188 {
12189   // Skip call that requires a thunk. We generate conversions inside the thunk.
12190   if (this->is_concurrent_ || this->is_deferred_)
12191     return;
12192 
12193   if (this->args_ == NULL || this->args_->empty())
12194     return;
12195 
12196   Function_type* fntype = this->get_function_type();
12197   if (fntype == NULL)
12198     {
12199       go_assert(saw_errors());
12200       return;
12201     }
12202   if (fntype->parameters() == NULL || fntype->parameters()->empty())
12203     return;
12204 
12205   Location loc = this->location();
12206   Expression_list::iterator pa = this->args_->begin();
12207   Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
12208   bool is_interface_method =
12209     this->fn_->interface_field_reference_expression() != NULL;
12210   size_t argcount = this->args_->size();
12211   if (!is_interface_method && fntype->is_method())
12212     {
12213       // Skip the receiver argument, which cannot be interface.
12214       pa++;
12215       argcount--;
12216     }
12217   if (argcount != fntype->parameters()->size())
12218     {
12219       go_assert(saw_errors());
12220       return;
12221     }
12222   for (; pa != this->args_->end(); ++pa, ++pp)
12223     {
12224       Type* pt = pp->type();
12225       if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
12226           && pt->interface_type() != NULL)
12227         *pa = Expression::make_cast(pt, *pa, loc);
12228     }
12229 }
12230 
12231 // Get the function type.  This can return NULL in error cases.
12232 
12233 Function_type*
get_function_type() const12234 Call_expression::get_function_type() const
12235 {
12236   return this->fn_->type()->function_type();
12237 }
12238 
12239 // Return the number of values which this call will return.
12240 
12241 size_t
result_count() const12242 Call_expression::result_count() const
12243 {
12244   const Function_type* fntype = this->get_function_type();
12245   if (fntype == NULL)
12246     return 0;
12247   if (fntype->results() == NULL)
12248     return 0;
12249   return fntype->results()->size();
12250 }
12251 
12252 // Return the temporary that holds the result for a call with multiple
12253 // results.
12254 
12255 Temporary_statement*
results() const12256 Call_expression::results() const
12257 {
12258   if (this->call_temp_ == NULL)
12259     {
12260       go_assert(saw_errors());
12261       return NULL;
12262     }
12263   return this->call_temp_;
12264 }
12265 
12266 // Set the number of results expected from a call expression.
12267 
12268 void
set_expected_result_count(size_t count)12269 Call_expression::set_expected_result_count(size_t count)
12270 {
12271   go_assert(this->expected_result_count_ == 0);
12272   this->expected_result_count_ = count;
12273 }
12274 
12275 // Return whether this is a call to the predeclared function recover.
12276 
12277 bool
is_recover_call() const12278 Call_expression::is_recover_call() const
12279 {
12280   return this->do_is_recover_call();
12281 }
12282 
12283 // Set the argument to the recover function.
12284 
12285 void
set_recover_arg(Expression * arg)12286 Call_expression::set_recover_arg(Expression* arg)
12287 {
12288   this->do_set_recover_arg(arg);
12289 }
12290 
12291 // Virtual functions also implemented by Builtin_call_expression.
12292 
12293 bool
do_is_recover_call() const12294 Call_expression::do_is_recover_call() const
12295 {
12296   return false;
12297 }
12298 
12299 void
do_set_recover_arg(Expression *)12300 Call_expression::do_set_recover_arg(Expression*)
12301 {
12302   go_unreachable();
12303 }
12304 
12305 // We have found an error with this call expression; return true if
12306 // we should report it.
12307 
12308 bool
issue_error()12309 Call_expression::issue_error()
12310 {
12311   if (this->issued_error_)
12312     return false;
12313   else
12314     {
12315       this->issued_error_ = true;
12316       return true;
12317     }
12318 }
12319 
12320 // Whether or not this call contains errors, either in the call or the
12321 // arguments to the call.
12322 
12323 bool
is_erroneous_call()12324 Call_expression::is_erroneous_call()
12325 {
12326   if (this->is_error_expression() || this->fn()->is_error_expression())
12327     return true;
12328 
12329   if (this->args() == NULL)
12330     return false;
12331   for (Expression_list::iterator pa = this->args()->begin();
12332        pa != this->args()->end();
12333        ++pa)
12334     {
12335       if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
12336         return true;
12337     }
12338   return false;
12339 }
12340 
12341 // Get the type.
12342 
12343 Type*
do_type()12344 Call_expression::do_type()
12345 {
12346   if (this->is_error_expression())
12347     return Type::make_error_type();
12348   if (this->type_ != NULL)
12349     return this->type_;
12350 
12351   Type* ret;
12352   Function_type* fntype = this->get_function_type();
12353   if (fntype == NULL)
12354     return Type::make_error_type();
12355 
12356   const Typed_identifier_list* results = fntype->results();
12357   if (results == NULL)
12358     ret = Type::make_void_type();
12359   else if (results->size() == 1)
12360     ret = results->begin()->type();
12361   else
12362     ret = Type::make_call_multiple_result_type(this);
12363 
12364   this->type_ = ret;
12365 
12366   return this->type_;
12367 }
12368 
12369 // Determine types for a call expression.  We can use the function
12370 // parameter types to set the types of the arguments.
12371 
12372 void
do_determine_type(const Type_context * context)12373 Call_expression::do_determine_type(const Type_context* context)
12374 {
12375   if (!this->determining_types())
12376     return;
12377 
12378   this->fn_->determine_type_no_context();
12379   Function_type* fntype = this->get_function_type();
12380   const Typed_identifier_list* parameters = NULL;
12381   if (fntype != NULL)
12382     parameters = fntype->parameters();
12383   if (this->args_ != NULL)
12384     {
12385       Typed_identifier_list::const_iterator pt;
12386       if (parameters != NULL)
12387 	pt = parameters->begin();
12388       bool first = true;
12389       for (Expression_list::const_iterator pa = this->args_->begin();
12390 	   pa != this->args_->end();
12391 	   ++pa)
12392 	{
12393 	  if (first)
12394 	    {
12395 	      first = false;
12396 	      // If this is a method, the first argument is the
12397 	      // receiver.
12398 	      if (fntype != NULL && fntype->is_method())
12399 		{
12400 		  Type* rtype = fntype->receiver()->type();
12401 		  // The receiver is always passed as a pointer.
12402 		  if (rtype->points_to() == NULL)
12403 		    rtype = Type::make_pointer_type(rtype);
12404 		  Type_context subcontext(rtype, false);
12405 		  (*pa)->determine_type(&subcontext);
12406 		  continue;
12407 		}
12408 	    }
12409 
12410 	  if (parameters != NULL && pt != parameters->end())
12411 	    {
12412 	      Type_context subcontext(pt->type(), false);
12413 	      (*pa)->determine_type(&subcontext);
12414 	      ++pt;
12415 	    }
12416 	  else
12417 	    (*pa)->determine_type_no_context();
12418 	}
12419     }
12420 
12421   // If this is a call to a generated equality function, we determine
12422   // the type based on the context.  See the comment in
12423   // Binary_expression::lower_array_comparison.
12424   if (this->is_equal_function_
12425       && !context->may_be_abstract
12426       && context->type != NULL
12427       && context->type->is_boolean_type()
12428       && context->type != Type::lookup_bool_type())
12429     {
12430       go_assert(this->type_ == NULL
12431 		|| this->type_ == Type::lookup_bool_type()
12432 		|| this->type_ == context->type
12433 		|| this->type_->is_error());
12434       this->type_ = context->type;
12435     }
12436 }
12437 
12438 // Called when determining types for a Call_expression.  Return true
12439 // if we should go ahead, false if they have already been determined.
12440 
12441 bool
determining_types()12442 Call_expression::determining_types()
12443 {
12444   if (this->types_are_determined_)
12445     return false;
12446   else
12447     {
12448       this->types_are_determined_ = true;
12449       return true;
12450     }
12451 }
12452 
12453 // Check types for parameter I.
12454 
12455 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)12456 Call_expression::check_argument_type(int i, const Type* parameter_type,
12457 				     const Type* argument_type,
12458 				     Location argument_location,
12459 				     bool issued_error)
12460 {
12461   std::string reason;
12462   if (!Type::are_assignable(parameter_type, argument_type, &reason))
12463     {
12464       if (!issued_error)
12465 	{
12466 	  if (reason.empty())
12467 	    go_error_at(argument_location, "argument %d has incompatible type", i);
12468 	  else
12469 	    go_error_at(argument_location,
12470 			"argument %d has incompatible type (%s)",
12471 			i, reason.c_str());
12472 	}
12473       this->set_is_error();
12474       return false;
12475     }
12476   return true;
12477 }
12478 
12479 // Check types.
12480 
12481 void
do_check_types(Gogo *)12482 Call_expression::do_check_types(Gogo*)
12483 {
12484   if (this->classification() == EXPRESSION_ERROR)
12485     return;
12486 
12487   Function_type* fntype = this->get_function_type();
12488   if (fntype == NULL)
12489     {
12490       if (!this->fn_->type()->is_error())
12491 	this->report_error(_("expected function"));
12492       return;
12493     }
12494 
12495   if (this->expected_result_count_ != 0
12496       && this->expected_result_count_ != this->result_count())
12497     {
12498       if (this->issue_error())
12499 	this->report_error(_("function result count mismatch"));
12500       this->set_is_error();
12501       return;
12502     }
12503 
12504   bool is_method = fntype->is_method();
12505   if (is_method)
12506     {
12507       go_assert(this->args_ != NULL && !this->args_->empty());
12508       Type* rtype = fntype->receiver()->type();
12509       Expression* first_arg = this->args_->front();
12510       // We dereference the values since receivers are always passed
12511       // as pointers.
12512       std::string reason;
12513       if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
12514 				&reason))
12515 	{
12516 	  if (reason.empty())
12517 	    this->report_error(_("incompatible type for receiver"));
12518 	  else
12519 	    {
12520 	      go_error_at(this->location(),
12521                           "incompatible type for receiver (%s)",
12522                           reason.c_str());
12523 	      this->set_is_error();
12524 	    }
12525 	}
12526     }
12527 
12528   // Note that varargs was handled by the lower_varargs() method, so
12529   // we don't have to worry about it here unless something is wrong.
12530   if (this->is_varargs_ && !this->varargs_are_lowered_)
12531     {
12532       if (!fntype->is_varargs())
12533 	{
12534 	  go_error_at(this->location(),
12535                       _("invalid use of %<...%> calling non-variadic function"));
12536 	  this->set_is_error();
12537 	  return;
12538 	}
12539     }
12540 
12541   const Typed_identifier_list* parameters = fntype->parameters();
12542   if (this->args_ == NULL || this->args_->size() == 0)
12543     {
12544       if (parameters != NULL && !parameters->empty())
12545 	this->report_error(_("not enough arguments"));
12546     }
12547   else if (parameters == NULL)
12548     {
12549       if (!is_method || this->args_->size() > 1)
12550 	this->report_error(_("too many arguments"));
12551     }
12552   else if (this->args_->size() == 1
12553 	   && this->args_->front()->call_expression() != NULL
12554 	   && this->args_->front()->call_expression()->result_count() > 1)
12555     {
12556       // This is F(G()) when G returns more than one result.  If the
12557       // results can be matched to parameters, it would have been
12558       // lowered in do_lower.  If we get here we know there is a
12559       // mismatch.
12560       if (this->args_->front()->call_expression()->result_count()
12561 	  < parameters->size())
12562 	this->report_error(_("not enough arguments"));
12563       else
12564 	this->report_error(_("too many arguments"));
12565     }
12566   else
12567     {
12568       int i = 0;
12569       Expression_list::const_iterator pa = this->args_->begin();
12570       if (is_method)
12571 	++pa;
12572       for (Typed_identifier_list::const_iterator pt = parameters->begin();
12573 	   pt != parameters->end();
12574 	   ++pt, ++pa, ++i)
12575 	{
12576 	  if (pa == this->args_->end())
12577 	    {
12578 	      this->report_error(_("not enough arguments"));
12579 	      return;
12580 	    }
12581 	  this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
12582 				    (*pa)->location(), false);
12583 	}
12584       if (pa != this->args_->end())
12585 	this->report_error(_("too many arguments"));
12586     }
12587 }
12588 
12589 Expression*
do_copy()12590 Call_expression::do_copy()
12591 {
12592   Call_expression* call =
12593     Expression::make_call(this->fn_->copy(),
12594 			  (this->args_ == NULL
12595 			   ? NULL
12596 			   : this->args_->copy()),
12597 			  this->is_varargs_, this->location());
12598 
12599   if (this->varargs_are_lowered_)
12600     call->set_varargs_are_lowered();
12601   if (this->is_deferred_)
12602     call->set_is_deferred();
12603   if (this->is_concurrent_)
12604     call->set_is_concurrent();
12605   return call;
12606 }
12607 
12608 // Return whether we have to use a temporary variable to ensure that
12609 // we evaluate this call expression in order.  If the call returns no
12610 // results then it will inevitably be executed last.
12611 
12612 bool
do_must_eval_in_order() const12613 Call_expression::do_must_eval_in_order() const
12614 {
12615   return this->result_count() > 0;
12616 }
12617 
12618 // Get the function and the first argument to use when calling an
12619 // interface method.
12620 
12621 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr,Location location)12622 Call_expression::interface_method_function(
12623     Interface_field_reference_expression* interface_method,
12624     Expression** first_arg_ptr,
12625     Location location)
12626 {
12627   Expression* object = interface_method->get_underlying_object();
12628   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
12629   *first_arg_ptr =
12630       Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
12631   return interface_method->get_function();
12632 }
12633 
12634 // Build the call expression.
12635 
12636 Bexpression*
do_get_backend(Translate_context * context)12637 Call_expression::do_get_backend(Translate_context* context)
12638 {
12639   Location location = this->location();
12640 
12641   if (this->call_ != NULL)
12642     {
12643       // If the call returns multiple results, make a new reference to
12644       // the temporary.
12645       if (this->call_temp_ != NULL)
12646 	{
12647 	  Expression* ref =
12648 	    Expression::make_temporary_reference(this->call_temp_, location);
12649 	  return ref->get_backend(context);
12650 	}
12651 
12652       return this->call_;
12653     }
12654 
12655   Function_type* fntype = this->get_function_type();
12656   if (fntype == NULL)
12657     return context->backend()->error_expression();
12658 
12659   if (this->fn_->is_error_expression())
12660     return context->backend()->error_expression();
12661 
12662   Gogo* gogo = context->gogo();
12663 
12664   Func_expression* func = this->fn_->func_expression();
12665   Interface_field_reference_expression* interface_method =
12666     this->fn_->interface_field_reference_expression();
12667   const bool has_closure = func != NULL && func->closure() != NULL;
12668   const bool is_interface_method = interface_method != NULL;
12669 
12670   bool has_closure_arg;
12671   if (has_closure)
12672     has_closure_arg = true;
12673   else if (func != NULL)
12674     has_closure_arg = false;
12675   else if (is_interface_method)
12676     has_closure_arg = false;
12677   else
12678     has_closure_arg = true;
12679 
12680   Expression* first_arg = NULL;
12681   if (!is_interface_method && fntype->is_method())
12682     {
12683       first_arg = this->args_->front();
12684       if (first_arg->type()->points_to() == NULL
12685           && first_arg->type()->is_direct_iface_type())
12686         first_arg = Expression::unpack_direct_iface(first_arg,
12687                                                     first_arg->location());
12688     }
12689 
12690   int nargs;
12691   std::vector<Bexpression*> fn_args;
12692   if (this->args_ == NULL || this->args_->empty())
12693     {
12694       nargs = is_interface_method ? 1 : 0;
12695       if (nargs > 0)
12696         fn_args.resize(1);
12697     }
12698   else if (fntype->parameters() == NULL || fntype->parameters()->empty())
12699     {
12700       // Passing a receiver parameter.
12701       go_assert(!is_interface_method
12702 		&& fntype->is_method()
12703 		&& this->args_->size() == 1);
12704       nargs = 1;
12705       fn_args.resize(1);
12706       fn_args[0] = first_arg->get_backend(context);
12707     }
12708   else
12709     {
12710       const Typed_identifier_list* params = fntype->parameters();
12711 
12712       nargs = this->args_->size();
12713       int i = is_interface_method ? 1 : 0;
12714       nargs += i;
12715       fn_args.resize(nargs);
12716 
12717       Typed_identifier_list::const_iterator pp = params->begin();
12718       Expression_list::const_iterator pe = this->args_->begin();
12719       if (!is_interface_method && fntype->is_method())
12720 	{
12721           fn_args[i] = first_arg->get_backend(context);
12722 	  ++pe;
12723 	  ++i;
12724 	}
12725       for (; pe != this->args_->end(); ++pe, ++pp, ++i)
12726 	{
12727 	  go_assert(pp != params->end());
12728           Expression* arg =
12729               Expression::convert_for_assignment(gogo, pp->type(), *pe,
12730                                                  location);
12731           fn_args[i] = arg->get_backend(context);
12732 	}
12733       go_assert(pp == params->end());
12734       go_assert(i == nargs);
12735     }
12736 
12737   Expression* fn;
12738   Expression* closure = NULL;
12739   if (func != NULL)
12740     {
12741       Named_object* no = func->named_object();
12742       fn = Expression::make_func_code_reference(no, location);
12743       if (has_closure)
12744         closure = func->closure();
12745     }
12746   else if (!is_interface_method)
12747     {
12748       closure = this->fn_;
12749 
12750       // The backend representation of this function type is a pointer
12751       // to a struct whose first field is the actual function to call.
12752       Type* pfntype =
12753           Type::make_pointer_type(
12754               Type::make_pointer_type(Type::make_void_type()));
12755       fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
12756       fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
12757     }
12758   else
12759     {
12760       Expression* arg0;
12761       fn = this->interface_method_function(interface_method, &arg0,
12762                                            location);
12763       fn_args[0] = arg0->get_backend(context);
12764     }
12765 
12766   Bexpression* bclosure = NULL;
12767   if (has_closure_arg)
12768     bclosure = closure->get_backend(context);
12769   else
12770     go_assert(closure == NULL);
12771 
12772   Bexpression* bfn = fn->get_backend(context);
12773 
12774   // When not calling a named function directly, use a type conversion
12775   // in case the type of the function is a recursive type which refers
12776   // to itself.  We don't do this for an interface method because 1)
12777   // an interface method never refers to itself, so we always have a
12778   // function type here; 2) we pass an extra first argument to an
12779   // interface method, so fntype is not correct.
12780   if (func == NULL && !is_interface_method)
12781     {
12782       Btype* bft = fntype->get_backend_fntype(gogo);
12783       bfn = gogo->backend()->convert_expression(bft, bfn, location);
12784     }
12785 
12786   Bfunction* bfunction = NULL;
12787   if (context->function())
12788     bfunction = context->function()->func_value()->get_decl();
12789   Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
12790                                                        fn_args, bclosure,
12791                                                        location);
12792 
12793   if (this->call_temp_ != NULL)
12794     {
12795       // This case occurs when the call returns multiple results.
12796 
12797       Expression* ref = Expression::make_temporary_reference(this->call_temp_,
12798 							     location);
12799       Bexpression* bref = ref->get_backend(context);
12800       Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
12801 								bref, call,
12802 								location);
12803 
12804       ref = Expression::make_temporary_reference(this->call_temp_, location);
12805       this->call_ = ref->get_backend(context);
12806 
12807       return gogo->backend()->compound_expression(bassn, this->call_,
12808 						  location);
12809     }
12810 
12811   this->call_ = call;
12812   return this->call_;
12813 }
12814 
12815 // The cost of inlining a call expression.
12816 
12817 int
do_inlining_cost() const12818 Call_expression::do_inlining_cost() const
12819 {
12820   Func_expression* fn = this->fn_->func_expression();
12821 
12822   // FIXME: We don't yet support all kinds of calls.
12823   if (fn != NULL && fn->closure() != NULL)
12824     return 0x100000;
12825   if (this->fn_->interface_field_reference_expression())
12826     return 0x100000;
12827   if (this->get_function_type()->is_method())
12828     return 0x100000;
12829 
12830   return 5;
12831 }
12832 
12833 // Export a call expression.
12834 
12835 void
do_export(Export_function_body * efb) const12836 Call_expression::do_export(Export_function_body* efb) const
12837 {
12838   bool simple_call = (this->fn_->func_expression() != NULL);
12839   if (!simple_call)
12840     efb->write_c_string("(");
12841   this->fn_->export_expression(efb);
12842   if (!simple_call)
12843     efb->write_c_string(")");
12844   this->export_arguments(efb);
12845 }
12846 
12847 // Export call expression arguments.
12848 
12849 void
export_arguments(Export_function_body * efb) const12850 Call_expression::export_arguments(Export_function_body* efb) const
12851 {
12852   efb->write_c_string("(");
12853   if (this->args_ != NULL && !this->args_->empty())
12854     {
12855       Expression_list::const_iterator pa = this->args_->begin();
12856       (*pa)->export_expression(efb);
12857       for (pa++; pa != this->args_->end(); pa++)
12858 	{
12859 	  efb->write_c_string(", ");
12860 	  (*pa)->export_expression(efb);
12861 	}
12862       if (this->is_varargs_)
12863 	efb->write_c_string("...");
12864     }
12865   efb->write_c_string(")");
12866 }
12867 
12868 // Dump ast representation for a call expression.
12869 
12870 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12871 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12872 {
12873   this->fn_->dump_expression(ast_dump_context);
12874   ast_dump_context->ostream() << "(";
12875   if (args_ != NULL)
12876     ast_dump_context->dump_expression_list(this->args_);
12877 
12878   ast_dump_context->ostream() << ") ";
12879 }
12880 
12881 // Make a call expression.
12882 
12883 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)12884 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
12885 		      Location location)
12886 {
12887   return new Call_expression(fn, args, is_varargs, location);
12888 }
12889 
12890 // Class Call_result_expression.
12891 
12892 // Traverse a call result.
12893 
12894 int
do_traverse(Traverse * traverse)12895 Call_result_expression::do_traverse(Traverse* traverse)
12896 {
12897   if (traverse->remember_expression(this->call_))
12898     {
12899       // We have already traversed the call expression.
12900       return TRAVERSE_CONTINUE;
12901     }
12902   return Expression::traverse(&this->call_, traverse);
12903 }
12904 
12905 // Get the type.
12906 
12907 Type*
do_type()12908 Call_result_expression::do_type()
12909 {
12910   if (this->classification() == EXPRESSION_ERROR)
12911     return Type::make_error_type();
12912 
12913   // THIS->CALL_ can be replaced with a temporary reference due to
12914   // Call_expression::do_must_eval_in_order when there is an error.
12915   Call_expression* ce = this->call_->call_expression();
12916   if (ce == NULL)
12917     {
12918       this->set_is_error();
12919       return Type::make_error_type();
12920     }
12921   Function_type* fntype = ce->get_function_type();
12922   if (fntype == NULL)
12923     {
12924       if (ce->issue_error())
12925 	{
12926 	  if (!ce->fn()->type()->is_error())
12927 	    this->report_error(_("expected function"));
12928 	}
12929       this->set_is_error();
12930       return Type::make_error_type();
12931     }
12932   const Typed_identifier_list* results = fntype->results();
12933   if (results == NULL || results->size() < 2)
12934     {
12935       if (ce->issue_error())
12936 	this->report_error(_("number of results does not match "
12937 			     "number of values"));
12938       return Type::make_error_type();
12939     }
12940   Typed_identifier_list::const_iterator pr = results->begin();
12941   for (unsigned int i = 0; i < this->index_; ++i)
12942     {
12943       if (pr == results->end())
12944 	break;
12945       ++pr;
12946     }
12947   if (pr == results->end())
12948     {
12949       if (ce->issue_error())
12950 	this->report_error(_("number of results does not match "
12951 			     "number of values"));
12952       return Type::make_error_type();
12953     }
12954   return pr->type();
12955 }
12956 
12957 // Check the type.  Just make sure that we trigger the warning in
12958 // do_type.
12959 
12960 void
do_check_types(Gogo *)12961 Call_result_expression::do_check_types(Gogo*)
12962 {
12963   this->type();
12964 }
12965 
12966 // Determine the type.  We have nothing to do here, but the 0 result
12967 // needs to pass down to the caller.
12968 
12969 void
do_determine_type(const Type_context *)12970 Call_result_expression::do_determine_type(const Type_context*)
12971 {
12972   this->call_->determine_type_no_context();
12973 }
12974 
12975 // Return the backend representation.  We just refer to the temporary set by the
12976 // call expression.  We don't do this at lowering time because it makes it
12977 // hard to evaluate the call at the right time.
12978 
12979 Bexpression*
do_get_backend(Translate_context * context)12980 Call_result_expression::do_get_backend(Translate_context* context)
12981 {
12982   Call_expression* ce = this->call_->call_expression();
12983   if (ce == NULL)
12984     {
12985       go_assert(this->call_->is_error_expression());
12986       return context->backend()->error_expression();
12987     }
12988   Temporary_statement* ts = ce->results();
12989   if (ts == NULL)
12990     {
12991       go_assert(saw_errors());
12992       return context->backend()->error_expression();
12993     }
12994   Expression* ref = Expression::make_temporary_reference(ts, this->location());
12995   ref = Expression::make_field_reference(ref, this->index_, this->location());
12996   return ref->get_backend(context);
12997 }
12998 
12999 // Dump ast representation for a call result expression.
13000 
13001 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13002 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13003     const
13004 {
13005   // FIXME: Wouldn't it be better if the call is assigned to a temporary
13006   // (struct) and the fields are referenced instead.
13007   ast_dump_context->ostream() << this->index_ << "@(";
13008   ast_dump_context->dump_expression(this->call_);
13009   ast_dump_context->ostream() << ")";
13010 }
13011 
13012 // Make a reference to a single result of a call which returns
13013 // multiple results.
13014 
13015 Expression*
make_call_result(Call_expression * call,unsigned int index)13016 Expression::make_call_result(Call_expression* call, unsigned int index)
13017 {
13018   return new Call_result_expression(call, index);
13019 }
13020 
13021 // Class Index_expression.
13022 
13023 // Traversal.
13024 
13025 int
do_traverse(Traverse * traverse)13026 Index_expression::do_traverse(Traverse* traverse)
13027 {
13028   if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
13029       || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
13030       || (this->end_ != NULL
13031 	  && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13032       || (this->cap_ != NULL
13033           && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
13034     return TRAVERSE_EXIT;
13035   return TRAVERSE_CONTINUE;
13036 }
13037 
13038 // Lower an index expression.  This converts the generic index
13039 // expression into an array index, a string index, or a map index.
13040 
13041 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)13042 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
13043 {
13044   Location location = this->location();
13045   Expression* left = this->left_;
13046   Expression* start = this->start_;
13047   Expression* end = this->end_;
13048   Expression* cap = this->cap_;
13049 
13050   Type* type = left->type();
13051   if (type->is_error())
13052     {
13053       go_assert(saw_errors());
13054       return Expression::make_error(location);
13055     }
13056   else if (left->is_type_expression())
13057     {
13058       go_error_at(location, "attempt to index type expression");
13059       return Expression::make_error(location);
13060     }
13061   else if (type->array_type() != NULL)
13062     return Expression::make_array_index(left, start, end, cap, location);
13063   else if (type->points_to() != NULL
13064 	   && type->points_to()->array_type() != NULL
13065 	   && !type->points_to()->is_slice_type())
13066     {
13067       Expression* deref =
13068           Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
13069 
13070       // For an ordinary index into the array, the pointer will be
13071       // dereferenced.  For a slice it will not--the resulting slice
13072       // will simply reuse the pointer, which is incorrect if that
13073       // pointer is nil.
13074       if (end != NULL || cap != NULL)
13075 	deref->issue_nil_check();
13076 
13077       return Expression::make_array_index(deref, start, end, cap, location);
13078     }
13079   else if (type->is_string_type())
13080     {
13081       if (cap != NULL)
13082         {
13083           go_error_at(location, "invalid 3-index slice of string");
13084           return Expression::make_error(location);
13085         }
13086       return Expression::make_string_index(left, start, end, location);
13087     }
13088   else if (type->map_type() != NULL)
13089     {
13090       if (end != NULL || cap != NULL)
13091 	{
13092 	  go_error_at(location, "invalid slice of map");
13093 	  return Expression::make_error(location);
13094 	}
13095       return Expression::make_map_index(left, start, location);
13096     }
13097   else if (cap != NULL)
13098     {
13099       go_error_at(location,
13100 		  "invalid 3-index slice of object that is not a slice");
13101       return Expression::make_error(location);
13102     }
13103   else if (end != NULL)
13104     {
13105       go_error_at(location,
13106 		  ("attempt to slice object that is not "
13107 		   "array, slice, or string"));
13108       return Expression::make_error(location);
13109     }
13110   else
13111     {
13112       go_error_at(location,
13113                   ("attempt to index object that is not "
13114 		   "array, slice, string, or map"));
13115       return Expression::make_error(location);
13116     }
13117 }
13118 
13119 // Write an indexed expression
13120 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
13121 
13122 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)13123 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
13124 					const Expression* expr,
13125 					const Expression* start,
13126 					const Expression* end,
13127 					const Expression* cap)
13128 {
13129   expr->dump_expression(ast_dump_context);
13130   ast_dump_context->ostream() << "[";
13131   start->dump_expression(ast_dump_context);
13132   if (end != NULL)
13133     {
13134       ast_dump_context->ostream() << ":";
13135       end->dump_expression(ast_dump_context);
13136     }
13137   if (cap != NULL)
13138     {
13139       ast_dump_context->ostream() << ":";
13140       cap->dump_expression(ast_dump_context);
13141     }
13142   ast_dump_context->ostream() << "]";
13143 }
13144 
13145 // Dump ast representation for an index expression.
13146 
13147 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13148 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13149     const
13150 {
13151   Index_expression::dump_index_expression(ast_dump_context, this->left_,
13152                                           this->start_, this->end_, this->cap_);
13153 }
13154 
13155 // Make an index expression.
13156 
13157 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)13158 Expression::make_index(Expression* left, Expression* start, Expression* end,
13159 		       Expression* cap, Location location)
13160 {
13161   return new Index_expression(left, start, end, cap, location);
13162 }
13163 
13164 // Class Array_index_expression.
13165 
13166 // Array index traversal.
13167 
13168 int
do_traverse(Traverse * traverse)13169 Array_index_expression::do_traverse(Traverse* traverse)
13170 {
13171   if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
13172     return TRAVERSE_EXIT;
13173   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
13174     return TRAVERSE_EXIT;
13175   if (this->end_ != NULL)
13176     {
13177       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13178 	return TRAVERSE_EXIT;
13179     }
13180   if (this->cap_ != NULL)
13181     {
13182       if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
13183         return TRAVERSE_EXIT;
13184     }
13185   return TRAVERSE_CONTINUE;
13186 }
13187 
13188 // Return the type of an array index.
13189 
13190 Type*
do_type()13191 Array_index_expression::do_type()
13192 {
13193   if (this->type_ == NULL)
13194     {
13195      Array_type* type = this->array_->type()->array_type();
13196       if (type == NULL)
13197 	this->type_ = Type::make_error_type();
13198       else if (this->end_ == NULL)
13199 	this->type_ = type->element_type();
13200       else if (type->is_slice_type())
13201 	{
13202 	  // A slice of a slice has the same type as the original
13203 	  // slice.
13204 	  this->type_ = this->array_->type()->deref();
13205 	}
13206       else
13207 	{
13208 	  // A slice of an array is a slice.
13209 	  this->type_ = Type::make_array_type(type->element_type(), NULL);
13210 	}
13211     }
13212   return this->type_;
13213 }
13214 
13215 // Set the type of an array index.
13216 
13217 void
do_determine_type(const Type_context *)13218 Array_index_expression::do_determine_type(const Type_context*)
13219 {
13220   this->array_->determine_type_no_context();
13221 
13222   Type_context index_context(Type::lookup_integer_type("int"), false);
13223   this->start_->determine_type(&index_context);
13224   if (this->end_ != NULL)
13225     this->end_->determine_type(&index_context);
13226   if (this->cap_ != NULL)
13227     this->cap_->determine_type(&index_context);
13228 }
13229 
13230 // Check types of an array index.
13231 
13232 void
do_check_types(Gogo *)13233 Array_index_expression::do_check_types(Gogo*)
13234 {
13235   Numeric_constant nc;
13236   unsigned long v;
13237   if (this->start_->type()->integer_type() == NULL
13238       && !this->start_->type()->is_error()
13239       && (!this->start_->type()->is_abstract()
13240 	  || !this->start_->numeric_constant_value(&nc)
13241 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13242     this->report_error(_("index must be integer"));
13243   if (this->end_ != NULL
13244       && this->end_->type()->integer_type() == NULL
13245       && !this->end_->type()->is_error()
13246       && !this->end_->is_nil_expression()
13247       && !this->end_->is_error_expression()
13248       && (!this->end_->type()->is_abstract()
13249 	  || !this->end_->numeric_constant_value(&nc)
13250 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13251     this->report_error(_("slice end must be integer"));
13252   if (this->cap_ != NULL
13253       && this->cap_->type()->integer_type() == NULL
13254       && !this->cap_->type()->is_error()
13255       && !this->cap_->is_nil_expression()
13256       && !this->cap_->is_error_expression()
13257       && (!this->cap_->type()->is_abstract()
13258 	  || !this->cap_->numeric_constant_value(&nc)
13259 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13260     this->report_error(_("slice capacity must be integer"));
13261 
13262   Array_type* array_type = this->array_->type()->array_type();
13263   if (array_type == NULL)
13264     {
13265       go_assert(this->array_->type()->is_error());
13266       return;
13267     }
13268 
13269   unsigned int int_bits =
13270     Type::lookup_integer_type("int")->integer_type()->bits();
13271 
13272   Numeric_constant lvalnc;
13273   mpz_t lval;
13274   bool lval_valid = (array_type->length() != NULL
13275 		     && array_type->length()->numeric_constant_value(&lvalnc)
13276 		     && lvalnc.to_int(&lval));
13277   Numeric_constant inc;
13278   mpz_t ival;
13279   bool ival_valid = false;
13280   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
13281     {
13282       ival_valid = true;
13283       if (mpz_sgn(ival) < 0
13284 	  || mpz_sizeinbase(ival, 2) >= int_bits
13285 	  || (lval_valid
13286 	      && (this->end_ == NULL
13287 		  ? mpz_cmp(ival, lval) >= 0
13288 		  : mpz_cmp(ival, lval) > 0)))
13289 	{
13290 	  go_error_at(this->start_->location(), "array index out of bounds");
13291 	  this->set_is_error();
13292 	}
13293     }
13294   if (this->end_ != NULL && !this->end_->is_nil_expression())
13295     {
13296       Numeric_constant enc;
13297       mpz_t eval;
13298       bool eval_valid = false;
13299       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
13300 	{
13301 	  eval_valid = true;
13302 	  if (mpz_sgn(eval) < 0
13303 	      || mpz_sizeinbase(eval, 2) >= int_bits
13304 	      || (lval_valid && mpz_cmp(eval, lval) > 0))
13305 	    {
13306 	      go_error_at(this->end_->location(), "array index out of bounds");
13307 	      this->set_is_error();
13308 	    }
13309 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
13310 	    this->report_error(_("inverted slice range"));
13311 	}
13312 
13313       Numeric_constant cnc;
13314       mpz_t cval;
13315       if (this->cap_ != NULL
13316           && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
13317         {
13318           if (mpz_sgn(cval) < 0
13319               || mpz_sizeinbase(cval, 2) >= int_bits
13320               || (lval_valid && mpz_cmp(cval, lval) > 0))
13321             {
13322               go_error_at(this->cap_->location(), "array index out of bounds");
13323               this->set_is_error();
13324             }
13325 	  else if (ival_valid && mpz_cmp(ival, cval) > 0)
13326 	    {
13327 	      go_error_at(this->cap_->location(),
13328                           "invalid slice index: capacity less than start");
13329 	      this->set_is_error();
13330 	    }
13331           else if (eval_valid && mpz_cmp(eval, cval) > 0)
13332             {
13333               go_error_at(this->cap_->location(),
13334                           "invalid slice index: capacity less than length");
13335               this->set_is_error();
13336             }
13337           mpz_clear(cval);
13338         }
13339 
13340       if (eval_valid)
13341         mpz_clear(eval);
13342     }
13343   if (ival_valid)
13344     mpz_clear(ival);
13345   if (lval_valid)
13346     mpz_clear(lval);
13347 
13348   // A slice of an array requires an addressable array.  A slice of a
13349   // slice is always possible.
13350   if (this->end_ != NULL && !array_type->is_slice_type())
13351     {
13352       if (!this->array_->is_addressable())
13353 	this->report_error(_("slice of unaddressable value"));
13354       else
13355         // Set the array address taken but not escape. The escape
13356         // analysis will make it escape to heap when needed.
13357         this->array_->address_taken(false);
13358     }
13359 }
13360 
13361 // The subexpressions of an array index must be evaluated in order.
13362 // If this is indexing into an array, rather than a slice, then only
13363 // the index should be evaluated.  Since this is called for values on
13364 // the left hand side of an assigment, evaluating the array, meaning
13365 // copying the array, will cause a different array to be modified.
13366 
13367 bool
do_must_eval_subexpressions_in_order(int * skip) const13368 Array_index_expression::do_must_eval_subexpressions_in_order(
13369     int* skip) const
13370 {
13371   *skip = this->array_->type()->is_slice_type() ? 0 : 1;
13372   return true;
13373 }
13374 
13375 // Flatten array indexing: add temporary variables and bounds checks.
13376 
13377 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13378 Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
13379                                    Statement_inserter* inserter)
13380 {
13381   if (this->is_flattened_)
13382     return this;
13383   this->is_flattened_ = true;
13384 
13385   Location loc = this->location();
13386 
13387   if (this->is_error_expression())
13388     return Expression::make_error(loc);
13389 
13390   Expression* array = this->array_;
13391   Expression* start = this->start_;
13392   Expression* end = this->end_;
13393   Expression* cap = this->cap_;
13394   if (array->is_error_expression()
13395       || array->type()->is_error_type()
13396       || start->is_error_expression()
13397       || start->type()->is_error_type()
13398       || (end != NULL
13399           && (end->is_error_expression() || end->type()->is_error_type()))
13400       || (cap != NULL
13401           && (cap->is_error_expression() || cap->type()->is_error_type())))
13402     {
13403       go_assert(saw_errors());
13404       return Expression::make_error(loc);
13405     }
13406 
13407   Array_type* array_type = this->array_->type()->array_type();
13408   if (array_type == NULL)
13409     {
13410       go_assert(saw_errors());
13411       return Expression::make_error(loc);
13412     }
13413 
13414   Temporary_statement* temp;
13415   if (array_type->is_slice_type() && !array->is_multi_eval_safe())
13416     {
13417       temp = Statement::make_temporary(NULL, array, loc);
13418       inserter->insert(temp);
13419       this->array_ = Expression::make_temporary_reference(temp, loc);
13420       array = this->array_;
13421     }
13422   if (!start->is_multi_eval_safe())
13423     {
13424       temp = Statement::make_temporary(NULL, start, loc);
13425       inserter->insert(temp);
13426       this->start_ = Expression::make_temporary_reference(temp, loc);
13427       start = this->start_;
13428     }
13429   if (end != NULL
13430       && !end->is_nil_expression()
13431       && !end->is_multi_eval_safe())
13432     {
13433       temp = Statement::make_temporary(NULL, end, loc);
13434       inserter->insert(temp);
13435       this->end_ = Expression::make_temporary_reference(temp, loc);
13436       end = this->end_;
13437     }
13438   if (cap != NULL && !cap->is_multi_eval_safe())
13439     {
13440       temp = Statement::make_temporary(NULL, cap, loc);
13441       inserter->insert(temp);
13442       this->cap_ = Expression::make_temporary_reference(temp, loc);
13443       cap = this->cap_;
13444     }
13445 
13446   if (!this->needs_bounds_check_)
13447     return this;
13448 
13449   Expression* len;
13450   if (!array_type->is_slice_type())
13451     {
13452       len = array_type->get_length(gogo, this->array_);
13453       go_assert(len->is_constant());
13454     }
13455   else
13456     {
13457       len = array_type->get_length(gogo, this->array_->copy());
13458       temp = Statement::make_temporary(NULL, len, loc);
13459       inserter->insert(temp);
13460       len = Expression::make_temporary_reference(temp, loc);
13461     }
13462 
13463   Expression* scap = NULL;
13464   if (array_type->is_slice_type())
13465     {
13466       scap = array_type->get_capacity(gogo, this->array_->copy());
13467       temp = Statement::make_temporary(NULL, scap, loc);
13468       inserter->insert(temp);
13469       scap = Expression::make_temporary_reference(temp, loc);
13470     }
13471 
13472   // The order of bounds checks here matches the order used by the gc
13473   // compiler, as tested by issue30116[u].go.
13474 
13475   if (cap != NULL)
13476     {
13477       if (array_type->is_slice_type())
13478 	Expression::check_bounds(cap, OPERATOR_LE, scap,
13479 				 Runtime::PANIC_SLICE3_ACAP,
13480 				 Runtime::PANIC_SLICE3_ACAP_U,
13481 				 Runtime::PANIC_EXTEND_SLICE3_ACAP,
13482 				 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
13483 				 inserter, loc);
13484       else
13485 	Expression::check_bounds(cap, OPERATOR_LE, len,
13486 				 Runtime::PANIC_SLICE3_ALEN,
13487 				 Runtime::PANIC_SLICE3_ALEN_U,
13488 				 Runtime::PANIC_EXTEND_SLICE3_ALEN,
13489 				 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
13490 				 inserter, loc);
13491 
13492       Expression* start_bound = cap;
13493       if (end != NULL && !end->is_nil_expression())
13494 	{
13495 	  Expression::check_bounds(end, OPERATOR_LE, cap,
13496 				   Runtime::PANIC_SLICE3_B,
13497 				   Runtime::PANIC_SLICE3_B_U,
13498 				   Runtime::PANIC_EXTEND_SLICE3_B,
13499 				   Runtime::PANIC_EXTEND_SLICE3_B_U,
13500 				   inserter, loc);
13501 	  start_bound = end;
13502 	}
13503 
13504       Expression::check_bounds(start, OPERATOR_LE, start_bound,
13505 			       Runtime::PANIC_SLICE3_C,
13506 			       Runtime::PANIC_SLICE3_C_U,
13507 			       Runtime::PANIC_EXTEND_SLICE3_C,
13508 			       Runtime::PANIC_EXTEND_SLICE3_C_U,
13509 			       inserter, loc);
13510     }
13511   else if (end != NULL && !end->is_nil_expression())
13512     {
13513       if (array_type->is_slice_type())
13514 	Expression::check_bounds(end, OPERATOR_LE, scap,
13515 				 Runtime::PANIC_SLICE_ACAP,
13516 				 Runtime::PANIC_SLICE_ACAP_U,
13517 				 Runtime::PANIC_EXTEND_SLICE_ACAP,
13518 				 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
13519 				 inserter, loc);
13520       else
13521 	Expression::check_bounds(end, OPERATOR_LE, len,
13522 				 Runtime::PANIC_SLICE_ALEN,
13523 				 Runtime::PANIC_SLICE_ALEN_U,
13524 				 Runtime::PANIC_EXTEND_SLICE_ALEN,
13525 				 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13526 				 inserter, loc);
13527 
13528       Expression::check_bounds(start, OPERATOR_LE, end,
13529 			       Runtime::PANIC_SLICE_B,
13530 			       Runtime::PANIC_SLICE_B_U,
13531 			       Runtime::PANIC_EXTEND_SLICE_B,
13532 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13533 			       inserter, loc);
13534     }
13535   else if (end != NULL)
13536     {
13537       Expression* start_bound;
13538       if (array_type->is_slice_type())
13539 	start_bound = scap;
13540       else
13541 	start_bound = len;
13542       Expression::check_bounds(start, OPERATOR_LE, start_bound,
13543 			       Runtime::PANIC_SLICE_B,
13544 			       Runtime::PANIC_SLICE_B_U,
13545 			       Runtime::PANIC_EXTEND_SLICE_B,
13546 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13547 			       inserter, loc);
13548     }
13549   else
13550     Expression::check_bounds(start, OPERATOR_LT, len,
13551 			     Runtime::PANIC_INDEX,
13552 			     Runtime::PANIC_INDEX_U,
13553 			     Runtime::PANIC_EXTEND_INDEX,
13554 			     Runtime::PANIC_EXTEND_INDEX_U,
13555 			     inserter, loc);
13556 
13557   return this;
13558 }
13559 
13560 // Return whether this expression is addressable.
13561 
13562 bool
do_is_addressable() const13563 Array_index_expression::do_is_addressable() const
13564 {
13565   // A slice expression is not addressable.
13566   if (this->end_ != NULL)
13567     return false;
13568 
13569   // An index into a slice is addressable.
13570   if (this->array_->type()->is_slice_type())
13571     return true;
13572 
13573   // An index into an array is addressable if the array is
13574   // addressable.
13575   return this->array_->is_addressable();
13576 }
13577 
13578 void
do_address_taken(bool escapes)13579 Array_index_expression::do_address_taken(bool escapes)
13580 {
13581   // In &x[0], if x is a slice, then x's address is not taken.
13582   if (!this->array_->type()->is_slice_type())
13583     this->array_->address_taken(escapes);
13584 }
13585 
13586 // Get the backend representation for an array index.
13587 
13588 Bexpression*
do_get_backend(Translate_context * context)13589 Array_index_expression::do_get_backend(Translate_context* context)
13590 {
13591   Array_type* array_type = this->array_->type()->array_type();
13592   if (array_type == NULL)
13593     {
13594       go_assert(this->array_->type()->is_error());
13595       return context->backend()->error_expression();
13596     }
13597   go_assert(!array_type->is_slice_type()
13598 	    || this->array_->is_multi_eval_safe());
13599 
13600   Location loc = this->location();
13601   Gogo* gogo = context->gogo();
13602 
13603   Type* int_type = Type::lookup_integer_type("int");
13604   Btype* int_btype = int_type->get_backend(gogo);
13605 
13606   // Convert the length and capacity to "int".  FIXME: Do we need to
13607   // do this?
13608   Bexpression* length = NULL;
13609   if (this->end_ == NULL || this->end_->is_nil_expression())
13610     {
13611       Expression* len = array_type->get_length(gogo, this->array_);
13612       length = len->get_backend(context);
13613       length = gogo->backend()->convert_expression(int_btype, length, loc);
13614     }
13615 
13616   Bexpression* capacity = NULL;
13617   if (this->end_ != NULL)
13618     {
13619       Expression* cap = array_type->get_capacity(gogo, this->array_);
13620       capacity = cap->get_backend(context);
13621       capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
13622     }
13623 
13624   Bexpression* cap_arg = capacity;
13625   if (this->cap_ != NULL)
13626     {
13627       cap_arg = this->cap_->get_backend(context);
13628       cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
13629     }
13630 
13631   if (length == NULL)
13632     length = cap_arg;
13633 
13634   if (this->start_->type()->integer_type() == NULL
13635       && !Type::are_convertible(int_type, this->start_->type(), NULL))
13636     {
13637       go_assert(saw_errors());
13638       return context->backend()->error_expression();
13639     }
13640 
13641   Bexpression* start = this->start_->get_backend(context);
13642   start = gogo->backend()->convert_expression(int_btype, start, loc);
13643 
13644   Bfunction* bfn = context->function()->func_value()->get_decl();
13645   if (this->end_ == NULL)
13646     {
13647       // Simple array indexing.
13648       Bexpression* ret;
13649       if (!array_type->is_slice_type())
13650 	{
13651 	  Bexpression* array = this->array_->get_backend(context);
13652 	  ret = gogo->backend()->array_index_expression(array, start, loc);
13653 	}
13654       else
13655 	{
13656 	  Expression* valptr =
13657               array_type->get_value_pointer(gogo, this->array_,
13658                                             this->is_lvalue_);
13659 	  Bexpression* ptr = valptr->get_backend(context);
13660           ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
13661 
13662 	  Type* ele_type = this->array_->type()->array_type()->element_type();
13663 	  Btype* ele_btype = ele_type->get_backend(gogo);
13664 	  ret = gogo->backend()->indirect_expression(ele_btype, ptr, false,
13665 						     loc);
13666 	}
13667       return ret;
13668     }
13669 
13670   // Slice expression.
13671 
13672   Bexpression* end;
13673   if (this->end_->is_nil_expression())
13674     end = length;
13675   else
13676     {
13677       end = this->end_->get_backend(context);
13678       end = gogo->backend()->convert_expression(int_btype, end, loc);
13679     }
13680 
13681   Bexpression* result_length =
13682     gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
13683 
13684   Bexpression* result_capacity =
13685     gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
13686 
13687   // If the new capacity is zero, don't change val.  Otherwise we can
13688   // get a pointer to the next object in memory, keeping it live
13689   // unnecessarily.  When the capacity is zero, the actual pointer
13690   // value doesn't matter.
13691   Bexpression* zero =
13692     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13693   Bexpression* cond =
13694     gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
13695 				       loc);
13696   Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
13697 								cond, zero,
13698 								start, loc);
13699   Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
13700                                                      this->is_lvalue_);
13701   Bexpression* val = valptr->get_backend(context);
13702   val = gogo->backend()->pointer_offset_expression(val, offset, loc);
13703 
13704   Btype* struct_btype = this->type()->get_backend(gogo);
13705   std::vector<Bexpression*> init;
13706   init.push_back(val);
13707   init.push_back(result_length);
13708   init.push_back(result_capacity);
13709 
13710   return gogo->backend()->constructor_expression(struct_btype, init, loc);
13711 }
13712 
13713 // Export an array index expression.
13714 
13715 void
do_export(Export_function_body * efb) const13716 Array_index_expression::do_export(Export_function_body* efb) const
13717 {
13718   efb->write_c_string("(");
13719   this->array_->export_expression(efb);
13720   efb->write_c_string(")[");
13721 
13722   Type* old_context = efb->type_context();
13723   efb->set_type_context(Type::lookup_integer_type("int"));
13724 
13725   this->start_->export_expression(efb);
13726   if (this->end_ == NULL)
13727     go_assert(this->cap_ == NULL);
13728   else
13729     {
13730       efb->write_c_string(":");
13731       if (!this->end_->is_nil_expression())
13732 	this->end_->export_expression(efb);
13733       if (this->cap_ != NULL)
13734 	{
13735 	  efb->write_c_string(":");
13736 	  this->cap_->export_expression(efb);
13737 	}
13738     }
13739 
13740   efb->set_type_context(old_context);
13741 
13742   efb->write_c_string("]");
13743 }
13744 
13745 // Dump ast representation for an array index expression.
13746 
13747 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13748 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13749     const
13750 {
13751   Index_expression::dump_index_expression(ast_dump_context, this->array_,
13752                                           this->start_, this->end_, this->cap_);
13753 }
13754 
13755 // Make an array index expression.  END and CAP may be NULL.
13756 
13757 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)13758 Expression::make_array_index(Expression* array, Expression* start,
13759                              Expression* end, Expression* cap,
13760                              Location location)
13761 {
13762   return new Array_index_expression(array, start, end, cap, location);
13763 }
13764 
13765 // Class String_index_expression.
13766 
13767 // String index traversal.
13768 
13769 int
do_traverse(Traverse * traverse)13770 String_index_expression::do_traverse(Traverse* traverse)
13771 {
13772   if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
13773     return TRAVERSE_EXIT;
13774   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
13775     return TRAVERSE_EXIT;
13776   if (this->end_ != NULL)
13777     {
13778       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13779 	return TRAVERSE_EXIT;
13780     }
13781   return TRAVERSE_CONTINUE;
13782 }
13783 
13784 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13785 String_index_expression::do_flatten(Gogo*, Named_object*,
13786                                     Statement_inserter* inserter)
13787 {
13788   if (this->is_flattened_)
13789     return this;
13790   this->is_flattened_ = true;
13791 
13792   Location loc = this->location();
13793 
13794   if (this->is_error_expression())
13795     return Expression::make_error(loc);
13796 
13797   Expression* string = this->string_;
13798   Expression* start = this->start_;
13799   Expression* end = this->end_;
13800   if (string->is_error_expression()
13801       || string->type()->is_error_type()
13802       || start->is_error_expression()
13803       || start->type()->is_error_type()
13804       || (end != NULL
13805           && (end->is_error_expression() || end->type()->is_error_type())))
13806     {
13807       go_assert(saw_errors());
13808       return Expression::make_error(loc);
13809     }
13810 
13811   Temporary_statement* temp;
13812   if (!string->is_multi_eval_safe())
13813     {
13814       temp = Statement::make_temporary(NULL, string, loc);
13815       inserter->insert(temp);
13816       this->string_ = Expression::make_temporary_reference(temp, loc);
13817       string = this->string_;
13818     }
13819   if (!start->is_multi_eval_safe())
13820     {
13821       temp = Statement::make_temporary(NULL, start, loc);
13822       inserter->insert(temp);
13823       this->start_ = Expression::make_temporary_reference(temp, loc);
13824       start = this->start_;
13825     }
13826   if (end != NULL
13827       && !end->is_nil_expression()
13828       && !end->is_multi_eval_safe())
13829     {
13830       temp = Statement::make_temporary(NULL, end, loc);
13831       inserter->insert(temp);
13832       this->end_ = Expression::make_temporary_reference(temp, loc);
13833       end = this->end_;
13834     }
13835 
13836   Expression* len = Expression::make_string_info(string->copy(),
13837 						 STRING_INFO_LENGTH, loc);
13838   temp = Statement::make_temporary(NULL, len, loc);
13839   inserter->insert(temp);
13840   len = Expression::make_temporary_reference(temp, loc);
13841 
13842   // The order of bounds checks here matches the order used by the gc
13843   // compiler, as tested by issue30116[u].go.
13844 
13845   if (end != NULL && !end->is_nil_expression())
13846     {
13847       Expression::check_bounds(end, OPERATOR_LE, len,
13848 			       Runtime::PANIC_SLICE_ALEN,
13849 			       Runtime::PANIC_SLICE_ALEN_U,
13850 			       Runtime::PANIC_EXTEND_SLICE_ALEN,
13851 			       Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13852 			       inserter, loc);
13853       Expression::check_bounds(start, OPERATOR_LE, end,
13854 			       Runtime::PANIC_SLICE_B,
13855 			       Runtime::PANIC_SLICE_B_U,
13856 			       Runtime::PANIC_EXTEND_SLICE_B,
13857 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13858 			       inserter, loc);
13859     }
13860   else if (end != NULL)
13861     Expression::check_bounds(start, OPERATOR_LE, len,
13862 			     Runtime::PANIC_SLICE_B,
13863 			     Runtime::PANIC_SLICE_B_U,
13864 			     Runtime::PANIC_EXTEND_SLICE_B,
13865 			     Runtime::PANIC_EXTEND_SLICE_B_U,
13866 			     inserter, loc);
13867   else
13868     Expression::check_bounds(start, OPERATOR_LT, len,
13869 			     Runtime::PANIC_INDEX,
13870 			     Runtime::PANIC_INDEX_U,
13871 			     Runtime::PANIC_EXTEND_INDEX,
13872 			     Runtime::PANIC_EXTEND_INDEX_U,
13873 			     inserter, loc);
13874 
13875   return this;
13876 }
13877 
13878 // Return the type of a string index.
13879 
13880 Type*
do_type()13881 String_index_expression::do_type()
13882 {
13883   if (this->end_ == NULL)
13884     return Type::lookup_integer_type("byte");
13885   else
13886     return this->string_->type();
13887 }
13888 
13889 // Determine the type of a string index.
13890 
13891 void
do_determine_type(const Type_context *)13892 String_index_expression::do_determine_type(const Type_context*)
13893 {
13894   this->string_->determine_type_no_context();
13895 
13896   Type_context index_context(Type::lookup_integer_type("int"), false);
13897   this->start_->determine_type(&index_context);
13898   if (this->end_ != NULL)
13899     this->end_->determine_type(&index_context);
13900 }
13901 
13902 // Check types of a string index.
13903 
13904 void
do_check_types(Gogo *)13905 String_index_expression::do_check_types(Gogo*)
13906 {
13907   Numeric_constant nc;
13908   unsigned long v;
13909   if (this->start_->type()->integer_type() == NULL
13910       && !this->start_->type()->is_error()
13911       && (!this->start_->type()->is_abstract()
13912 	  || !this->start_->numeric_constant_value(&nc)
13913 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13914     this->report_error(_("index must be integer"));
13915   if (this->end_ != NULL
13916       && this->end_->type()->integer_type() == NULL
13917       && !this->end_->type()->is_error()
13918       && !this->end_->is_nil_expression()
13919       && !this->end_->is_error_expression()
13920       && (!this->end_->type()->is_abstract()
13921 	  || !this->end_->numeric_constant_value(&nc)
13922 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13923     this->report_error(_("slice end must be integer"));
13924 
13925   std::string sval;
13926   bool sval_valid = this->string_->string_constant_value(&sval);
13927 
13928   Numeric_constant inc;
13929   mpz_t ival;
13930   bool ival_valid = false;
13931   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
13932     {
13933       ival_valid = true;
13934       if (mpz_sgn(ival) < 0
13935 	  || (sval_valid
13936 	      && (this->end_ == NULL
13937 		  ? mpz_cmp_ui(ival, sval.length()) >= 0
13938 		  : mpz_cmp_ui(ival, sval.length()) > 0)))
13939 	{
13940 	  go_error_at(this->start_->location(), "string index out of bounds");
13941 	  this->set_is_error();
13942 	}
13943     }
13944   if (this->end_ != NULL && !this->end_->is_nil_expression())
13945     {
13946       Numeric_constant enc;
13947       mpz_t eval;
13948       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
13949 	{
13950 	  if (mpz_sgn(eval) < 0
13951 	      || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
13952 	    {
13953 	      go_error_at(this->end_->location(), "string index out of bounds");
13954 	      this->set_is_error();
13955 	    }
13956 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
13957 	    this->report_error(_("inverted slice range"));
13958 	  mpz_clear(eval);
13959 	}
13960     }
13961   if (ival_valid)
13962     mpz_clear(ival);
13963 }
13964 
13965 // Get the backend representation for a string index.
13966 
13967 Bexpression*
do_get_backend(Translate_context * context)13968 String_index_expression::do_get_backend(Translate_context* context)
13969 {
13970   Location loc = this->location();
13971   Gogo* gogo = context->gogo();
13972 
13973   Type* int_type = Type::lookup_integer_type("int");
13974 
13975   // It is possible that an error occurred earlier because the start index
13976   // cannot be represented as an integer type.  In this case, we shouldn't
13977   // try casting the starting index into an integer since
13978   // Type_conversion_expression will fail to get the backend representation.
13979   // FIXME.
13980   if (this->start_->type()->integer_type() == NULL
13981       && !Type::are_convertible(int_type, this->start_->type(), NULL))
13982     {
13983       go_assert(saw_errors());
13984       return context->backend()->error_expression();
13985     }
13986 
13987   go_assert(this->string_->is_multi_eval_safe());
13988   go_assert(this->start_->is_multi_eval_safe());
13989 
13990   Expression* start = Expression::make_cast(int_type, this->start_, loc);
13991   Bfunction* bfn = context->function()->func_value()->get_decl();
13992 
13993   Expression* length =
13994     Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
13995   Expression* bytes =
13996     Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
13997 
13998   Bexpression* bstart = start->get_backend(context);
13999   Bexpression* ptr = bytes->get_backend(context);
14000 
14001   if (this->end_ == NULL)
14002     {
14003       ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
14004       Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
14005       return gogo->backend()->indirect_expression(ubtype, ptr, false, loc);
14006     }
14007 
14008   Expression* end = NULL;
14009   if (this->end_->is_nil_expression())
14010     end = length;
14011   else
14012     {
14013       go_assert(this->end_->is_multi_eval_safe());
14014       end = Expression::make_cast(int_type, this->end_, loc);
14015     }
14016 
14017   end = end->copy();
14018   Bexpression* bend = end->get_backend(context);
14019   Bexpression* new_length =
14020     gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
14021 
14022   // If the new length is zero, don't change pointer.  Otherwise we can
14023   // get a pointer to the next object in memory, keeping it live
14024   // unnecessarily.  When the length is zero, the actual pointer
14025   // value doesn't matter.
14026   Btype* int_btype = int_type->get_backend(gogo);
14027   Bexpression* zero =
14028     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
14029   Bexpression* cond =
14030     gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
14031                                        loc);
14032   Bexpression* offset =
14033     gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
14034                                             bstart, loc);
14035 
14036   ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
14037 
14038   Btype* str_btype = this->type()->get_backend(gogo);
14039   std::vector<Bexpression*> init;
14040   init.push_back(ptr);
14041   init.push_back(new_length);
14042   return gogo->backend()->constructor_expression(str_btype, init, loc);
14043 }
14044 
14045 // Export a string index expression.
14046 
14047 void
do_export(Export_function_body * efb) const14048 String_index_expression::do_export(Export_function_body* efb) const
14049 {
14050   efb->write_c_string("(");
14051   this->string_->export_expression(efb);
14052   efb->write_c_string(")[");
14053 
14054   Type* old_context = efb->type_context();
14055   efb->set_type_context(Type::lookup_integer_type("int"));
14056 
14057   this->start_->export_expression(efb);
14058   if (this->end_ != NULL)
14059     {
14060       efb->write_c_string(":");
14061       if (!this->end_->is_nil_expression())
14062 	this->end_->export_expression(efb);
14063     }
14064 
14065   efb->set_type_context(old_context);
14066 
14067   efb->write_c_string("]");
14068 }
14069 
14070 // Dump ast representation for a string index expression.
14071 
14072 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14073 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14074     const
14075 {
14076   Index_expression::dump_index_expression(ast_dump_context, this->string_,
14077                                           this->start_, this->end_, NULL);
14078 }
14079 
14080 // Make a string index expression.  END may be NULL.
14081 
14082 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)14083 Expression::make_string_index(Expression* string, Expression* start,
14084 			      Expression* end, Location location)
14085 {
14086   return new String_index_expression(string, start, end, location);
14087 }
14088 
14089 // Class Map_index.
14090 
14091 // Get the type of the map.
14092 
14093 Map_type*
get_map_type() const14094 Map_index_expression::get_map_type() const
14095 {
14096   Map_type* mt = this->map_->type()->map_type();
14097   if (mt == NULL)
14098     go_assert(saw_errors());
14099   return mt;
14100 }
14101 
14102 // Map index traversal.
14103 
14104 int
do_traverse(Traverse * traverse)14105 Map_index_expression::do_traverse(Traverse* traverse)
14106 {
14107   if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
14108     return TRAVERSE_EXIT;
14109   return Expression::traverse(&this->index_, traverse);
14110 }
14111 
14112 // We need to pass in a pointer to the key, so flatten the index into a
14113 // temporary variable if it isn't already.  The value pointer will be
14114 // dereferenced and checked for nil, so flatten into a temporary to avoid
14115 // recomputation.
14116 
14117 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)14118 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
14119 				 Statement_inserter* inserter)
14120 {
14121   Location loc = this->location();
14122   Map_type* mt = this->get_map_type();
14123   if (this->index()->is_error_expression()
14124       || this->index()->type()->is_error_type()
14125       || mt->is_error_type())
14126     {
14127       go_assert(saw_errors());
14128       return Expression::make_error(loc);
14129     }
14130 
14131   // Avoid copy for string([]byte) conversions used in map keys.
14132   // mapaccess doesn't keep the reference, so this is safe.
14133   Type_conversion_expression* ce = this->index_->conversion_expression();
14134   if (ce != NULL && ce->type()->is_string_type()
14135       && ce->expr()->type()->is_slice_type())
14136     ce->set_no_copy(true);
14137 
14138   if (!Type::are_identical(mt->key_type(), this->index_->type(),
14139 			   Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
14140 			   NULL))
14141     {
14142       if (this->index_->type()->interface_type() != NULL
14143 	  && !this->index_->is_multi_eval_safe())
14144 	{
14145 	  Temporary_statement* temp =
14146 	    Statement::make_temporary(NULL, this->index_, loc);
14147 	  inserter->insert(temp);
14148 	  this->index_ = Expression::make_temporary_reference(temp, loc);
14149 	}
14150       this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
14151 							this->index_, loc);
14152     }
14153 
14154   if (!this->index_->is_multi_eval_safe())
14155     {
14156       Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
14157                                                             loc);
14158       inserter->insert(temp);
14159       this->index_ = Expression::make_temporary_reference(temp, loc);
14160     }
14161 
14162   if (this->value_pointer_ == NULL)
14163     this->get_value_pointer(gogo);
14164   if (this->value_pointer_->is_error_expression()
14165       || this->value_pointer_->type()->is_error_type())
14166     return Expression::make_error(loc);
14167   if (!this->value_pointer_->is_multi_eval_safe())
14168     {
14169       Temporary_statement* temp =
14170 	Statement::make_temporary(NULL, this->value_pointer_, loc);
14171       inserter->insert(temp);
14172       this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
14173     }
14174 
14175   return this;
14176 }
14177 
14178 // Return the type of a map index.
14179 
14180 Type*
do_type()14181 Map_index_expression::do_type()
14182 {
14183   Map_type* mt = this->get_map_type();
14184   if (mt == NULL)
14185     return Type::make_error_type();
14186   return mt->val_type();
14187 }
14188 
14189 // Fix the type of a map index.
14190 
14191 void
do_determine_type(const Type_context *)14192 Map_index_expression::do_determine_type(const Type_context*)
14193 {
14194   this->map_->determine_type_no_context();
14195   Map_type* mt = this->get_map_type();
14196   Type* key_type = mt == NULL ? NULL : mt->key_type();
14197   Type_context subcontext(key_type, false);
14198   this->index_->determine_type(&subcontext);
14199 }
14200 
14201 // Check types of a map index.
14202 
14203 void
do_check_types(Gogo *)14204 Map_index_expression::do_check_types(Gogo*)
14205 {
14206   std::string reason;
14207   Map_type* mt = this->get_map_type();
14208   if (mt == NULL)
14209     return;
14210   if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
14211     {
14212       if (reason.empty())
14213 	this->report_error(_("incompatible type for map index"));
14214       else
14215 	{
14216 	  go_error_at(this->location(), "incompatible type for map index (%s)",
14217                       reason.c_str());
14218 	  this->set_is_error();
14219 	}
14220     }
14221 }
14222 
14223 // Add explicit type conversions.
14224 
14225 void
do_add_conversions()14226 Map_index_expression::do_add_conversions()
14227 {
14228   Map_type* mt = this->get_map_type();
14229   if (mt == NULL)
14230     return;
14231   Type* lt = mt->key_type();
14232   Type* rt = this->index_->type();
14233   if (!Type::are_identical(lt, rt, 0, NULL)
14234       && lt->interface_type() != NULL)
14235     this->index_ = Expression::make_cast(lt, this->index_, this->location());
14236 }
14237 
14238 // Get the backend representation for a map index.
14239 
14240 Bexpression*
do_get_backend(Translate_context * context)14241 Map_index_expression::do_get_backend(Translate_context* context)
14242 {
14243   Map_type* type = this->get_map_type();
14244   if (type == NULL)
14245     {
14246       go_assert(saw_errors());
14247       return context->backend()->error_expression();
14248     }
14249 
14250   go_assert(this->value_pointer_ != NULL
14251             && this->value_pointer_->is_multi_eval_safe());
14252 
14253   Expression* val = Expression::make_dereference(this->value_pointer_,
14254                                                  NIL_CHECK_NOT_NEEDED,
14255                                                  this->location());
14256   return val->get_backend(context);
14257 }
14258 
14259 // Get an expression for the map index.  This returns an expression
14260 // that evaluates to a pointer to a value.  If the key is not in the
14261 // map, the pointer will point to a zero value.
14262 
14263 Expression*
get_value_pointer(Gogo * gogo)14264 Map_index_expression::get_value_pointer(Gogo* gogo)
14265 {
14266   if (this->value_pointer_ == NULL)
14267     {
14268       Map_type* type = this->get_map_type();
14269       if (type == NULL)
14270 	{
14271 	  go_assert(saw_errors());
14272 	  return Expression::make_error(this->location());
14273 	}
14274 
14275       Location loc = this->location();
14276       Expression* map_ref = this->map_;
14277 
14278       Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
14279 						     this->index_,
14280                                                      loc);
14281 
14282       Expression* type_expr = Expression::make_type_descriptor(type, loc);
14283       Expression* zero = type->fat_zero_value(gogo);
14284       Expression* map_index;
14285       if (zero == NULL)
14286         {
14287           Runtime::Function code;
14288           Expression* key;
14289           switch (type->algorithm(gogo))
14290             {
14291               case Map_type::MAP_ALG_FAST32:
14292               case Map_type::MAP_ALG_FAST32PTR:
14293                 {
14294                   Type* uint32_type = Type::lookup_integer_type("uint32");
14295                   Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
14296                   key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
14297                                                      loc);
14298                   key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
14299                                                      loc);
14300                   code = Runtime::MAPACCESS1_FAST32;
14301                   break;
14302                 }
14303               case Map_type::MAP_ALG_FAST64:
14304               case Map_type::MAP_ALG_FAST64PTR:
14305                 {
14306                   Type* uint64_type = Type::lookup_integer_type("uint64");
14307                   Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
14308                   key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
14309                                                      loc);
14310                   key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
14311                                                      loc);
14312                   code = Runtime::MAPACCESS1_FAST64;
14313                   break;
14314                 }
14315               case Map_type::MAP_ALG_FASTSTR:
14316                 key = this->index_;
14317                 code = Runtime::MAPACCESS1_FASTSTR;
14318                 break;
14319               default:
14320                 key = index_ptr;
14321                 code = Runtime::MAPACCESS1;
14322                 break;
14323             }
14324           map_index = Runtime::make_call(code, loc, 3,
14325                                          type_expr, map_ref, key);
14326         }
14327       else
14328         map_index = Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
14329                                        type_expr, map_ref, index_ptr, zero);
14330 
14331       Type* val_type = type->val_type();
14332       this->value_pointer_ =
14333           Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
14334                                        map_index, this->location());
14335     }
14336 
14337   return this->value_pointer_;
14338 }
14339 
14340 // Export a map index expression.
14341 
14342 void
do_export(Export_function_body * efb) const14343 Map_index_expression::do_export(Export_function_body* efb) const
14344 {
14345   efb->write_c_string("(");
14346   this->map_->export_expression(efb);
14347   efb->write_c_string(")[");
14348 
14349   Type* old_context = efb->type_context();
14350   efb->set_type_context(this->get_map_type()->key_type());
14351 
14352   this->index_->export_expression(efb);
14353 
14354   efb->set_type_context(old_context);
14355 
14356   efb->write_c_string("]");
14357 }
14358 
14359 // Dump ast representation for a map index expression
14360 
14361 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14362 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14363     const
14364 {
14365   Index_expression::dump_index_expression(ast_dump_context, this->map_,
14366                                           this->index_, NULL, NULL);
14367 }
14368 
14369 // Make a map index expression.
14370 
14371 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)14372 Expression::make_map_index(Expression* map, Expression* index,
14373 			   Location location)
14374 {
14375   return new Map_index_expression(map, index, location);
14376 }
14377 
14378 // Class Field_reference_expression.
14379 
14380 // Lower a field reference expression.  There is nothing to lower, but
14381 // this is where we generate the tracking information for fields with
14382 // the magic go:"track" tag.
14383 
14384 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)14385 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
14386 				     Statement_inserter* inserter, int)
14387 {
14388   Struct_type* struct_type = this->expr_->type()->struct_type();
14389   if (struct_type == NULL)
14390     {
14391       // Error will be reported elsewhere.
14392       return this;
14393     }
14394   const Struct_field* field = struct_type->field(this->field_index_);
14395   if (field == NULL)
14396     return this;
14397   if (!field->has_tag())
14398     return this;
14399   if (field->tag().find("go:\"track\"") == std::string::npos)
14400     return this;
14401 
14402   // References from functions generated by the compiler don't count.
14403   if (function != NULL && function->func_value()->is_type_specific_function())
14404     return this;
14405 
14406   // We have found a reference to a tracked field.  Build a call to
14407   // the runtime function __go_fieldtrack with a string that describes
14408   // the field.  FIXME: We should only call this once per referenced
14409   // field per function, not once for each reference to the field.
14410 
14411   if (this->called_fieldtrack_)
14412     return this;
14413   this->called_fieldtrack_ = true;
14414 
14415   Location loc = this->location();
14416 
14417   std::string s = "fieldtrack \"";
14418   Named_type* nt = this->expr_->type()->unalias()->named_type();
14419   if (nt == NULL || nt->named_object()->package() == NULL)
14420     s.append(gogo->pkgpath());
14421   else
14422     s.append(nt->named_object()->package()->pkgpath());
14423   s.push_back('.');
14424   if (nt != NULL)
14425     s.append(Gogo::unpack_hidden_name(nt->name()));
14426   s.push_back('.');
14427   s.append(Gogo::unpack_hidden_name(field->field_name()));
14428   s.push_back('"');
14429 
14430   // We can't use a string here, because internally a string holds a
14431   // pointer to the actual bytes; when the linker garbage collects the
14432   // string, it won't garbage collect the bytes.  So we use a
14433   // [...]byte.
14434 
14435   Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
14436 
14437   Type* byte_type = Type::lookup_integer_type("byte");
14438   Array_type* array_type = Type::make_array_type(byte_type, length_expr);
14439   array_type->set_is_array_incomparable();
14440 
14441   Expression_list* bytes = new Expression_list();
14442   for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
14443     {
14444       unsigned char c = static_cast<unsigned char>(*p);
14445       bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
14446     }
14447 
14448   Expression* e = Expression::make_composite_literal(array_type, 0, false,
14449 						     bytes, false, loc);
14450 
14451   Variable* var = new Variable(array_type, e, true, false, false, loc);
14452 
14453   static int count;
14454   char buf[50];
14455   snprintf(buf, sizeof buf, "fieldtrack.%d", count);
14456   ++count;
14457 
14458   Named_object* no = gogo->add_variable(buf, var);
14459   e = Expression::make_var_reference(no, loc);
14460   e = Expression::make_unary(OPERATOR_AND, e, loc);
14461 
14462   Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
14463   gogo->lower_expression(function, inserter, &call);
14464   inserter->insert(Statement::make_statement(call, false));
14465 
14466   // Put this function, and the global variable we just created, into
14467   // unique sections.  This will permit the linker to garbage collect
14468   // them if they are not referenced.  The effect is that the only
14469   // strings, indicating field references, that will wind up in the
14470   // executable will be those for functions that are actually needed.
14471   if (function != NULL)
14472     function->func_value()->set_in_unique_section();
14473   var->set_in_unique_section();
14474 
14475   return this;
14476 }
14477 
14478 // Return the type of a field reference.
14479 
14480 Type*
do_type()14481 Field_reference_expression::do_type()
14482 {
14483   Type* type = this->expr_->type();
14484   if (type->is_error())
14485     return type;
14486   Struct_type* struct_type = type->struct_type();
14487   go_assert(struct_type != NULL);
14488   return struct_type->field(this->field_index_)->type();
14489 }
14490 
14491 // Check the types for a field reference.
14492 
14493 void
do_check_types(Gogo *)14494 Field_reference_expression::do_check_types(Gogo*)
14495 {
14496   Type* type = this->expr_->type();
14497   if (type->is_error())
14498     return;
14499   Struct_type* struct_type = type->struct_type();
14500   go_assert(struct_type != NULL);
14501   go_assert(struct_type->field(this->field_index_) != NULL);
14502 }
14503 
14504 // Get the backend representation for a field reference.
14505 
14506 Bexpression*
do_get_backend(Translate_context * context)14507 Field_reference_expression::do_get_backend(Translate_context* context)
14508 {
14509   Bexpression* bstruct = this->expr_->get_backend(context);
14510   return context->gogo()->backend()->struct_field_expression(bstruct,
14511 							     this->field_index_,
14512 							     this->location());
14513 }
14514 
14515 // Dump ast representation for a field reference expression.
14516 
14517 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14518 Field_reference_expression::do_dump_expression(
14519     Ast_dump_context* ast_dump_context) const
14520 {
14521   this->expr_->dump_expression(ast_dump_context);
14522   ast_dump_context->ostream() << "." <<  this->field_index_;
14523 }
14524 
14525 // Make a reference to a qualified identifier in an expression.
14526 
14527 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)14528 Expression::make_field_reference(Expression* expr, unsigned int field_index,
14529 				 Location location)
14530 {
14531   return new Field_reference_expression(expr, field_index, location);
14532 }
14533 
14534 // Class Interface_field_reference_expression.
14535 
14536 // Return an expression for the pointer to the function to call.
14537 
14538 Expression*
get_function()14539 Interface_field_reference_expression::get_function()
14540 {
14541   Expression* ref = this->expr_;
14542   Location loc = this->location();
14543   if (ref->type()->points_to() != NULL)
14544     ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
14545 
14546   Expression* mtable =
14547       Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
14548   Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
14549 
14550   std::string name = Gogo::unpack_hidden_name(this->name_);
14551   unsigned int index;
14552   const Struct_field* field = mtable_type->find_local_field(name, &index);
14553   go_assert(field != NULL);
14554 
14555   mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
14556   return Expression::make_field_reference(mtable, index, loc);
14557 }
14558 
14559 // Return an expression for the first argument to pass to the interface
14560 // function.
14561 
14562 Expression*
get_underlying_object()14563 Interface_field_reference_expression::get_underlying_object()
14564 {
14565   Expression* expr = this->expr_;
14566   if (expr->type()->points_to() != NULL)
14567     expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
14568                                         this->location());
14569   return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
14570                                          this->location());
14571 }
14572 
14573 // Traversal.
14574 
14575 int
do_traverse(Traverse * traverse)14576 Interface_field_reference_expression::do_traverse(Traverse* traverse)
14577 {
14578   return Expression::traverse(&this->expr_, traverse);
14579 }
14580 
14581 // Lower the expression.  If this expression is not called, we need to
14582 // evaluate the expression twice when converting to the backend
14583 // interface.  So introduce a temporary variable if necessary.
14584 
14585 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14586 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
14587 						 Statement_inserter* inserter)
14588 {
14589   if (this->expr_->is_error_expression()
14590       || this->expr_->type()->is_error_type())
14591     {
14592       go_assert(saw_errors());
14593       return Expression::make_error(this->location());
14594     }
14595 
14596   if (!this->expr_->is_multi_eval_safe())
14597     {
14598       Temporary_statement* temp =
14599 	Statement::make_temporary(NULL, this->expr_, this->location());
14600       inserter->insert(temp);
14601       this->expr_ = Expression::make_temporary_reference(temp, this->location());
14602     }
14603   return this;
14604 }
14605 
14606 // Return the type of an interface field reference.
14607 
14608 Type*
do_type()14609 Interface_field_reference_expression::do_type()
14610 {
14611   Type* expr_type = this->expr_->type();
14612 
14613   Type* points_to = expr_type->points_to();
14614   if (points_to != NULL)
14615     expr_type = points_to;
14616 
14617   Interface_type* interface_type = expr_type->interface_type();
14618   if (interface_type == NULL)
14619     return Type::make_error_type();
14620 
14621   const Typed_identifier* method = interface_type->find_method(this->name_);
14622   if (method == NULL)
14623     return Type::make_error_type();
14624 
14625   return method->type();
14626 }
14627 
14628 // Determine types.
14629 
14630 void
do_determine_type(const Type_context *)14631 Interface_field_reference_expression::do_determine_type(const Type_context*)
14632 {
14633   this->expr_->determine_type_no_context();
14634 }
14635 
14636 // Check the types for an interface field reference.
14637 
14638 void
do_check_types(Gogo *)14639 Interface_field_reference_expression::do_check_types(Gogo*)
14640 {
14641   Type* type = this->expr_->type();
14642 
14643   Type* points_to = type->points_to();
14644   if (points_to != NULL)
14645     type = points_to;
14646 
14647   Interface_type* interface_type = type->interface_type();
14648   if (interface_type == NULL)
14649     {
14650       if (!type->is_error_type())
14651 	this->report_error(_("expected interface or pointer to interface"));
14652     }
14653   else
14654     {
14655       const Typed_identifier* method =
14656 	interface_type->find_method(this->name_);
14657       if (method == NULL)
14658 	{
14659 	  go_error_at(this->location(), "method %qs not in interface",
14660                       Gogo::message_name(this->name_).c_str());
14661 	  this->set_is_error();
14662 	}
14663     }
14664 }
14665 
14666 // If an interface field reference is not simply called, then it is
14667 // represented as a closure.  The closure will hold a single variable,
14668 // the value of the interface on which the method should be called.
14669 // The function will be a simple thunk that pulls the value from the
14670 // closure and calls the method with the remaining arguments.
14671 
14672 // Because method values are not common, we don't build all thunks for
14673 // all possible interface methods, but instead only build them as we
14674 // need them.  In particular, we even build them on demand for
14675 // interface methods defined in other packages.
14676 
14677 Interface_field_reference_expression::Interface_method_thunks
14678   Interface_field_reference_expression::interface_method_thunks;
14679 
14680 // Find or create the thunk to call method NAME on TYPE.
14681 
14682 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)14683 Interface_field_reference_expression::create_thunk(Gogo* gogo,
14684 						   Interface_type* type,
14685 						   const std::string& name)
14686 {
14687   std::pair<Interface_type*, Method_thunks*> val(type, NULL);
14688   std::pair<Interface_method_thunks::iterator, bool> ins =
14689     Interface_field_reference_expression::interface_method_thunks.insert(val);
14690   if (ins.second)
14691     {
14692       // This is the first time we have seen this interface.
14693       ins.first->second = new Method_thunks();
14694     }
14695 
14696   for (Method_thunks::const_iterator p = ins.first->second->begin();
14697        p != ins.first->second->end();
14698        p++)
14699     if (p->first == name)
14700       return p->second;
14701 
14702   Location loc = type->location();
14703 
14704   const Typed_identifier* method_id = type->find_method(name);
14705   if (method_id == NULL)
14706     return Named_object::make_erroneous_name(gogo->thunk_name());
14707 
14708   Function_type* orig_fntype = method_id->type()->function_type();
14709   if (orig_fntype == NULL)
14710     return Named_object::make_erroneous_name(gogo->thunk_name());
14711 
14712   Struct_field_list* sfl = new Struct_field_list();
14713   // The type here is wrong--it should be the C function type.  But it
14714   // doesn't really matter.
14715   Type* vt = Type::make_pointer_type(Type::make_void_type());
14716   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
14717   sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
14718   Struct_type* st = Type::make_struct_type(sfl, loc);
14719   st->set_is_struct_incomparable();
14720   Type* closure_type = Type::make_pointer_type(st);
14721 
14722   Function_type* new_fntype = orig_fntype->copy_with_names();
14723 
14724   std::string thunk_name = gogo->thunk_name();
14725   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
14726 					      false, loc);
14727 
14728   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
14729   cvar->set_is_used();
14730   cvar->set_is_closure();
14731   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
14732 						 NULL, cvar);
14733   new_no->func_value()->set_closure_var(cp);
14734 
14735   gogo->start_block(loc);
14736 
14737   // Field 0 of the closure is the function code pointer, field 1 is
14738   // the value on which to invoke the method.
14739   Expression* arg = Expression::make_var_reference(cp, loc);
14740   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
14741   arg = Expression::make_field_reference(arg, 1, loc);
14742 
14743   Expression *ifre = Expression::make_interface_field_reference(arg, name,
14744 								loc);
14745 
14746   const Typed_identifier_list* orig_params = orig_fntype->parameters();
14747   Expression_list* args;
14748   if (orig_params == NULL || orig_params->empty())
14749     args = NULL;
14750   else
14751     {
14752       const Typed_identifier_list* new_params = new_fntype->parameters();
14753       args = new Expression_list();
14754       for (Typed_identifier_list::const_iterator p = new_params->begin();
14755 	   p != new_params->end();
14756 	   ++p)
14757 	{
14758 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
14759 	  go_assert(p_no != NULL
14760 		    && p_no->is_variable()
14761 		    && p_no->var_value()->is_parameter());
14762 	  args->push_back(Expression::make_var_reference(p_no, loc));
14763 	}
14764     }
14765 
14766   Call_expression* call = Expression::make_call(ifre, args,
14767 						orig_fntype->is_varargs(),
14768 						loc);
14769   call->set_varargs_are_lowered();
14770 
14771   Statement* s = Statement::make_return_from_call(call, loc);
14772   gogo->add_statement(s);
14773   Block* b = gogo->finish_block(loc);
14774   gogo->add_block(b, loc);
14775 
14776   // This is called after lowering but before determine_types.
14777   gogo->lower_block(new_no, b);
14778 
14779   gogo->finish_function(loc);
14780 
14781   ins.first->second->push_back(std::make_pair(name, new_no));
14782   return new_no;
14783 }
14784 
14785 // Lookup a thunk to call method NAME on TYPE.
14786 
14787 Named_object*
lookup_thunk(Interface_type * type,const std::string & name)14788 Interface_field_reference_expression::lookup_thunk(Interface_type* type,
14789 						   const std::string& name)
14790 {
14791   Interface_method_thunks::const_iterator p =
14792     Interface_field_reference_expression::interface_method_thunks.find(type);
14793   if (p == Interface_field_reference_expression::interface_method_thunks.end())
14794     return NULL;
14795   for (Method_thunks::const_iterator pm = p->second->begin();
14796        pm != p->second->end();
14797        ++pm)
14798     if (pm->first == name)
14799       return pm->second;
14800   return NULL;
14801 }
14802 
14803 // Get the backend representation for a method value.
14804 
14805 Bexpression*
do_get_backend(Translate_context * context)14806 Interface_field_reference_expression::do_get_backend(Translate_context* context)
14807 {
14808   Interface_type* type = this->expr_->type()->interface_type();
14809   if (type == NULL)
14810     {
14811       go_assert(saw_errors());
14812       return context->backend()->error_expression();
14813     }
14814 
14815   Named_object* thunk =
14816     Interface_field_reference_expression::lookup_thunk(type, this->name_);
14817 
14818   // The thunk should have been created during the
14819   // create_function_descriptors pass.
14820   if (thunk == NULL || thunk->is_erroneous())
14821     {
14822       go_assert(saw_errors());
14823       return context->backend()->error_expression();
14824     }
14825 
14826   // FIXME: We should lower this earlier, but we can't it lower it in
14827   // the lowering pass because at that point we don't know whether we
14828   // need to create the thunk or not.  If the expression is called, we
14829   // don't need the thunk.
14830 
14831   Location loc = this->location();
14832 
14833   Struct_field_list* fields = new Struct_field_list();
14834   fields->push_back(Struct_field(Typed_identifier("fn",
14835 						  thunk->func_value()->type(),
14836 						  loc)));
14837   fields->push_back(Struct_field(Typed_identifier("val",
14838 						  this->expr_->type(),
14839 						  loc)));
14840   Struct_type* st = Type::make_struct_type(fields, loc);
14841   st->set_is_struct_incomparable();
14842 
14843   Expression_list* vals = new Expression_list();
14844   vals->push_back(Expression::make_func_code_reference(thunk, loc));
14845   vals->push_back(this->expr_);
14846 
14847   Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
14848   Bexpression* bclosure =
14849     Expression::make_heap_expression(expr, loc)->get_backend(context);
14850 
14851   Gogo* gogo = context->gogo();
14852   Btype* btype = this->type()->get_backend(gogo);
14853   bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
14854 
14855   Expression* nil_check =
14856       Expression::make_binary(OPERATOR_EQEQ, this->expr_,
14857                               Expression::make_nil(loc), loc);
14858   Bexpression* bnil_check = nil_check->get_backend(context);
14859 
14860   Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
14861   Bexpression* bcrash = crash->get_backend(context);
14862 
14863   Bfunction* bfn = context->function()->func_value()->get_decl();
14864   Bexpression* bcond =
14865       gogo->backend()->conditional_expression(bfn, NULL,
14866                                               bnil_check, bcrash, NULL, loc);
14867   Bfunction* bfunction = context->function()->func_value()->get_decl();
14868   Bstatement* cond_statement =
14869       gogo->backend()->expression_statement(bfunction, bcond);
14870   return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
14871 }
14872 
14873 // Dump ast representation for an interface field reference.
14874 
14875 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14876 Interface_field_reference_expression::do_dump_expression(
14877     Ast_dump_context* ast_dump_context) const
14878 {
14879   this->expr_->dump_expression(ast_dump_context);
14880   ast_dump_context->ostream() << "." << this->name_;
14881 }
14882 
14883 // Make a reference to a field in an interface.
14884 
14885 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)14886 Expression::make_interface_field_reference(Expression* expr,
14887 					   const std::string& field,
14888 					   Location location)
14889 {
14890   return new Interface_field_reference_expression(expr, field, location);
14891 }
14892 
14893 // A general selector.  This is a Parser_expression for LEFT.NAME.  It
14894 // is lowered after we know the type of the left hand side.
14895 
14896 class Selector_expression : public Parser_expression
14897 {
14898  public:
Selector_expression(Expression * left,const std::string & name,Location location)14899   Selector_expression(Expression* left, const std::string& name,
14900 		      Location location)
14901     : Parser_expression(EXPRESSION_SELECTOR, location),
14902       left_(left), name_(name)
14903   { }
14904 
14905  protected:
14906   int
do_traverse(Traverse * traverse)14907   do_traverse(Traverse* traverse)
14908   { return Expression::traverse(&this->left_, traverse); }
14909 
14910   Expression*
14911   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
14912 
14913   Expression*
do_copy()14914   do_copy()
14915   {
14916     return new Selector_expression(this->left_->copy(), this->name_,
14917 				   this->location());
14918   }
14919 
14920   void
14921   do_dump_expression(Ast_dump_context* ast_dump_context) const;
14922 
14923  private:
14924   Expression*
14925   lower_method_expression(Gogo*);
14926 
14927   // The expression on the left hand side.
14928   Expression* left_;
14929   // The name on the right hand side.
14930   std::string name_;
14931 };
14932 
14933 // Lower a selector expression once we know the real type of the left
14934 // hand side.
14935 
14936 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)14937 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
14938 			      int)
14939 {
14940   Expression* left = this->left_;
14941   if (left->is_type_expression())
14942     return this->lower_method_expression(gogo);
14943   return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
14944 				    this->location());
14945 }
14946 
14947 // Lower a method expression T.M or (*T).M.  We turn this into a
14948 // function literal.
14949 
14950 Expression*
lower_method_expression(Gogo * gogo)14951 Selector_expression::lower_method_expression(Gogo* gogo)
14952 {
14953   Location location = this->location();
14954   Type* left_type = this->left_->type();
14955   Type* type = left_type;
14956   const std::string& name(this->name_);
14957 
14958   bool is_pointer;
14959   if (type->points_to() == NULL)
14960     is_pointer = false;
14961   else
14962     {
14963       is_pointer = true;
14964       type = type->points_to();
14965     }
14966 
14967   Named_type* nt = type->named_type();
14968   Struct_type* st = type->struct_type();
14969   bool is_ambiguous;
14970   Method* method = NULL;
14971   if (nt != NULL)
14972     method = nt->method_function(name, &is_ambiguous);
14973   else if (st != NULL)
14974     method = st->method_function(name, &is_ambiguous);
14975   const Typed_identifier* imethod = NULL;
14976   if (method == NULL && !is_pointer)
14977     {
14978       Interface_type* it = type->interface_type();
14979       if (it != NULL)
14980 	imethod = it->find_method(name);
14981     }
14982 
14983   if ((method == NULL && imethod == NULL)
14984       || (left_type->named_type() != NULL && left_type->points_to() != NULL))
14985     {
14986       if (nt != NULL)
14987 	{
14988 	  if (!is_ambiguous)
14989 	    go_error_at(location, "type %<%s%s%> has no method %<%s%>",
14990 			is_pointer ? "*" : "",
14991 			nt->message_name().c_str(),
14992 			Gogo::message_name(name).c_str());
14993 	  else
14994 	    go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
14995 			Gogo::message_name(name).c_str(),
14996 			is_pointer ? "*" : "",
14997 			nt->message_name().c_str());
14998 	}
14999       else
15000 	{
15001 	  if (!is_ambiguous)
15002 	    go_error_at(location, "type has no method %<%s%>",
15003 			Gogo::message_name(name).c_str());
15004 	  else
15005 	    go_error_at(location, "method %<%s%> is ambiguous",
15006 			Gogo::message_name(name).c_str());
15007 	}
15008       return Expression::make_error(location);
15009     }
15010 
15011   if (method != NULL && !is_pointer && !method->is_value_method())
15012     {
15013       go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
15014                   nt->message_name().c_str(),
15015                   Gogo::message_name(name).c_str());
15016       return Expression::make_error(location);
15017     }
15018 
15019   // Build a new function type in which the receiver becomes the first
15020   // argument.
15021   Function_type* method_type;
15022   if (method != NULL)
15023     {
15024       method_type = method->type();
15025       go_assert(method_type->is_method());
15026     }
15027   else
15028     {
15029       method_type = imethod->type()->function_type();
15030       go_assert(method_type != NULL && !method_type->is_method());
15031     }
15032 
15033   const char* const receiver_name = "$this";
15034   Typed_identifier_list* parameters = new Typed_identifier_list();
15035   parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
15036 					 location));
15037 
15038   const Typed_identifier_list* method_parameters = method_type->parameters();
15039   if (method_parameters != NULL)
15040     {
15041       int i = 0;
15042       for (Typed_identifier_list::const_iterator p = method_parameters->begin();
15043 	   p != method_parameters->end();
15044 	   ++p, ++i)
15045 	{
15046 	  if (!p->name().empty())
15047 	    parameters->push_back(*p);
15048 	  else
15049 	    {
15050 	      char buf[20];
15051 	      snprintf(buf, sizeof buf, "$param%d", i);
15052 	      parameters->push_back(Typed_identifier(buf, p->type(),
15053 						     p->location()));
15054 	    }
15055 	}
15056     }
15057 
15058   const Typed_identifier_list* method_results = method_type->results();
15059   Typed_identifier_list* results;
15060   if (method_results == NULL)
15061     results = NULL;
15062   else
15063     {
15064       results = new Typed_identifier_list();
15065       for (Typed_identifier_list::const_iterator p = method_results->begin();
15066 	   p != method_results->end();
15067 	   ++p)
15068 	results->push_back(*p);
15069     }
15070 
15071   Function_type* fntype = Type::make_function_type(NULL, parameters, results,
15072 						   location);
15073   if (method_type->is_varargs())
15074     fntype->set_is_varargs();
15075 
15076   // We generate methods which always takes a pointer to the receiver
15077   // as their first argument.  If this is for a pointer type, we can
15078   // simply reuse the existing function.  We use an internal hack to
15079   // get the right type.
15080   // FIXME: This optimization is disabled because it doesn't yet work
15081   // with function descriptors when the method expression is not
15082   // directly called.
15083   if (method != NULL && is_pointer && false)
15084     {
15085       Named_object* mno = (method->needs_stub_method()
15086 			   ? method->stub_object()
15087 			   : method->named_object());
15088       Expression* f = Expression::make_func_reference(mno, NULL, location);
15089       f = Expression::make_cast(fntype, f, location);
15090       Type_conversion_expression* tce =
15091 	static_cast<Type_conversion_expression*>(f);
15092       tce->set_may_convert_function_types();
15093       return f;
15094     }
15095 
15096   Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
15097 					  location);
15098 
15099   Named_object* vno = gogo->lookup(receiver_name, NULL);
15100   go_assert(vno != NULL);
15101   Expression* ve = Expression::make_var_reference(vno, location);
15102   Expression* bm;
15103   if (method != NULL)
15104     bm = Type::bind_field_or_method(gogo, type, ve, name, location);
15105   else
15106     bm = Expression::make_interface_field_reference(ve, name, location);
15107 
15108   // Even though we found the method above, if it has an error type we
15109   // may see an error here.
15110   if (bm->is_error_expression())
15111     {
15112       gogo->finish_function(location);
15113       return bm;
15114     }
15115 
15116   Expression_list* args;
15117   if (parameters->size() <= 1)
15118     args = NULL;
15119   else
15120     {
15121       args = new Expression_list();
15122       Typed_identifier_list::const_iterator p = parameters->begin();
15123       ++p;
15124       for (; p != parameters->end(); ++p)
15125 	{
15126 	  vno = gogo->lookup(p->name(), NULL);
15127 	  go_assert(vno != NULL);
15128 	  args->push_back(Expression::make_var_reference(vno, location));
15129 	}
15130     }
15131 
15132   gogo->start_block(location);
15133 
15134   Call_expression* call = Expression::make_call(bm, args,
15135 						method_type->is_varargs(),
15136 						location);
15137 
15138   Statement* s = Statement::make_return_from_call(call, location);
15139   gogo->add_statement(s);
15140 
15141   Block* b = gogo->finish_block(location);
15142 
15143   gogo->add_block(b, location);
15144 
15145   // Lower the call in case there are multiple results.
15146   gogo->lower_block(no, b);
15147   gogo->flatten_block(no, b);
15148 
15149   gogo->finish_function(location);
15150 
15151   return Expression::make_func_reference(no, NULL, location);
15152 }
15153 
15154 // Dump the ast for a selector expression.
15155 
15156 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15157 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
15158     const
15159 {
15160   ast_dump_context->dump_expression(this->left_);
15161   ast_dump_context->ostream() << ".";
15162   ast_dump_context->ostream() << this->name_;
15163 }
15164 
15165 // Make a selector expression.
15166 
15167 Expression*
make_selector(Expression * left,const std::string & name,Location location)15168 Expression::make_selector(Expression* left, const std::string& name,
15169 			  Location location)
15170 {
15171   return new Selector_expression(left, name, location);
15172 }
15173 
15174 // Class Allocation_expression.
15175 
15176 int
do_traverse(Traverse * traverse)15177 Allocation_expression::do_traverse(Traverse* traverse)
15178 {
15179   return Type::traverse(this->type_, traverse);
15180 }
15181 
15182 Type*
do_type()15183 Allocation_expression::do_type()
15184 {
15185   return Type::make_pointer_type(this->type_);
15186 }
15187 
15188 void
do_check_types(Gogo *)15189 Allocation_expression::do_check_types(Gogo*)
15190 {
15191   if (!this->type_->in_heap())
15192     go_error_at(this->location(), "cannot heap allocate go:notinheap type");
15193 }
15194 
15195 // Make a copy of an allocation expression.
15196 
15197 Expression*
do_copy()15198 Allocation_expression::do_copy()
15199 {
15200   Allocation_expression* alloc =
15201     new Allocation_expression(this->type_->copy_expressions(),
15202 			      this->location());
15203   if (this->allocate_on_stack_)
15204     alloc->set_allocate_on_stack();
15205   if (this->no_zero_)
15206     alloc->set_no_zero();
15207   return alloc;
15208 }
15209 
15210 // Return the backend representation for an allocation expression.
15211 
15212 Bexpression*
do_get_backend(Translate_context * context)15213 Allocation_expression::do_get_backend(Translate_context* context)
15214 {
15215   Gogo* gogo = context->gogo();
15216   Location loc = this->location();
15217   Btype* btype = this->type_->get_backend(gogo);
15218 
15219   if (this->allocate_on_stack_)
15220     {
15221       int64_t size;
15222       bool ok = this->type_->backend_type_size(gogo, &size);
15223       if (!ok)
15224         {
15225           go_assert(saw_errors());
15226           return gogo->backend()->error_expression();
15227         }
15228       Bstatement* decl;
15229       Named_object* fn = context->function();
15230       go_assert(fn != NULL);
15231       Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
15232       Bexpression* init = (this->no_zero_
15233                            ? NULL
15234                            : gogo->backend()->zero_expression(btype));
15235       Bvariable* temp =
15236         gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
15237                                             init,
15238 					    Backend::variable_address_is_taken,
15239 					    loc, &decl);
15240       Bexpression* ret = gogo->backend()->var_expression(temp, loc);
15241       ret = gogo->backend()->address_expression(ret, loc);
15242       ret = gogo->backend()->compound_expression(decl, ret, loc);
15243       return ret;
15244     }
15245 
15246   Bexpression* space =
15247     gogo->allocate_memory(this->type_, loc)->get_backend(context);
15248   Btype* pbtype = gogo->backend()->pointer_type(btype);
15249   return gogo->backend()->convert_expression(pbtype, space, loc);
15250 }
15251 
15252 // Dump ast representation for an allocation expression.
15253 
15254 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15255 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
15256     const
15257 {
15258   ast_dump_context->ostream() << "new(";
15259   ast_dump_context->dump_type(this->type_);
15260   ast_dump_context->ostream() << ")";
15261 }
15262 
15263 // Make an allocation expression.
15264 
15265 Expression*
make_allocation(Type * type,Location location)15266 Expression::make_allocation(Type* type, Location location)
15267 {
15268   return new Allocation_expression(type, location);
15269 }
15270 
15271 // Class Ordered_value_list.
15272 
15273 int
traverse_vals(Traverse * traverse)15274 Ordered_value_list::traverse_vals(Traverse* traverse)
15275 {
15276   if (this->vals_ != NULL)
15277     {
15278       if (this->traverse_order_ == NULL)
15279 	{
15280 	  if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
15281 	    return TRAVERSE_EXIT;
15282 	}
15283       else
15284 	{
15285 	  for (std::vector<unsigned long>::const_iterator p =
15286 		   this->traverse_order_->begin();
15287 	       p != this->traverse_order_->end();
15288 	       ++p)
15289 	    {
15290 	      if (Expression::traverse(&this->vals_->at(*p), traverse)
15291 		  == TRAVERSE_EXIT)
15292 		return TRAVERSE_EXIT;
15293 	    }
15294 	}
15295     }
15296   return TRAVERSE_CONTINUE;
15297 }
15298 
15299 // Class Struct_construction_expression.
15300 
15301 // Traversal.
15302 
15303 int
do_traverse(Traverse * traverse)15304 Struct_construction_expression::do_traverse(Traverse* traverse)
15305 {
15306   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
15307     return TRAVERSE_EXIT;
15308   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15309     return TRAVERSE_EXIT;
15310   return TRAVERSE_CONTINUE;
15311 }
15312 
15313 // Return whether this is a constant initializer.
15314 
15315 bool
is_constant_struct() const15316 Struct_construction_expression::is_constant_struct() const
15317 {
15318   if (this->vals() == NULL)
15319     return true;
15320   for (Expression_list::const_iterator pv = this->vals()->begin();
15321        pv != this->vals()->end();
15322        ++pv)
15323     {
15324       if (*pv != NULL
15325 	  && !(*pv)->is_constant()
15326 	  && (!(*pv)->is_composite_literal()
15327 	      || (*pv)->is_nonconstant_composite_literal()))
15328 	return false;
15329     }
15330 
15331   const Struct_field_list* fields = this->type_->struct_type()->fields();
15332   for (Struct_field_list::const_iterator pf = fields->begin();
15333        pf != fields->end();
15334        ++pf)
15335     {
15336       // There are no constant constructors for interfaces.
15337       if (pf->type()->interface_type() != NULL)
15338 	return false;
15339     }
15340 
15341   return true;
15342 }
15343 
15344 // Return whether this is a zero value.
15345 
15346 bool
do_is_zero_value() const15347 Struct_construction_expression::do_is_zero_value() const
15348 {
15349   if (this->vals() == NULL)
15350     return true;
15351   for (Expression_list::const_iterator pv = this->vals()->begin();
15352        pv != this->vals()->end();
15353        ++pv)
15354     if (*pv != NULL && !(*pv)->is_zero_value())
15355       return false;
15356 
15357   const Struct_field_list* fields = this->type_->struct_type()->fields();
15358   for (Struct_field_list::const_iterator pf = fields->begin();
15359        pf != fields->end();
15360        ++pf)
15361     {
15362       // Interface conversion may cause a zero value being converted
15363       // to a non-zero value, like interface{}(0).  Be conservative.
15364       if (pf->type()->interface_type() != NULL)
15365         return false;
15366     }
15367 
15368   return true;
15369 }
15370 
15371 // Return whether this struct can be used as a constant initializer.
15372 
15373 bool
do_is_static_initializer() const15374 Struct_construction_expression::do_is_static_initializer() const
15375 {
15376   if (this->vals() == NULL)
15377     return true;
15378   for (Expression_list::const_iterator pv = this->vals()->begin();
15379        pv != this->vals()->end();
15380        ++pv)
15381     {
15382       if (*pv != NULL && !(*pv)->is_static_initializer())
15383 	return false;
15384     }
15385 
15386   const Struct_field_list* fields = this->type_->struct_type()->fields();
15387   for (Struct_field_list::const_iterator pf = fields->begin();
15388        pf != fields->end();
15389        ++pf)
15390     {
15391       // There are no constant constructors for interfaces.
15392       if (pf->type()->interface_type() != NULL)
15393 	return false;
15394     }
15395 
15396   return true;
15397 }
15398 
15399 // Final type determination.
15400 
15401 void
do_determine_type(const Type_context *)15402 Struct_construction_expression::do_determine_type(const Type_context*)
15403 {
15404   if (this->vals() == NULL)
15405     return;
15406   const Struct_field_list* fields = this->type_->struct_type()->fields();
15407   Expression_list::const_iterator pv = this->vals()->begin();
15408   for (Struct_field_list::const_iterator pf = fields->begin();
15409        pf != fields->end();
15410        ++pf, ++pv)
15411     {
15412       if (pv == this->vals()->end())
15413 	return;
15414       if (*pv != NULL)
15415 	{
15416 	  Type_context subcontext(pf->type(), false);
15417 	  (*pv)->determine_type(&subcontext);
15418 	}
15419     }
15420   // Extra values are an error we will report elsewhere; we still want
15421   // to determine the type to avoid knockon errors.
15422   for (; pv != this->vals()->end(); ++pv)
15423     (*pv)->determine_type_no_context();
15424 }
15425 
15426 // Check types.
15427 
15428 void
do_check_types(Gogo *)15429 Struct_construction_expression::do_check_types(Gogo*)
15430 {
15431   if (this->vals() == NULL)
15432     return;
15433 
15434   Struct_type* st = this->type_->struct_type();
15435   if (this->vals()->size() > st->field_count())
15436     {
15437       this->report_error(_("too many expressions for struct"));
15438       return;
15439     }
15440 
15441   const Struct_field_list* fields = st->fields();
15442   Expression_list::const_iterator pv = this->vals()->begin();
15443   int i = 0;
15444   for (Struct_field_list::const_iterator pf = fields->begin();
15445        pf != fields->end();
15446        ++pf, ++pv, ++i)
15447     {
15448       if (pv == this->vals()->end())
15449 	{
15450 	  this->report_error(_("too few expressions for struct"));
15451 	  break;
15452 	}
15453 
15454       if (*pv == NULL)
15455 	continue;
15456 
15457       std::string reason;
15458       if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
15459 	{
15460 	  if (reason.empty())
15461 	    go_error_at((*pv)->location(),
15462                         "incompatible type for field %d in struct construction",
15463                         i + 1);
15464 	  else
15465 	    go_error_at((*pv)->location(),
15466                         ("incompatible type for field %d in "
15467                          "struct construction (%s)"),
15468                         i + 1, reason.c_str());
15469 	  this->set_is_error();
15470 	}
15471     }
15472   go_assert(pv == this->vals()->end());
15473 }
15474 
15475 // Copy.
15476 
15477 Expression*
do_copy()15478 Struct_construction_expression::do_copy()
15479 {
15480   Struct_construction_expression* ret =
15481     new Struct_construction_expression(this->type_->copy_expressions(),
15482 				       (this->vals() == NULL
15483 					? NULL
15484 					: this->vals()->copy()),
15485 				       this->location());
15486   if (this->traverse_order() != NULL)
15487     ret->set_traverse_order(this->traverse_order());
15488   return ret;
15489 }
15490 
15491 // Make implicit type conversions explicit.
15492 
15493 void
do_add_conversions()15494 Struct_construction_expression::do_add_conversions()
15495 {
15496   if (this->vals() == NULL)
15497     return;
15498 
15499   Location loc = this->location();
15500   const Struct_field_list* fields = this->type_->struct_type()->fields();
15501   Expression_list::iterator pv = this->vals()->begin();
15502   for (Struct_field_list::const_iterator pf = fields->begin();
15503        pf != fields->end();
15504        ++pf, ++pv)
15505     {
15506       if (pv == this->vals()->end())
15507         break;
15508       if (*pv != NULL)
15509         {
15510           Type* ft = pf->type();
15511           if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
15512               && ft->interface_type() != NULL)
15513            *pv = Expression::make_cast(ft, *pv, loc);
15514         }
15515     }
15516 }
15517 
15518 // Return the backend representation for constructing a struct.
15519 
15520 Bexpression*
do_get_backend(Translate_context * context)15521 Struct_construction_expression::do_get_backend(Translate_context* context)
15522 {
15523   Gogo* gogo = context->gogo();
15524 
15525   Btype* btype = this->type_->get_backend(gogo);
15526   if (this->vals() == NULL)
15527     return gogo->backend()->zero_expression(btype);
15528 
15529   const Struct_field_list* fields = this->type_->struct_type()->fields();
15530   Expression_list::const_iterator pv = this->vals()->begin();
15531   std::vector<Bexpression*> init;
15532   for (Struct_field_list::const_iterator pf = fields->begin();
15533        pf != fields->end();
15534        ++pf)
15535     {
15536       Btype* fbtype = pf->type()->get_backend(gogo);
15537       if (pv == this->vals()->end())
15538         init.push_back(gogo->backend()->zero_expression(fbtype));
15539       else if (*pv == NULL)
15540 	{
15541           init.push_back(gogo->backend()->zero_expression(fbtype));
15542 	  ++pv;
15543 	}
15544       else
15545 	{
15546           Expression* val =
15547               Expression::convert_for_assignment(gogo, pf->type(),
15548                                                  *pv, this->location());
15549           init.push_back(val->get_backend(context));
15550 	  ++pv;
15551 	}
15552     }
15553   if (this->type_->struct_type()->has_padding())
15554     {
15555       // Feed an extra value if there is a padding field.
15556       Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
15557       init.push_back(gogo->backend()->zero_expression(fbtype));
15558     }
15559   return gogo->backend()->constructor_expression(btype, init, this->location());
15560 }
15561 
15562 // Export a struct construction.
15563 
15564 void
do_export(Export_function_body * efb) const15565 Struct_construction_expression::do_export(Export_function_body* efb) const
15566 {
15567   efb->write_c_string("$convert(");
15568   efb->write_type(this->type_);
15569   for (Expression_list::const_iterator pv = this->vals()->begin();
15570        pv != this->vals()->end();
15571        ++pv)
15572     {
15573       efb->write_c_string(", ");
15574       if (*pv != NULL)
15575 	(*pv)->export_expression(efb);
15576     }
15577   efb->write_c_string(")");
15578 }
15579 
15580 // Dump ast representation of a struct construction expression.
15581 
15582 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15583 Struct_construction_expression::do_dump_expression(
15584     Ast_dump_context* ast_dump_context) const
15585 {
15586   ast_dump_context->dump_type(this->type_);
15587   ast_dump_context->ostream() << "{";
15588   ast_dump_context->dump_expression_list(this->vals());
15589   ast_dump_context->ostream() << "}";
15590 }
15591 
15592 // Make a struct composite literal.  This used by the thunk code.
15593 
15594 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)15595 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
15596 					  Location location)
15597 {
15598   go_assert(type->struct_type() != NULL);
15599   return new Struct_construction_expression(type, vals, location);
15600 }
15601 
15602 // Class Array_construction_expression.
15603 
15604 // Traversal.
15605 
15606 int
do_traverse(Traverse * traverse)15607 Array_construction_expression::do_traverse(Traverse* traverse)
15608 {
15609   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
15610     return TRAVERSE_EXIT;
15611   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15612     return TRAVERSE_EXIT;
15613   return TRAVERSE_CONTINUE;
15614 }
15615 
15616 // Return whether this is a constant initializer.
15617 
15618 bool
is_constant_array() const15619 Array_construction_expression::is_constant_array() const
15620 {
15621   if (this->vals() == NULL)
15622     return true;
15623 
15624   // There are no constant constructors for interfaces.
15625   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15626     return false;
15627 
15628   for (Expression_list::const_iterator pv = this->vals()->begin();
15629        pv != this->vals()->end();
15630        ++pv)
15631     {
15632       if (*pv != NULL
15633 	  && !(*pv)->is_constant()
15634 	  && (!(*pv)->is_composite_literal()
15635 	      || (*pv)->is_nonconstant_composite_literal()))
15636 	return false;
15637     }
15638   return true;
15639 }
15640 
15641 // Return whether this is a zero value.
15642 
15643 bool
do_is_zero_value() const15644 Array_construction_expression::do_is_zero_value() const
15645 {
15646   if (this->vals() == NULL)
15647     return true;
15648 
15649   // Interface conversion may cause a zero value being converted
15650   // to a non-zero value, like interface{}(0).  Be conservative.
15651   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15652     return false;
15653 
15654   for (Expression_list::const_iterator pv = this->vals()->begin();
15655        pv != this->vals()->end();
15656        ++pv)
15657     if (*pv != NULL && !(*pv)->is_zero_value())
15658       return false;
15659 
15660   return true;
15661 }
15662 
15663 // Return whether this can be used a constant initializer.
15664 
15665 bool
do_is_static_initializer() const15666 Array_construction_expression::do_is_static_initializer() const
15667 {
15668   if (this->vals() == NULL)
15669     return true;
15670 
15671   // There are no constant constructors for interfaces.
15672   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15673     return false;
15674 
15675   for (Expression_list::const_iterator pv = this->vals()->begin();
15676        pv != this->vals()->end();
15677        ++pv)
15678     {
15679       if (*pv != NULL && !(*pv)->is_static_initializer())
15680 	return false;
15681     }
15682   return true;
15683 }
15684 
15685 // Final type determination.
15686 
15687 void
do_determine_type(const Type_context *)15688 Array_construction_expression::do_determine_type(const Type_context*)
15689 {
15690   if (this->is_error_expression())
15691     {
15692       go_assert(saw_errors());
15693       return;
15694     }
15695 
15696   if (this->vals() == NULL)
15697     return;
15698   Array_type* at = this->type_->array_type();
15699   if (at == NULL || at->is_error() || at->element_type()->is_error())
15700     {
15701       go_assert(saw_errors());
15702       this->set_is_error();
15703       return;
15704     }
15705   Type_context subcontext(at->element_type(), false);
15706   for (Expression_list::const_iterator pv = this->vals()->begin();
15707        pv != this->vals()->end();
15708        ++pv)
15709     {
15710       if (*pv != NULL)
15711 	(*pv)->determine_type(&subcontext);
15712     }
15713 }
15714 
15715 // Check types.
15716 
15717 void
do_check_types(Gogo *)15718 Array_construction_expression::do_check_types(Gogo*)
15719 {
15720   if (this->is_error_expression())
15721     {
15722       go_assert(saw_errors());
15723       return;
15724     }
15725 
15726   if (this->vals() == NULL)
15727     return;
15728 
15729   Array_type* at = this->type_->array_type();
15730   if (at == NULL || at->is_error() || at->element_type()->is_error())
15731     {
15732       go_assert(saw_errors());
15733       this->set_is_error();
15734       return;
15735     }
15736   int i = 0;
15737   Type* element_type = at->element_type();
15738   for (Expression_list::const_iterator pv = this->vals()->begin();
15739        pv != this->vals()->end();
15740        ++pv, ++i)
15741     {
15742       if (*pv != NULL
15743 	  && !Type::are_assignable(element_type, (*pv)->type(), NULL))
15744 	{
15745 	  go_error_at((*pv)->location(),
15746                       "incompatible type for element %d in composite literal",
15747                       i + 1);
15748 	  this->set_is_error();
15749 	}
15750     }
15751 }
15752 
15753 // Make implicit type conversions explicit.
15754 
15755 void
do_add_conversions()15756 Array_construction_expression::do_add_conversions()
15757 {
15758   if (this->is_error_expression())
15759     {
15760       go_assert(saw_errors());
15761       return;
15762     }
15763 
15764   if (this->vals() == NULL)
15765     return;
15766 
15767   Type* et = this->type_->array_type()->element_type();
15768   if (et->interface_type() == NULL)
15769     return;
15770 
15771   Location loc = this->location();
15772   for (Expression_list::iterator pv = this->vals()->begin();
15773        pv != this->vals()->end();
15774        ++pv)
15775     if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
15776       *pv = Expression::make_cast(et, *pv, loc);
15777 }
15778 
15779 // Get a constructor expression for the array values.
15780 
15781 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)15782 Array_construction_expression::get_constructor(Translate_context* context,
15783                                                Btype* array_btype)
15784 {
15785   Type* element_type = this->type_->array_type()->element_type();
15786 
15787   std::vector<unsigned long> indexes;
15788   std::vector<Bexpression*> vals;
15789   Gogo* gogo = context->gogo();
15790   if (this->vals() != NULL)
15791     {
15792       size_t i = 0;
15793       std::vector<unsigned long>::const_iterator pi;
15794       if (this->indexes_ != NULL)
15795 	pi = this->indexes_->begin();
15796       for (Expression_list::const_iterator pv = this->vals()->begin();
15797 	   pv != this->vals()->end();
15798 	   ++pv, ++i)
15799 	{
15800 	  if (this->indexes_ != NULL)
15801 	    go_assert(pi != this->indexes_->end());
15802 
15803 	  if (this->indexes_ == NULL)
15804 	    indexes.push_back(i);
15805 	  else
15806 	    indexes.push_back(*pi);
15807 	  if (*pv == NULL)
15808 	    {
15809 	      Btype* ebtype = element_type->get_backend(gogo);
15810 	      Bexpression *zv = gogo->backend()->zero_expression(ebtype);
15811 	      vals.push_back(zv);
15812 	    }
15813 	  else
15814 	    {
15815               Expression* val_expr =
15816                   Expression::convert_for_assignment(gogo, element_type, *pv,
15817                                                      this->location());
15818 	      vals.push_back(val_expr->get_backend(context));
15819 	    }
15820 	  if (this->indexes_ != NULL)
15821 	    ++pi;
15822 	}
15823       if (this->indexes_ != NULL)
15824 	go_assert(pi == this->indexes_->end());
15825     }
15826   return gogo->backend()->array_constructor_expression(array_btype, indexes,
15827                                                        vals, this->location());
15828 }
15829 
15830 // Export an array construction.
15831 
15832 void
do_export(Export_function_body * efb) const15833 Array_construction_expression::do_export(Export_function_body* efb) const
15834 {
15835   efb->write_c_string("$convert(");
15836   efb->write_type(this->type_);
15837   if (this->vals() != NULL)
15838     {
15839       std::vector<unsigned long>::const_iterator pi;
15840       if (this->indexes_ != NULL)
15841 	pi = this->indexes_->begin();
15842       for (Expression_list::const_iterator pv = this->vals()->begin();
15843 	   pv != this->vals()->end();
15844 	   ++pv)
15845 	{
15846 	  efb->write_c_string(", ");
15847 
15848 	  if (this->indexes_ != NULL)
15849 	    {
15850 	      char buf[100];
15851 	      snprintf(buf, sizeof buf, "%lu", *pi);
15852 	      efb->write_c_string(buf);
15853 	      efb->write_c_string(":");
15854 	    }
15855 
15856 	  if (*pv != NULL)
15857 	    (*pv)->export_expression(efb);
15858 
15859 	  if (this->indexes_ != NULL)
15860 	    ++pi;
15861 	}
15862     }
15863   efb->write_c_string(")");
15864 }
15865 
15866 // Dump ast representation of an array construction expression.
15867 
15868 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15869 Array_construction_expression::do_dump_expression(
15870     Ast_dump_context* ast_dump_context) const
15871 {
15872   Expression* length = this->type_->array_type()->length();
15873 
15874   ast_dump_context->ostream() << "[" ;
15875   if (length != NULL)
15876     {
15877       ast_dump_context->dump_expression(length);
15878     }
15879   ast_dump_context->ostream() << "]" ;
15880   ast_dump_context->dump_type(this->type_);
15881   this->dump_slice_storage_expression(ast_dump_context);
15882   ast_dump_context->ostream() << "{" ;
15883   if (this->indexes_ == NULL)
15884     ast_dump_context->dump_expression_list(this->vals());
15885   else
15886     {
15887       Expression_list::const_iterator pv = this->vals()->begin();
15888       for (std::vector<unsigned long>::const_iterator pi =
15889 	     this->indexes_->begin();
15890 	   pi != this->indexes_->end();
15891 	   ++pi, ++pv)
15892 	{
15893 	  if (pi != this->indexes_->begin())
15894 	    ast_dump_context->ostream() << ", ";
15895 	  ast_dump_context->ostream() << *pi << ':';
15896 	  ast_dump_context->dump_expression(*pv);
15897 	}
15898     }
15899   ast_dump_context->ostream() << "}" ;
15900 
15901 }
15902 
15903 // Class Fixed_array_construction_expression.
15904 
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15905 Fixed_array_construction_expression::Fixed_array_construction_expression(
15906     Type* type, const std::vector<unsigned long>* indexes,
15907     Expression_list* vals, Location location)
15908   : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
15909 				  type, indexes, vals, location)
15910 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
15911 
15912 
15913 // Copy.
15914 
15915 Expression*
do_copy()15916 Fixed_array_construction_expression::do_copy()
15917 {
15918   Type* t = this->type()->copy_expressions();
15919   return new Fixed_array_construction_expression(t, this->indexes(),
15920 						 (this->vals() == NULL
15921 						  ? NULL
15922 						  : this->vals()->copy()),
15923 						 this->location());
15924 }
15925 
15926 // Return the backend representation for constructing a fixed array.
15927 
15928 Bexpression*
do_get_backend(Translate_context * context)15929 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
15930 {
15931   Type* type = this->type();
15932   Btype* btype = type->get_backend(context->gogo());
15933   return this->get_constructor(context, btype);
15934 }
15935 
15936 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)15937 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
15938                                          Location location)
15939 {
15940   go_assert(type->array_type() != NULL && !type->is_slice_type());
15941   return new Fixed_array_construction_expression(type, NULL, vals, location);
15942 }
15943 
15944 // Class Slice_construction_expression.
15945 
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15946 Slice_construction_expression::Slice_construction_expression(
15947   Type* type, const std::vector<unsigned long>* indexes,
15948   Expression_list* vals, Location location)
15949   : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
15950 				  type, indexes, vals, location),
15951     valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
15952     storage_escapes_(true)
15953 {
15954   go_assert(type->is_slice_type());
15955 
15956   unsigned long lenval;
15957   Expression* length;
15958   if (vals == NULL || vals->empty())
15959     lenval = 0;
15960   else
15961     {
15962       if (this->indexes() == NULL)
15963 	lenval = vals->size();
15964       else
15965 	lenval = indexes->back() + 1;
15966     }
15967   Type* int_type = Type::lookup_integer_type("int");
15968   length = Expression::make_integer_ul(lenval, int_type, location);
15969   Type* element_type = type->array_type()->element_type();
15970   Array_type* array_type = Type::make_array_type(element_type, length);
15971   array_type->set_is_array_incomparable();
15972   this->valtype_ = array_type;
15973 }
15974 
15975 // Traversal.
15976 
15977 int
do_traverse(Traverse * traverse)15978 Slice_construction_expression::do_traverse(Traverse* traverse)
15979 {
15980   if (this->Array_construction_expression::do_traverse(traverse)
15981       == TRAVERSE_EXIT)
15982     return TRAVERSE_EXIT;
15983   if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
15984     return TRAVERSE_EXIT;
15985   if (this->array_val_ != NULL
15986       && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
15987     return TRAVERSE_EXIT;
15988   if (this->slice_storage_ != NULL
15989       && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
15990     return TRAVERSE_EXIT;
15991   return TRAVERSE_CONTINUE;
15992 }
15993 
15994 // Helper routine to create fixed array value underlying the slice literal.
15995 // May be called during flattening, or later during do_get_backend().
15996 
15997 Expression*
create_array_val()15998 Slice_construction_expression::create_array_val()
15999 {
16000   Array_type* array_type = this->type()->array_type();
16001   if (array_type == NULL)
16002     {
16003       go_assert(this->type()->is_error());
16004       return NULL;
16005     }
16006 
16007   Location loc = this->location();
16008   go_assert(this->valtype_ != NULL);
16009 
16010   Expression_list* vals = this->vals();
16011   return new Fixed_array_construction_expression(
16012       this->valtype_, this->indexes(), vals, loc);
16013 }
16014 
16015 // If we're previous established that the slice storage does not
16016 // escape, then create a separate array temp val here for it. We
16017 // need to do this as part of flattening so as to be able to insert
16018 // the new temp statement.
16019 
16020 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)16021 Slice_construction_expression::do_flatten(Gogo*, Named_object*,
16022                                           Statement_inserter* inserter)
16023 {
16024   if (this->type()->array_type() == NULL)
16025     {
16026       go_assert(saw_errors());
16027       return Expression::make_error(this->location());
16028     }
16029 
16030   // Create a stack-allocated storage temp if storage won't escape
16031   if (!this->storage_escapes_
16032       && this->slice_storage_ == NULL
16033       && this->element_count() > 0)
16034     {
16035       Location loc = this->location();
16036       this->array_val_ = this->create_array_val();
16037       go_assert(this->array_val_ != NULL);
16038       Temporary_statement* temp =
16039           Statement::make_temporary(this->valtype_, this->array_val_, loc);
16040       inserter->insert(temp);
16041       this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
16042     }
16043   return this;
16044 }
16045 
16046 // When dumping a slice construction expression that has an explicit
16047 // storeage temp, emit the temp here (if we don't do this the storage
16048 // temp appears unused in the AST dump).
16049 
16050 void
16051 Slice_construction_expression::
dump_slice_storage_expression(Ast_dump_context * ast_dump_context) const16052 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
16053 {
16054   if (this->slice_storage_ == NULL)
16055     return;
16056   ast_dump_context->ostream() << "storage=" ;
16057   ast_dump_context->dump_expression(this->slice_storage_);
16058 }
16059 
16060 // Copy.
16061 
16062 Expression*
do_copy()16063 Slice_construction_expression::do_copy()
16064 {
16065   return new Slice_construction_expression(this->type()->copy_expressions(),
16066 					   this->indexes(),
16067 					   (this->vals() == NULL
16068 					    ? NULL
16069 					    : this->vals()->copy()),
16070 					   this->location());
16071 }
16072 
16073 // Return the backend representation for constructing a slice.
16074 
16075 Bexpression*
do_get_backend(Translate_context * context)16076 Slice_construction_expression::do_get_backend(Translate_context* context)
16077 {
16078   if (this->array_val_ == NULL)
16079     this->array_val_ = this->create_array_val();
16080   if (this->array_val_ == NULL)
16081     {
16082       go_assert(this->type()->is_error());
16083       return context->backend()->error_expression();
16084     }
16085 
16086   Location loc = this->location();
16087 
16088   bool is_static_initializer = this->array_val_->is_static_initializer();
16089 
16090   // We have to copy the initial values into heap memory if we are in
16091   // a function or if the values are not constants.
16092   bool copy_to_heap = context->function() != NULL || !is_static_initializer;
16093 
16094   Expression* space;
16095 
16096   if (this->slice_storage_ != NULL)
16097     {
16098       go_assert(!this->storage_escapes_);
16099       space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
16100     }
16101   else if (!copy_to_heap)
16102     {
16103       // The initializer will only run once.
16104       space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
16105       space->unary_expression()->set_is_slice_init();
16106     }
16107   else
16108     {
16109       go_assert(this->storage_escapes_ || this->element_count() == 0);
16110       space = Expression::make_heap_expression(this->array_val_, loc);
16111     }
16112   Array_type* at = this->valtype_->array_type();
16113   Type* et = at->element_type();
16114   space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
16115 				       space, loc);
16116 
16117   // Build a constructor for the slice.
16118   Expression* len = at->length();
16119   Expression* slice_val =
16120     Expression::make_slice_value(this->type(), space, len, len, loc);
16121   return slice_val->get_backend(context);
16122 }
16123 
16124 // Make a slice composite literal.  This is used by the type
16125 // descriptor code.
16126 
16127 Slice_construction_expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)16128 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
16129 					 Location location)
16130 {
16131   go_assert(type->is_slice_type());
16132   return new Slice_construction_expression(type, NULL, vals, location);
16133 }
16134 
16135 // Class Map_construction_expression.
16136 
16137 // Traversal.
16138 
16139 int
do_traverse(Traverse * traverse)16140 Map_construction_expression::do_traverse(Traverse* traverse)
16141 {
16142   if (this->vals_ != NULL
16143       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
16144     return TRAVERSE_EXIT;
16145   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16146     return TRAVERSE_EXIT;
16147   return TRAVERSE_CONTINUE;
16148 }
16149 
16150 // Flatten constructor initializer into a temporary variable since
16151 // we need to take its address for __go_construct_map.
16152 
16153 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)16154 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
16155                                         Statement_inserter* inserter)
16156 {
16157   if (!this->is_error_expression()
16158       && this->vals_ != NULL
16159       && !this->vals_->empty()
16160       && this->constructor_temp_ == NULL)
16161     {
16162       Map_type* mt = this->type_->map_type();
16163       Type* key_type = mt->key_type();
16164       Type* val_type = mt->val_type();
16165       this->element_type_ = Type::make_builtin_struct_type(2,
16166                                                            "__key", key_type,
16167                                                            "__val", val_type);
16168 
16169       Expression_list* value_pairs = new Expression_list();
16170       Location loc = this->location();
16171 
16172       size_t i = 0;
16173       for (Expression_list::const_iterator pv = this->vals_->begin();
16174            pv != this->vals_->end();
16175            ++pv, ++i)
16176         {
16177           Expression_list* key_value_pair = new Expression_list();
16178           Expression* key = *pv;
16179           if (key->is_error_expression() || key->type()->is_error_type())
16180             {
16181               go_assert(saw_errors());
16182               return Expression::make_error(loc);
16183             }
16184 	  if (key->type()->interface_type() != NULL
16185 	      && !key->is_multi_eval_safe())
16186 	    {
16187 	      Temporary_statement* temp =
16188 		Statement::make_temporary(NULL, key, loc);
16189 	      inserter->insert(temp);
16190 	      key = Expression::make_temporary_reference(temp, loc);
16191 	    }
16192 	  key = Expression::convert_for_assignment(gogo, key_type, key, loc);
16193 
16194           ++pv;
16195           Expression* val = *pv;
16196           if (val->is_error_expression() || val->type()->is_error_type())
16197             {
16198               go_assert(saw_errors());
16199               return Expression::make_error(loc);
16200             }
16201 	  if (val->type()->interface_type() != NULL
16202 	      && !val->is_multi_eval_safe())
16203 	    {
16204 	      Temporary_statement* temp =
16205 		Statement::make_temporary(NULL, val, loc);
16206 	      inserter->insert(temp);
16207 	      val = Expression::make_temporary_reference(temp, loc);
16208 	    }
16209 	  val = Expression::convert_for_assignment(gogo, val_type, val, loc);
16210 
16211           key_value_pair->push_back(key);
16212           key_value_pair->push_back(val);
16213           value_pairs->push_back(
16214               Expression::make_struct_composite_literal(this->element_type_,
16215                                                         key_value_pair, loc));
16216         }
16217 
16218       Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
16219       Array_type* ctor_type =
16220           Type::make_array_type(this->element_type_, element_count);
16221       ctor_type->set_is_array_incomparable();
16222       Expression* constructor =
16223           new Fixed_array_construction_expression(ctor_type, NULL,
16224                                                   value_pairs, loc);
16225 
16226       this->constructor_temp_ =
16227           Statement::make_temporary(NULL, constructor, loc);
16228       constructor->issue_nil_check();
16229       this->constructor_temp_->set_is_address_taken();
16230       inserter->insert(this->constructor_temp_);
16231     }
16232 
16233   return this;
16234 }
16235 
16236 // Final type determination.
16237 
16238 void
do_determine_type(const Type_context *)16239 Map_construction_expression::do_determine_type(const Type_context*)
16240 {
16241   if (this->vals_ == NULL)
16242     return;
16243 
16244   Map_type* mt = this->type_->map_type();
16245   Type_context key_context(mt->key_type(), false);
16246   Type_context val_context(mt->val_type(), false);
16247   for (Expression_list::const_iterator pv = this->vals_->begin();
16248        pv != this->vals_->end();
16249        ++pv)
16250     {
16251       (*pv)->determine_type(&key_context);
16252       ++pv;
16253       (*pv)->determine_type(&val_context);
16254     }
16255 }
16256 
16257 // Check types.
16258 
16259 void
do_check_types(Gogo *)16260 Map_construction_expression::do_check_types(Gogo*)
16261 {
16262   if (this->vals_ == NULL)
16263     return;
16264 
16265   Map_type* mt = this->type_->map_type();
16266   int i = 0;
16267   Type* key_type = mt->key_type();
16268   Type* val_type = mt->val_type();
16269   for (Expression_list::const_iterator pv = this->vals_->begin();
16270        pv != this->vals_->end();
16271        ++pv, ++i)
16272     {
16273       if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
16274 	{
16275 	  go_error_at((*pv)->location(),
16276                       "incompatible type for element %d key in map construction",
16277                       i + 1);
16278 	  this->set_is_error();
16279 	}
16280       ++pv;
16281       if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
16282 	{
16283 	  go_error_at((*pv)->location(),
16284                       ("incompatible type for element %d value "
16285                        "in map construction"),
16286 		   i + 1);
16287 	  this->set_is_error();
16288 	}
16289     }
16290 }
16291 
16292 // Copy.
16293 
16294 Expression*
do_copy()16295 Map_construction_expression::do_copy()
16296 {
16297   return new Map_construction_expression(this->type_->copy_expressions(),
16298 					 (this->vals_ == NULL
16299 					  ? NULL
16300 					  : this->vals_->copy()),
16301 					 this->location());
16302 }
16303 
16304 // Make implicit type conversions explicit.
16305 
16306 void
do_add_conversions()16307 Map_construction_expression::do_add_conversions()
16308 {
16309   if (this->vals_ == NULL || this->vals_->empty())
16310     return;
16311 
16312   Map_type* mt = this->type_->map_type();
16313   Type* kt = mt->key_type();
16314   Type* vt = mt->val_type();
16315   bool key_is_interface = (kt->interface_type() != NULL);
16316   bool val_is_interface = (vt->interface_type() != NULL);
16317   if (!key_is_interface && !val_is_interface)
16318     return;
16319 
16320   Location loc = this->location();
16321   for (Expression_list::iterator pv = this->vals_->begin();
16322        pv != this->vals_->end();
16323        ++pv)
16324     {
16325       if (key_is_interface &&
16326           !Type::are_identical(kt, (*pv)->type(), 0, NULL))
16327         *pv = Expression::make_cast(kt, *pv, loc);
16328       ++pv;
16329       if (val_is_interface &&
16330           !Type::are_identical(vt, (*pv)->type(), 0, NULL))
16331         *pv = Expression::make_cast(vt, *pv, loc);
16332     }
16333 }
16334 
16335 // Return the backend representation for constructing a map.
16336 
16337 Bexpression*
do_get_backend(Translate_context * context)16338 Map_construction_expression::do_get_backend(Translate_context* context)
16339 {
16340   if (this->is_error_expression())
16341     return context->backend()->error_expression();
16342   Location loc = this->location();
16343 
16344   size_t i = 0;
16345   Expression* ventries;
16346   if (this->vals_ == NULL || this->vals_->empty())
16347     ventries = Expression::make_nil(loc);
16348   else
16349     {
16350       go_assert(this->constructor_temp_ != NULL);
16351       i = this->vals_->size() / 2;
16352 
16353       Expression* ctor_ref =
16354           Expression::make_temporary_reference(this->constructor_temp_, loc);
16355       ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
16356     }
16357 
16358   Map_type* mt = this->type_->map_type();
16359   if (this->element_type_ == NULL)
16360       this->element_type_ =
16361           Type::make_builtin_struct_type(2,
16362                                          "__key", mt->key_type(),
16363                                          "__val", mt->val_type());
16364   Expression* descriptor = Expression::make_type_descriptor(mt, loc);
16365 
16366   Type* uintptr_t = Type::lookup_integer_type("uintptr");
16367   Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
16368 
16369   Expression* entry_size =
16370       Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
16371 
16372   unsigned int field_index;
16373   const Struct_field* valfield =
16374       this->element_type_->find_local_field("__val", &field_index);
16375   Expression* val_offset =
16376       Expression::make_struct_field_offset(this->element_type_, valfield);
16377 
16378   Expression* map_ctor =
16379       Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
16380                          entry_size, val_offset, ventries);
16381   return map_ctor->get_backend(context);
16382 }
16383 
16384 // Export an array construction.
16385 
16386 void
do_export(Export_function_body * efb) const16387 Map_construction_expression::do_export(Export_function_body* efb) const
16388 {
16389   efb->write_c_string("$convert(");
16390   efb->write_type(this->type_);
16391   for (Expression_list::const_iterator pv = this->vals_->begin();
16392        pv != this->vals_->end();
16393        ++pv)
16394     {
16395       efb->write_c_string(", ");
16396       (*pv)->export_expression(efb);
16397     }
16398   efb->write_c_string(")");
16399 }
16400 
16401 // Dump ast representation for a map construction expression.
16402 
16403 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16404 Map_construction_expression::do_dump_expression(
16405     Ast_dump_context* ast_dump_context) const
16406 {
16407   ast_dump_context->ostream() << "{" ;
16408   ast_dump_context->dump_expression_list(this->vals_, true);
16409   ast_dump_context->ostream() << "}";
16410 }
16411 
16412 // A composite literal key.  This is seen during parsing, but is not
16413 // resolved to a named_object in case this is a composite literal of
16414 // struct type.
16415 
16416 class Composite_literal_key_expression : public Parser_expression
16417 {
16418  public:
Composite_literal_key_expression(const std::string & name,Location location)16419   Composite_literal_key_expression(const std::string& name, Location location)
16420     : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
16421       name_(name)
16422   { }
16423 
16424   const std::string&
name() const16425   name() const
16426   { return this->name_; }
16427 
16428  protected:
16429   Expression*
16430   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
16431 
16432   Expression*
do_copy()16433   do_copy()
16434   {
16435     return new Composite_literal_key_expression(this->name_, this->location());
16436   }
16437 
16438   void
16439   do_dump_expression(Ast_dump_context*) const;
16440 
16441  private:
16442   // The name.
16443   std::string name_;
16444 };
16445 
16446 // Lower a composite literal key.  We will never get here for keys in
16447 // composite literals of struct types, because that is prevented by
16448 // Composite_literal_expression::do_traverse.  So if we do get here,
16449 // this must be a regular name reference after all.
16450 
16451 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)16452 Composite_literal_key_expression::do_lower(Gogo* gogo, Named_object*,
16453 					   Statement_inserter*, int)
16454 {
16455   Named_object* no = gogo->lookup(this->name_, NULL);
16456   if (no == NULL)
16457     {
16458       // Gogo::lookup doesn't look in the global namespace, and names
16459       // used in composite literal keys aren't seen by
16460       // Gogo::define_global_names, so we have to look in the global
16461       // namespace ourselves.
16462       no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
16463       if (no == NULL)
16464 	{
16465 	  go_error_at(this->location(), "reference to undefined name %qs",
16466 		      Gogo::message_name(this->name_).c_str());
16467 	  return Expression::make_error(this->location());
16468 	}
16469     }
16470   return Expression::make_unknown_reference(no, this->location());
16471 }
16472 
16473 // Dump a composite literal key.
16474 
16475 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16476 Composite_literal_key_expression::do_dump_expression(
16477     Ast_dump_context* ast_dump_context) const
16478 {
16479   ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
16480 }
16481 
16482 // Make a composite literal key.
16483 
16484 Expression*
make_composite_literal_key(const std::string & name,Location location)16485 Expression::make_composite_literal_key(const std::string& name,
16486 				       Location location)
16487 {
16488   return new Composite_literal_key_expression(name, location);
16489 }
16490 
16491 // Class Composite_literal_expression.
16492 
16493 // Traversal.
16494 
16495 int
do_traverse(Traverse * traverse)16496 Composite_literal_expression::do_traverse(Traverse* traverse)
16497 {
16498   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16499     return TRAVERSE_EXIT;
16500 
16501   // If this is a struct composite literal with keys, then the keys
16502   // are field names, not expressions.  We don't want to traverse them
16503   // in that case.  If we do, we can give an erroneous error "variable
16504   // initializer refers to itself."  See bug482.go in the testsuite.
16505   if (this->has_keys_ && this->vals_ != NULL)
16506     {
16507       // The type may not be resolvable at this point.
16508       Type* type = this->type_;
16509 
16510       for (int depth = 0; depth < this->depth_; ++depth)
16511         {
16512 	  type = type->deref();
16513           if (type->array_type() != NULL)
16514             type = type->array_type()->element_type();
16515           else if (type->map_type() != NULL)
16516             {
16517               if (this->key_path_[depth])
16518                 type = type->map_type()->key_type();
16519               else
16520                 type = type->map_type()->val_type();
16521             }
16522           else
16523             {
16524               // This error will be reported during lowering.
16525               return TRAVERSE_CONTINUE;
16526             }
16527         }
16528       type = type->deref();
16529 
16530       while (true)
16531 	{
16532 	  if (type->classification() == Type::TYPE_NAMED)
16533 	    type = type->named_type()->real_type();
16534 	  else if (type->classification() == Type::TYPE_FORWARD)
16535 	    {
16536 	      Type* t = type->forwarded();
16537 	      if (t == type)
16538 		break;
16539 	      type = t;
16540 	    }
16541 	  else
16542 	    break;
16543 	}
16544 
16545       if (type->classification() == Type::TYPE_STRUCT)
16546 	{
16547 	  Expression_list::iterator p = this->vals_->begin();
16548 	  while (p != this->vals_->end())
16549 	    {
16550 	      // Skip key.
16551 	      ++p;
16552 	      go_assert(p != this->vals_->end());
16553 	      if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16554 		return TRAVERSE_EXIT;
16555 	      ++p;
16556 	    }
16557 	  return TRAVERSE_CONTINUE;
16558 	}
16559     }
16560 
16561   if (this->vals_ != NULL)
16562     return this->vals_->traverse(traverse);
16563 
16564   return TRAVERSE_CONTINUE;
16565 }
16566 
16567 // Lower a generic composite literal into a specific version based on
16568 // the type.
16569 
16570 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)16571 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
16572 				       Statement_inserter* inserter, int)
16573 {
16574   Type* type = this->type_;
16575 
16576   for (int depth = 0; depth < this->depth_; ++depth)
16577     {
16578       type = type->deref();
16579       if (type->array_type() != NULL)
16580 	type = type->array_type()->element_type();
16581       else if (type->map_type() != NULL)
16582         {
16583           if (this->key_path_[depth])
16584             type = type->map_type()->key_type();
16585           else
16586             type = type->map_type()->val_type();
16587         }
16588       else
16589 	{
16590 	  if (!type->is_error())
16591 	    go_error_at(this->location(),
16592                         ("may only omit types within composite literals "
16593                          "of slice, array, or map type"));
16594 	  return Expression::make_error(this->location());
16595 	}
16596     }
16597 
16598   Type *pt = type->points_to();
16599   bool is_pointer = false;
16600   if (pt != NULL)
16601     {
16602       is_pointer = true;
16603       type = pt;
16604     }
16605 
16606   Expression* ret;
16607   if (type->is_error())
16608     return Expression::make_error(this->location());
16609   else if (type->struct_type() != NULL)
16610     ret = this->lower_struct(gogo, type);
16611   else if (type->array_type() != NULL)
16612     ret = this->lower_array(type);
16613   else if (type->map_type() != NULL)
16614     ret = this->lower_map(gogo, function, inserter, type);
16615   else
16616     {
16617       go_error_at(this->location(),
16618                   ("expected struct, slice, array, or map type "
16619                    "for composite literal"));
16620       return Expression::make_error(this->location());
16621     }
16622 
16623   if (is_pointer)
16624     ret = Expression::make_heap_expression(ret, this->location());
16625 
16626   return ret;
16627 }
16628 
16629 // Lower a struct composite literal.
16630 
16631 Expression*
lower_struct(Gogo * gogo,Type * type)16632 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
16633 {
16634   Location location = this->location();
16635   Struct_type* st = type->struct_type();
16636   if (this->vals_ == NULL || !this->has_keys_)
16637     {
16638       if (this->vals_ != NULL
16639 	  && !this->vals_->empty()
16640 	  && type->named_type() != NULL
16641 	  && type->named_type()->named_object()->package() != NULL)
16642 	{
16643 	  for (Struct_field_list::const_iterator pf = st->fields()->begin();
16644 	       pf != st->fields()->end();
16645 	       ++pf)
16646 	    {
16647 	      if (Gogo::is_hidden_name(pf->field_name())
16648 		  || pf->is_embedded_builtin(gogo))
16649 		go_error_at(this->location(),
16650                             "assignment of unexported field %qs in %qs literal",
16651                             Gogo::message_name(pf->field_name()).c_str(),
16652                             type->named_type()->message_name().c_str());
16653 	    }
16654 	}
16655 
16656       return new Struct_construction_expression(type, this->vals_, location);
16657     }
16658 
16659   size_t field_count = st->field_count();
16660   std::vector<Expression*> vals(field_count);
16661   std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
16662   Expression_list::const_iterator p = this->vals_->begin();
16663   Expression* external_expr = NULL;
16664   const Named_object* external_no = NULL;
16665   while (p != this->vals_->end())
16666     {
16667       Expression* name_expr = *p;
16668 
16669       ++p;
16670       go_assert(p != this->vals_->end());
16671       Expression* val = *p;
16672 
16673       ++p;
16674 
16675       if (name_expr == NULL)
16676 	{
16677 	  go_error_at(val->location(),
16678                       "mixture of field and value initializers");
16679 	  return Expression::make_error(location);
16680 	}
16681 
16682       bool bad_key = false;
16683       std::string name;
16684       const Named_object* no = NULL;
16685       switch (name_expr->classification())
16686 	{
16687 	case EXPRESSION_COMPOSITE_LITERAL_KEY:
16688 	  name =
16689 	    static_cast<Composite_literal_key_expression*>(name_expr)->name();
16690 	  break;
16691 
16692 	case EXPRESSION_UNKNOWN_REFERENCE:
16693 	  name = name_expr->unknown_expression()->name();
16694 	  if (type->named_type() != NULL)
16695 	    {
16696 	      // If the named object found for this field name comes from a
16697 	      // different package than the struct it is a part of, do not count
16698 	      // this incorrect lookup as a usage of the object's package.
16699 	      no = name_expr->unknown_expression()->named_object();
16700 	      if (no->package() != NULL
16701 		  && no->package() != type->named_type()->named_object()->package())
16702 		no->package()->forget_usage(name_expr);
16703 	    }
16704 	  break;
16705 
16706 	case EXPRESSION_CONST_REFERENCE:
16707 	  no = static_cast<Const_expression*>(name_expr)->named_object();
16708 	  break;
16709 
16710 	case EXPRESSION_TYPE:
16711 	  {
16712 	    Type* t = name_expr->type();
16713 	    Named_type* nt = t->named_type();
16714 	    if (nt == NULL)
16715 	      bad_key = true;
16716 	    else
16717 	      no = nt->named_object();
16718 	  }
16719 	  break;
16720 
16721 	case EXPRESSION_VAR_REFERENCE:
16722 	  no = name_expr->var_expression()->named_object();
16723 	  break;
16724 
16725 	case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16726 	  no = name_expr->enclosed_var_expression()->variable();
16727 	  break;
16728 
16729 	case EXPRESSION_FUNC_REFERENCE:
16730 	  no = name_expr->func_expression()->named_object();
16731 	  break;
16732 
16733 	default:
16734 	  bad_key = true;
16735 	  break;
16736 	}
16737       if (bad_key)
16738 	{
16739 	  go_error_at(name_expr->location(), "expected struct field name");
16740 	  return Expression::make_error(location);
16741 	}
16742 
16743       if (no != NULL)
16744 	{
16745 	  if (no->package() != NULL && external_expr == NULL)
16746 	    {
16747 	      external_expr = name_expr;
16748 	      external_no = no;
16749 	    }
16750 
16751 	  name = no->name();
16752 
16753 	  // A predefined name won't be packed.  If it starts with a
16754 	  // lower case letter we need to check for that case, because
16755 	  // the field name will be packed.  FIXME.
16756 	  if (!Gogo::is_hidden_name(name)
16757 	      && name[0] >= 'a'
16758 	      && name[0] <= 'z')
16759 	    {
16760 	      Named_object* gno = gogo->lookup_global(name.c_str());
16761 	      if (gno == no)
16762 		name = gogo->pack_hidden_name(name, false);
16763 	    }
16764 	}
16765 
16766       unsigned int index;
16767       const Struct_field* sf = st->find_local_field(name, &index);
16768       if (sf == NULL)
16769 	{
16770 	  go_error_at(name_expr->location(), "unknown field %qs in %qs",
16771                       Gogo::message_name(name).c_str(),
16772                       (type->named_type() != NULL
16773                        ? type->named_type()->message_name().c_str()
16774                        : "unnamed struct"));
16775 	  return Expression::make_error(location);
16776 	}
16777       if (vals[index] != NULL)
16778 	{
16779 	  go_error_at(name_expr->location(),
16780                       "duplicate value for field %qs in %qs",
16781                       Gogo::message_name(name).c_str(),
16782                       (type->named_type() != NULL
16783                        ? type->named_type()->message_name().c_str()
16784                        : "unnamed struct"));
16785 	  return Expression::make_error(location);
16786 	}
16787 
16788       if (type->named_type() != NULL
16789 	  && type->named_type()->named_object()->package() != NULL
16790 	  && (Gogo::is_hidden_name(sf->field_name())
16791 	      || sf->is_embedded_builtin(gogo)))
16792 	go_error_at(name_expr->location(),
16793                     "assignment of unexported field %qs in %qs literal",
16794                     Gogo::message_name(sf->field_name()).c_str(),
16795                     type->named_type()->message_name().c_str());
16796 
16797       vals[index] = val;
16798       traverse_order->push_back(static_cast<unsigned long>(index));
16799     }
16800 
16801   if (!this->all_are_names_)
16802     {
16803       // This is a weird case like bug462 in the testsuite.
16804       if (external_expr == NULL)
16805 	go_error_at(this->location(), "unknown field in %qs literal",
16806                     (type->named_type() != NULL
16807                      ? type->named_type()->message_name().c_str()
16808                      : "unnamed struct"));
16809       else
16810 	go_error_at(external_expr->location(), "unknown field %qs in %qs",
16811                     external_no->message_name().c_str(),
16812                     (type->named_type() != NULL
16813                      ? type->named_type()->message_name().c_str()
16814                      : "unnamed struct"));
16815       return Expression::make_error(location);
16816     }
16817 
16818   Expression_list* list = new Expression_list;
16819   list->reserve(field_count);
16820   for (size_t i = 0; i < field_count; ++i)
16821     list->push_back(vals[i]);
16822 
16823   Struct_construction_expression* ret =
16824     new Struct_construction_expression(type, list, location);
16825   ret->set_traverse_order(traverse_order);
16826   return ret;
16827 }
16828 
16829 // Index/value/traversal-order triple.
16830 
16831 struct IVT_triple {
16832   unsigned long index;
16833   unsigned long traversal_order;
16834   Expression* expr;
IVT_tripleIVT_triple16835   IVT_triple(unsigned long i, unsigned long to, Expression *e)
16836       : index(i), traversal_order(to), expr(e) { }
operator <IVT_triple16837   bool operator<(const IVT_triple& other) const
16838   { return this->index < other.index; }
16839 };
16840 
16841 // Lower an array composite literal.
16842 
16843 Expression*
lower_array(Type * type)16844 Composite_literal_expression::lower_array(Type* type)
16845 {
16846   Location location = this->location();
16847   if (this->vals_ == NULL || !this->has_keys_)
16848     return this->make_array(type, NULL, this->vals_);
16849 
16850   std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
16851   indexes->reserve(this->vals_->size());
16852   bool indexes_out_of_order = false;
16853   Expression_list* vals = new Expression_list();
16854   vals->reserve(this->vals_->size());
16855   unsigned long index = 0;
16856   Expression_list::const_iterator p = this->vals_->begin();
16857   while (p != this->vals_->end())
16858     {
16859       Expression* index_expr = *p;
16860 
16861       ++p;
16862       go_assert(p != this->vals_->end());
16863       Expression* val = *p;
16864 
16865       ++p;
16866 
16867       if (index_expr == NULL)
16868 	{
16869 	  if (std::find(indexes->begin(), indexes->end(), index)
16870 	      != indexes->end())
16871 	    {
16872 	      go_error_at(val->location(),
16873 			  "duplicate value for index %lu", index);
16874 	      return Expression::make_error(location);
16875 	    }
16876 	  if (!indexes->empty())
16877 	    indexes->push_back(index);
16878 	}
16879       else
16880 	{
16881 	  if (indexes->empty() && !vals->empty())
16882 	    {
16883 	      for (size_t i = 0; i < vals->size(); ++i)
16884 		indexes->push_back(i);
16885 	    }
16886 
16887 	  Numeric_constant nc;
16888 	  if (!index_expr->numeric_constant_value(&nc))
16889 	    {
16890 	      go_error_at(index_expr->location(),
16891                           "index expression is not integer constant");
16892 	      return Expression::make_error(location);
16893 	    }
16894 
16895 	  switch (nc.to_unsigned_long(&index))
16896 	    {
16897 	    case Numeric_constant::NC_UL_VALID:
16898 	      break;
16899 	    case Numeric_constant::NC_UL_NOTINT:
16900 	      go_error_at(index_expr->location(),
16901                           "index expression is not integer constant");
16902 	      return Expression::make_error(location);
16903 	    case Numeric_constant::NC_UL_NEGATIVE:
16904 	      go_error_at(index_expr->location(),
16905                           "index expression is negative");
16906 	      return Expression::make_error(location);
16907 	    case Numeric_constant::NC_UL_BIG:
16908 	      go_error_at(index_expr->location(), "index value overflow");
16909 	      return Expression::make_error(location);
16910 	    default:
16911 	      go_unreachable();
16912 	    }
16913 
16914 	  Named_type* ntype = Type::lookup_integer_type("int");
16915 	  Integer_type* inttype = ntype->integer_type();
16916 	  if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
16917 	      && index >> (inttype->bits() - 1) != 0)
16918 	    {
16919 	      go_error_at(index_expr->location(), "index value overflow");
16920 	      return Expression::make_error(location);
16921 	    }
16922 
16923 	  if (std::find(indexes->begin(), indexes->end(), index)
16924 	      != indexes->end())
16925 	    {
16926 	      go_error_at(index_expr->location(),
16927                           "duplicate value for index %lu",
16928                           index);
16929 	      return Expression::make_error(location);
16930 	    }
16931 
16932 	  if (!indexes->empty() && index < indexes->back())
16933 	    indexes_out_of_order = true;
16934 
16935 	  indexes->push_back(index);
16936 	}
16937 
16938       vals->push_back(val);
16939 
16940       ++index;
16941     }
16942 
16943   if (indexes->empty())
16944     {
16945       delete indexes;
16946       indexes = NULL;
16947     }
16948 
16949   std::vector<unsigned long>* traverse_order = NULL;
16950   if (indexes_out_of_order)
16951     {
16952       typedef std::vector<IVT_triple> V;
16953 
16954       V v;
16955       v.reserve(indexes->size());
16956       std::vector<unsigned long>::const_iterator pi = indexes->begin();
16957       unsigned long torder = 0;
16958       for (Expression_list::const_iterator pe = vals->begin();
16959 	   pe != vals->end();
16960 	   ++pe, ++pi, ++torder)
16961 	v.push_back(IVT_triple(*pi, torder, *pe));
16962 
16963       std::sort(v.begin(), v.end());
16964 
16965       delete indexes;
16966       delete vals;
16967 
16968       indexes = new std::vector<unsigned long>();
16969       indexes->reserve(v.size());
16970       vals = new Expression_list();
16971       vals->reserve(v.size());
16972       traverse_order = new std::vector<unsigned long>();
16973       traverse_order->reserve(v.size());
16974 
16975       for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
16976 	{
16977 	  indexes->push_back(pv->index);
16978 	  vals->push_back(pv->expr);
16979 	  traverse_order->push_back(pv->traversal_order);
16980 	}
16981     }
16982 
16983   Expression* ret = this->make_array(type, indexes, vals);
16984   Array_construction_expression* ace = ret->array_literal();
16985   if (ace != NULL && traverse_order != NULL)
16986     ace->set_traverse_order(traverse_order);
16987   return ret;
16988 }
16989 
16990 // Actually build the array composite literal. This handles
16991 // [...]{...}.
16992 
16993 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)16994 Composite_literal_expression::make_array(
16995     Type* type,
16996     const std::vector<unsigned long>* indexes,
16997     Expression_list* vals)
16998 {
16999   Location location = this->location();
17000   Array_type* at = type->array_type();
17001 
17002   if (at->length() != NULL && at->length()->is_nil_expression())
17003     {
17004       size_t size;
17005       if (vals == NULL)
17006 	size = 0;
17007       else if (indexes != NULL)
17008 	size = indexes->back() + 1;
17009       else
17010 	{
17011 	  size = vals->size();
17012 	  Integer_type* it = Type::lookup_integer_type("int")->integer_type();
17013 	  if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
17014 	      && size >> (it->bits() - 1) != 0)
17015 	    {
17016 	      go_error_at(location, "too many elements in composite literal");
17017 	      return Expression::make_error(location);
17018 	    }
17019 	}
17020 
17021       Expression* elen = Expression::make_integer_ul(size, NULL, location);
17022       at = Type::make_array_type(at->element_type(), elen);
17023       type = at;
17024     }
17025   else if (at->length() != NULL
17026 	   && !at->length()->is_error_expression()
17027 	   && this->vals_ != NULL)
17028     {
17029       Numeric_constant nc;
17030       unsigned long val;
17031       if (at->length()->numeric_constant_value(&nc)
17032 	  && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
17033 	{
17034 	  if (indexes == NULL)
17035 	    {
17036 	      if (this->vals_->size() > val)
17037 		{
17038 		  go_error_at(location,
17039                               "too many elements in composite literal");
17040 		  return Expression::make_error(location);
17041 		}
17042 	    }
17043 	  else
17044 	    {
17045 	      unsigned long max = indexes->back();
17046 	      if (max >= val)
17047 		{
17048 		  go_error_at(location,
17049                               ("some element keys in composite literal "
17050                                "are out of range"));
17051 		  return Expression::make_error(location);
17052 		}
17053 	    }
17054 	}
17055     }
17056 
17057   if (at->length() != NULL)
17058     return new Fixed_array_construction_expression(type, indexes, vals,
17059 						   location);
17060   else
17061     return new Slice_construction_expression(type, indexes, vals, location);
17062 }
17063 
17064 // Lower a map composite literal.
17065 
17066 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)17067 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
17068 					Statement_inserter* inserter,
17069 					Type* type)
17070 {
17071   Location location = this->location();
17072   Unordered_map(unsigned int, std::vector<Expression*>) st;
17073   Unordered_map(unsigned int, std::vector<Expression*>) nt;
17074   if (this->vals_ != NULL)
17075     {
17076       if (!this->has_keys_)
17077 	{
17078 	  go_error_at(location, "map composite literal must have keys");
17079 	  return Expression::make_error(location);
17080 	}
17081 
17082       for (Expression_list::iterator p = this->vals_->begin();
17083 	   p != this->vals_->end();
17084 	   p += 2)
17085 	{
17086 	  if (*p == NULL)
17087 	    {
17088 	      ++p;
17089 	      go_error_at((*p)->location(),
17090                           ("map composite literal must "
17091                            "have keys for every value"));
17092 	      return Expression::make_error(location);
17093 	    }
17094 	  // Make sure we have lowered the key; it may not have been
17095 	  // lowered in order to handle keys for struct composite
17096 	  // literals.  Lower it now to get the right error message.
17097 	  if ((*p)->unknown_expression() != NULL)
17098 	    {
17099 	      gogo->lower_expression(function, inserter, &*p);
17100 	      go_assert((*p)->is_error_expression());
17101 	      return Expression::make_error(location);
17102 	    }
17103 	  // Check if there are duplicate constant keys.
17104 	  if (!(*p)->is_constant())
17105 	    continue;
17106 	  std::string sval;
17107 	  Numeric_constant nval;
17108 	  if ((*p)->string_constant_value(&sval)) // Check string keys.
17109 	    {
17110 	      unsigned int h = Gogo::hash_string(sval, 0);
17111 	      // Search the index h in the hash map.
17112 	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
17113 	      mit = st.find(h);
17114 	      if (mit == st.end())
17115 		{
17116 		  // No duplicate since h is a new index.
17117 		  // Create a new vector indexed by h and add it to the hash map.
17118 		  std::vector<Expression*> l;
17119 		  l.push_back(*p);
17120 		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
17121 		  st.insert(val);
17122 		}
17123 	      else
17124 		{
17125 		  // Do further check since index h already exists.
17126 		  for (std::vector<Expression*>::iterator lit =
17127 			   mit->second.begin();
17128 		       lit != mit->second.end();
17129 		       lit++)
17130 		    {
17131 		      std::string s;
17132 		      bool ok = (*lit)->string_constant_value(&s);
17133 		      go_assert(ok);
17134 		      if (s == sval)
17135 			{
17136 			  go_error_at((*p)->location(), ("duplicate key "
17137 				      "in map literal"));
17138 			  return Expression::make_error(location);
17139 			}
17140 		    }
17141 		  // Add this new string key to the vector indexed by h.
17142 		  mit->second.push_back(*p);
17143 		}
17144 	    }
17145 	  else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
17146 	    {
17147 	      unsigned int h = nval.hash(0);
17148 	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
17149 	      mit = nt.find(h);
17150 	      if (mit == nt.end())
17151 		{
17152 		  // No duplicate since h is a new code.
17153 		  // Create a new vector indexed by h and add it to the hash map.
17154 		  std::vector<Expression*> l;
17155 		  l.push_back(*p);
17156 		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
17157 		  nt.insert(val);
17158 		}
17159 	      else
17160 		{
17161 		  // Do further check since h already exists.
17162 		  for (std::vector<Expression*>::iterator lit =
17163 			   mit->second.begin();
17164 		       lit != mit->second.end();
17165 		       lit++)
17166 		    {
17167 		      Numeric_constant rval;
17168 		      bool ok = (*lit)->numeric_constant_value(&rval);
17169 		      go_assert(ok);
17170 		      if (nval.equals(rval))
17171 			{
17172 			  go_error_at((*p)->location(),
17173 				      "duplicate key in map literal");
17174 			  return Expression::make_error(location);
17175 			}
17176 		    }
17177 		  // Add this new numeric key to the vector indexed by h.
17178 		  mit->second.push_back(*p);
17179 		}
17180 	    }
17181 	}
17182     }
17183 
17184   return new Map_construction_expression(type, this->vals_, location);
17185 }
17186 
17187 // Copy.
17188 
17189 Expression*
do_copy()17190 Composite_literal_expression::do_copy()
17191 {
17192   Composite_literal_expression* ret =
17193     new Composite_literal_expression(this->type_->copy_expressions(),
17194 				     this->depth_, this->has_keys_,
17195 				     (this->vals_ == NULL
17196 				      ? NULL
17197 				      : this->vals_->copy()),
17198 				     this->all_are_names_,
17199 				     this->location());
17200   ret->key_path_ = this->key_path_;
17201   return ret;
17202 }
17203 
17204 // Dump ast representation for a composite literal expression.
17205 
17206 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17207 Composite_literal_expression::do_dump_expression(
17208                                Ast_dump_context* ast_dump_context) const
17209 {
17210   ast_dump_context->ostream() << "composite(";
17211   ast_dump_context->dump_type(this->type_);
17212   ast_dump_context->ostream() << ", {";
17213   ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
17214   ast_dump_context->ostream() << "})";
17215 }
17216 
17217 // Make a composite literal expression.
17218 
17219 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)17220 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
17221 				   Expression_list* vals, bool all_are_names,
17222 				   Location location)
17223 {
17224   return new Composite_literal_expression(type, depth, has_keys, vals,
17225 					  all_are_names, location);
17226 }
17227 
17228 // Return whether this expression is a composite literal.
17229 
17230 bool
is_composite_literal() const17231 Expression::is_composite_literal() const
17232 {
17233   switch (this->classification_)
17234     {
17235     case EXPRESSION_COMPOSITE_LITERAL:
17236     case EXPRESSION_STRUCT_CONSTRUCTION:
17237     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
17238     case EXPRESSION_SLICE_CONSTRUCTION:
17239     case EXPRESSION_MAP_CONSTRUCTION:
17240       return true;
17241     default:
17242       return false;
17243     }
17244 }
17245 
17246 // Return whether this expression is a composite literal which is not
17247 // constant.
17248 
17249 bool
is_nonconstant_composite_literal() const17250 Expression::is_nonconstant_composite_literal() const
17251 {
17252   switch (this->classification_)
17253     {
17254     case EXPRESSION_STRUCT_CONSTRUCTION:
17255       {
17256 	const Struct_construction_expression *psce =
17257 	  static_cast<const Struct_construction_expression*>(this);
17258 	return !psce->is_constant_struct();
17259       }
17260     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
17261       {
17262 	const Fixed_array_construction_expression *pace =
17263 	  static_cast<const Fixed_array_construction_expression*>(this);
17264 	return !pace->is_constant_array();
17265       }
17266     case EXPRESSION_SLICE_CONSTRUCTION:
17267       {
17268 	const Slice_construction_expression *pace =
17269 	  static_cast<const Slice_construction_expression*>(this);
17270 	return !pace->is_constant_array();
17271       }
17272     case EXPRESSION_MAP_CONSTRUCTION:
17273       return true;
17274     default:
17275       return false;
17276     }
17277 }
17278 
17279 // Return true if this is a variable or temporary_variable.
17280 
17281 bool
is_variable() const17282 Expression::is_variable() const
17283 {
17284   switch (this->classification_)
17285     {
17286     case EXPRESSION_VAR_REFERENCE:
17287     case EXPRESSION_TEMPORARY_REFERENCE:
17288     case EXPRESSION_SET_AND_USE_TEMPORARY:
17289     case EXPRESSION_ENCLOSED_VAR_REFERENCE:
17290       return true;
17291     default:
17292       return false;
17293     }
17294 }
17295 
17296 // Return true if this is a reference to a local variable.
17297 
17298 bool
is_local_variable() const17299 Expression::is_local_variable() const
17300 {
17301   const Var_expression* ve = this->var_expression();
17302   if (ve == NULL)
17303     return false;
17304   const Named_object* no = ve->named_object();
17305   return (no->is_result_variable()
17306 	  || (no->is_variable() && !no->var_value()->is_global()));
17307 }
17308 
17309 // Return true if multiple evaluations are OK.
17310 
17311 bool
is_multi_eval_safe()17312 Expression::is_multi_eval_safe()
17313 {
17314   switch (this->classification_)
17315     {
17316     case EXPRESSION_VAR_REFERENCE:
17317       {
17318 	// A variable is a simple reference if not stored in the heap.
17319 	const Named_object* no = this->var_expression()->named_object();
17320 	if (no->is_variable())
17321 	  return !no->var_value()->is_in_heap();
17322 	else if (no->is_result_variable())
17323 	  return !no->result_var_value()->is_in_heap();
17324 	else
17325 	  go_unreachable();
17326       }
17327 
17328     case EXPRESSION_TEMPORARY_REFERENCE:
17329       return true;
17330 
17331     default:
17332       break;
17333     }
17334 
17335   if (!this->is_constant())
17336     return false;
17337 
17338   // Only numeric and boolean constants are really multi-evaluation
17339   // safe.  We don't want multiple copies of string constants.
17340   Type* type = this->type();
17341   return type->is_numeric_type() || type->is_boolean_type();
17342 }
17343 
17344 const Named_object*
named_constant() const17345 Expression::named_constant() const
17346 {
17347   if (this->classification() != EXPRESSION_CONST_REFERENCE)
17348     return NULL;
17349   const Const_expression* ce = static_cast<const Const_expression*>(this);
17350   return ce->named_object();
17351 }
17352 
17353 // Class Type_guard_expression.
17354 
17355 // Traversal.
17356 
17357 int
do_traverse(Traverse * traverse)17358 Type_guard_expression::do_traverse(Traverse* traverse)
17359 {
17360   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
17361       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17362     return TRAVERSE_EXIT;
17363   return TRAVERSE_CONTINUE;
17364 }
17365 
17366 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)17367 Type_guard_expression::do_flatten(Gogo*, Named_object*,
17368                                   Statement_inserter* inserter)
17369 {
17370   if (this->expr_->is_error_expression()
17371       || this->expr_->type()->is_error_type())
17372     {
17373       go_assert(saw_errors());
17374       return Expression::make_error(this->location());
17375     }
17376 
17377   if (!this->expr_->is_multi_eval_safe())
17378     {
17379       Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
17380                                                             this->location());
17381       inserter->insert(temp);
17382       this->expr_ =
17383           Expression::make_temporary_reference(temp, this->location());
17384     }
17385   return this;
17386 }
17387 
17388 // Check types of a type guard expression.  The expression must have
17389 // an interface type, but the actual type conversion is checked at run
17390 // time.
17391 
17392 void
do_check_types(Gogo *)17393 Type_guard_expression::do_check_types(Gogo*)
17394 {
17395   Type* expr_type = this->expr_->type();
17396   if (expr_type->interface_type() == NULL)
17397     {
17398       if (!expr_type->is_error() && !this->type_->is_error())
17399 	this->report_error(_("type assertion only valid for interface types"));
17400       this->set_is_error();
17401     }
17402   else if (this->type_->interface_type() == NULL)
17403     {
17404       std::string reason;
17405       if (!expr_type->interface_type()->implements_interface(this->type_,
17406 							     &reason))
17407 	{
17408 	  if (!this->type_->is_error())
17409 	    {
17410 	      if (reason.empty())
17411 		this->report_error(_("impossible type assertion: "
17412 				     "type does not implement interface"));
17413 	      else
17414 		go_error_at(this->location(),
17415                             ("impossible type assertion: "
17416                              "type does not implement interface (%s)"),
17417                             reason.c_str());
17418 	    }
17419 	  this->set_is_error();
17420 	}
17421     }
17422 }
17423 
17424 // Copy.
17425 
17426 Expression*
do_copy()17427 Type_guard_expression::do_copy()
17428 {
17429   return new Type_guard_expression(this->expr_->copy(),
17430 				   this->type_->copy_expressions(),
17431 				   this->location());
17432 }
17433 
17434 // Return the backend representation for a type guard expression.
17435 
17436 Bexpression*
do_get_backend(Translate_context * context)17437 Type_guard_expression::do_get_backend(Translate_context* context)
17438 {
17439   Expression* conversion;
17440   if (this->type_->interface_type() != NULL)
17441     conversion =
17442         Expression::convert_interface_to_interface(this->type_, this->expr_,
17443                                                    true, this->location());
17444   else
17445     conversion =
17446         Expression::convert_for_assignment(context->gogo(), this->type_,
17447                                            this->expr_, this->location());
17448 
17449   Gogo* gogo = context->gogo();
17450   Btype* bt = this->type_->get_backend(gogo);
17451   Bexpression* bexpr = conversion->get_backend(context);
17452   return gogo->backend()->convert_expression(bt, bexpr, this->location());
17453 }
17454 
17455 // Dump ast representation for a type guard expression.
17456 
17457 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17458 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
17459     const
17460 {
17461   this->expr_->dump_expression(ast_dump_context);
17462   ast_dump_context->ostream() <<  ".";
17463   ast_dump_context->dump_type(this->type_);
17464 }
17465 
17466 // Make a type guard expression.
17467 
17468 Expression*
make_type_guard(Expression * expr,Type * type,Location location)17469 Expression::make_type_guard(Expression* expr, Type* type,
17470 			    Location location)
17471 {
17472   return new Type_guard_expression(expr, type, location);
17473 }
17474 
17475 // Class Heap_expression.
17476 
17477 // Return the type of the expression stored on the heap.
17478 
17479 Type*
do_type()17480 Heap_expression::do_type()
17481 { return Type::make_pointer_type(this->expr_->type()); }
17482 
17483 // Return the backend representation for allocating an expression on the heap.
17484 
17485 Bexpression*
do_get_backend(Translate_context * context)17486 Heap_expression::do_get_backend(Translate_context* context)
17487 {
17488   Type* etype = this->expr_->type();
17489   if (this->expr_->is_error_expression() || etype->is_error())
17490     return context->backend()->error_expression();
17491 
17492   Location loc = this->location();
17493   Gogo* gogo = context->gogo();
17494   Btype* btype = this->type()->get_backend(gogo);
17495 
17496   Expression* alloc = Expression::make_allocation(etype, loc);
17497   if (this->allocate_on_stack_)
17498     alloc->allocation_expression()->set_allocate_on_stack();
17499   Bexpression* space = alloc->get_backend(context);
17500 
17501   Bstatement* decl;
17502   Named_object* fn = context->function();
17503   go_assert(fn != NULL);
17504   Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
17505   Bvariable* space_temp =
17506     gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
17507 					space,
17508 					Backend::variable_address_is_taken,
17509 					loc, &decl);
17510   Btype* expr_btype = etype->get_backend(gogo);
17511 
17512   Bexpression* bexpr = this->expr_->get_backend(context);
17513 
17514   // If this assignment needs a write barrier, call typedmemmove.  We
17515   // don't do this in the write barrier pass because in some cases
17516   // backend conversion can introduce new Heap_expression values.
17517   Bstatement* assn;
17518   if (!etype->has_pointer() || this->allocate_on_stack_)
17519     {
17520       space = gogo->backend()->var_expression(space_temp, loc);
17521       Bexpression* ref =
17522 	gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17523       assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
17524     }
17525   else
17526     {
17527       Bstatement* edecl;
17528       Bvariable* btemp =
17529 	gogo->backend()->temporary_variable(fndecl, context->bblock(),
17530 					    expr_btype, bexpr,
17531 					    Backend::variable_address_is_taken,
17532 					    loc, &edecl);
17533       Bexpression* btempref = gogo->backend()->var_expression(btemp,
17534 							      loc);
17535       space = gogo->backend()->var_expression(space_temp, loc);
17536       Type* etype_ptr = Type::make_pointer_type(etype);
17537       Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
17538       Expression* erhs;
17539       Expression* call;
17540       if (etype->is_direct_iface_type())
17541         {
17542           // Single pointer.
17543           Type* uintptr_type = Type::lookup_integer_type("uintptr");
17544           erhs = Expression::make_backend(btempref, etype, loc);
17545           erhs = Expression::unpack_direct_iface(erhs, loc);
17546           erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
17547           call = Runtime::make_call(Runtime::GCWRITEBARRIER, loc, 2,
17548                                     elhs, erhs);
17549         }
17550       else
17551         {
17552           Expression* td = Expression::make_type_descriptor(etype, loc);
17553           Bexpression* addr =
17554             gogo->backend()->address_expression(btempref, loc);
17555           erhs = Expression::make_backend(addr, etype_ptr, loc);
17556           call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
17557                                     td, elhs, erhs);
17558         }
17559       Statement* cs = Statement::make_statement(call, false);
17560 
17561       space = gogo->backend()->var_expression(space_temp, loc);
17562       Bexpression* ref =
17563         gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17564       Expression* eref = Expression::make_backend(ref, etype, loc);
17565       btempref = gogo->backend()->var_expression(btemp, loc);
17566       erhs = Expression::make_backend(btempref, etype, loc);
17567       Statement* as = Statement::make_assignment(eref, erhs, loc);
17568 
17569       as = gogo->check_write_barrier(context->block(), as, cs);
17570       Bstatement* s = as->get_backend(context);
17571 
17572       assn = gogo->backend()->compound_statement(edecl, s);
17573     }
17574   decl = gogo->backend()->compound_statement(decl, assn);
17575   space = gogo->backend()->var_expression(space_temp, loc);
17576   return gogo->backend()->compound_expression(decl, space, loc);
17577 }
17578 
17579 // Dump ast representation for a heap expression.
17580 
17581 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17582 Heap_expression::do_dump_expression(
17583     Ast_dump_context* ast_dump_context) const
17584 {
17585   ast_dump_context->ostream() << "&(";
17586   ast_dump_context->dump_expression(this->expr_);
17587   ast_dump_context->ostream() << ")";
17588 }
17589 
17590 // Allocate an expression on the heap.
17591 
17592 Expression*
make_heap_expression(Expression * expr,Location location)17593 Expression::make_heap_expression(Expression* expr, Location location)
17594 {
17595   return new Heap_expression(expr, location);
17596 }
17597 
17598 // Class Receive_expression.
17599 
17600 // Return the type of a receive expression.
17601 
17602 Type*
do_type()17603 Receive_expression::do_type()
17604 {
17605   if (this->is_error_expression())
17606     return Type::make_error_type();
17607   Channel_type* channel_type = this->channel_->type()->channel_type();
17608   if (channel_type == NULL)
17609     {
17610       this->report_error(_("expected channel"));
17611       return Type::make_error_type();
17612     }
17613   return channel_type->element_type();
17614 }
17615 
17616 // Check types for a receive expression.
17617 
17618 void
do_check_types(Gogo *)17619 Receive_expression::do_check_types(Gogo*)
17620 {
17621   Type* type = this->channel_->type();
17622   if (type->is_error())
17623     {
17624       go_assert(saw_errors());
17625       this->set_is_error();
17626       return;
17627     }
17628   if (type->channel_type() == NULL)
17629     {
17630       this->report_error(_("expected channel"));
17631       return;
17632     }
17633   if (!type->channel_type()->may_receive())
17634     {
17635       this->report_error(_("invalid receive on send-only channel"));
17636       return;
17637     }
17638 }
17639 
17640 // Flattening for receive expressions creates a temporary variable to store
17641 // received data in for receives.
17642 
17643 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)17644 Receive_expression::do_flatten(Gogo*, Named_object*,
17645                                Statement_inserter* inserter)
17646 {
17647   Channel_type* channel_type = this->channel_->type()->channel_type();
17648   if (channel_type == NULL)
17649     {
17650       go_assert(saw_errors());
17651       return this;
17652     }
17653   else if (this->channel_->is_error_expression())
17654    {
17655      go_assert(saw_errors());
17656      return Expression::make_error(this->location());
17657    }
17658 
17659   Type* element_type = channel_type->element_type();
17660   if (this->temp_receiver_ == NULL)
17661     {
17662       this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
17663 						       this->location());
17664       this->temp_receiver_->set_is_address_taken();
17665       inserter->insert(this->temp_receiver_);
17666     }
17667 
17668   return this;
17669 }
17670 
17671 // Get the backend representation for a receive expression.
17672 
17673 Bexpression*
do_get_backend(Translate_context * context)17674 Receive_expression::do_get_backend(Translate_context* context)
17675 {
17676   Location loc = this->location();
17677 
17678   Channel_type* channel_type = this->channel_->type()->channel_type();
17679   if (channel_type == NULL)
17680     {
17681       go_assert(this->channel_->type()->is_error());
17682       return context->backend()->error_expression();
17683     }
17684 
17685   Expression* recv_ref =
17686     Expression::make_temporary_reference(this->temp_receiver_, loc);
17687   Expression* recv_addr =
17688     Expression::make_temporary_reference(this->temp_receiver_, loc);
17689   recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
17690   Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
17691 					this->channel_, recv_addr);
17692   return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
17693 }
17694 
17695 // Export a receive expression.
17696 
17697 void
do_export(Export_function_body * efb) const17698 Receive_expression::do_export(Export_function_body* efb) const
17699 {
17700   efb->write_c_string("<-");
17701   this->channel_->export_expression(efb);
17702 }
17703 
17704 // Dump ast representation for a receive expression.
17705 
17706 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17707 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
17708 {
17709   ast_dump_context->ostream() << " <- " ;
17710   ast_dump_context->dump_expression(channel_);
17711 }
17712 
17713 // Import a receive expression.
17714 
17715 Expression*
do_import(Import_expression * imp,Location loc)17716 Receive_expression::do_import(Import_expression* imp, Location loc)
17717 {
17718   imp->require_c_string("<-");
17719   Expression* expr = Expression::import_expression(imp, loc);
17720   return Expression::make_receive(expr, loc);
17721 }
17722 
17723 // Make a receive expression.
17724 
17725 Receive_expression*
make_receive(Expression * channel,Location location)17726 Expression::make_receive(Expression* channel, Location location)
17727 {
17728   return new Receive_expression(channel, location);
17729 }
17730 
17731 // An expression which evaluates to a pointer to the type descriptor
17732 // of a type.
17733 
17734 class Type_descriptor_expression : public Expression
17735 {
17736  public:
Type_descriptor_expression(Type * type,Location location)17737   Type_descriptor_expression(Type* type, Location location)
17738     : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
17739       type_(type)
17740   { }
17741 
17742  protected:
17743   int
17744   do_traverse(Traverse*);
17745 
17746   Type*
do_type()17747   do_type()
17748   { return Type::make_type_descriptor_ptr_type(); }
17749 
17750   bool
do_is_static_initializer() const17751   do_is_static_initializer() const
17752   { return true; }
17753 
17754   void
do_determine_type(const Type_context *)17755   do_determine_type(const Type_context*)
17756   { }
17757 
17758   Expression*
do_copy()17759   do_copy()
17760   { return this; }
17761 
17762   Bexpression*
do_get_backend(Translate_context * context)17763   do_get_backend(Translate_context* context)
17764   {
17765     return this->type_->type_descriptor_pointer(context->gogo(),
17766 						this->location());
17767   }
17768 
17769   void
17770   do_dump_expression(Ast_dump_context*) const;
17771 
17772  private:
17773   // The type for which this is the descriptor.
17774   Type* type_;
17775 };
17776 
17777 int
do_traverse(Traverse * traverse)17778 Type_descriptor_expression::do_traverse(Traverse* traverse)
17779 {
17780   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17781     return TRAVERSE_EXIT;
17782   return TRAVERSE_CONTINUE;
17783 }
17784 
17785 // Dump ast representation for a type descriptor expression.
17786 
17787 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17788 Type_descriptor_expression::do_dump_expression(
17789     Ast_dump_context* ast_dump_context) const
17790 {
17791   ast_dump_context->dump_type(this->type_);
17792 }
17793 
17794 // Make a type descriptor expression.
17795 
17796 Expression*
make_type_descriptor(Type * type,Location location)17797 Expression::make_type_descriptor(Type* type, Location location)
17798 {
17799   return new Type_descriptor_expression(type, location);
17800 }
17801 
17802 // An expression which evaluates to a pointer to the Garbage Collection symbol
17803 // of a type.
17804 
17805 class GC_symbol_expression : public Expression
17806 {
17807  public:
GC_symbol_expression(Type * type)17808   GC_symbol_expression(Type* type)
17809     : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
17810       type_(type)
17811   {}
17812 
17813  protected:
17814   Type*
do_type()17815   do_type()
17816   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17817 
17818   bool
do_is_static_initializer() const17819   do_is_static_initializer() const
17820   { return true; }
17821 
17822   void
do_determine_type(const Type_context *)17823   do_determine_type(const Type_context*)
17824   { }
17825 
17826   Expression*
do_copy()17827   do_copy()
17828   { return this; }
17829 
17830   Bexpression*
do_get_backend(Translate_context * context)17831   do_get_backend(Translate_context* context)
17832   { return this->type_->gc_symbol_pointer(context->gogo()); }
17833 
17834   void
17835   do_dump_expression(Ast_dump_context*) const;
17836 
17837  private:
17838   // The type which this gc symbol describes.
17839   Type* type_;
17840 };
17841 
17842 // Dump ast representation for a gc symbol expression.
17843 
17844 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17845 GC_symbol_expression::do_dump_expression(
17846     Ast_dump_context* ast_dump_context) const
17847 {
17848   ast_dump_context->ostream() << "gcdata(";
17849   ast_dump_context->dump_type(this->type_);
17850   ast_dump_context->ostream() << ")";
17851 }
17852 
17853 // Make a gc symbol expression.
17854 
17855 Expression*
make_gc_symbol(Type * type)17856 Expression::make_gc_symbol(Type* type)
17857 {
17858   return new GC_symbol_expression(type);
17859 }
17860 
17861 // An expression that evaluates to a pointer to a symbol holding the
17862 // ptrmask data of a type.
17863 
17864 class Ptrmask_symbol_expression : public Expression
17865 {
17866  public:
Ptrmask_symbol_expression(Type * type)17867   Ptrmask_symbol_expression(Type* type)
17868     : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
17869       type_(type)
17870   {}
17871 
17872  protected:
17873   Type*
do_type()17874   do_type()
17875   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17876 
17877   bool
do_is_static_initializer() const17878   do_is_static_initializer() const
17879   { return true; }
17880 
17881   void
do_determine_type(const Type_context *)17882   do_determine_type(const Type_context*)
17883   { }
17884 
17885   Expression*
do_copy()17886   do_copy()
17887   { return this; }
17888 
17889   Bexpression*
17890   do_get_backend(Translate_context*);
17891 
17892   void
17893   do_dump_expression(Ast_dump_context*) const;
17894 
17895  private:
17896   // The type that this ptrmask symbol describes.
17897   Type* type_;
17898 };
17899 
17900 // Return the ptrmask variable.
17901 
17902 Bexpression*
do_get_backend(Translate_context * context)17903 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
17904 {
17905   Gogo* gogo = context->gogo();
17906 
17907   // If this type does not need a gcprog, then we can use the standard
17908   // GC symbol.
17909   int64_t ptrsize, ptrdata;
17910   if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
17911     return this->type_->gc_symbol_pointer(gogo);
17912 
17913   // Otherwise we have to build a ptrmask variable, and return a
17914   // pointer to it.
17915 
17916   Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
17917   Location bloc = Linemap::predeclared_location();
17918   Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
17919   Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
17920 
17921   Type* uint8_type = Type::lookup_integer_type("uint8");
17922   Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
17923   Btype* ubtype = pointer_uint8_type->get_backend(gogo);
17924   return gogo->backend()->convert_expression(ubtype, baddr, bloc);
17925 }
17926 
17927 // Dump AST for a ptrmask symbol expression.
17928 
17929 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17930 Ptrmask_symbol_expression::do_dump_expression(
17931     Ast_dump_context* ast_dump_context) const
17932 {
17933   ast_dump_context->ostream() << "ptrmask(";
17934   ast_dump_context->dump_type(this->type_);
17935   ast_dump_context->ostream() << ")";
17936 }
17937 
17938 // Make a ptrmask symbol expression.
17939 
17940 Expression*
make_ptrmask_symbol(Type * type)17941 Expression::make_ptrmask_symbol(Type* type)
17942 {
17943   return new Ptrmask_symbol_expression(type);
17944 }
17945 
17946 // An expression which evaluates to some characteristic of a type.
17947 // This is only used to initialize fields of a type descriptor.  Using
17948 // a new expression class is slightly inefficient but gives us a good
17949 // separation between the frontend and the middle-end with regard to
17950 // how types are laid out.
17951 
17952 class Type_info_expression : public Expression
17953 {
17954  public:
Type_info_expression(Type * type,Type_info type_info)17955   Type_info_expression(Type* type, Type_info type_info)
17956     : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
17957       type_(type), type_info_(type_info)
17958   { }
17959 
17960  protected:
17961   bool
do_is_static_initializer() const17962   do_is_static_initializer() const
17963   { return true; }
17964 
17965   Type*
17966   do_type();
17967 
17968   void
do_determine_type(const Type_context *)17969   do_determine_type(const Type_context*)
17970   { }
17971 
17972   Expression*
do_copy()17973   do_copy()
17974   { return this; }
17975 
17976   Bexpression*
17977   do_get_backend(Translate_context* context);
17978 
17979   void
17980   do_dump_expression(Ast_dump_context*) const;
17981 
17982  private:
17983   // The type for which we are getting information.
17984   Type* type_;
17985   // What information we want.
17986   Type_info type_info_;
17987 };
17988 
17989 // The type is chosen to match what the type descriptor struct
17990 // expects.
17991 
17992 Type*
do_type()17993 Type_info_expression::do_type()
17994 {
17995   switch (this->type_info_)
17996     {
17997     case TYPE_INFO_SIZE:
17998     case TYPE_INFO_BACKEND_PTRDATA:
17999     case TYPE_INFO_DESCRIPTOR_PTRDATA:
18000       return Type::lookup_integer_type("uintptr");
18001     case TYPE_INFO_ALIGNMENT:
18002     case TYPE_INFO_FIELD_ALIGNMENT:
18003       return Type::lookup_integer_type("uint8");
18004     default:
18005       go_unreachable();
18006     }
18007 }
18008 
18009 // Return the backend representation for type information.
18010 
18011 Bexpression*
do_get_backend(Translate_context * context)18012 Type_info_expression::do_get_backend(Translate_context* context)
18013 {
18014   Gogo* gogo = context->gogo();
18015   bool ok = true;
18016   int64_t val;
18017   switch (this->type_info_)
18018     {
18019     case TYPE_INFO_SIZE:
18020       ok = this->type_->backend_type_size(gogo, &val);
18021       break;
18022     case TYPE_INFO_ALIGNMENT:
18023       ok = this->type_->backend_type_align(gogo, &val);
18024       break;
18025     case TYPE_INFO_FIELD_ALIGNMENT:
18026       ok = this->type_->backend_type_field_align(gogo, &val);
18027       break;
18028     case TYPE_INFO_BACKEND_PTRDATA:
18029       ok = this->type_->backend_type_ptrdata(gogo, &val);
18030       break;
18031     case TYPE_INFO_DESCRIPTOR_PTRDATA:
18032       ok = this->type_->descriptor_ptrdata(gogo, &val);
18033       break;
18034     default:
18035       go_unreachable();
18036     }
18037   if (!ok)
18038     {
18039       go_assert(saw_errors());
18040       return gogo->backend()->error_expression();
18041     }
18042   Expression* e = Expression::make_integer_int64(val, this->type(),
18043 						 this->location());
18044   return e->get_backend(context);
18045 }
18046 
18047 // Dump ast representation for a type info expression.
18048 
18049 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18050 Type_info_expression::do_dump_expression(
18051     Ast_dump_context* ast_dump_context) const
18052 {
18053   ast_dump_context->ostream() << "typeinfo(";
18054   ast_dump_context->dump_type(this->type_);
18055   ast_dump_context->ostream() << ",";
18056   ast_dump_context->ostream() <<
18057     (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
18058     : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
18059     : this->type_info_ == TYPE_INFO_SIZE ? "size"
18060     : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
18061     : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
18062     : "unknown");
18063   ast_dump_context->ostream() << ")";
18064 }
18065 
18066 // Make a type info expression.
18067 
18068 Expression*
make_type_info(Type * type,Type_info type_info)18069 Expression::make_type_info(Type* type, Type_info type_info)
18070 {
18071   return new Type_info_expression(type, type_info);
18072 }
18073 
18074 // Slice_info_expression.
18075 
18076 // Return the type of the slice info.
18077 
18078 Type*
do_type()18079 Slice_info_expression::do_type()
18080 {
18081   switch (this->slice_info_)
18082     {
18083     case SLICE_INFO_VALUE_POINTER:
18084       return Type::make_pointer_type(
18085           this->slice_->type()->array_type()->element_type());
18086     case SLICE_INFO_LENGTH:
18087     case SLICE_INFO_CAPACITY:
18088         return Type::lookup_integer_type("int");
18089     default:
18090       go_unreachable();
18091     }
18092 }
18093 
18094 // Return the backend information for slice information.
18095 
18096 Bexpression*
do_get_backend(Translate_context * context)18097 Slice_info_expression::do_get_backend(Translate_context* context)
18098 {
18099   Gogo* gogo = context->gogo();
18100   Bexpression* bslice = this->slice_->get_backend(context);
18101   switch (this->slice_info_)
18102     {
18103     case SLICE_INFO_VALUE_POINTER:
18104     case SLICE_INFO_LENGTH:
18105     case SLICE_INFO_CAPACITY:
18106       return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
18107 						      this->location());
18108       break;
18109     default:
18110       go_unreachable();
18111     }
18112 }
18113 
18114 // Dump ast representation for a type info expression.
18115 
18116 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18117 Slice_info_expression::do_dump_expression(
18118     Ast_dump_context* ast_dump_context) const
18119 {
18120   ast_dump_context->ostream() << "sliceinfo(";
18121   this->slice_->dump_expression(ast_dump_context);
18122   ast_dump_context->ostream() << ",";
18123   ast_dump_context->ostream() <<
18124       (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
18125     : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
18126     : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
18127     : "unknown");
18128   ast_dump_context->ostream() << ")";
18129 }
18130 
18131 // Make a slice info expression.
18132 
18133 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)18134 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
18135                             Location location)
18136 {
18137   return new Slice_info_expression(slice, slice_info, location);
18138 }
18139 
18140 // Class Slice_value_expression.
18141 
18142 int
do_traverse(Traverse * traverse)18143 Slice_value_expression::do_traverse(Traverse* traverse)
18144 {
18145   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
18146       || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
18147       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
18148       || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
18149     return TRAVERSE_EXIT;
18150   return TRAVERSE_CONTINUE;
18151 }
18152 
18153 Expression*
do_copy()18154 Slice_value_expression::do_copy()
18155 {
18156   return new Slice_value_expression(this->type_->copy_expressions(),
18157 				    this->valmem_->copy(),
18158 				    this->len_->copy(), this->cap_->copy(),
18159 				    this->location());
18160 }
18161 
18162 Bexpression*
do_get_backend(Translate_context * context)18163 Slice_value_expression::do_get_backend(Translate_context* context)
18164 {
18165   std::vector<Bexpression*> vals(3);
18166   vals[0] = this->valmem_->get_backend(context);
18167   vals[1] = this->len_->get_backend(context);
18168   vals[2] = this->cap_->get_backend(context);
18169 
18170   Gogo* gogo = context->gogo();
18171   Btype* btype = this->type_->get_backend(gogo);
18172   return gogo->backend()->constructor_expression(btype, vals, this->location());
18173 }
18174 
18175 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18176 Slice_value_expression::do_dump_expression(
18177     Ast_dump_context* ast_dump_context) const
18178 {
18179   ast_dump_context->ostream() << "slicevalue(";
18180   ast_dump_context->ostream() << "values: ";
18181   this->valmem_->dump_expression(ast_dump_context);
18182   ast_dump_context->ostream() << ", length: ";
18183   this->len_->dump_expression(ast_dump_context);
18184   ast_dump_context->ostream() << ", capacity: ";
18185   this->cap_->dump_expression(ast_dump_context);
18186   ast_dump_context->ostream() << ")";
18187 }
18188 
18189 Expression*
make_slice_value(Type * at,Expression * valmem,Expression * len,Expression * cap,Location location)18190 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
18191                              Expression* cap, Location location)
18192 {
18193   go_assert(at->is_slice_type());
18194   go_assert(valmem->is_nil_expression()
18195 	    || (at->array_type()->element_type()
18196 		== valmem->type()->points_to()));
18197   return new Slice_value_expression(at, valmem, len, cap, location);
18198 }
18199 
18200 // Look through the expression of a Slice_value_expression's valmem to
18201 // find an call to makeslice.  If found, return the call expression and
18202 // the containing temporary statement (if any).
18203 
18204 std::pair<Call_expression*, Temporary_statement*>
find_makeslice_call(Expression * expr)18205 Expression::find_makeslice_call(Expression* expr)
18206 {
18207   Unsafe_type_conversion_expression* utce =
18208     expr->unsafe_conversion_expression();
18209   if (utce != NULL)
18210     expr = utce->expr();
18211 
18212   Slice_value_expression* sve = expr->slice_value_expression();
18213   if (sve == NULL)
18214     return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
18215   expr = sve->valmem();
18216 
18217   utce = expr->unsafe_conversion_expression();
18218   if (utce != NULL)
18219     expr = utce->expr();
18220 
18221   Temporary_reference_expression* tre = expr->temporary_reference_expression();
18222   Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
18223   if (ts != NULL && ts->init() != NULL && !ts->assigned()
18224       && !ts->is_address_taken())
18225     expr = ts->init();
18226 
18227   Call_expression* call = expr->call_expression();
18228   if (call == NULL)
18229     return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
18230 
18231   Func_expression* fe = call->fn()->func_expression();
18232   if (fe != NULL
18233       && fe->runtime_code() == Runtime::MAKESLICE)
18234     return std::make_pair(call, ts);
18235 
18236   return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
18237 }
18238 
18239 // An expression that evaluates to some characteristic of a non-empty interface.
18240 // This is used to access the method table or underlying object of an interface.
18241 
18242 class Interface_info_expression : public Expression
18243 {
18244  public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)18245   Interface_info_expression(Expression* iface, Interface_info iface_info,
18246                             Location location)
18247     : Expression(EXPRESSION_INTERFACE_INFO, location),
18248       iface_(iface), iface_info_(iface_info)
18249   { }
18250 
18251  protected:
18252   Type*
18253   do_type();
18254 
18255   void
do_determine_type(const Type_context *)18256   do_determine_type(const Type_context*)
18257   { }
18258 
18259   Expression*
do_copy()18260   do_copy()
18261   {
18262     return new Interface_info_expression(this->iface_->copy(),
18263                                          this->iface_info_, this->location());
18264   }
18265 
18266   Bexpression*
18267   do_get_backend(Translate_context* context);
18268 
18269   void
18270   do_dump_expression(Ast_dump_context*) const;
18271 
18272   void
do_issue_nil_check()18273   do_issue_nil_check()
18274   { this->iface_->issue_nil_check(); }
18275 
18276  private:
18277   // The interface for which we are getting information.
18278   Expression* iface_;
18279   // What information we want.
18280   Interface_info iface_info_;
18281 };
18282 
18283 // Return the type of the interface info.
18284 
18285 Type*
do_type()18286 Interface_info_expression::do_type()
18287 {
18288   switch (this->iface_info_)
18289     {
18290     case INTERFACE_INFO_METHODS:
18291       {
18292         typedef Unordered_map(Interface_type*, Type*) Hashtable;
18293         static Hashtable result_types;
18294 
18295         Interface_type* itype = this->iface_->type()->interface_type();
18296 
18297         Hashtable::const_iterator pr = result_types.find(itype);
18298         if (pr != result_types.end())
18299           return pr->second;
18300 
18301         Type* pdt = Type::make_type_descriptor_ptr_type();
18302         if (itype->is_empty())
18303           {
18304             result_types[itype] = pdt;
18305             return pdt;
18306           }
18307 
18308         Location loc = this->location();
18309         Struct_field_list* sfl = new Struct_field_list();
18310         sfl->push_back(
18311             Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
18312 
18313         for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
18314              p != itype->methods()->end();
18315              ++p)
18316           {
18317             Function_type* ft = p->type()->function_type();
18318             go_assert(ft->receiver() == NULL);
18319 
18320             const Typed_identifier_list* params = ft->parameters();
18321             Typed_identifier_list* mparams = new Typed_identifier_list();
18322             if (params != NULL)
18323               mparams->reserve(params->size() + 1);
18324             Type* vt = Type::make_pointer_type(Type::make_void_type());
18325             mparams->push_back(Typed_identifier("", vt, ft->location()));
18326             if (params != NULL)
18327               {
18328                 for (Typed_identifier_list::const_iterator pp = params->begin();
18329                      pp != params->end();
18330                      ++pp)
18331                   mparams->push_back(*pp);
18332               }
18333 
18334             Typed_identifier_list* mresults = (ft->results() == NULL
18335                                                ? NULL
18336                                                : ft->results()->copy());
18337             Backend_function_type* mft =
18338                 Type::make_backend_function_type(NULL, mparams, mresults,
18339                                                  ft->location());
18340 
18341             std::string fname = Gogo::unpack_hidden_name(p->name());
18342             sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
18343           }
18344 
18345 	Struct_type* st = Type::make_struct_type(sfl, loc);
18346 	st->set_is_struct_incomparable();
18347 	Pointer_type *pt = Type::make_pointer_type(st);
18348         result_types[itype] = pt;
18349         return pt;
18350       }
18351     case INTERFACE_INFO_OBJECT:
18352       return Type::make_pointer_type(Type::make_void_type());
18353     default:
18354       go_unreachable();
18355     }
18356 }
18357 
18358 // Return the backend representation for interface information.
18359 
18360 Bexpression*
do_get_backend(Translate_context * context)18361 Interface_info_expression::do_get_backend(Translate_context* context)
18362 {
18363   Gogo* gogo = context->gogo();
18364   Bexpression* biface = this->iface_->get_backend(context);
18365   switch (this->iface_info_)
18366     {
18367     case INTERFACE_INFO_METHODS:
18368     case INTERFACE_INFO_OBJECT:
18369       return gogo->backend()->struct_field_expression(biface, this->iface_info_,
18370 						      this->location());
18371       break;
18372     default:
18373       go_unreachable();
18374     }
18375 }
18376 
18377 // Dump ast representation for an interface info expression.
18378 
18379 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18380 Interface_info_expression::do_dump_expression(
18381     Ast_dump_context* ast_dump_context) const
18382 {
18383   bool is_empty = this->iface_->type()->interface_type()->is_empty();
18384   ast_dump_context->ostream() << "interfaceinfo(";
18385   this->iface_->dump_expression(ast_dump_context);
18386   ast_dump_context->ostream() << ",";
18387   ast_dump_context->ostream() <<
18388       (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
18389     : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
18390     : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
18391     : "unknown");
18392   ast_dump_context->ostream() << ")";
18393 }
18394 
18395 // Make an interface info expression.
18396 
18397 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)18398 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
18399                                 Location location)
18400 {
18401   return new Interface_info_expression(iface, iface_info, location);
18402 }
18403 
18404 // An expression that represents an interface value.  The first field is either
18405 // a type descriptor for an empty interface or a pointer to the interface method
18406 // table for a non-empty interface.  The second field is always the object.
18407 
18408 class Interface_value_expression : public Expression
18409 {
18410  public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)18411   Interface_value_expression(Type* type, Expression* first_field,
18412                              Expression* obj, Location location)
18413       : Expression(EXPRESSION_INTERFACE_VALUE, location),
18414         type_(type), first_field_(first_field), obj_(obj)
18415   { }
18416 
18417  protected:
18418   int
18419   do_traverse(Traverse*);
18420 
18421   Type*
do_type()18422   do_type()
18423   { return this->type_; }
18424 
18425   void
do_determine_type(const Type_context *)18426   do_determine_type(const Type_context*)
18427   { go_unreachable(); }
18428 
18429   Expression*
do_copy()18430   do_copy()
18431   {
18432     return new Interface_value_expression(this->type_->copy_expressions(),
18433                                           this->first_field_->copy(),
18434                                           this->obj_->copy(), this->location());
18435   }
18436 
18437   Bexpression*
18438   do_get_backend(Translate_context* context);
18439 
18440   void
18441   do_dump_expression(Ast_dump_context*) const;
18442 
18443  private:
18444   // The type of the interface value.
18445   Type* type_;
18446   // The first field of the interface (either a type descriptor or a pointer
18447   // to the method table.
18448   Expression* first_field_;
18449   // The underlying object of the interface.
18450   Expression* obj_;
18451 };
18452 
18453 int
do_traverse(Traverse * traverse)18454 Interface_value_expression::do_traverse(Traverse* traverse)
18455 {
18456   if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
18457       || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
18458     return TRAVERSE_EXIT;
18459   return TRAVERSE_CONTINUE;
18460 }
18461 
18462 Bexpression*
do_get_backend(Translate_context * context)18463 Interface_value_expression::do_get_backend(Translate_context* context)
18464 {
18465   std::vector<Bexpression*> vals(2);
18466   vals[0] = this->first_field_->get_backend(context);
18467   vals[1] = this->obj_->get_backend(context);
18468 
18469   Gogo* gogo = context->gogo();
18470   Btype* btype = this->type_->get_backend(gogo);
18471   return gogo->backend()->constructor_expression(btype, vals, this->location());
18472 }
18473 
18474 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18475 Interface_value_expression::do_dump_expression(
18476     Ast_dump_context* ast_dump_context) const
18477 {
18478   ast_dump_context->ostream() << "interfacevalue(";
18479   ast_dump_context->ostream() <<
18480       (this->type_->interface_type()->is_empty()
18481        ? "type_descriptor: "
18482        : "methods: ");
18483   this->first_field_->dump_expression(ast_dump_context);
18484   ast_dump_context->ostream() << ", object: ";
18485   this->obj_->dump_expression(ast_dump_context);
18486   ast_dump_context->ostream() << ")";
18487 }
18488 
18489 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)18490 Expression::make_interface_value(Type* type, Expression* first_value,
18491                                  Expression* object, Location location)
18492 {
18493   return new Interface_value_expression(type, first_value, object, location);
18494 }
18495 
18496 // An interface method table for a pair of types: an interface type and a type
18497 // that implements that interface.
18498 
18499 class Interface_mtable_expression : public Expression
18500 {
18501  public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)18502   Interface_mtable_expression(Interface_type* itype, Type* type,
18503                               bool is_pointer, Location location)
18504       : Expression(EXPRESSION_INTERFACE_MTABLE, location),
18505         itype_(itype), type_(type), is_pointer_(is_pointer),
18506 	method_table_type_(NULL), bvar_(NULL)
18507   { }
18508 
18509  protected:
18510   int
18511   do_traverse(Traverse*);
18512 
18513   Type*
18514   do_type();
18515 
18516   bool
do_is_static_initializer() const18517   do_is_static_initializer() const
18518   { return true; }
18519 
18520   void
do_determine_type(const Type_context *)18521   do_determine_type(const Type_context*)
18522   { go_unreachable(); }
18523 
18524   Expression*
do_copy()18525   do_copy()
18526   {
18527     Interface_type* itype = this->itype_->copy_expressions()->interface_type();
18528     return new Interface_mtable_expression(itype,
18529 					   this->type_->copy_expressions(),
18530                                            this->is_pointer_, this->location());
18531   }
18532 
18533   bool
do_is_addressable() const18534   do_is_addressable() const
18535   { return true; }
18536 
18537   Bexpression*
18538   do_get_backend(Translate_context* context);
18539 
18540   void
18541   do_dump_expression(Ast_dump_context*) const;
18542 
18543  private:
18544   // The interface type for which the methods are defined.
18545   Interface_type* itype_;
18546   // The type to construct the interface method table for.
18547   Type* type_;
18548   // Whether this table contains the method set for the receiver type or the
18549   // pointer receiver type.
18550   bool is_pointer_;
18551   // The type of the method table.
18552   Type* method_table_type_;
18553   // The backend variable that refers to the interface method table.
18554   Bvariable* bvar_;
18555 };
18556 
18557 int
do_traverse(Traverse * traverse)18558 Interface_mtable_expression::do_traverse(Traverse* traverse)
18559 {
18560   if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
18561       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
18562     return TRAVERSE_EXIT;
18563   return TRAVERSE_CONTINUE;
18564 }
18565 
18566 Type*
do_type()18567 Interface_mtable_expression::do_type()
18568 {
18569   if (this->method_table_type_ != NULL)
18570     return this->method_table_type_;
18571 
18572   const Typed_identifier_list* interface_methods = this->itype_->methods();
18573   go_assert(!interface_methods->empty());
18574 
18575   Struct_field_list* sfl = new Struct_field_list;
18576   Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
18577                        this->location());
18578   sfl->push_back(Struct_field(tid));
18579   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
18580   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18581        p != interface_methods->end();
18582        ++p)
18583     {
18584       // We want C function pointers here, not func descriptors; model
18585       // using void* pointers.
18586       Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
18587       sfl->push_back(Struct_field(method));
18588     }
18589   Struct_type* st = Type::make_struct_type(sfl, this->location());
18590   st->set_is_struct_incomparable();
18591   this->method_table_type_ = st;
18592   return this->method_table_type_;
18593 }
18594 
18595 Bexpression*
do_get_backend(Translate_context * context)18596 Interface_mtable_expression::do_get_backend(Translate_context* context)
18597 {
18598   Gogo* gogo = context->gogo();
18599   Location loc = Linemap::predeclared_location();
18600   if (this->bvar_ != NULL)
18601     return gogo->backend()->var_expression(this->bvar_, this->location());
18602 
18603   const Typed_identifier_list* interface_methods = this->itype_->methods();
18604   go_assert(!interface_methods->empty());
18605 
18606   std::string mangled_name =
18607     gogo->interface_method_table_name(this->itype_, this->type_,
18608 				      this->is_pointer_);
18609 
18610   // Set is_public if we are converting a named type to an interface
18611   // type that is defined in the same package as the named type, and
18612   // the interface has hidden methods.  In that case the interface
18613   // method table will be defined by the package that defines the
18614   // types.
18615   bool is_public = false;
18616   if (this->type_->named_type() != NULL
18617       && (this->type_->named_type()->named_object()->package()
18618 	  == this->itype_->package()))
18619     {
18620       for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18621 	   p != interface_methods->end();
18622 	   ++p)
18623 	{
18624 	  if (Gogo::is_hidden_name(p->name()))
18625 	    {
18626 	      is_public = true;
18627 	      break;
18628 	    }
18629 	}
18630     }
18631 
18632   if (is_public
18633       && this->type_->named_type()->named_object()->package() != NULL)
18634     {
18635       // The interface conversion table is defined elsewhere.
18636       Btype* btype = this->type()->get_backend(gogo);
18637       this->bvar_ =
18638           gogo->backend()->immutable_struct_reference(mangled_name, "",
18639                                                       btype, loc);
18640       return gogo->backend()->var_expression(this->bvar_, this->location());
18641     }
18642 
18643   // The first element is the type descriptor.
18644   Type* td_type;
18645   if (!this->is_pointer_)
18646     td_type = this->type_;
18647   else
18648     td_type = Type::make_pointer_type(this->type_);
18649 
18650   std::vector<Backend::Btyped_identifier> bstructfields;
18651 
18652   // Build an interface method table for a type: a type descriptor followed by a
18653   // list of function pointers, one for each interface method.  This is used for
18654   // interfaces.
18655   Expression_list* svals = new Expression_list();
18656   Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
18657   svals->push_back(tdescriptor);
18658 
18659   Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
18660   Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
18661   bstructfields.push_back(btd);
18662 
18663   Named_type* nt = this->type_->named_type();
18664   Struct_type* st = this->type_->struct_type();
18665   go_assert(nt != NULL || st != NULL);
18666 
18667   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18668        p != interface_methods->end();
18669        ++p)
18670     {
18671       bool is_ambiguous;
18672       Method* m;
18673       if (nt != NULL)
18674 	m = nt->method_function(p->name(), &is_ambiguous);
18675       else
18676 	m = st->method_function(p->name(), &is_ambiguous);
18677       go_assert(m != NULL);
18678 
18679       // See the comment in Type::method_constructor.
18680       bool use_direct_iface_stub = false;
18681       if (m->is_value_method()
18682 	  && this->is_pointer_
18683 	  && this->type_->is_direct_iface_type())
18684 	use_direct_iface_stub = true;
18685       if (!m->is_value_method()
18686 	  && this->is_pointer_
18687 	  && !this->type_->in_heap())
18688 	use_direct_iface_stub = true;
18689       Named_object* no = (use_direct_iface_stub
18690 			  ? m->iface_stub_object()
18691 			  : m->named_object());
18692 
18693       go_assert(no->is_function() || no->is_function_declaration());
18694 
18695       Function_type* fcn_type = (no->is_function()
18696                                  ? no->func_value()->type()
18697                                  : no->func_declaration_value()->type());
18698       Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
18699       Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
18700       bstructfields.push_back(bmtype);
18701 
18702       svals->push_back(Expression::make_func_code_reference(no, loc));
18703     }
18704 
18705   Btype *btype = gogo->backend()->struct_type(bstructfields);
18706   std::vector<Bexpression*> ctor_bexprs;
18707   for (Expression_list::const_iterator pe = svals->begin();
18708        pe != svals->end();
18709        ++pe)
18710     {
18711       ctor_bexprs.push_back((*pe)->get_backend(context));
18712     }
18713   Bexpression* ctor =
18714       gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
18715 
18716   unsigned int flags = 0;
18717   if (!is_public)
18718     flags |= Backend::variable_is_hidden;
18719   this->bvar_ = gogo->backend()->immutable_struct(mangled_name, "", flags,
18720 						  btype, loc);
18721   gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, flags,
18722 					     btype, loc, ctor);
18723   return gogo->backend()->var_expression(this->bvar_, loc);
18724 }
18725 
18726 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18727 Interface_mtable_expression::do_dump_expression(
18728     Ast_dump_context* ast_dump_context) const
18729 {
18730   ast_dump_context->ostream() << "__go_"
18731                               << (this->is_pointer_ ? "pimt__" : "imt_");
18732   ast_dump_context->dump_type(this->itype_);
18733   ast_dump_context->ostream() << "__";
18734   ast_dump_context->dump_type(this->type_);
18735 }
18736 
18737 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)18738 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
18739                                       bool is_pointer, Location location)
18740 {
18741   return new Interface_mtable_expression(itype, type, is_pointer, location);
18742 }
18743 
18744 // An expression which evaluates to the offset of a field within a
18745 // struct.  This, like Type_info_expression, q.v., is only used to
18746 // initialize fields of a type descriptor.
18747 
18748 class Struct_field_offset_expression : public Expression
18749 {
18750  public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)18751   Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
18752     : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
18753 		 Linemap::predeclared_location()),
18754       type_(type), field_(field)
18755   { }
18756 
18757  protected:
18758   bool
do_is_static_initializer() const18759   do_is_static_initializer() const
18760   { return true; }
18761 
18762   Type*
do_type()18763   do_type()
18764   { return Type::lookup_integer_type("uintptr"); }
18765 
18766   void
do_determine_type(const Type_context *)18767   do_determine_type(const Type_context*)
18768   { }
18769 
18770   Expression*
do_copy()18771   do_copy()
18772   { return this; }
18773 
18774   Bexpression*
18775   do_get_backend(Translate_context* context);
18776 
18777   void
18778   do_dump_expression(Ast_dump_context*) const;
18779 
18780  private:
18781   // The type of the struct.
18782   Struct_type* type_;
18783   // The field.
18784   const Struct_field* field_;
18785 };
18786 
18787 // Return the backend representation for a struct field offset.
18788 
18789 Bexpression*
do_get_backend(Translate_context * context)18790 Struct_field_offset_expression::do_get_backend(Translate_context* context)
18791 {
18792   const Struct_field_list* fields = this->type_->fields();
18793   Struct_field_list::const_iterator p;
18794   unsigned i = 0;
18795   for (p = fields->begin();
18796        p != fields->end();
18797        ++p, ++i)
18798     if (&*p == this->field_)
18799       break;
18800   go_assert(&*p == this->field_);
18801 
18802   Gogo* gogo = context->gogo();
18803   Btype* btype = this->type_->get_backend(gogo);
18804 
18805   int64_t offset = gogo->backend()->type_field_offset(btype, i);
18806   Type* uptr_type = Type::lookup_integer_type("uintptr");
18807   Expression* ret =
18808     Expression::make_integer_int64(offset, uptr_type,
18809 				   Linemap::predeclared_location());
18810   return ret->get_backend(context);
18811 }
18812 
18813 // Dump ast representation for a struct field offset expression.
18814 
18815 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18816 Struct_field_offset_expression::do_dump_expression(
18817     Ast_dump_context* ast_dump_context) const
18818 {
18819   ast_dump_context->ostream() <<  "unsafe.Offsetof(";
18820   ast_dump_context->dump_type(this->type_);
18821   ast_dump_context->ostream() << '.';
18822   ast_dump_context->ostream() <<
18823     Gogo::message_name(this->field_->field_name());
18824   ast_dump_context->ostream() << ")";
18825 }
18826 
18827 // Make an expression for a struct field offset.
18828 
18829 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)18830 Expression::make_struct_field_offset(Struct_type* type,
18831 				     const Struct_field* field)
18832 {
18833   return new Struct_field_offset_expression(type, field);
18834 }
18835 
18836 // An expression which evaluates to the address of an unnamed label.
18837 
18838 class Label_addr_expression : public Expression
18839 {
18840  public:
Label_addr_expression(Label * label,Location location)18841   Label_addr_expression(Label* label, Location location)
18842     : Expression(EXPRESSION_LABEL_ADDR, location),
18843       label_(label)
18844   { }
18845 
18846  protected:
18847   Type*
do_type()18848   do_type()
18849   { return Type::make_pointer_type(Type::make_void_type()); }
18850 
18851   void
do_determine_type(const Type_context *)18852   do_determine_type(const Type_context*)
18853   { }
18854 
18855   Expression*
do_copy()18856   do_copy()
18857   { return new Label_addr_expression(this->label_, this->location()); }
18858 
18859   Bexpression*
do_get_backend(Translate_context * context)18860   do_get_backend(Translate_context* context)
18861   { return this->label_->get_addr(context, this->location()); }
18862 
18863   void
do_dump_expression(Ast_dump_context * ast_dump_context) const18864   do_dump_expression(Ast_dump_context* ast_dump_context) const
18865   { ast_dump_context->ostream() << this->label_->name(); }
18866 
18867  private:
18868   // The label whose address we are taking.
18869   Label* label_;
18870 };
18871 
18872 // Make an expression for the address of an unnamed label.
18873 
18874 Expression*
make_label_addr(Label * label,Location location)18875 Expression::make_label_addr(Label* label, Location location)
18876 {
18877   return new Label_addr_expression(label, location);
18878 }
18879 
18880 // Class Conditional_expression.
18881 
18882 // Traversal.
18883 
18884 int
do_traverse(Traverse * traverse)18885 Conditional_expression::do_traverse(Traverse* traverse)
18886 {
18887   if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
18888       || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
18889       || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
18890     return TRAVERSE_EXIT;
18891   return TRAVERSE_CONTINUE;
18892 }
18893 
18894 // Return the type of the conditional expression.
18895 
18896 Type*
do_type()18897 Conditional_expression::do_type()
18898 {
18899   Type* result_type = Type::make_void_type();
18900   if (Type::are_identical(this->then_->type(), this->else_->type(),
18901 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
18902                           NULL))
18903     result_type = this->then_->type();
18904   else if (this->then_->is_nil_expression()
18905            || this->else_->is_nil_expression())
18906     result_type = (!this->then_->is_nil_expression()
18907                    ? this->then_->type()
18908                    : this->else_->type());
18909   return result_type;
18910 }
18911 
18912 // Determine type for a conditional expression.
18913 
18914 void
do_determine_type(const Type_context * context)18915 Conditional_expression::do_determine_type(const Type_context* context)
18916 {
18917   this->cond_->determine_type_no_context();
18918   this->then_->determine_type(context);
18919   this->else_->determine_type(context);
18920 }
18921 
18922 // Get the backend representation of a conditional expression.
18923 
18924 Bexpression*
do_get_backend(Translate_context * context)18925 Conditional_expression::do_get_backend(Translate_context* context)
18926 {
18927   Gogo* gogo = context->gogo();
18928   Btype* result_btype = this->type()->get_backend(gogo);
18929   Bexpression* cond = this->cond_->get_backend(context);
18930   Bexpression* then = this->then_->get_backend(context);
18931   Bexpression* belse = this->else_->get_backend(context);
18932   Bfunction* bfn = context->function()->func_value()->get_decl();
18933   return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
18934 						 belse, this->location());
18935 }
18936 
18937 // Dump ast representation of a conditional expression.
18938 
18939 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18940 Conditional_expression::do_dump_expression(
18941     Ast_dump_context* ast_dump_context) const
18942 {
18943   ast_dump_context->ostream() << "(";
18944   ast_dump_context->dump_expression(this->cond_);
18945   ast_dump_context->ostream() << " ? ";
18946   ast_dump_context->dump_expression(this->then_);
18947   ast_dump_context->ostream() << " : ";
18948   ast_dump_context->dump_expression(this->else_);
18949   ast_dump_context->ostream() << ") ";
18950 }
18951 
18952 // Make a conditional expression.
18953 
18954 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)18955 Expression::make_conditional(Expression* cond, Expression* then,
18956                              Expression* else_expr, Location location)
18957 {
18958   return new Conditional_expression(cond, then, else_expr, location);
18959 }
18960 
18961 // Class Compound_expression.
18962 
18963 // Traversal.
18964 
18965 int
do_traverse(Traverse * traverse)18966 Compound_expression::do_traverse(Traverse* traverse)
18967 {
18968   if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
18969       || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
18970     return TRAVERSE_EXIT;
18971   return TRAVERSE_CONTINUE;
18972 }
18973 
18974 // Return the type of the compound expression.
18975 
18976 Type*
do_type()18977 Compound_expression::do_type()
18978 {
18979   return this->expr_->type();
18980 }
18981 
18982 // Determine type for a compound expression.
18983 
18984 void
do_determine_type(const Type_context * context)18985 Compound_expression::do_determine_type(const Type_context* context)
18986 {
18987   this->init_->determine_type_no_context();
18988   this->expr_->determine_type(context);
18989 }
18990 
18991 // Get the backend representation of a compound expression.
18992 
18993 Bexpression*
do_get_backend(Translate_context * context)18994 Compound_expression::do_get_backend(Translate_context* context)
18995 {
18996   Gogo* gogo = context->gogo();
18997   Bexpression* binit = this->init_->get_backend(context);
18998   Bfunction* bfunction = context->function()->func_value()->get_decl();
18999   Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
19000                                                                 binit);
19001   Bexpression* bexpr = this->expr_->get_backend(context);
19002   return gogo->backend()->compound_expression(init_stmt, bexpr,
19003 					      this->location());
19004 }
19005 
19006 // Dump ast representation of a conditional expression.
19007 
19008 void
do_dump_expression(Ast_dump_context * ast_dump_context) const19009 Compound_expression::do_dump_expression(
19010     Ast_dump_context* ast_dump_context) const
19011 {
19012   ast_dump_context->ostream() << "(";
19013   ast_dump_context->dump_expression(this->init_);
19014   ast_dump_context->ostream() << ",";
19015   ast_dump_context->dump_expression(this->expr_);
19016   ast_dump_context->ostream() << ") ";
19017 }
19018 
19019 // Make a compound expression.
19020 
19021 Expression*
make_compound(Expression * init,Expression * expr,Location location)19022 Expression::make_compound(Expression* init, Expression* expr, Location location)
19023 {
19024   return new Compound_expression(init, expr, location);
19025 }
19026 
19027 // Class Backend_expression.
19028 
19029 int
do_traverse(Traverse *)19030 Backend_expression::do_traverse(Traverse*)
19031 {
19032   return TRAVERSE_CONTINUE;
19033 }
19034 
19035 Expression*
do_copy()19036 Backend_expression::do_copy()
19037 {
19038   return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
19039 				this->location());
19040 }
19041 
19042 void
do_dump_expression(Ast_dump_context * ast_dump_context) const19043 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
19044 {
19045   ast_dump_context->ostream() << "backend_expression<";
19046   ast_dump_context->dump_type(this->type_);
19047   ast_dump_context->ostream() << ">";
19048 }
19049 
19050 Expression*
make_backend(Bexpression * bexpr,Type * type,Location location)19051 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
19052 {
19053   return new Backend_expression(bexpr, type, location);
19054 }
19055 
19056 // Import an expression.  This comes at the end in order to see the
19057 // various class definitions.
19058 
19059 Expression*
import_expression(Import_expression * imp,Location loc)19060 Expression::import_expression(Import_expression* imp, Location loc)
19061 {
19062   Expression* expr = Expression::import_expression_without_suffix(imp, loc);
19063   while (true)
19064     {
19065       if (imp->match_c_string("("))
19066 	{
19067 	  imp->advance(1);
19068 	  Expression_list* args = new Expression_list();
19069 	  bool is_varargs = false;
19070 	  while (!imp->match_c_string(")"))
19071 	    {
19072 	      Expression* arg = Expression::import_expression(imp, loc);
19073 	      if (arg->is_error_expression())
19074 		return arg;
19075 	      args->push_back(arg);
19076 	      if (imp->match_c_string(")"))
19077 		break;
19078 	      else if (imp->match_c_string("...)"))
19079 		{
19080 		  imp->advance(3);
19081 		  is_varargs = true;
19082 		  break;
19083 		}
19084 	      imp->require_c_string(", ");
19085 	    }
19086 	  imp->require_c_string(")");
19087 	  expr = Expression::make_call(expr, args, is_varargs, loc);
19088           expr->call_expression()->set_varargs_are_lowered();
19089 	}
19090       else if (imp->match_c_string("["))
19091 	{
19092 	  imp->advance(1);
19093 	  Expression* start = Expression::import_expression(imp, loc);
19094 	  Expression* end = NULL;
19095 	  Expression* cap = NULL;
19096 	  if (imp->match_c_string(":"))
19097 	    {
19098 	      imp->advance(1);
19099 	      int c = imp->peek_char();
19100 	      if (c == ':' || c == ']')
19101 		end = Expression::make_nil(loc);
19102 	      else
19103 		end = Expression::import_expression(imp, loc);
19104 	      if (imp->match_c_string(":"))
19105 		{
19106 		  imp->advance(1);
19107 		  cap = Expression::import_expression(imp, loc);
19108 		}
19109 	    }
19110 	  imp->require_c_string("]");
19111 	  expr = Expression::make_index(expr, start, end, cap, loc);
19112 	}
19113       else
19114 	break;
19115     }
19116 
19117   return expr;
19118 }
19119 
19120 // Import an expression without considering a suffix (function
19121 // arguments, index operations, etc.).
19122 
19123 Expression*
import_expression_without_suffix(Import_expression * imp,Location loc)19124 Expression::import_expression_without_suffix(Import_expression* imp,
19125 					     Location loc)
19126 {
19127   int c = imp->peek_char();
19128   if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
19129     return Unary_expression::do_import(imp, loc);
19130   else if (c == '(')
19131     return Binary_expression::do_import(imp, loc);
19132   else if (imp->match_c_string("$true")
19133 	   || imp->match_c_string("$false")
19134 	   || (imp->version() < EXPORT_FORMAT_V3
19135 	       && (imp->match_c_string("true")
19136 		   || imp->match_c_string("false"))))
19137     return Boolean_expression::do_import(imp, loc);
19138   else if (c == '"')
19139     return String_expression::do_import(imp, loc);
19140   else if (c == '-' || (c >= '0' && c <= '9'))
19141     {
19142       // This handles integers, floats and complex constants.
19143       return Integer_expression::do_import(imp, loc);
19144     }
19145   else if (imp->match_c_string("<-"))
19146     return Receive_expression::do_import(imp, loc);
19147   else if (imp->match_c_string("$nil")
19148 	   || (imp->version() < EXPORT_FORMAT_V3
19149 	       && imp->match_c_string("nil")))
19150     return Nil_expression::do_import(imp, loc);
19151   else if (imp->match_c_string("$convert")
19152 	   || (imp->version() < EXPORT_FORMAT_V3
19153 	       && imp->match_c_string("convert")))
19154     return Type_conversion_expression::do_import(imp, loc);
19155 
19156   Import_function_body* ifb = imp->ifb();
19157   if (ifb == NULL)
19158     {
19159       go_error_at(imp->location(), "import error: expected expression");
19160       return Expression::make_error(loc);
19161     }
19162   if (ifb->saw_error())
19163     return Expression::make_error(loc);
19164 
19165   if (ifb->match_c_string("$t"))
19166     return Temporary_reference_expression::do_import(ifb, loc);
19167 
19168   return Expression::import_identifier(ifb, loc);
19169 }
19170 
19171 // Import an identifier in an expression.  This is a reference to a
19172 // variable or function.
19173 
19174 Expression*
import_identifier(Import_function_body * ifb,Location loc)19175 Expression::import_identifier(Import_function_body* ifb, Location loc)
19176 {
19177   std::string id;
19178   Package* pkg;
19179   bool is_exported;
19180   if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
19181     {
19182       if (!ifb->saw_error())
19183 	go_error_at(ifb->location(),
19184 		    "import error for %qs: bad qualified identifier at %lu",
19185 		    ifb->name().c_str(),
19186 		    static_cast<unsigned long>(ifb->off()));
19187       ifb->set_saw_error();
19188       return Expression::make_error(loc);
19189     }
19190 
19191   Named_object* no = NULL;
19192   if (pkg == NULL && is_exported)
19193     no = ifb->block()->bindings()->lookup(id);
19194   if (no == NULL)
19195     {
19196       const Package* ipkg = pkg;
19197       if (ipkg == NULL)
19198 	ipkg = ifb->function()->package();
19199       if (!is_exported)
19200 	id = '.' + ipkg->pkgpath() + '.' + id;
19201       no = ipkg->bindings()->lookup(id);
19202     }
19203   if (no == NULL)
19204     no = ifb->gogo()->lookup_global(id.c_str());
19205 
19206   if (no == NULL)
19207     {
19208       if (!ifb->saw_error())
19209 	go_error_at(ifb->location(),
19210 		    "import error for %qs: lookup of %qs failed",
19211 		    ifb->name().c_str(), id.c_str());
19212       ifb->set_saw_error();
19213       return Expression::make_error(loc);
19214     }
19215 
19216   if (no->is_variable() || no->is_result_variable())
19217     return Expression::make_var_reference(no, loc);
19218   else if (no->is_function() || no->is_function_declaration())
19219     return Expression::make_func_reference(no, NULL, loc);
19220   else
19221     {
19222       if (!ifb->saw_error())
19223 	go_error_at(ifb->location(),
19224 		    ("import error for %qs: "
19225 		     "unexpected type of identifier %qs (%d)"),
19226 		    ifb->name().c_str(),
19227 		    id.c_str(), no->classification());
19228       ifb->set_saw_error();
19229       return Expression::make_error(loc);
19230     }
19231 }
19232 
19233 // Class Expression_list.
19234 
19235 // Traverse the list.
19236 
19237 int
traverse(Traverse * traverse)19238 Expression_list::traverse(Traverse* traverse)
19239 {
19240   for (Expression_list::iterator p = this->begin();
19241        p != this->end();
19242        ++p)
19243     {
19244       if (*p != NULL)
19245 	{
19246 	  if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
19247 	    return TRAVERSE_EXIT;
19248 	}
19249     }
19250   return TRAVERSE_CONTINUE;
19251 }
19252 
19253 // Copy the list.
19254 
19255 Expression_list*
copy()19256 Expression_list::copy()
19257 {
19258   Expression_list* ret = new Expression_list();
19259   for (Expression_list::iterator p = this->begin();
19260        p != this->end();
19261        ++p)
19262     {
19263       if (*p == NULL)
19264 	ret->push_back(NULL);
19265       else
19266 	ret->push_back((*p)->copy());
19267     }
19268   return ret;
19269 }
19270 
19271 // Return whether an expression list has an error expression.
19272 
19273 bool
contains_error() const19274 Expression_list::contains_error() const
19275 {
19276   for (Expression_list::const_iterator p = this->begin();
19277        p != this->end();
19278        ++p)
19279     if (*p != NULL && (*p)->is_error_expression())
19280       return true;
19281   return false;
19282 }
19283 
19284 // Class Numeric_constant.
19285 
19286 // Destructor.
19287 
~Numeric_constant()19288 Numeric_constant::~Numeric_constant()
19289 {
19290   this->clear();
19291 }
19292 
19293 // Copy constructor.
19294 
Numeric_constant(const Numeric_constant & a)19295 Numeric_constant::Numeric_constant(const Numeric_constant& a)
19296   : classification_(a.classification_), type_(a.type_)
19297 {
19298   switch (a.classification_)
19299     {
19300     case NC_INVALID:
19301       break;
19302     case NC_INT:
19303     case NC_RUNE:
19304       mpz_init_set(this->u_.int_val, a.u_.int_val);
19305       break;
19306     case NC_FLOAT:
19307       mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
19308       break;
19309     case NC_COMPLEX:
19310       mpc_init2(this->u_.complex_val, mpc_precision);
19311       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
19312       break;
19313     default:
19314       go_unreachable();
19315     }
19316 }
19317 
19318 // Assignment operator.
19319 
19320 Numeric_constant&
operator =(const Numeric_constant & a)19321 Numeric_constant::operator=(const Numeric_constant& a)
19322 {
19323   this->clear();
19324   this->classification_ = a.classification_;
19325   this->type_ = a.type_;
19326   switch (a.classification_)
19327     {
19328     case NC_INVALID:
19329       break;
19330     case NC_INT:
19331     case NC_RUNE:
19332       mpz_init_set(this->u_.int_val, a.u_.int_val);
19333       break;
19334     case NC_FLOAT:
19335       mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
19336       break;
19337     case NC_COMPLEX:
19338       mpc_init2(this->u_.complex_val, mpc_precision);
19339       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
19340       break;
19341     default:
19342       go_unreachable();
19343     }
19344   return *this;
19345 }
19346 
19347 // Check equality with another numeric constant.
19348 
19349 bool
equals(const Numeric_constant & a) const19350 Numeric_constant::equals(const Numeric_constant& a) const
19351 {
19352   if (this->classification_ != a.classification_)
19353     return false;
19354 
19355   if (this->type_ != NULL && a.type_ != NULL
19356       && !Type::are_identical(this->type_, a.type_,
19357 			      Type::COMPARE_ALIASES, NULL))
19358     return false;
19359 
19360   switch (a.classification_)
19361     {
19362     case NC_INVALID:
19363       break;
19364     case NC_INT:
19365     case NC_RUNE:
19366       return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
19367     case NC_FLOAT:
19368       return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
19369     case NC_COMPLEX:
19370       return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
19371     default:
19372       go_unreachable();
19373     }
19374   return false;
19375 }
19376 
19377 // Clear the contents.
19378 
19379 void
clear()19380 Numeric_constant::clear()
19381 {
19382   switch (this->classification_)
19383     {
19384     case NC_INVALID:
19385       break;
19386     case NC_INT:
19387     case NC_RUNE:
19388       mpz_clear(this->u_.int_val);
19389       break;
19390     case NC_FLOAT:
19391       mpfr_clear(this->u_.float_val);
19392       break;
19393     case NC_COMPLEX:
19394       mpc_clear(this->u_.complex_val);
19395       break;
19396     default:
19397       go_unreachable();
19398     }
19399   this->classification_ = NC_INVALID;
19400 }
19401 
19402 // Set to an unsigned long value.
19403 
19404 void
set_unsigned_long(Type * type,unsigned long val)19405 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
19406 {
19407   this->clear();
19408   this->classification_ = NC_INT;
19409   this->type_ = type;
19410   mpz_init_set_ui(this->u_.int_val, val);
19411 }
19412 
19413 // Set to an integer value.
19414 
19415 void
set_int(Type * type,const mpz_t val)19416 Numeric_constant::set_int(Type* type, const mpz_t val)
19417 {
19418   this->clear();
19419   this->classification_ = NC_INT;
19420   this->type_ = type;
19421   mpz_init_set(this->u_.int_val, val);
19422 }
19423 
19424 // Set to a rune value.
19425 
19426 void
set_rune(Type * type,const mpz_t val)19427 Numeric_constant::set_rune(Type* type, const mpz_t val)
19428 {
19429   this->clear();
19430   this->classification_ = NC_RUNE;
19431   this->type_ = type;
19432   mpz_init_set(this->u_.int_val, val);
19433 }
19434 
19435 // Set to a floating point value.
19436 
19437 void
set_float(Type * type,const mpfr_t val)19438 Numeric_constant::set_float(Type* type, const mpfr_t val)
19439 {
19440   this->clear();
19441   this->classification_ = NC_FLOAT;
19442   this->type_ = type;
19443 
19444   // Numeric constants do not have negative zero values, so remove
19445   // them here.  They also don't have infinity or NaN values, but we
19446   // should never see them here.
19447   int bits = 0;
19448   if (type != NULL
19449       && type->float_type() != NULL
19450       && !type->float_type()->is_abstract())
19451     bits = type->float_type()->bits();
19452   if (Numeric_constant::is_float_neg_zero(val, bits))
19453     mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
19454   else
19455     mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
19456 }
19457 
19458 // Set to a complex value.
19459 
19460 void
set_complex(Type * type,const mpc_t val)19461 Numeric_constant::set_complex(Type* type, const mpc_t val)
19462 {
19463   this->clear();
19464   this->classification_ = NC_COMPLEX;
19465   this->type_ = type;
19466 
19467   // Avoid negative zero as in set_float.
19468   int bits = 0;
19469   if (type != NULL
19470       && type->complex_type() != NULL
19471       && !type->complex_type()->is_abstract())
19472     bits = type->complex_type()->bits() / 2;
19473 
19474   mpfr_t real;
19475   mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
19476   if (Numeric_constant::is_float_neg_zero(real, bits))
19477     mpfr_set_ui(real, 0, MPFR_RNDN);
19478 
19479   mpfr_t imag;
19480   mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
19481   if (Numeric_constant::is_float_neg_zero(imag, bits))
19482     mpfr_set_ui(imag, 0, MPFR_RNDN);
19483 
19484   mpc_init2(this->u_.complex_val, mpc_precision);
19485   mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
19486 
19487   mpfr_clear(real);
19488   mpfr_clear(imag);
19489 }
19490 
19491 // Return whether VAL, at a precision of BITS, is a negative zero.
19492 // BITS may be zero in which case it is ignored.
19493 
19494 bool
is_float_neg_zero(const mpfr_t val,int bits)19495 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
19496 {
19497   if (!mpfr_signbit(val))
19498     return false;
19499   if (mpfr_zero_p(val))
19500     return true;
19501   mpfr_exp_t min_exp;
19502   switch (bits)
19503     {
19504     case 0:
19505       return false;
19506     case 32:
19507       // In a denormalized float32 the exponent is -126, and there are
19508       // 24 bits of which at least the last must be 1, so the smallest
19509       // representable non-zero exponent is -126 - (24 - 1) == -149.
19510       min_exp = -149;
19511       break;
19512     case 64:
19513       // Minimum exponent is -1022, there are 53 bits.
19514       min_exp = -1074;
19515       break;
19516     default:
19517       go_unreachable();
19518     }
19519   return mpfr_get_exp(val) < min_exp;
19520 }
19521 
19522 // Get an int value.
19523 
19524 void
get_int(mpz_t * val) const19525 Numeric_constant::get_int(mpz_t* val) const
19526 {
19527   go_assert(this->is_int());
19528   mpz_init_set(*val, this->u_.int_val);
19529 }
19530 
19531 // Get a rune value.
19532 
19533 void
get_rune(mpz_t * val) const19534 Numeric_constant::get_rune(mpz_t* val) const
19535 {
19536   go_assert(this->is_rune());
19537   mpz_init_set(*val, this->u_.int_val);
19538 }
19539 
19540 // Get a floating point value.
19541 
19542 void
get_float(mpfr_t * val) const19543 Numeric_constant::get_float(mpfr_t* val) const
19544 {
19545   go_assert(this->is_float());
19546   mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19547 }
19548 
19549 // Get a complex value.
19550 
19551 void
get_complex(mpc_t * val) const19552 Numeric_constant::get_complex(mpc_t* val) const
19553 {
19554   go_assert(this->is_complex());
19555   mpc_init2(*val, mpc_precision);
19556   mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19557 }
19558 
19559 // Express value as unsigned long if possible.
19560 
19561 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const19562 Numeric_constant::to_unsigned_long(unsigned long* val) const
19563 {
19564   switch (this->classification_)
19565     {
19566     case NC_INT:
19567     case NC_RUNE:
19568       return this->mpz_to_unsigned_long(this->u_.int_val, val);
19569     case NC_FLOAT:
19570       return this->mpfr_to_unsigned_long(this->u_.float_val, val);
19571     case NC_COMPLEX:
19572       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19573 	return NC_UL_NOTINT;
19574       return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
19575 					 val);
19576     default:
19577       go_unreachable();
19578     }
19579 }
19580 
19581 // Express integer value as unsigned long if possible.
19582 
19583 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const19584 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
19585 				       unsigned long *val) const
19586 {
19587   if (mpz_sgn(ival) < 0)
19588     return NC_UL_NEGATIVE;
19589   unsigned long ui = mpz_get_ui(ival);
19590   if (mpz_cmp_ui(ival, ui) != 0)
19591     return NC_UL_BIG;
19592   *val = ui;
19593   return NC_UL_VALID;
19594 }
19595 
19596 // Express floating point value as unsigned long if possible.
19597 
19598 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const19599 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
19600 					unsigned long *val) const
19601 {
19602   if (!mpfr_integer_p(fval))
19603     return NC_UL_NOTINT;
19604   mpz_t ival;
19605   mpz_init(ival);
19606   mpfr_get_z(ival, fval, MPFR_RNDN);
19607   To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
19608   mpz_clear(ival);
19609   return ret;
19610 }
19611 
19612 // Express value as memory size if possible.
19613 
19614 bool
to_memory_size(int64_t * val) const19615 Numeric_constant::to_memory_size(int64_t* val) const
19616 {
19617   switch (this->classification_)
19618     {
19619     case NC_INT:
19620     case NC_RUNE:
19621       return this->mpz_to_memory_size(this->u_.int_val, val);
19622     case NC_FLOAT:
19623       return this->mpfr_to_memory_size(this->u_.float_val, val);
19624     case NC_COMPLEX:
19625       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19626 	return false;
19627       return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
19628     default:
19629       go_unreachable();
19630     }
19631 }
19632 
19633 // Express integer as memory size if possible.
19634 
19635 bool
mpz_to_memory_size(const mpz_t ival,int64_t * val) const19636 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
19637 {
19638   if (mpz_sgn(ival) < 0)
19639     return false;
19640   if (mpz_fits_slong_p(ival))
19641     {
19642       *val = static_cast<int64_t>(mpz_get_si(ival));
19643       return true;
19644     }
19645 
19646   // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
19647   // positive value.
19648   if (mpz_sizeinbase(ival, 2) >= 64)
19649     return false;
19650 
19651   mpz_t q, r;
19652   mpz_init(q);
19653   mpz_init(r);
19654   mpz_tdiv_q_2exp(q, ival, 32);
19655   mpz_tdiv_r_2exp(r, ival, 32);
19656   go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
19657   *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
19658 	  + static_cast<int64_t>(mpz_get_ui(r)));
19659   mpz_clear(r);
19660   mpz_clear(q);
19661   return true;
19662 }
19663 
19664 // Express floating point value as memory size if possible.
19665 
19666 bool
mpfr_to_memory_size(const mpfr_t fval,int64_t * val) const19667 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
19668 {
19669   if (!mpfr_integer_p(fval))
19670     return false;
19671   mpz_t ival;
19672   mpz_init(ival);
19673   mpfr_get_z(ival, fval, MPFR_RNDN);
19674   bool ret = this->mpz_to_memory_size(ival, val);
19675   mpz_clear(ival);
19676   return ret;
19677 }
19678 
19679 // Convert value to integer if possible.
19680 
19681 bool
to_int(mpz_t * val) const19682 Numeric_constant::to_int(mpz_t* val) const
19683 {
19684   switch (this->classification_)
19685     {
19686     case NC_INT:
19687     case NC_RUNE:
19688       mpz_init_set(*val, this->u_.int_val);
19689       return true;
19690     case NC_FLOAT:
19691       if (!mpfr_integer_p(this->u_.float_val))
19692 	return false;
19693       mpz_init(*val);
19694       mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
19695       return true;
19696     case NC_COMPLEX:
19697       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
19698 	  || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
19699 	return false;
19700       mpz_init(*val);
19701       mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19702       return true;
19703     default:
19704       go_unreachable();
19705     }
19706 }
19707 
19708 // Convert value to floating point if possible.
19709 
19710 bool
to_float(mpfr_t * val) const19711 Numeric_constant::to_float(mpfr_t* val) const
19712 {
19713   switch (this->classification_)
19714     {
19715     case NC_INT:
19716     case NC_RUNE:
19717       mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
19718       return true;
19719     case NC_FLOAT:
19720       mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19721       return true;
19722     case NC_COMPLEX:
19723       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19724 	return false;
19725       mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19726       return true;
19727     default:
19728       go_unreachable();
19729     }
19730 }
19731 
19732 // Convert value to complex.
19733 
19734 bool
to_complex(mpc_t * val) const19735 Numeric_constant::to_complex(mpc_t* val) const
19736 {
19737   mpc_init2(*val, mpc_precision);
19738   switch (this->classification_)
19739     {
19740     case NC_INT:
19741     case NC_RUNE:
19742       mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
19743       return true;
19744     case NC_FLOAT:
19745       mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
19746       return true;
19747     case NC_COMPLEX:
19748       mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19749       return true;
19750     default:
19751       go_unreachable();
19752     }
19753 }
19754 
19755 // Get the type.
19756 
19757 Type*
type() const19758 Numeric_constant::type() const
19759 {
19760   if (this->type_ != NULL)
19761     return this->type_;
19762   switch (this->classification_)
19763     {
19764     case NC_INT:
19765       return Type::make_abstract_integer_type();
19766     case NC_RUNE:
19767       return Type::make_abstract_character_type();
19768     case NC_FLOAT:
19769       return Type::make_abstract_float_type();
19770     case NC_COMPLEX:
19771       return Type::make_abstract_complex_type();
19772     default:
19773       go_unreachable();
19774     }
19775 }
19776 
19777 // If the constant can be expressed in TYPE, then set the type of the
19778 // constant to TYPE and return true.  Otherwise return false, and, if
19779 // ISSUE_ERROR is true, report an appropriate error message.
19780 
19781 bool
set_type(Type * type,bool issue_error,Location loc)19782 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
19783 {
19784   bool ret;
19785   if (type == NULL || type->is_error())
19786     ret = true;
19787   else if (type->integer_type() != NULL)
19788     ret = this->check_int_type(type->integer_type(), issue_error, loc);
19789   else if (type->float_type() != NULL)
19790     ret = this->check_float_type(type->float_type(), issue_error, loc);
19791   else if (type->complex_type() != NULL)
19792     ret = this->check_complex_type(type->complex_type(), issue_error, loc);
19793   else
19794     {
19795       ret = false;
19796       if (issue_error)
19797         go_assert(saw_errors());
19798     }
19799   if (ret)
19800     this->type_ = type;
19801   return ret;
19802 }
19803 
19804 // Check whether the constant can be expressed in an integer type.
19805 
19806 bool
check_int_type(Integer_type * type,bool issue_error,Location location)19807 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
19808 				 Location location)
19809 {
19810   mpz_t val;
19811   switch (this->classification_)
19812     {
19813     case NC_INT:
19814     case NC_RUNE:
19815       mpz_init_set(val, this->u_.int_val);
19816       break;
19817 
19818     case NC_FLOAT:
19819       if (!mpfr_integer_p(this->u_.float_val))
19820 	{
19821 	  if (issue_error)
19822             {
19823               go_error_at(location,
19824                           "floating-point constant truncated to integer");
19825               this->set_invalid();
19826             }
19827 	  return false;
19828 	}
19829       mpz_init(val);
19830       mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
19831       break;
19832 
19833     case NC_COMPLEX:
19834       if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
19835 	  || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19836 	{
19837 	  if (issue_error)
19838             {
19839               go_error_at(location, "complex constant truncated to integer");
19840               this->set_invalid();
19841             }
19842 	  return false;
19843 	}
19844       mpz_init(val);
19845       mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19846       break;
19847 
19848     default:
19849       go_unreachable();
19850     }
19851 
19852   bool ret;
19853   if (type->is_abstract())
19854     ret = true;
19855   else
19856     {
19857       int bits = mpz_sizeinbase(val, 2);
19858       if (type->is_unsigned())
19859 	{
19860 	  // For an unsigned type we can only accept a nonnegative
19861 	  // number, and we must be able to represents at least BITS.
19862 	  ret = mpz_sgn(val) >= 0 && bits <= type->bits();
19863 	}
19864       else
19865 	{
19866 	  // For a signed type we need an extra bit to indicate the
19867 	  // sign.  We have to handle the most negative integer
19868 	  // specially.
19869 	  ret = (bits + 1 <= type->bits()
19870 		 || (bits <= type->bits()
19871 		     && mpz_sgn(val) < 0
19872 		     && (mpz_scan1(val, 0)
19873 			 == static_cast<unsigned long>(type->bits() - 1))
19874 		     && mpz_scan0(val, type->bits()) == ULONG_MAX));
19875 	}
19876     }
19877 
19878   if (!ret && issue_error)
19879     {
19880       go_error_at(location, "integer constant overflow");
19881       this->set_invalid();
19882     }
19883 
19884   return ret;
19885 }
19886 
19887 // Check whether the constant can be expressed in a floating point
19888 // type.
19889 
19890 bool
check_float_type(Float_type * type,bool issue_error,Location location)19891 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
19892 				   Location location)
19893 {
19894   mpfr_t val;
19895   switch (this->classification_)
19896     {
19897     case NC_INT:
19898     case NC_RUNE:
19899       mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
19900       break;
19901 
19902     case NC_FLOAT:
19903       mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
19904       break;
19905 
19906     case NC_COMPLEX:
19907       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19908 	{
19909 	  if (issue_error)
19910             {
19911               this->set_invalid();
19912               go_error_at(location,
19913 			  "complex constant truncated to floating-point");
19914             }
19915 	  return false;
19916 	}
19917       mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19918       break;
19919 
19920     default:
19921       go_unreachable();
19922     }
19923 
19924   bool ret;
19925   if (type->is_abstract())
19926     ret = true;
19927   else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
19928     {
19929       // A NaN or Infinity always fits in the range of the type.
19930       ret = true;
19931     }
19932   else
19933     {
19934       mpfr_exp_t exp = mpfr_get_exp(val);
19935       mpfr_exp_t max_exp;
19936       switch (type->bits())
19937 	{
19938 	case 32:
19939 	  max_exp = 128;
19940 	  break;
19941 	case 64:
19942 	  max_exp = 1024;
19943 	  break;
19944 	default:
19945 	  go_unreachable();
19946 	}
19947 
19948       ret = exp <= max_exp;
19949 
19950       if (ret)
19951 	{
19952 	  // Round the constant to the desired type.
19953 	  mpfr_t t;
19954 	  mpfr_init(t);
19955 	  switch (type->bits())
19956 	    {
19957 	    case 32:
19958 	      mpfr_set_prec(t, 24);
19959 	      break;
19960 	    case 64:
19961 	      mpfr_set_prec(t, 53);
19962 	      break;
19963 	    default:
19964 	      go_unreachable();
19965 	    }
19966 	  mpfr_set(t, val, MPFR_RNDN);
19967 	  mpfr_set(val, t, MPFR_RNDN);
19968 	  mpfr_clear(t);
19969 
19970 	  this->set_float(type, val);
19971 	}
19972     }
19973 
19974   mpfr_clear(val);
19975 
19976   if (!ret && issue_error)
19977     {
19978       go_error_at(location, "floating-point constant overflow");
19979       this->set_invalid();
19980     }
19981 
19982   return ret;
19983 }
19984 
19985 // Check whether the constant can be expressed in a complex type.
19986 
19987 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)19988 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
19989 				     Location location)
19990 {
19991   if (type->is_abstract())
19992     return true;
19993 
19994   mpfr_exp_t max_exp;
19995   switch (type->bits())
19996     {
19997     case 64:
19998       max_exp = 128;
19999       break;
20000     case 128:
20001       max_exp = 1024;
20002       break;
20003     default:
20004       go_unreachable();
20005     }
20006 
20007   mpc_t val;
20008   mpc_init2(val, mpc_precision);
20009   switch (this->classification_)
20010     {
20011     case NC_INT:
20012     case NC_RUNE:
20013       mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
20014       break;
20015 
20016     case NC_FLOAT:
20017       mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
20018       break;
20019 
20020     case NC_COMPLEX:
20021       mpc_set(val, this->u_.complex_val, MPC_RNDNN);
20022       break;
20023 
20024     default:
20025       go_unreachable();
20026     }
20027 
20028   bool ret = true;
20029   if (!mpfr_nan_p(mpc_realref(val))
20030       && !mpfr_inf_p(mpc_realref(val))
20031       && !mpfr_zero_p(mpc_realref(val))
20032       && mpfr_get_exp(mpc_realref(val)) > max_exp)
20033     {
20034       if (issue_error)
20035         {
20036           go_error_at(location, "complex real part overflow");
20037           this->set_invalid();
20038         }
20039       ret = false;
20040     }
20041 
20042   if (!mpfr_nan_p(mpc_imagref(val))
20043       && !mpfr_inf_p(mpc_imagref(val))
20044       && !mpfr_zero_p(mpc_imagref(val))
20045       && mpfr_get_exp(mpc_imagref(val)) > max_exp)
20046     {
20047       if (issue_error)
20048         {
20049           go_error_at(location, "complex imaginary part overflow");
20050           this->set_invalid();
20051         }
20052       ret = false;
20053     }
20054 
20055   if (ret)
20056     {
20057       // Round the constant to the desired type.
20058       mpc_t t;
20059       switch (type->bits())
20060 	{
20061 	case 64:
20062 	  mpc_init2(t, 24);
20063 	  break;
20064 	case 128:
20065 	  mpc_init2(t, 53);
20066 	  break;
20067 	default:
20068 	  go_unreachable();
20069 	}
20070       mpc_set(t, val, MPC_RNDNN);
20071       mpc_set(val, t, MPC_RNDNN);
20072       mpc_clear(t);
20073 
20074       this->set_complex(type, val);
20075     }
20076 
20077   mpc_clear(val);
20078 
20079   return ret;
20080 }
20081 
20082 // Return an Expression for this value.
20083 
20084 Expression*
expression(Location loc) const20085 Numeric_constant::expression(Location loc) const
20086 {
20087   switch (this->classification_)
20088     {
20089     case NC_INT:
20090       return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
20091     case NC_RUNE:
20092       return Expression::make_character(&this->u_.int_val, this->type_, loc);
20093     case NC_FLOAT:
20094       return Expression::make_float(&this->u_.float_val, this->type_, loc);
20095     case NC_COMPLEX:
20096       return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
20097     case NC_INVALID:
20098       go_assert(saw_errors());
20099       return Expression::make_error(loc);
20100     default:
20101       go_unreachable();
20102     }
20103 }
20104 
20105 // Calculate a hash code with a given seed.
20106 
20107 unsigned int
hash(unsigned int seed) const20108 Numeric_constant::hash(unsigned int seed) const
20109 {
20110   unsigned long val;
20111   const unsigned int PRIME = 97;
20112   long e = 0;
20113   double f = 1.0;
20114   mpfr_t m;
20115 
20116   switch (this->classification_)
20117     {
20118     case NC_INVALID:
20119       return PRIME;
20120     case NC_INT:
20121     case NC_RUNE:
20122       val = mpz_get_ui(this->u_.int_val);
20123       break;
20124     case NC_COMPLEX:
20125       mpfr_init(m);
20126       mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
20127       val = mpfr_get_ui(m, MPFR_RNDN);
20128       mpfr_clear(m);
20129       break;
20130     case NC_FLOAT:
20131       f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
20132       val = static_cast<unsigned long>(e + static_cast<long>(f));
20133       break;
20134     default:
20135       go_unreachable();
20136     }
20137 
20138   return (static_cast<unsigned int>(val) + seed) * PRIME;
20139 }
20140