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 // Default implementation for do_traverse for child classes.
63 
64 int
do_traverse(Traverse *)65 Expression::do_traverse(Traverse*)
66 {
67   return TRAVERSE_CONTINUE;
68 }
69 
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded.  By default, we give an error.
72 // Expressions with side effects override.
73 
74 bool
do_discarding_value()75 Expression::do_discarding_value()
76 {
77   this->unused_value_error();
78   return false;
79 }
80 
81 // This virtual function is called to export expressions.  This will
82 // only be used by expressions which may be constant.
83 
84 void
do_export(Export_function_body *) const85 Expression::do_export(Export_function_body*) const
86 {
87   go_unreachable();
88 }
89 
90 // Write a name to the export data.
91 
92 void
export_name(Export_function_body * efb,const Named_object * no)93 Expression::export_name(Export_function_body* efb, const Named_object* no)
94 {
95   if (no->package() != NULL)
96     {
97       char buf[50];
98       snprintf(buf, sizeof buf, "<p%d>", efb->package_index(no->package()));
99       efb->write_c_string(buf);
100     }
101 
102   if (!Gogo::is_hidden_name(no->name()))
103     efb->write_string(no->name());
104   else
105     {
106       efb->write_c_string(".");
107       efb->write_string(Gogo::unpack_hidden_name(no->name()));
108     }
109 }
110 
111 // Give an error saying that the value of the expression is not used.
112 
113 void
unused_value_error()114 Expression::unused_value_error()
115 {
116   this->report_error(_("value computed is not used"));
117 }
118 
119 // Note that this expression is an error.  This is called by children
120 // when they discover an error.
121 
122 void
set_is_error()123 Expression::set_is_error()
124 {
125   this->classification_ = EXPRESSION_ERROR;
126 }
127 
128 // For children to call to report an error conveniently.
129 
130 void
report_error(const char * msg)131 Expression::report_error(const char* msg)
132 {
133   go_error_at(this->location_, "%s", msg);
134   this->set_is_error();
135 }
136 
137 // Set types of variables and constants.  This is implemented by the
138 // child class.
139 
140 void
determine_type(const Type_context * context)141 Expression::determine_type(const Type_context* context)
142 {
143   this->do_determine_type(context);
144 }
145 
146 // Set types when there is no context.
147 
148 void
determine_type_no_context()149 Expression::determine_type_no_context()
150 {
151   Type_context context;
152   this->do_determine_type(&context);
153 }
154 
155 // Return true if two expressions refer to the same variable or struct
156 // field.  This can only be true when there are no side effects.
157 
158 bool
is_same_variable(Expression * a,Expression * b)159 Expression::is_same_variable(Expression* a, Expression* b)
160 {
161   if (a->classification() != b->classification())
162     return false;
163 
164   Var_expression* av = a->var_expression();
165   if (av != NULL)
166     return av->named_object() == b->var_expression()->named_object();
167 
168   Field_reference_expression* af = a->field_reference_expression();
169   if (af != NULL)
170     {
171       Field_reference_expression* bf = b->field_reference_expression();
172       return (af->field_index() == bf->field_index()
173 	      && Expression::is_same_variable(af->expr(), bf->expr()));
174     }
175 
176   Unary_expression* au = a->unary_expression();
177   if (au != NULL)
178     {
179       Unary_expression* bu = b->unary_expression();
180       return (au->op() == OPERATOR_MULT
181 	      && bu->op() == OPERATOR_MULT
182 	      && Expression::is_same_variable(au->operand(),
183 					      bu->operand()));
184     }
185 
186   Array_index_expression* aie = a->array_index_expression();
187   if (aie != NULL)
188     {
189       Array_index_expression* bie = b->array_index_expression();
190       return (aie->end() == NULL
191 	      && bie->end() == NULL
192 	      && Expression::is_same_variable(aie->array(), bie->array())
193 	      && Expression::is_same_variable(aie->start(), bie->start()));
194     }
195 
196   Numeric_constant aval;
197   if (a->numeric_constant_value(&aval))
198     {
199       Numeric_constant bval;
200       if (b->numeric_constant_value(&bval))
201 	return aval.equals(bval);
202     }
203 
204   return false;
205 }
206 
207 // Return an expression handling any conversions which must be done during
208 // assignment.
209 
210 Expression*
convert_for_assignment(Gogo *,Type * lhs_type,Expression * rhs,Location location)211 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
212 				   Expression* rhs, Location location)
213 {
214   Type* rhs_type = rhs->type();
215   if (lhs_type->is_error()
216       || rhs_type->is_error()
217       || rhs->is_error_expression())
218     return Expression::make_error(location);
219 
220   bool are_identical = Type::are_identical(lhs_type, rhs_type,
221 					   (Type::COMPARE_ERRORS
222 					    | Type::COMPARE_TAGS),
223 					   NULL);
224   if (!are_identical && lhs_type->interface_type() != NULL)
225     {
226       // Type to interface conversions have been made explicit early.
227       go_assert(rhs_type->interface_type() != NULL);
228       return Expression::convert_interface_to_interface(lhs_type, rhs, false,
229                                                         location);
230     }
231   else if (!are_identical && rhs_type->interface_type() != NULL)
232     return Expression::convert_interface_to_type(lhs_type, rhs, location);
233   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
234     {
235       // Assigning nil to a slice.
236       Expression* nil = Expression::make_nil(location);
237       Expression* zero = Expression::make_integer_ul(0, NULL, location);
238       return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
239     }
240   else if (rhs_type->is_nil_type())
241     return Expression::make_nil(location);
242   else if (are_identical)
243     {
244       if (lhs_type->forwarded() != rhs_type->forwarded())
245 	{
246 	  // Different but identical types require an explicit
247 	  // conversion.  This happens with type aliases.
248 	  return Expression::make_cast(lhs_type, rhs, location);
249 	}
250 
251       // No conversion is needed.
252       return rhs;
253     }
254   else if (lhs_type->points_to() != NULL)
255     return Expression::make_unsafe_cast(lhs_type, rhs, location);
256   else if (lhs_type->is_numeric_type())
257     return Expression::make_cast(lhs_type, rhs, location);
258   else if ((lhs_type->struct_type() != NULL
259             && rhs_type->struct_type() != NULL)
260            || (lhs_type->array_type() != NULL
261                && rhs_type->array_type() != NULL))
262     {
263       // This conversion must be permitted by Go, or we wouldn't have
264       // gotten here.
265       return Expression::make_unsafe_cast(lhs_type, rhs, location);
266     }
267   else
268     return rhs;
269 }
270 
271 // Return an expression for a conversion from a non-interface type to an
272 // interface type.  If ON_STACK is true, it can allocate the storage on
273 // stack.
274 
275 Expression*
convert_type_to_interface(Type * lhs_type,Expression * rhs,bool on_stack,Location location)276 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
277                                       bool on_stack, Location location)
278 {
279   Interface_type* lhs_interface_type = lhs_type->interface_type();
280   bool lhs_is_empty = lhs_interface_type->is_empty();
281 
282   // Since RHS_TYPE is a static type, we can create the interface
283   // method table at compile time.
284 
285   // When setting an interface to nil, we just set both fields to
286   // NULL.
287   Type* rhs_type = rhs->type();
288   if (rhs_type->is_nil_type())
289     {
290       Expression* nil = Expression::make_nil(location);
291       return Expression::make_interface_value(lhs_type, nil, nil, location);
292     }
293 
294   // This should have been checked already.
295   if (!lhs_interface_type->implements_interface(rhs_type, NULL))
296     {
297       go_assert(saw_errors());
298       return Expression::make_error(location);
299     }
300 
301   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
302   // then the first field is the type descriptor for RHS_TYPE.
303   // Otherwise it is the interface method table for RHS_TYPE.
304   Expression* first_field;
305   if (lhs_is_empty)
306     first_field = Expression::make_type_descriptor(rhs_type, location);
307   else
308     {
309       // Build the interface method table for this interface and this
310       // object type: a list of function pointers for each interface
311       // method.
312       Named_type* rhs_named_type = rhs_type->named_type();
313       Struct_type* rhs_struct_type = rhs_type->struct_type();
314       bool is_pointer = false;
315       if (rhs_named_type == NULL && rhs_struct_type == NULL)
316 	{
317 	  rhs_named_type = rhs_type->deref()->named_type();
318 	  rhs_struct_type = rhs_type->deref()->struct_type();
319 	  is_pointer = true;
320 	}
321       if (rhs_named_type != NULL)
322 	first_field =
323 	  rhs_named_type->interface_method_table(lhs_interface_type,
324                                                  is_pointer);
325       else if (rhs_struct_type != NULL)
326 	first_field =
327 	  rhs_struct_type->interface_method_table(lhs_interface_type,
328                                                   is_pointer);
329       else
330 	first_field = Expression::make_nil(location);
331     }
332 
333   Expression* obj;
334   if (rhs_type->is_direct_iface_type())
335     {
336       // We are assigning a pointer to the interface; the interface
337       // holds the pointer itself.
338       obj = unpack_direct_iface(rhs, location);
339     }
340   else
341     {
342       // We are assigning a non-pointer value to the interface; the
343       // interface gets a copy of the value in the heap if it escapes.
344       if (rhs->is_constant())
345         obj = Expression::make_unary(OPERATOR_AND, rhs, location);
346       else
347         {
348           obj = Expression::make_heap_expression(rhs, location);
349           if (on_stack)
350             obj->heap_expression()->set_allocate_on_stack();
351         }
352     }
353 
354   return Expression::make_interface_value(lhs_type, first_field, obj, location);
355 }
356 
357 // Return an expression for the pointer-typed value of a direct interface
358 // type.  Specifically, for single field struct or array, get the single
359 // field, and do this recursively.  The reason for this is that we don't
360 // want to assign a struct or an array to a pointer-typed field.  The
361 // backend may not like that.
362 
363 Expression*
unpack_direct_iface(Expression * rhs,Location loc)364 Expression::unpack_direct_iface(Expression* rhs, Location loc)
365 {
366   Struct_type* st = rhs->type()->struct_type();
367   if (st != NULL)
368     {
369       go_assert(st->field_count() == 1);
370       Expression* field = Expression::make_field_reference(rhs, 0, loc);
371       return unpack_direct_iface(field, loc);
372     }
373   Array_type* at = rhs->type()->array_type();
374   if (at != NULL)
375     {
376       int64_t len;
377       bool ok = at->int_length(&len);
378       go_assert(ok && len == 1);
379       Type* int_type = Type::lookup_integer_type("int");
380       Expression* index = Expression::make_integer_ul(0, int_type, loc);
381       Expression* elem = Expression::make_array_index(rhs, index, NULL, NULL, loc);
382       return unpack_direct_iface(elem, loc);
383     }
384   return rhs;
385 }
386 
387 // The opposite of unpack_direct_iface.
388 
389 Expression*
pack_direct_iface(Type * t,Expression * rhs,Location loc)390 Expression::pack_direct_iface(Type* t, Expression* rhs, Location loc)
391 {
392   if (rhs->type() == t)
393     return rhs;
394   Struct_type* st = t->struct_type();
395   if (st != NULL)
396     {
397       Expression_list* vals = new Expression_list();
398       vals->push_back(pack_direct_iface(st->field(0)->type(), rhs, loc));
399       return Expression::make_struct_composite_literal(t, vals, loc);
400     }
401   Array_type* at = t->array_type();
402   if (at != NULL)
403     {
404       Expression_list* vals = new Expression_list();
405       vals->push_back(pack_direct_iface(at->element_type(), rhs, loc));
406       return Expression::make_array_composite_literal(t, vals, loc);
407     }
408   return Expression::make_unsafe_cast(t, rhs, loc);
409 }
410 
411 // Return an expression for the type descriptor of RHS.
412 
413 Expression*
get_interface_type_descriptor(Expression * rhs)414 Expression::get_interface_type_descriptor(Expression* rhs)
415 {
416   go_assert(rhs->type()->interface_type() != NULL);
417   Location location = rhs->location();
418 
419   // The type descriptor is the first field of an empty interface.
420   if (rhs->type()->interface_type()->is_empty())
421     return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
422                                            location);
423 
424   Expression* mtable =
425       Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
426 
427   Expression* descriptor =
428       Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
429   descriptor = Expression::make_field_reference(descriptor, 0, location);
430   Expression* nil = Expression::make_nil(location);
431 
432   Expression* eq =
433       Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
434   return Expression::make_conditional(eq, nil, descriptor, location);
435 }
436 
437 // Return an expression for the conversion of an interface type to an
438 // interface type.
439 
440 Expression*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)441 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
442                                            bool for_type_guard,
443                                            Location location)
444 {
445   if (Type::are_identical(lhs_type, rhs->type(),
446 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
447 			  NULL))
448     return rhs;
449 
450   Interface_type* lhs_interface_type = lhs_type->interface_type();
451   bool lhs_is_empty = lhs_interface_type->is_empty();
452 
453   // In the general case this requires runtime examination of the type
454   // method table to match it up with the interface methods.
455 
456   // FIXME: If all of the methods in the right hand side interface
457   // also appear in the left hand side interface, then we don't need
458   // to do a runtime check, although we still need to build a new
459   // method table.
460 
461   // We are going to evaluate RHS multiple times.
462   go_assert(rhs->is_variable());
463 
464   // Get the type descriptor for the right hand side.  This will be
465   // NULL for a nil interface.
466   Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
467   Expression* lhs_type_expr =
468       Expression::make_type_descriptor(lhs_type, location);
469 
470   Expression* first_field;
471   if (for_type_guard)
472     {
473       // A type assertion fails when converting a nil interface.
474       first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
475 				       lhs_type_expr, rhs_type_expr);
476     }
477   else if (lhs_is_empty)
478     {
479       // A conversion to an empty interface always succeeds, and the
480       // first field is just the type descriptor of the object.
481       first_field = rhs_type_expr;
482     }
483   else
484     {
485       // A conversion to a non-empty interface may fail, but unlike a
486       // type assertion converting nil will always succeed.
487       first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
488 				       lhs_type_expr, rhs_type_expr);
489     }
490 
491   // The second field is simply the object pointer.
492   Expression* obj =
493       Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
494   return Expression::make_interface_value(lhs_type, first_field, obj, location);
495 }
496 
497 // Return an expression for the conversion of an interface type to a
498 // non-interface type.
499 
500 Expression*
convert_interface_to_type(Type * lhs_type,Expression * rhs,Location location)501 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
502                                       Location location)
503 {
504   // We are going to evaluate RHS multiple times.
505   go_assert(rhs->is_variable());
506 
507   // Build an expression to check that the type is valid.  It will
508   // panic with an appropriate runtime type error if the type is not
509   // valid.
510   // (lhs_type != rhs_type ? panicdottype(lhs_type, rhs_type, inter_type) :
511   //    nil /*dummy*/)
512   Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
513                                                                 location);
514   Expression* rhs_descriptor =
515       Expression::get_interface_type_descriptor(rhs);
516 
517   Type* rhs_type = rhs->type();
518   Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
519                                                                 location);
520 
521   Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, lhs_type_expr,
522                                              rhs_descriptor, location);
523   rhs_descriptor = Expression::get_interface_type_descriptor(rhs);
524   Expression* panic = Runtime::make_call(Runtime::PANICDOTTYPE, location,
525                                          3, lhs_type_expr->copy(),
526                                          rhs_descriptor,
527                                          rhs_inter_expr);
528   Expression* nil = Expression::make_nil(location);
529   Expression* check = Expression::make_conditional(cond, panic, nil,
530                                                    location);
531 
532   // If the conversion succeeds, pull out the value.
533   Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
534                                                     location);
535 
536   // If the value is a direct interface, then it is the value we want.
537   // Otherwise it points to the value.
538   if (lhs_type->is_direct_iface_type())
539     obj = Expression::pack_direct_iface(lhs_type, obj, location);
540   else
541     {
542       obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
543                                          location);
544       obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
545                                          location);
546     }
547   return Expression::make_compound(check, obj, location);
548 }
549 
550 // Convert an expression to its backend representation.  This is implemented by
551 // the child class.  Not that it is not in general safe to call this multiple
552 // times for a single expression, but that we don't catch such errors.
553 
554 Bexpression*
get_backend(Translate_context * context)555 Expression::get_backend(Translate_context* context)
556 {
557   // The child may have marked this expression as having an error.
558   if (this->classification_ == EXPRESSION_ERROR)
559     return context->backend()->error_expression();
560 
561   return this->do_get_backend(context);
562 }
563 
564 // Return a backend expression for VAL.
565 Bexpression*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)566 Expression::backend_numeric_constant_expression(Translate_context* context,
567                                                 Numeric_constant* val)
568 {
569   Gogo* gogo = context->gogo();
570   Type* type = val->type();
571   if (type == NULL)
572     return gogo->backend()->error_expression();
573 
574   Btype* btype = type->get_backend(gogo);
575   Bexpression* ret;
576   if (type->integer_type() != NULL)
577     {
578       mpz_t ival;
579       if (!val->to_int(&ival))
580         {
581           go_assert(saw_errors());
582           return gogo->backend()->error_expression();
583         }
584       ret = gogo->backend()->integer_constant_expression(btype, ival);
585       mpz_clear(ival);
586     }
587   else if (type->float_type() != NULL)
588     {
589       mpfr_t fval;
590       if (!val->to_float(&fval))
591         {
592           go_assert(saw_errors());
593           return gogo->backend()->error_expression();
594         }
595       ret = gogo->backend()->float_constant_expression(btype, fval);
596       mpfr_clear(fval);
597     }
598   else if (type->complex_type() != NULL)
599     {
600       mpc_t cval;
601       if (!val->to_complex(&cval))
602         {
603           go_assert(saw_errors());
604           return gogo->backend()->error_expression();
605         }
606       ret = gogo->backend()->complex_constant_expression(btype, cval);
607       mpc_clear(cval);
608     }
609   else
610     go_unreachable();
611 
612   return ret;
613 }
614 
615 // Insert bounds checks for an index expression.  Check that that VAL
616 // >= 0 and that it fits in an int.  Then check that VAL OP BOUND is
617 // true.  If any condition is false, call one of the CODE runtime
618 // functions, which will panic.
619 
620 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)621 Expression::check_bounds(Expression* val, Operator op, Expression* bound,
622 			 Runtime::Function code,
623 			 Runtime::Function code_u,
624 			 Runtime::Function code_extend,
625 			 Runtime::Function code_extend_u,
626 			 Statement_inserter* inserter,
627 			 Location loc)
628 {
629   go_assert(val->is_variable() || val->is_constant());
630   go_assert(bound->is_variable() || bound->is_constant());
631 
632   Type* int_type = Type::lookup_integer_type("int");
633   int int_type_size = int_type->integer_type()->bits();
634 
635   Type* val_type = val->type();
636   if (val_type->integer_type() == NULL)
637     {
638       go_assert(saw_errors());
639       return;
640     }
641   int val_type_size = val_type->integer_type()->bits();
642   bool val_is_unsigned = val_type->integer_type()->is_unsigned();
643 
644   // Check that VAL >= 0.
645   Expression* check = NULL;
646   if (!val_is_unsigned)
647     {
648       Expression* zero = Expression::make_integer_ul(0, val_type, loc);
649       check = Expression::make_binary(OPERATOR_GE, val->copy(), zero, loc);
650     }
651 
652   // If VAL's type is larger than int, check that VAL fits in an int.
653   if (val_type_size > int_type_size
654       || (val_type_size == int_type_size
655 	  && val_is_unsigned))
656     {
657       mpz_t one;
658       mpz_init_set_ui(one, 1UL);
659 
660       // maxval = 2^(int_type_size - 1) - 1
661       mpz_t maxval;
662       mpz_init(maxval);
663       mpz_mul_2exp(maxval, one, int_type_size - 1);
664       mpz_sub_ui(maxval, maxval, 1);
665       Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
666       mpz_clear(one);
667       mpz_clear(maxval);
668 
669       Expression* cmp = Expression::make_binary(OPERATOR_LE, val->copy(),
670 						max, loc);
671       if (check == NULL)
672 	check = cmp;
673       else
674 	check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
675     }
676 
677   // For the final check we can assume that VAL fits in an int.
678   Expression* ival;
679   if (val_type == int_type)
680     ival = val->copy();
681   else
682     ival = Expression::make_cast(int_type, val->copy(), loc);
683 
684   // BOUND is assumed to fit in an int.  Either it comes from len or
685   // cap, or it was checked by an earlier call.
686   Expression* ibound;
687   if (bound->type() == int_type)
688     ibound = bound->copy();
689   else
690     ibound = Expression::make_cast(int_type, bound->copy(), loc);
691 
692   Expression* cmp = Expression::make_binary(op, ival, ibound, loc);
693   if (check == NULL)
694     check = cmp;
695   else
696     check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
697 
698   Runtime::Function c;
699   if (val_type_size > int_type_size)
700     {
701       if (val_is_unsigned)
702 	c = code_extend_u;
703       else
704 	c = code_extend;
705     }
706   else
707     {
708       if (val_is_unsigned)
709 	c = code_u;
710       else
711 	c = code;
712     }
713 
714   Expression* ignore = Expression::make_boolean(true, loc);
715   Expression* crash = Runtime::make_call(c, loc, 2,
716 					 val->copy(), bound->copy());
717   Expression* cond = Expression::make_conditional(check, ignore, crash, loc);
718   inserter->insert(Statement::make_statement(cond, true));
719 }
720 
721 void
dump_expression(Ast_dump_context * ast_dump_context) const722 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
723 {
724   this->do_dump_expression(ast_dump_context);
725 }
726 
727 // Error expressions.  This are used to avoid cascading errors.
728 
729 class Error_expression : public Expression
730 {
731  public:
Error_expression(Location location)732   Error_expression(Location location)
733     : Expression(EXPRESSION_ERROR, location)
734   { }
735 
736  protected:
737   bool
do_is_constant() const738   do_is_constant() const
739   { return true; }
740 
741   bool
do_numeric_constant_value(Numeric_constant * nc) const742   do_numeric_constant_value(Numeric_constant* nc) const
743   {
744     nc->set_unsigned_long(NULL, 0);
745     return true;
746   }
747 
748   bool
do_discarding_value()749   do_discarding_value()
750   { return true; }
751 
752   Type*
do_type()753   do_type()
754   { return Type::make_error_type(); }
755 
756   void
do_determine_type(const Type_context *)757   do_determine_type(const Type_context*)
758   { }
759 
760   Expression*
do_copy()761   do_copy()
762   { return this; }
763 
764   bool
do_is_addressable() const765   do_is_addressable() const
766   { return true; }
767 
768   Bexpression*
do_get_backend(Translate_context * context)769   do_get_backend(Translate_context* context)
770   { return context->backend()->error_expression(); }
771 
772   void
773   do_dump_expression(Ast_dump_context*) const;
774 };
775 
776 // Dump the ast representation for an error expression to a dump context.
777 
778 void
do_dump_expression(Ast_dump_context * ast_dump_context) const779 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
780 {
781   ast_dump_context->ostream() << "_Error_" ;
782 }
783 
784 Expression*
make_error(Location location)785 Expression::make_error(Location location)
786 {
787   return new Error_expression(location);
788 }
789 
790 // An expression which is really a type.  This is used during parsing.
791 // It is an error if these survive after lowering.
792 
793 class
794 Type_expression : public Expression
795 {
796  public:
Type_expression(Type * type,Location location)797   Type_expression(Type* type, Location location)
798     : Expression(EXPRESSION_TYPE, location),
799       type_(type)
800   { }
801 
802  protected:
803   int
do_traverse(Traverse * traverse)804   do_traverse(Traverse* traverse)
805   { return Type::traverse(this->type_, traverse); }
806 
807   Type*
do_type()808   do_type()
809   { return this->type_; }
810 
811   void
do_determine_type(const Type_context *)812   do_determine_type(const Type_context*)
813   { }
814 
815   void
do_check_types(Gogo *)816   do_check_types(Gogo*)
817   { this->report_error(_("invalid use of type")); }
818 
819   Expression*
do_copy()820   do_copy()
821   { return this; }
822 
823   Bexpression*
do_get_backend(Translate_context *)824   do_get_backend(Translate_context*)
825   { go_unreachable(); }
826 
827   void do_dump_expression(Ast_dump_context*) const;
828 
829  private:
830   // The type which we are representing as an expression.
831   Type* type_;
832 };
833 
834 void
do_dump_expression(Ast_dump_context * ast_dump_context) const835 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
836 {
837   ast_dump_context->dump_type(this->type_);
838 }
839 
840 Expression*
make_type(Type * type,Location location)841 Expression::make_type(Type* type, Location location)
842 {
843   return new Type_expression(type, location);
844 }
845 
846 // Class Parser_expression.
847 
848 Type*
do_type()849 Parser_expression::do_type()
850 {
851   // We should never really ask for the type of a Parser_expression.
852   // However, it can happen, at least when we have an invalid const
853   // whose initializer refers to the const itself.  In that case we
854   // may ask for the type when lowering the const itself.
855   go_assert(saw_errors());
856   return Type::make_error_type();
857 }
858 
859 // Class Var_expression.
860 
861 // Lower a variable expression.  Here we just make sure that the
862 // initialization expression of the variable has been lowered.  This
863 // ensures that we will be able to determine the type of the variable
864 // if necessary.
865 
866 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)867 Var_expression::do_lower(Gogo* gogo, Named_object* function,
868 			 Statement_inserter* inserter, int)
869 {
870   if (this->variable_->is_variable())
871     {
872       Variable* var = this->variable_->var_value();
873       // This is either a local variable or a global variable.  A
874       // reference to a variable which is local to an enclosing
875       // function will be a reference to a field in a closure.
876       if (var->is_global())
877 	{
878 	  function = NULL;
879 	  inserter = NULL;
880 	}
881       var->lower_init_expression(gogo, function, inserter);
882     }
883   return this;
884 }
885 
886 // Return the type of a reference to a variable.
887 
888 Type*
do_type()889 Var_expression::do_type()
890 {
891   if (this->variable_->is_variable())
892     return this->variable_->var_value()->type();
893   else if (this->variable_->is_result_variable())
894     return this->variable_->result_var_value()->type();
895   else
896     go_unreachable();
897 }
898 
899 // Determine the type of a reference to a variable.
900 
901 void
do_determine_type(const Type_context *)902 Var_expression::do_determine_type(const Type_context*)
903 {
904   if (this->variable_->is_variable())
905     this->variable_->var_value()->determine_type();
906 }
907 
908 // Something takes the address of this variable.  This means that we
909 // may want to move the variable onto the heap.
910 
911 void
do_address_taken(bool escapes)912 Var_expression::do_address_taken(bool escapes)
913 {
914   if (!escapes)
915     {
916       if (this->variable_->is_variable())
917 	this->variable_->var_value()->set_non_escaping_address_taken();
918       else if (this->variable_->is_result_variable())
919 	this->variable_->result_var_value()->set_non_escaping_address_taken();
920       else
921 	go_unreachable();
922     }
923   else
924     {
925       if (this->variable_->is_variable())
926 	this->variable_->var_value()->set_address_taken();
927       else if (this->variable_->is_result_variable())
928 	this->variable_->result_var_value()->set_address_taken();
929       else
930 	go_unreachable();
931     }
932 
933   if (this->variable_->is_variable()
934       && this->variable_->var_value()->is_in_heap())
935     {
936       Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
937       Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
938     }
939 }
940 
941 // Export a reference to a variable.
942 
943 void
do_export(Export_function_body * efb) const944 Var_expression::do_export(Export_function_body* efb) const
945 {
946   Named_object* no = this->variable_;
947   if (no->is_result_variable() || !no->var_value()->is_global())
948     efb->write_string(Gogo::unpack_hidden_name(no->name()));
949   else
950     Expression::export_name(efb, no);
951 }
952 
953 // Get the backend representation for a reference to a variable.
954 
955 Bexpression*
do_get_backend(Translate_context * context)956 Var_expression::do_get_backend(Translate_context* context)
957 {
958   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
959 							  context->function());
960   bool is_in_heap;
961   Location loc = this->location();
962   Btype* btype;
963   Gogo* gogo = context->gogo();
964   if (this->variable_->is_variable())
965     {
966       is_in_heap = this->variable_->var_value()->is_in_heap();
967       btype = this->variable_->var_value()->type()->get_backend(gogo);
968     }
969   else if (this->variable_->is_result_variable())
970     {
971       is_in_heap = this->variable_->result_var_value()->is_in_heap();
972       btype = this->variable_->result_var_value()->type()->get_backend(gogo);
973     }
974   else
975     go_unreachable();
976 
977   Bexpression* ret =
978       context->backend()->var_expression(bvar, loc);
979   if (is_in_heap)
980     ret = context->backend()->indirect_expression(btype, ret, true, loc);
981   return ret;
982 }
983 
984 // Ast dump for variable expression.
985 
986 void
do_dump_expression(Ast_dump_context * ast_dump_context) const987 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
988 {
989   ast_dump_context->ostream() << this->variable_->message_name() ;
990 }
991 
992 // Make a reference to a variable in an expression.
993 
994 Expression*
make_var_reference(Named_object * var,Location location)995 Expression::make_var_reference(Named_object* var, Location location)
996 {
997   if (var->is_sink())
998     return Expression::make_sink(location);
999 
1000   // FIXME: Creating a new object for each reference to a variable is
1001   // wasteful.
1002   return new Var_expression(var, location);
1003 }
1004 
1005 // Class Enclosed_var_expression.
1006 
1007 int
do_traverse(Traverse *)1008 Enclosed_var_expression::do_traverse(Traverse*)
1009 {
1010   return TRAVERSE_CONTINUE;
1011 }
1012 
1013 // Lower the reference to the enclosed variable.
1014 
1015 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)1016 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
1017 				  Statement_inserter* inserter, int)
1018 {
1019   gogo->lower_expression(function, inserter, &this->reference_);
1020   return this;
1021 }
1022 
1023 // Flatten the reference to the enclosed variable.
1024 
1025 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)1026 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
1027 				    Statement_inserter* inserter)
1028 {
1029   gogo->flatten_expression(function, inserter, &this->reference_);
1030   return this;
1031 }
1032 
1033 void
do_address_taken(bool escapes)1034 Enclosed_var_expression::do_address_taken(bool escapes)
1035 {
1036   if (!escapes)
1037     {
1038       if (this->variable_->is_variable())
1039 	this->variable_->var_value()->set_non_escaping_address_taken();
1040       else if (this->variable_->is_result_variable())
1041 	this->variable_->result_var_value()->set_non_escaping_address_taken();
1042       else
1043 	go_unreachable();
1044     }
1045   else
1046     {
1047       if (this->variable_->is_variable())
1048 	this->variable_->var_value()->set_address_taken();
1049       else if (this->variable_->is_result_variable())
1050 	this->variable_->result_var_value()->set_address_taken();
1051       else
1052 	go_unreachable();
1053     }
1054 
1055   if (this->variable_->is_variable()
1056       && this->variable_->var_value()->is_in_heap())
1057     Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1058 }
1059 
1060 // Ast dump for enclosed variable expression.
1061 
1062 void
do_dump_expression(Ast_dump_context * adc) const1063 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
1064 {
1065   adc->ostream() << this->variable_->message_name();
1066 }
1067 
1068 // Make a reference to a variable within an enclosing function.
1069 
1070 Expression*
make_enclosing_var_reference(Expression * reference,Named_object * var,Location location)1071 Expression::make_enclosing_var_reference(Expression* reference,
1072 					 Named_object* var, Location location)
1073 {
1074   return new Enclosed_var_expression(reference, var, location);
1075 }
1076 
1077 // Class Temporary_reference_expression.
1078 
1079 // The type.
1080 
1081 Type*
do_type()1082 Temporary_reference_expression::do_type()
1083 {
1084   return this->statement_->type();
1085 }
1086 
1087 // Called if something takes the address of this temporary variable.
1088 // We never have to move temporary variables to the heap, but we do
1089 // need to know that they must live in the stack rather than in a
1090 // register.
1091 
1092 void
do_address_taken(bool)1093 Temporary_reference_expression::do_address_taken(bool)
1094 {
1095   this->statement_->set_is_address_taken();
1096 }
1097 
1098 // Export a reference to a temporary.
1099 
1100 void
do_export(Export_function_body * efb) const1101 Temporary_reference_expression::do_export(Export_function_body* efb) const
1102 {
1103   unsigned int idx = efb->temporary_index(this->statement_);
1104   char buf[50];
1105   snprintf(buf, sizeof buf, "$t%u", idx);
1106   efb->write_c_string(buf);
1107 }
1108 
1109 // Import a reference to a temporary.
1110 
1111 Expression*
do_import(Import_function_body * ifb,Location loc)1112 Temporary_reference_expression::do_import(Import_function_body* ifb,
1113 					  Location loc)
1114 {
1115   std::string id = ifb->read_identifier();
1116   go_assert(id[0] == '$' && id[1] == 't');
1117   const char *p = id.c_str();
1118   char *end;
1119   long idx = strtol(p + 2, &end, 10);
1120   if (*end != '\0' || idx > 0x7fffffff)
1121     {
1122       if (!ifb->saw_error())
1123 	go_error_at(loc,
1124 		    ("invalid export data for %qs: "
1125 		     "invalid temporary reference index at %lu"),
1126 		    ifb->name().c_str(),
1127 		    static_cast<unsigned long>(ifb->off()));
1128       ifb->set_saw_error();
1129       return Expression::make_error(loc);
1130     }
1131 
1132   Temporary_statement* temp =
1133     ifb->temporary_statement(static_cast<unsigned int>(idx));
1134   if (temp == NULL)
1135     {
1136       if (!ifb->saw_error())
1137 	go_error_at(loc,
1138 		    ("invalid export data for %qs: "
1139 		     "undefined temporary reference index at %lu"),
1140 		    ifb->name().c_str(),
1141 		    static_cast<unsigned long>(ifb->off()));
1142       ifb->set_saw_error();
1143       return Expression::make_error(loc);
1144     }
1145 
1146   return Expression::make_temporary_reference(temp, loc);
1147 }
1148 
1149 // Get a backend expression referring to the variable.
1150 
1151 Bexpression*
do_get_backend(Translate_context * context)1152 Temporary_reference_expression::do_get_backend(Translate_context* context)
1153 {
1154   Gogo* gogo = context->gogo();
1155   Bvariable* bvar = this->statement_->get_backend_variable(context);
1156   Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
1157 
1158   // The backend can't always represent the same set of recursive types
1159   // that the Go frontend can.  In some cases this means that a
1160   // temporary variable won't have the right backend type.  Correct
1161   // that here by adding a type cast.  We need to use base() to push
1162   // the circularity down one level.
1163   Type* stype = this->statement_->type();
1164   if (!this->is_lvalue_
1165       && stype->points_to() != NULL
1166       && stype->points_to()->is_void_type())
1167     {
1168       Btype* btype = this->type()->base()->get_backend(gogo);
1169       ret = gogo->backend()->convert_expression(btype, ret, this->location());
1170     }
1171   return ret;
1172 }
1173 
1174 // Ast dump for temporary reference.
1175 
1176 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1177 Temporary_reference_expression::do_dump_expression(
1178                                 Ast_dump_context* ast_dump_context) const
1179 {
1180   ast_dump_context->dump_temp_variable_name(this->statement_);
1181 }
1182 
1183 // Make a reference to a temporary variable.
1184 
1185 Temporary_reference_expression*
make_temporary_reference(Temporary_statement * statement,Location location)1186 Expression::make_temporary_reference(Temporary_statement* statement,
1187 				     Location location)
1188 {
1189   statement->add_use();
1190   return new Temporary_reference_expression(statement, location);
1191 }
1192 
1193 // Class Set_and_use_temporary_expression.
1194 
1195 // Return the type.
1196 
1197 Type*
do_type()1198 Set_and_use_temporary_expression::do_type()
1199 {
1200   return this->statement_->type();
1201 }
1202 
1203 // Determine the type of the expression.
1204 
1205 void
do_determine_type(const Type_context * context)1206 Set_and_use_temporary_expression::do_determine_type(
1207     const Type_context* context)
1208 {
1209   this->expr_->determine_type(context);
1210 }
1211 
1212 // Take the address.
1213 
1214 void
do_address_taken(bool)1215 Set_and_use_temporary_expression::do_address_taken(bool)
1216 {
1217   this->statement_->set_is_address_taken();
1218 }
1219 
1220 // Return the backend representation.
1221 
1222 Bexpression*
do_get_backend(Translate_context * context)1223 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
1224 {
1225   Location loc = this->location();
1226   Gogo* gogo = context->gogo();
1227   Bvariable* bvar = this->statement_->get_backend_variable(context);
1228   Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
1229 
1230   Named_object* fn = context->function();
1231   go_assert(fn != NULL);
1232   Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
1233   Bexpression* bexpr = this->expr_->get_backend(context);
1234   Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
1235                                                           bexpr, loc);
1236   Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
1237   Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
1238   return ret;
1239 }
1240 
1241 // Dump.
1242 
1243 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1244 Set_and_use_temporary_expression::do_dump_expression(
1245     Ast_dump_context* ast_dump_context) const
1246 {
1247   ast_dump_context->ostream() << '(';
1248   ast_dump_context->dump_temp_variable_name(this->statement_);
1249   ast_dump_context->ostream() << " = ";
1250   this->expr_->dump_expression(ast_dump_context);
1251   ast_dump_context->ostream() << ')';
1252 }
1253 
1254 // Make a set-and-use temporary.
1255 
1256 Set_and_use_temporary_expression*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)1257 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1258 				       Expression* expr, Location location)
1259 {
1260   return new Set_and_use_temporary_expression(statement, expr, location);
1261 }
1262 
1263 // A sink expression--a use of the blank identifier _.
1264 
1265 class Sink_expression : public Expression
1266 {
1267  public:
Sink_expression(Location location)1268   Sink_expression(Location location)
1269     : Expression(EXPRESSION_SINK, location),
1270       type_(NULL), bvar_(NULL)
1271   { }
1272 
1273  protected:
1274   bool
do_discarding_value()1275   do_discarding_value()
1276   { return true; }
1277 
1278   Type*
1279   do_type();
1280 
1281   void
1282   do_determine_type(const Type_context*);
1283 
1284   Expression*
do_copy()1285   do_copy()
1286   { return new Sink_expression(this->location()); }
1287 
1288   Bexpression*
1289   do_get_backend(Translate_context*);
1290 
1291   void
1292   do_dump_expression(Ast_dump_context*) const;
1293 
1294  private:
1295   // The type of this sink variable.
1296   Type* type_;
1297   // The temporary variable we generate.
1298   Bvariable* bvar_;
1299 };
1300 
1301 // Return the type of a sink expression.
1302 
1303 Type*
do_type()1304 Sink_expression::do_type()
1305 {
1306   if (this->type_ == NULL)
1307     return Type::make_sink_type();
1308   return this->type_;
1309 }
1310 
1311 // Determine the type of a sink expression.
1312 
1313 void
do_determine_type(const Type_context * context)1314 Sink_expression::do_determine_type(const Type_context* context)
1315 {
1316   if (context->type != NULL)
1317     this->type_ = context->type;
1318 }
1319 
1320 // Return a temporary variable for a sink expression.  This will
1321 // presumably be a write-only variable which the middle-end will drop.
1322 
1323 Bexpression*
do_get_backend(Translate_context * context)1324 Sink_expression::do_get_backend(Translate_context* context)
1325 {
1326   Location loc = this->location();
1327   Gogo* gogo = context->gogo();
1328   if (this->bvar_ == NULL)
1329     {
1330       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1331       Named_object* fn = context->function();
1332       go_assert(fn != NULL);
1333       Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1334       Btype* bt = this->type_->get_backend(context->gogo());
1335       Bstatement* decl;
1336       this->bvar_ =
1337 	gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1338 					    false, loc, &decl);
1339       Bexpression* var_ref =
1340           gogo->backend()->var_expression(this->bvar_, loc);
1341       var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1342       return var_ref;
1343     }
1344   return gogo->backend()->var_expression(this->bvar_, loc);
1345 }
1346 
1347 // Ast dump for sink expression.
1348 
1349 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1350 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1351 {
1352   ast_dump_context->ostream() << "_" ;
1353 }
1354 
1355 // Make a sink expression.
1356 
1357 Expression*
make_sink(Location location)1358 Expression::make_sink(Location location)
1359 {
1360   return new Sink_expression(location);
1361 }
1362 
1363 // Class Func_expression.
1364 
1365 // FIXME: Can a function expression appear in a constant expression?
1366 // The value is unchanging.  Initializing a constant to the address of
1367 // a function seems like it could work, though there might be little
1368 // point to it.
1369 
1370 // Traversal.
1371 
1372 int
do_traverse(Traverse * traverse)1373 Func_expression::do_traverse(Traverse* traverse)
1374 {
1375   return (this->closure_ == NULL
1376 	  ? TRAVERSE_CONTINUE
1377 	  : Expression::traverse(&this->closure_, traverse));
1378 }
1379 
1380 // Return the type of a function expression.
1381 
1382 Type*
do_type()1383 Func_expression::do_type()
1384 {
1385   if (this->function_->is_function())
1386     return this->function_->func_value()->type();
1387   else if (this->function_->is_function_declaration())
1388     return this->function_->func_declaration_value()->type();
1389   else
1390     go_unreachable();
1391 }
1392 
1393 // Get the backend representation for the code of a function expression.
1394 
1395 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1396 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1397 {
1398   Function_type* fntype;
1399   if (no->is_function())
1400     fntype = no->func_value()->type();
1401   else if (no->is_function_declaration())
1402     fntype = no->func_declaration_value()->type();
1403   else
1404     go_unreachable();
1405 
1406   // Builtin functions are handled specially by Call_expression.  We
1407   // can't take their address.
1408   if (fntype->is_builtin())
1409     {
1410       go_error_at(loc,
1411 		  ("invalid use of special built-in function %qs; "
1412 		   "must be called"),
1413 		  no->message_name().c_str());
1414       return gogo->backend()->error_expression();
1415     }
1416 
1417   Bfunction* fndecl;
1418   if (no->is_function())
1419     fndecl = no->func_value()->get_or_make_decl(gogo, no);
1420   else if (no->is_function_declaration())
1421     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1422   else
1423     go_unreachable();
1424 
1425   return gogo->backend()->function_code_expression(fndecl, loc);
1426 }
1427 
1428 // Get the backend representation for a function expression.  This is used when
1429 // we take the address of a function rather than simply calling it.  A func
1430 // value is represented as a pointer to a block of memory.  The first
1431 // word of that memory is a pointer to the function code.  The
1432 // remaining parts of that memory are the addresses of variables that
1433 // the function closes over.
1434 
1435 Bexpression*
do_get_backend(Translate_context * context)1436 Func_expression::do_get_backend(Translate_context* context)
1437 {
1438   // If there is no closure, just use the function descriptor.
1439   if (this->closure_ == NULL)
1440     {
1441       Gogo* gogo = context->gogo();
1442       Named_object* no = this->function_;
1443       Expression* descriptor;
1444       if (no->is_function())
1445 	descriptor = no->func_value()->descriptor(gogo, no);
1446       else if (no->is_function_declaration())
1447 	{
1448 	  if (no->func_declaration_value()->type()->is_builtin())
1449 	    {
1450 	      go_error_at(this->location(),
1451 			  ("invalid use of special built-in function %qs; "
1452 			   "must be called"),
1453 			  no->message_name().c_str());
1454 	      return gogo->backend()->error_expression();
1455 	    }
1456 	  descriptor = no->func_declaration_value()->descriptor(gogo, no);
1457 	}
1458       else
1459 	go_unreachable();
1460 
1461       Bexpression* bdesc = descriptor->get_backend(context);
1462       return gogo->backend()->address_expression(bdesc, this->location());
1463     }
1464 
1465   go_assert(this->function_->func_value()->enclosing() != NULL);
1466 
1467   // If there is a closure, then the closure is itself the function
1468   // expression.  It is a pointer to a struct whose first field points
1469   // to the function code and whose remaining fields are the addresses
1470   // of the closed-over variables.
1471   Bexpression *bexpr = this->closure_->get_backend(context);
1472 
1473   // Introduce a backend type conversion, to account for any differences
1474   // between the argument type (function descriptor, struct with a
1475   // single field) and the closure (struct with multiple fields).
1476   Gogo* gogo = context->gogo();
1477   Btype *btype = this->type()->get_backend(gogo);
1478   return gogo->backend()->convert_expression(btype, bexpr, this->location());
1479 }
1480 
1481 // The cost of inlining a function reference.
1482 
1483 int
do_inlining_cost() const1484 Func_expression::do_inlining_cost() const
1485 {
1486   // FIXME: We don't inline references to nested functions.
1487   if (this->closure_ != NULL)
1488     return 0x100000;
1489   if (this->function_->is_function()
1490       && this->function_->func_value()->enclosing() != NULL)
1491     return 0x100000;
1492 
1493   return 1;
1494 }
1495 
1496 // Export a reference to a function.
1497 
1498 void
do_export(Export_function_body * efb) const1499 Func_expression::do_export(Export_function_body* efb) const
1500 {
1501   Expression::export_name(efb, this->function_);
1502 }
1503 
1504 // Ast dump for function.
1505 
1506 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1507 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1508 {
1509   ast_dump_context->ostream() << this->function_->name();
1510   if (this->closure_ != NULL)
1511     {
1512       ast_dump_context->ostream() << " {closure =  ";
1513       this->closure_->dump_expression(ast_dump_context);
1514       ast_dump_context->ostream() << "}";
1515     }
1516 }
1517 
1518 // Make a reference to a function in an expression.
1519 
1520 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1521 Expression::make_func_reference(Named_object* function, Expression* closure,
1522 				Location location)
1523 {
1524   Func_expression* fe = new Func_expression(function, closure, location);
1525 
1526   // Detect references to builtin functions and set the runtime code if
1527   // appropriate.
1528   if (function->is_function_declaration())
1529     fe->set_runtime_code(Runtime::name_to_code(function->name()));
1530   return fe;
1531 }
1532 
1533 // Class Func_descriptor_expression.
1534 
1535 // Constructor.
1536 
Func_descriptor_expression(Named_object * fn)1537 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1538   : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1539     fn_(fn), dvar_(NULL)
1540 {
1541   go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1542 }
1543 
1544 // Traversal.
1545 
1546 int
do_traverse(Traverse *)1547 Func_descriptor_expression::do_traverse(Traverse*)
1548 {
1549   return TRAVERSE_CONTINUE;
1550 }
1551 
1552 // All function descriptors have the same type.
1553 
1554 Type* Func_descriptor_expression::descriptor_type;
1555 
1556 void
make_func_descriptor_type()1557 Func_descriptor_expression::make_func_descriptor_type()
1558 {
1559   if (Func_descriptor_expression::descriptor_type != NULL)
1560     return;
1561   Type* uintptr_type = Type::lookup_integer_type("uintptr");
1562   Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1563   Func_descriptor_expression::descriptor_type =
1564     Type::make_builtin_named_type("functionDescriptor", struct_type);
1565 }
1566 
1567 Type*
do_type()1568 Func_descriptor_expression::do_type()
1569 {
1570   Func_descriptor_expression::make_func_descriptor_type();
1571   return Func_descriptor_expression::descriptor_type;
1572 }
1573 
1574 // The backend representation for a function descriptor.
1575 
1576 Bexpression*
do_get_backend(Translate_context * context)1577 Func_descriptor_expression::do_get_backend(Translate_context* context)
1578 {
1579   Named_object* no = this->fn_;
1580   Location loc = no->location();
1581   if (this->dvar_ != NULL)
1582     return context->backend()->var_expression(this->dvar_, loc);
1583 
1584   Gogo* gogo = context->gogo();
1585   std::string var_name(gogo->function_descriptor_name(no));
1586   bool is_descriptor = false;
1587   if (no->is_function_declaration()
1588       && !no->func_declaration_value()->asm_name().empty()
1589       && Linemap::is_predeclared_location(no->location()))
1590     is_descriptor = true;
1591 
1592   // The runtime package implements some functions defined in the
1593   // syscall package.  Let the syscall package define the descriptor
1594   // in this case.
1595   if (gogo->compiling_runtime()
1596       && gogo->package_name() == "runtime"
1597       && no->is_function()
1598       && !no->func_value()->asm_name().empty()
1599       && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1600     is_descriptor = true;
1601 
1602   Btype* btype = this->type()->get_backend(gogo);
1603 
1604   Bvariable* bvar;
1605   std::string asm_name(go_selectively_encode_id(var_name));
1606   if (no->package() != NULL || is_descriptor)
1607     bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1608                                                           btype, loc);
1609   else
1610     {
1611       Location bloc = Linemap::predeclared_location();
1612 
1613       // The runtime package has hash/equality functions that are
1614       // referenced by type descriptors outside of the runtime, so the
1615       // function descriptors must be visible even though they are not
1616       // exported.
1617       bool is_exported_runtime = false;
1618       if (gogo->compiling_runtime()
1619 	  && gogo->package_name() == "runtime"
1620 	  && (no->name().find("hash") != std::string::npos
1621 	      || no->name().find("equal") != std::string::npos))
1622 	is_exported_runtime = true;
1623 
1624       bool is_hidden = ((no->is_function()
1625 			 && no->func_value()->enclosing() != NULL)
1626 			|| (Gogo::is_hidden_name(no->name())
1627 			    && !is_exported_runtime)
1628 			|| Gogo::is_thunk(no));
1629 
1630       if (no->is_function() && no->func_value()->is_referenced_by_inline())
1631 	is_hidden = false;
1632 
1633       bvar = context->backend()->immutable_struct(var_name, asm_name,
1634                                                   is_hidden, false,
1635 						  btype, bloc);
1636       Expression_list* vals = new Expression_list();
1637       vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1638       Expression* init =
1639 	Expression::make_struct_composite_literal(this->type(), vals, bloc);
1640       Translate_context bcontext(gogo, NULL, NULL, NULL);
1641       bcontext.set_is_const();
1642       Bexpression* binit = init->get_backend(&bcontext);
1643       context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1644 						    false, btype, bloc, binit);
1645     }
1646 
1647   this->dvar_ = bvar;
1648   return gogo->backend()->var_expression(bvar, loc);
1649 }
1650 
1651 // Print a function descriptor expression.
1652 
1653 void
do_dump_expression(Ast_dump_context * context) const1654 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1655 {
1656   context->ostream() << "[descriptor " << this->fn_->name() << "]";
1657 }
1658 
1659 // Make a function descriptor expression.
1660 
1661 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1662 Expression::make_func_descriptor(Named_object* fn)
1663 {
1664   return new Func_descriptor_expression(fn);
1665 }
1666 
1667 // Make the function descriptor type, so that it can be converted.
1668 
1669 void
make_func_descriptor_type()1670 Expression::make_func_descriptor_type()
1671 {
1672   Func_descriptor_expression::make_func_descriptor_type();
1673 }
1674 
1675 // A reference to just the code of a function.
1676 
1677 class Func_code_reference_expression : public Expression
1678 {
1679  public:
Func_code_reference_expression(Named_object * function,Location location)1680   Func_code_reference_expression(Named_object* function, Location location)
1681     : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1682       function_(function)
1683   { }
1684 
1685  protected:
1686   int
do_traverse(Traverse *)1687   do_traverse(Traverse*)
1688   { return TRAVERSE_CONTINUE; }
1689 
1690   bool
do_is_static_initializer() const1691   do_is_static_initializer() const
1692   { return true; }
1693 
1694   Type*
do_type()1695   do_type()
1696   { return Type::make_pointer_type(Type::make_void_type()); }
1697 
1698   void
do_determine_type(const Type_context *)1699   do_determine_type(const Type_context*)
1700   { }
1701 
1702   Expression*
do_copy()1703   do_copy()
1704   {
1705     return Expression::make_func_code_reference(this->function_,
1706 						this->location());
1707   }
1708 
1709   Bexpression*
1710   do_get_backend(Translate_context*);
1711 
1712   void
do_dump_expression(Ast_dump_context * context) const1713   do_dump_expression(Ast_dump_context* context) const
1714   { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1715 
1716  private:
1717   // The function.
1718   Named_object* function_;
1719 };
1720 
1721 // Get the backend representation for a reference to function code.
1722 
1723 Bexpression*
do_get_backend(Translate_context * context)1724 Func_code_reference_expression::do_get_backend(Translate_context* context)
1725 {
1726   return Func_expression::get_code_pointer(context->gogo(), this->function_,
1727 					   this->location());
1728 }
1729 
1730 // Make a reference to the code of a function.
1731 
1732 Expression*
make_func_code_reference(Named_object * function,Location location)1733 Expression::make_func_code_reference(Named_object* function, Location location)
1734 {
1735   return new Func_code_reference_expression(function, location);
1736 }
1737 
1738 // Class Unknown_expression.
1739 
1740 // Return the name of an unknown expression.
1741 
1742 const std::string&
name() const1743 Unknown_expression::name() const
1744 {
1745   return this->named_object_->name();
1746 }
1747 
1748 // Lower a reference to an unknown name.
1749 
1750 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1751 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1752 {
1753   Location location = this->location();
1754   Named_object* no = this->named_object_;
1755   Named_object* real;
1756   if (!no->is_unknown())
1757     real = no;
1758   else
1759     {
1760       real = no->unknown_value()->real_named_object();
1761       if (real == NULL)
1762 	{
1763 	  if (!this->no_error_message_)
1764 	    go_error_at(location, "reference to undefined name %qs",
1765 			this->named_object_->message_name().c_str());
1766 	  return Expression::make_error(location);
1767 	}
1768     }
1769   switch (real->classification())
1770     {
1771     case Named_object::NAMED_OBJECT_CONST:
1772       return Expression::make_const_reference(real, location);
1773     case Named_object::NAMED_OBJECT_TYPE:
1774       return Expression::make_type(real->type_value(), location);
1775     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1776       if (!this->no_error_message_)
1777 	go_error_at(location, "reference to undefined type %qs",
1778 		    real->message_name().c_str());
1779       return Expression::make_error(location);
1780     case Named_object::NAMED_OBJECT_VAR:
1781       real->var_value()->set_is_used();
1782       return Expression::make_var_reference(real, location);
1783     case Named_object::NAMED_OBJECT_FUNC:
1784     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1785       return Expression::make_func_reference(real, NULL, location);
1786     case Named_object::NAMED_OBJECT_PACKAGE:
1787       if (!this->no_error_message_)
1788 	go_error_at(location, "unexpected reference to package");
1789       return Expression::make_error(location);
1790     default:
1791       go_unreachable();
1792     }
1793 }
1794 
1795 // Dump the ast representation for an unknown expression to a dump context.
1796 
1797 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1798 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1799 {
1800   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1801 			      << ")";
1802 }
1803 
1804 // Make a reference to an unknown name.
1805 
1806 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1807 Expression::make_unknown_reference(Named_object* no, Location location)
1808 {
1809   return new Unknown_expression(no, location);
1810 }
1811 
1812 // A boolean expression.
1813 
1814 class Boolean_expression : public Expression
1815 {
1816  public:
Boolean_expression(bool val,Location location)1817   Boolean_expression(bool val, Location location)
1818     : Expression(EXPRESSION_BOOLEAN, location),
1819       val_(val), type_(NULL)
1820   { }
1821 
1822   static Expression*
1823   do_import(Import_expression*, Location);
1824 
1825  protected:
1826   int
1827   do_traverse(Traverse*);
1828 
1829   bool
do_is_constant() const1830   do_is_constant() const
1831   { return true; }
1832 
1833   bool
do_is_zero_value() const1834   do_is_zero_value() const
1835   { return this->val_ == false; }
1836 
1837   bool
do_boolean_constant_value(bool * val) const1838   do_boolean_constant_value(bool* val) const
1839   {
1840     *val = this->val_;
1841     return true;
1842   }
1843 
1844   bool
do_is_static_initializer() const1845   do_is_static_initializer() const
1846   { return true; }
1847 
1848   Type*
1849   do_type();
1850 
1851   void
1852   do_determine_type(const Type_context*);
1853 
1854   Expression*
do_copy()1855   do_copy()
1856   { return this; }
1857 
1858   Bexpression*
do_get_backend(Translate_context * context)1859   do_get_backend(Translate_context* context)
1860   { return context->backend()->boolean_constant_expression(this->val_); }
1861 
1862   int
do_inlining_cost() const1863   do_inlining_cost() const
1864   { return 1; }
1865 
1866   void
do_export(Export_function_body * efb) const1867   do_export(Export_function_body* efb) const
1868   { efb->write_c_string(this->val_ ? "$true" : "$false"); }
1869 
1870   void
do_dump_expression(Ast_dump_context * ast_dump_context) const1871   do_dump_expression(Ast_dump_context* ast_dump_context) const
1872   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1873 
1874  private:
1875   // The constant.
1876   bool val_;
1877   // The type as determined by context.
1878   Type* type_;
1879 };
1880 
1881 // Traverse a boolean expression.  We just need to traverse the type
1882 // if there is one.
1883 
1884 int
do_traverse(Traverse * traverse)1885 Boolean_expression::do_traverse(Traverse* traverse)
1886 {
1887   if (this->type_ != NULL)
1888     return Type::traverse(this->type_, traverse);
1889   return TRAVERSE_CONTINUE;
1890 }
1891 
1892 // Get the type.
1893 
1894 Type*
do_type()1895 Boolean_expression::do_type()
1896 {
1897   if (this->type_ == NULL)
1898     this->type_ = Type::make_boolean_type();
1899   return this->type_;
1900 }
1901 
1902 // Set the type from the context.
1903 
1904 void
do_determine_type(const Type_context * context)1905 Boolean_expression::do_determine_type(const Type_context* context)
1906 {
1907   if (this->type_ != NULL && !this->type_->is_abstract())
1908     ;
1909   else if (context->type != NULL && context->type->is_boolean_type())
1910     this->type_ = context->type;
1911   else if (!context->may_be_abstract)
1912     this->type_ = Type::lookup_bool_type();
1913 }
1914 
1915 // Import a boolean constant.
1916 
1917 Expression*
do_import(Import_expression * imp,Location loc)1918 Boolean_expression::do_import(Import_expression* imp, Location loc)
1919 {
1920   if (imp->version() >= EXPORT_FORMAT_V3)
1921     imp->require_c_string("$");
1922   if (imp->peek_char() == 't')
1923     {
1924       imp->require_c_string("true");
1925       return Expression::make_boolean(true, loc);
1926     }
1927   else
1928     {
1929       imp->require_c_string("false");
1930       return Expression::make_boolean(false, loc);
1931     }
1932 }
1933 
1934 // Make a boolean expression.
1935 
1936 Expression*
make_boolean(bool val,Location location)1937 Expression::make_boolean(bool val, Location location)
1938 {
1939   return new Boolean_expression(val, location);
1940 }
1941 
1942 // Class String_expression.
1943 
1944 // Traverse a string expression.  We just need to traverse the type
1945 // if there is one.
1946 
1947 int
do_traverse(Traverse * traverse)1948 String_expression::do_traverse(Traverse* traverse)
1949 {
1950   if (this->type_ != NULL)
1951     return Type::traverse(this->type_, traverse);
1952   return TRAVERSE_CONTINUE;
1953 }
1954 
1955 // Get the type.
1956 
1957 Type*
do_type()1958 String_expression::do_type()
1959 {
1960   if (this->type_ == NULL)
1961     this->type_ = Type::make_string_type();
1962   return this->type_;
1963 }
1964 
1965 // Set the type from the context.
1966 
1967 void
do_determine_type(const Type_context * context)1968 String_expression::do_determine_type(const Type_context* context)
1969 {
1970   if (this->type_ != NULL && !this->type_->is_abstract())
1971     ;
1972   else if (context->type != NULL && context->type->is_string_type())
1973     this->type_ = context->type;
1974   else if (!context->may_be_abstract)
1975     this->type_ = Type::lookup_string_type();
1976 }
1977 
1978 // Build a string constant.
1979 
1980 Bexpression*
do_get_backend(Translate_context * context)1981 String_expression::do_get_backend(Translate_context* context)
1982 {
1983   Gogo* gogo = context->gogo();
1984   Btype* btype = Type::make_string_type()->get_backend(gogo);
1985 
1986   Location loc = this->location();
1987   std::vector<Bexpression*> init(2);
1988   Bexpression* str_cst =
1989       gogo->backend()->string_constant_expression(this->val_);
1990   init[0] = gogo->backend()->address_expression(str_cst, loc);
1991 
1992   Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1993   mpz_t lenval;
1994   mpz_init_set_ui(lenval, this->val_.length());
1995   init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1996   mpz_clear(lenval);
1997 
1998   return gogo->backend()->constructor_expression(btype, init, loc);
1999 }
2000 
2001  // Write string literal to string dump.
2002 
2003 void
export_string(String_dump * exp,const String_expression * str)2004 String_expression::export_string(String_dump* exp,
2005 				 const String_expression* str)
2006 {
2007   std::string s;
2008   s.reserve(str->val_.length() * 4 + 2);
2009   s += '"';
2010   for (std::string::const_iterator p = str->val_.begin();
2011        p != str->val_.end();
2012        ++p)
2013     {
2014       if (*p == '\\' || *p == '"')
2015 	{
2016 	  s += '\\';
2017 	  s += *p;
2018 	}
2019       else if (*p >= 0x20 && *p < 0x7f)
2020 	s += *p;
2021       else if (*p == '\n')
2022 	s += "\\n";
2023       else if (*p == '\t')
2024 	s += "\\t";
2025       else
2026 	{
2027 	  s += "\\x";
2028 	  unsigned char c = *p;
2029 	  unsigned int dig = c >> 4;
2030 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2031 	  dig = c & 0xf;
2032 	  s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2033 	}
2034     }
2035   s += '"';
2036   exp->write_string(s);
2037 }
2038 
2039 // Export a string expression.
2040 
2041 void
do_export(Export_function_body * efb) const2042 String_expression::do_export(Export_function_body* efb) const
2043 {
2044   String_expression::export_string(efb, this);
2045 }
2046 
2047 // Import a string expression.
2048 
2049 Expression*
do_import(Import_expression * imp,Location loc)2050 String_expression::do_import(Import_expression* imp, Location loc)
2051 {
2052   imp->require_c_string("\"");
2053   std::string val;
2054   while (true)
2055     {
2056       int c = imp->get_char();
2057       if (c == '"' || c == -1)
2058 	break;
2059       if (c != '\\')
2060 	val += static_cast<char>(c);
2061       else
2062 	{
2063 	  c = imp->get_char();
2064 	  if (c == '\\' || c == '"')
2065 	    val += static_cast<char>(c);
2066 	  else if (c == 'n')
2067 	    val += '\n';
2068 	  else if (c == 't')
2069 	    val += '\t';
2070 	  else if (c == 'x')
2071 	    {
2072 	      c = imp->get_char();
2073 	      unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2074 	      c = imp->get_char();
2075 	      unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2076 	      char v = (vh << 4) | vl;
2077 	      val += v;
2078 	    }
2079 	  else
2080 	    {
2081 	      go_error_at(imp->location(), "bad string constant");
2082 	      return Expression::make_error(loc);
2083 	    }
2084 	}
2085     }
2086   return Expression::make_string(val, loc);
2087 }
2088 
2089 // Ast dump for string expression.
2090 
2091 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2092 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2093 {
2094   String_expression::export_string(ast_dump_context, this);
2095 }
2096 
2097 // Make a string expression with abstract string type (common case).
2098 
2099 Expression*
make_string(const std::string & val,Location location)2100 Expression::make_string(const std::string& val, Location location)
2101 {
2102   return new String_expression(val, NULL, location);
2103 }
2104 
2105 // Make a string expression with a specific string type.
2106 
2107 Expression*
make_string_typed(const std::string & val,Type * type,Location location)2108 Expression::make_string_typed(const std::string& val, Type* type, Location location)
2109 {
2110   return new String_expression(val, type, location);
2111 }
2112 
2113 // An expression that evaluates to some characteristic of a string.
2114 // This is used when indexing, bound-checking, or nil checking a string.
2115 
2116 class String_info_expression : public Expression
2117 {
2118  public:
String_info_expression(Expression * string,String_info string_info,Location location)2119   String_info_expression(Expression* string, String_info string_info,
2120                         Location location)
2121     : Expression(EXPRESSION_STRING_INFO, location),
2122       string_(string), string_info_(string_info)
2123   { }
2124 
2125  protected:
2126   Type*
2127   do_type();
2128 
2129   void
do_determine_type(const Type_context *)2130   do_determine_type(const Type_context*)
2131   { go_unreachable(); }
2132 
2133   Expression*
do_copy()2134   do_copy()
2135   {
2136     return new String_info_expression(this->string_->copy(), this->string_info_,
2137 				      this->location());
2138   }
2139 
2140   Bexpression*
2141   do_get_backend(Translate_context* context);
2142 
2143   void
2144   do_dump_expression(Ast_dump_context*) const;
2145 
2146   void
do_issue_nil_check()2147   do_issue_nil_check()
2148   { this->string_->issue_nil_check(); }
2149 
2150  private:
2151   // The string for which we are getting information.
2152   Expression* string_;
2153   // What information we want.
2154   String_info string_info_;
2155 };
2156 
2157 // Return the type of the string info.
2158 
2159 Type*
do_type()2160 String_info_expression::do_type()
2161 {
2162   switch (this->string_info_)
2163     {
2164     case STRING_INFO_DATA:
2165       {
2166 	Type* byte_type = Type::lookup_integer_type("uint8");
2167 	return Type::make_pointer_type(byte_type);
2168       }
2169     case STRING_INFO_LENGTH:
2170         return Type::lookup_integer_type("int");
2171     default:
2172       go_unreachable();
2173     }
2174 }
2175 
2176 // Return string information in GENERIC.
2177 
2178 Bexpression*
do_get_backend(Translate_context * context)2179 String_info_expression::do_get_backend(Translate_context* context)
2180 {
2181   Gogo* gogo = context->gogo();
2182 
2183   Bexpression* bstring = this->string_->get_backend(context);
2184   switch (this->string_info_)
2185     {
2186     case STRING_INFO_DATA:
2187     case STRING_INFO_LENGTH:
2188       return gogo->backend()->struct_field_expression(bstring,
2189 						      this->string_info_,
2190 						      this->location());
2191       break;
2192     default:
2193       go_unreachable();
2194     }
2195 }
2196 
2197 // Dump ast representation for a type info expression.
2198 
2199 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2200 String_info_expression::do_dump_expression(
2201     Ast_dump_context* ast_dump_context) const
2202 {
2203   ast_dump_context->ostream() << "stringinfo(";
2204   this->string_->dump_expression(ast_dump_context);
2205   ast_dump_context->ostream() << ",";
2206   ast_dump_context->ostream() <<
2207       (this->string_info_ == STRING_INFO_DATA ? "data"
2208     : this->string_info_ == STRING_INFO_LENGTH ? "length"
2209     : "unknown");
2210   ast_dump_context->ostream() << ")";
2211 }
2212 
2213 // Make a string info expression.
2214 
2215 Expression*
make_string_info(Expression * string,String_info string_info,Location location)2216 Expression::make_string_info(Expression* string, String_info string_info,
2217                             Location location)
2218 {
2219   return new String_info_expression(string, string_info, location);
2220 }
2221 
2222 // An expression that represents an string value: a struct with value pointer
2223 // and length fields.
2224 
2225 class String_value_expression : public Expression
2226 {
2227  public:
String_value_expression(Expression * valptr,Expression * len,Location location)2228   String_value_expression(Expression* valptr, Expression* len, Location location)
2229       : Expression(EXPRESSION_STRING_VALUE, location),
2230         valptr_(valptr), len_(len)
2231   { }
2232 
2233  protected:
2234   int
2235   do_traverse(Traverse*);
2236 
2237   Type*
do_type()2238   do_type()
2239   { return Type::make_string_type(); }
2240 
2241   void
do_determine_type(const Type_context *)2242   do_determine_type(const Type_context*)
2243   { go_unreachable(); }
2244 
2245   Expression*
do_copy()2246   do_copy()
2247   {
2248     return new String_value_expression(this->valptr_->copy(),
2249                                        this->len_->copy(),
2250                                        this->location());
2251   }
2252 
2253   Bexpression*
2254   do_get_backend(Translate_context* context);
2255 
2256   void
2257   do_dump_expression(Ast_dump_context*) const;
2258 
2259  private:
2260   // The value pointer.
2261   Expression* valptr_;
2262   // The length.
2263   Expression* len_;
2264 };
2265 
2266 int
do_traverse(Traverse * traverse)2267 String_value_expression::do_traverse(Traverse* traverse)
2268 {
2269   if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2270       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
2271     return TRAVERSE_EXIT;
2272   return TRAVERSE_CONTINUE;
2273 }
2274 
2275 Bexpression*
do_get_backend(Translate_context * context)2276 String_value_expression::do_get_backend(Translate_context* context)
2277 {
2278   std::vector<Bexpression*> vals(2);
2279   vals[0] = this->valptr_->get_backend(context);
2280   vals[1] = this->len_->get_backend(context);
2281 
2282   Gogo* gogo = context->gogo();
2283   Btype* btype = Type::make_string_type()->get_backend(gogo);
2284   return gogo->backend()->constructor_expression(btype, vals, this->location());
2285 }
2286 
2287 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2288 String_value_expression::do_dump_expression(
2289     Ast_dump_context* ast_dump_context) const
2290 {
2291   ast_dump_context->ostream() << "stringvalue(";
2292   ast_dump_context->ostream() << "value: ";
2293   this->valptr_->dump_expression(ast_dump_context);
2294   ast_dump_context->ostream() << ", length: ";
2295   this->len_->dump_expression(ast_dump_context);
2296   ast_dump_context->ostream() << ")";
2297 }
2298 
2299 Expression*
make_string_value(Expression * valptr,Expression * len,Location location)2300 Expression::make_string_value(Expression* valptr, Expression* len,
2301                               Location location)
2302 {
2303   return new String_value_expression(valptr, len, location);
2304 }
2305 
2306 // Make an integer expression.
2307 
2308 class Integer_expression : public Expression
2309 {
2310  public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)2311   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
2312 		     Location location)
2313     : Expression(EXPRESSION_INTEGER, location),
2314       type_(type), is_character_constant_(is_character_constant)
2315   { mpz_init_set(this->val_, *val); }
2316 
2317   static Expression*
2318   do_import(Import_expression*, Location);
2319 
2320   // Write VAL to string dump.
2321   static void
2322   export_integer(String_dump* exp, const mpz_t val);
2323 
2324   // Write VAL to dump context.
2325   static void
2326   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
2327 
2328  protected:
2329   int
2330   do_traverse(Traverse*);
2331 
2332   bool
do_is_constant() const2333   do_is_constant() const
2334   { return true; }
2335 
2336   bool
do_is_zero_value() const2337   do_is_zero_value() const
2338   { return mpz_sgn(this->val_) == 0; }
2339 
2340   bool
do_is_static_initializer() const2341   do_is_static_initializer() const
2342   { return true; }
2343 
2344   bool
2345   do_numeric_constant_value(Numeric_constant* nc) const;
2346 
2347   Type*
2348   do_type();
2349 
2350   void
2351   do_determine_type(const Type_context* context);
2352 
2353   void
2354   do_check_types(Gogo*);
2355 
2356   Bexpression*
2357   do_get_backend(Translate_context*);
2358 
2359   Expression*
do_copy()2360   do_copy()
2361   {
2362     if (this->is_character_constant_)
2363       return Expression::make_character(&this->val_,
2364 					(this->type_ == NULL
2365 					 ? NULL
2366 					 : this->type_->copy_expressions()),
2367 					this->location());
2368     else
2369       return Expression::make_integer_z(&this->val_,
2370 					(this->type_ == NULL
2371 					 ? NULL
2372 					 : this->type_->copy_expressions()),
2373 					this->location());
2374   }
2375 
2376   int
do_inlining_cost() const2377   do_inlining_cost() const
2378   { return 1; }
2379 
2380   void
2381   do_export(Export_function_body*) const;
2382 
2383   void
2384   do_dump_expression(Ast_dump_context*) const;
2385 
2386  private:
2387   // The integer value.
2388   mpz_t val_;
2389   // The type so far.
2390   Type* type_;
2391   // Whether this is a character constant.
2392   bool is_character_constant_;
2393 };
2394 
2395 // Traverse an integer expression.  We just need to traverse the type
2396 // if there is one.
2397 
2398 int
do_traverse(Traverse * traverse)2399 Integer_expression::do_traverse(Traverse* traverse)
2400 {
2401   if (this->type_ != NULL)
2402     return Type::traverse(this->type_, traverse);
2403   return TRAVERSE_CONTINUE;
2404 }
2405 
2406 // Return a numeric constant for this expression.  We have to mark
2407 // this as a character when appropriate.
2408 
2409 bool
do_numeric_constant_value(Numeric_constant * nc) const2410 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
2411 {
2412   if (this->is_character_constant_)
2413     nc->set_rune(this->type_, this->val_);
2414   else
2415     nc->set_int(this->type_, this->val_);
2416   return true;
2417 }
2418 
2419 // Return the current type.  If we haven't set the type yet, we return
2420 // an abstract integer type.
2421 
2422 Type*
do_type()2423 Integer_expression::do_type()
2424 {
2425   if (this->type_ == NULL)
2426     {
2427       if (this->is_character_constant_)
2428 	this->type_ = Type::make_abstract_character_type();
2429       else
2430 	this->type_ = Type::make_abstract_integer_type();
2431     }
2432   return this->type_;
2433 }
2434 
2435 // Set the type of the integer value.  Here we may switch from an
2436 // abstract type to a real type.
2437 
2438 void
do_determine_type(const Type_context * context)2439 Integer_expression::do_determine_type(const Type_context* context)
2440 {
2441   if (this->type_ != NULL && !this->type_->is_abstract())
2442     ;
2443   else if (context->type != NULL && context->type->is_numeric_type())
2444     this->type_ = context->type;
2445   else if (!context->may_be_abstract)
2446     {
2447       if (this->is_character_constant_)
2448 	this->type_ = Type::lookup_integer_type("int32");
2449       else
2450 	this->type_ = Type::lookup_integer_type("int");
2451     }
2452 }
2453 
2454 // Check the type of an integer constant.
2455 
2456 void
do_check_types(Gogo *)2457 Integer_expression::do_check_types(Gogo*)
2458 {
2459   Type* type = this->type_;
2460   if (type == NULL)
2461     return;
2462   Numeric_constant nc;
2463   if (this->is_character_constant_)
2464     nc.set_rune(NULL, this->val_);
2465   else
2466     nc.set_int(NULL, this->val_);
2467   if (!nc.set_type(type, true, this->location()))
2468     this->set_is_error();
2469 }
2470 
2471 // Get the backend representation for an integer constant.
2472 
2473 Bexpression*
do_get_backend(Translate_context * context)2474 Integer_expression::do_get_backend(Translate_context* context)
2475 {
2476   if (this->is_error_expression()
2477       || (this->type_ != NULL && this->type_->is_error_type()))
2478     {
2479       go_assert(saw_errors());
2480       return context->gogo()->backend()->error_expression();
2481     }
2482 
2483   Type* resolved_type = NULL;
2484   if (this->type_ != NULL && !this->type_->is_abstract())
2485     resolved_type = this->type_;
2486   else if (this->type_ != NULL && this->type_->float_type() != NULL)
2487     {
2488       // We are converting to an abstract floating point type.
2489       resolved_type = Type::lookup_float_type("float64");
2490     }
2491   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2492     {
2493       // We are converting to an abstract complex type.
2494       resolved_type = Type::lookup_complex_type("complex128");
2495     }
2496   else
2497     {
2498       // If we still have an abstract type here, then this is being
2499       // used in a constant expression which didn't get reduced for
2500       // some reason.  Use a type which will fit the value.  We use <,
2501       // not <=, because we need an extra bit for the sign bit.
2502       int bits = mpz_sizeinbase(this->val_, 2);
2503       Type* int_type = Type::lookup_integer_type("int");
2504       if (bits < int_type->integer_type()->bits())
2505 	resolved_type = int_type;
2506       else if (bits < 64)
2507         resolved_type = Type::lookup_integer_type("int64");
2508       else
2509         {
2510           if (!saw_errors())
2511             go_error_at(this->location(),
2512                         "unknown type for large integer constant");
2513           return context->gogo()->backend()->error_expression();
2514         }
2515     }
2516   Numeric_constant nc;
2517   nc.set_int(resolved_type, this->val_);
2518   return Expression::backend_numeric_constant_expression(context, &nc);
2519 }
2520 
2521 // Write VAL to export data.
2522 
2523 void
export_integer(String_dump * exp,const mpz_t val)2524 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2525 {
2526   char* s = mpz_get_str(NULL, 10, val);
2527   exp->write_c_string(s);
2528   free(s);
2529 }
2530 
2531 // Export an integer in a constant expression.
2532 
2533 void
do_export(Export_function_body * efb) const2534 Integer_expression::do_export(Export_function_body* efb) const
2535 {
2536   bool added_type = false;
2537   if (this->type_ != NULL
2538       && !this->type_->is_abstract()
2539       && this->type_ != efb->type_context())
2540     {
2541       efb->write_c_string("$convert(");
2542       efb->write_type(this->type_);
2543       efb->write_c_string(", ");
2544       added_type = true;
2545     }
2546 
2547   Integer_expression::export_integer(efb, this->val_);
2548   if (this->is_character_constant_)
2549     efb->write_c_string("'");
2550   // A trailing space lets us reliably identify the end of the number.
2551   efb->write_c_string(" ");
2552 
2553   if (added_type)
2554     efb->write_c_string(")");
2555 }
2556 
2557 // Import an integer, floating point, or complex value.  This handles
2558 // all these types because they all start with digits.
2559 
2560 Expression*
do_import(Import_expression * imp,Location loc)2561 Integer_expression::do_import(Import_expression* imp, Location loc)
2562 {
2563   std::string num = imp->read_identifier();
2564   imp->require_c_string(" ");
2565   if (!num.empty() && num[num.length() - 1] == 'i')
2566     {
2567       mpfr_t real;
2568       size_t plus_pos = num.find('+', 1);
2569       size_t minus_pos = num.find('-', 1);
2570       size_t pos;
2571       if (plus_pos == std::string::npos)
2572 	pos = minus_pos;
2573       else if (minus_pos == std::string::npos)
2574 	pos = plus_pos;
2575       else
2576 	{
2577 	  go_error_at(imp->location(), "bad number in import data: %qs",
2578 		      num.c_str());
2579 	  return Expression::make_error(loc);
2580 	}
2581       if (pos == std::string::npos)
2582 	mpfr_set_ui(real, 0, MPFR_RNDN);
2583       else
2584 	{
2585 	  std::string real_str = num.substr(0, pos);
2586 	  if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
2587 	    {
2588 	      go_error_at(imp->location(), "bad number in import data: %qs",
2589 			  real_str.c_str());
2590 	      return Expression::make_error(loc);
2591 	    }
2592 	}
2593 
2594       std::string imag_str;
2595       if (pos == std::string::npos)
2596 	imag_str = num;
2597       else
2598 	imag_str = num.substr(pos);
2599       imag_str = imag_str.substr(0, imag_str.size() - 1);
2600       mpfr_t imag;
2601       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
2602 	{
2603 	  go_error_at(imp->location(), "bad number in import data: %qs",
2604 		      imag_str.c_str());
2605 	  return Expression::make_error(loc);
2606 	}
2607       mpc_t cval;
2608       mpc_init2(cval, mpc_precision);
2609       mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2610       mpfr_clear(real);
2611       mpfr_clear(imag);
2612       Expression* ret = Expression::make_complex(&cval, NULL, loc);
2613       mpc_clear(cval);
2614       return ret;
2615     }
2616   else if (num.find('.') == std::string::npos
2617 	   && num.find('E') == std::string::npos)
2618     {
2619       bool is_character_constant = (!num.empty()
2620 				    && num[num.length() - 1] == '\'');
2621       if (is_character_constant)
2622 	num = num.substr(0, num.length() - 1);
2623       mpz_t val;
2624       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2625 	{
2626 	  go_error_at(imp->location(), "bad number in import data: %qs",
2627 		      num.c_str());
2628 	  return Expression::make_error(loc);
2629 	}
2630       Expression* ret;
2631       if (is_character_constant)
2632 	ret = Expression::make_character(&val, NULL, loc);
2633       else
2634 	ret = Expression::make_integer_z(&val, NULL, loc);
2635       mpz_clear(val);
2636       return ret;
2637     }
2638   else
2639     {
2640       mpfr_t val;
2641       if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
2642 	{
2643 	  go_error_at(imp->location(), "bad number in import data: %qs",
2644 		      num.c_str());
2645 	  return Expression::make_error(loc);
2646 	}
2647       Expression* ret = Expression::make_float(&val, NULL, loc);
2648       mpfr_clear(val);
2649       return ret;
2650     }
2651 }
2652 // Ast dump for integer expression.
2653 
2654 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2655 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2656 {
2657   if (this->is_character_constant_)
2658     ast_dump_context->ostream() << '\'';
2659   Integer_expression::export_integer(ast_dump_context, this->val_);
2660   if (this->is_character_constant_)
2661     ast_dump_context->ostream() << '\'';
2662 }
2663 
2664 // Build a new integer value from a multi-precision integer.
2665 
2666 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2667 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2668 {
2669   return new Integer_expression(val, type, false, location);
2670 }
2671 
2672 // Build a new integer value from an unsigned long.
2673 
2674 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2675 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2676 {
2677   mpz_t zval;
2678   mpz_init_set_ui(zval, val);
2679   Expression* ret = Expression::make_integer_z(&zval, type, location);
2680   mpz_clear(zval);
2681   return ret;
2682 }
2683 
2684 // Build a new integer value from a signed long.
2685 
2686 Expression*
make_integer_sl(long val,Type * type,Location location)2687 Expression::make_integer_sl(long val, Type *type, Location location)
2688 {
2689   mpz_t zval;
2690   mpz_init_set_si(zval, val);
2691   Expression* ret = Expression::make_integer_z(&zval, type, location);
2692   mpz_clear(zval);
2693   return ret;
2694 }
2695 
2696 // Store an int64_t in an uninitialized mpz_t.
2697 
2698 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2699 set_mpz_from_int64(mpz_t* zval, int64_t val)
2700 {
2701   if (val >= 0)
2702     {
2703       unsigned long ul = static_cast<unsigned long>(val);
2704       if (static_cast<int64_t>(ul) == val)
2705 	{
2706 	  mpz_init_set_ui(*zval, ul);
2707 	  return;
2708 	}
2709     }
2710   uint64_t uv;
2711   if (val >= 0)
2712     uv = static_cast<uint64_t>(val);
2713   else
2714     uv = static_cast<uint64_t>(- val);
2715   unsigned long ul = uv & 0xffffffffUL;
2716   mpz_init_set_ui(*zval, ul);
2717   mpz_t hval;
2718   mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2719   mpz_mul_2exp(hval, hval, 32);
2720   mpz_add(*zval, *zval, hval);
2721   mpz_clear(hval);
2722   if (val < 0)
2723     mpz_neg(*zval, *zval);
2724 }
2725 
2726 // Build a new integer value from an int64_t.
2727 
2728 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2729 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2730 {
2731   mpz_t zval;
2732   set_mpz_from_int64(&zval, val);
2733   Expression* ret = Expression::make_integer_z(&zval, type, location);
2734   mpz_clear(zval);
2735   return ret;
2736 }
2737 
2738 // Build a new character constant value.
2739 
2740 Expression*
make_character(const mpz_t * val,Type * type,Location location)2741 Expression::make_character(const mpz_t* val, Type* type, Location location)
2742 {
2743   return new Integer_expression(val, type, true, location);
2744 }
2745 
2746 // Floats.
2747 
2748 class Float_expression : public Expression
2749 {
2750  public:
Float_expression(const mpfr_t * val,Type * type,Location location)2751   Float_expression(const mpfr_t* val, Type* type, Location location)
2752     : Expression(EXPRESSION_FLOAT, location),
2753       type_(type)
2754   {
2755     mpfr_init_set(this->val_, *val, MPFR_RNDN);
2756   }
2757 
2758   // Write VAL to export data.
2759   static void
2760   export_float(String_dump* exp, const mpfr_t val);
2761 
2762   // Write VAL to dump file.
2763   static void
2764   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2765 
2766  protected:
2767   int
2768   do_traverse(Traverse*);
2769 
2770   bool
do_is_constant() const2771   do_is_constant() const
2772   { return true; }
2773 
2774   bool
do_is_zero_value() const2775   do_is_zero_value() const
2776   {
2777     return mpfr_zero_p(this->val_) != 0
2778            && mpfr_signbit(this->val_) == 0;
2779   }
2780 
2781   bool
do_is_static_initializer() const2782   do_is_static_initializer() const
2783   { return true; }
2784 
2785   bool
do_numeric_constant_value(Numeric_constant * nc) const2786   do_numeric_constant_value(Numeric_constant* nc) const
2787   {
2788     nc->set_float(this->type_, this->val_);
2789     return true;
2790   }
2791 
2792   Type*
2793   do_type();
2794 
2795   void
2796   do_determine_type(const Type_context*);
2797 
2798   void
2799   do_check_types(Gogo*);
2800 
2801   Expression*
do_copy()2802   do_copy()
2803   { return Expression::make_float(&this->val_,
2804 				  (this->type_ == NULL
2805 				   ? NULL
2806 				   : this->type_->copy_expressions()),
2807 				  this->location()); }
2808 
2809   Bexpression*
2810   do_get_backend(Translate_context*);
2811 
2812   int
do_inlining_cost() const2813   do_inlining_cost() const
2814   { return 1; }
2815 
2816   void
2817   do_export(Export_function_body*) const;
2818 
2819   void
2820   do_dump_expression(Ast_dump_context*) const;
2821 
2822  private:
2823   // The floating point value.
2824   mpfr_t val_;
2825   // The type so far.
2826   Type* type_;
2827 };
2828 
2829 // Traverse a float expression.  We just need to traverse the type if
2830 // there is one.
2831 
2832 int
do_traverse(Traverse * traverse)2833 Float_expression::do_traverse(Traverse* traverse)
2834 {
2835   if (this->type_ != NULL)
2836     return Type::traverse(this->type_, traverse);
2837   return TRAVERSE_CONTINUE;
2838 }
2839 
2840 // Return the current type.  If we haven't set the type yet, we return
2841 // an abstract float type.
2842 
2843 Type*
do_type()2844 Float_expression::do_type()
2845 {
2846   if (this->type_ == NULL)
2847     this->type_ = Type::make_abstract_float_type();
2848   return this->type_;
2849 }
2850 
2851 // Set the type of the float value.  Here we may switch from an
2852 // abstract type to a real type.
2853 
2854 void
do_determine_type(const Type_context * context)2855 Float_expression::do_determine_type(const Type_context* context)
2856 {
2857   if (this->type_ != NULL && !this->type_->is_abstract())
2858     ;
2859   else if (context->type != NULL
2860 	   && (context->type->integer_type() != NULL
2861 	       || context->type->float_type() != NULL
2862 	       || context->type->complex_type() != NULL))
2863     this->type_ = context->type;
2864   else if (!context->may_be_abstract)
2865     this->type_ = Type::lookup_float_type("float64");
2866 }
2867 
2868 // Check the type of a float value.
2869 
2870 void
do_check_types(Gogo *)2871 Float_expression::do_check_types(Gogo*)
2872 {
2873   Type* type = this->type_;
2874   if (type == NULL)
2875     return;
2876   Numeric_constant nc;
2877   nc.set_float(NULL, this->val_);
2878   if (!nc.set_type(this->type_, true, this->location()))
2879     this->set_is_error();
2880 }
2881 
2882 // Get the backend representation for a float constant.
2883 
2884 Bexpression*
do_get_backend(Translate_context * context)2885 Float_expression::do_get_backend(Translate_context* context)
2886 {
2887   if (this->is_error_expression()
2888       || (this->type_ != NULL && this->type_->is_error_type()))
2889     {
2890       go_assert(saw_errors());
2891       return context->gogo()->backend()->error_expression();
2892     }
2893 
2894   Type* resolved_type;
2895   if (this->type_ != NULL && !this->type_->is_abstract())
2896     resolved_type = this->type_;
2897   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2898     {
2899       // We have an abstract integer type.  We just hope for the best.
2900       resolved_type = Type::lookup_integer_type("int");
2901     }
2902   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2903     {
2904       // We are converting to an abstract complex type.
2905       resolved_type = Type::lookup_complex_type("complex128");
2906     }
2907   else
2908     {
2909       // If we still have an abstract type here, then this is being
2910       // used in a constant expression which didn't get reduced.  We
2911       // just use float64 and hope for the best.
2912       resolved_type = Type::lookup_float_type("float64");
2913     }
2914 
2915   Numeric_constant nc;
2916   nc.set_float(resolved_type, this->val_);
2917   return Expression::backend_numeric_constant_expression(context, &nc);
2918 }
2919 
2920 // Write a floating point number to a string dump.
2921 
2922 void
export_float(String_dump * exp,const mpfr_t val)2923 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2924 {
2925   mpfr_exp_t exponent;
2926   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
2927   if (*s == '-')
2928     exp->write_c_string("-");
2929   exp->write_c_string("0.");
2930   exp->write_c_string(*s == '-' ? s + 1 : s);
2931   mpfr_free_str(s);
2932   char buf[30];
2933   snprintf(buf, sizeof buf, "E%ld", exponent);
2934   exp->write_c_string(buf);
2935 }
2936 
2937 // Export a floating point number in a constant expression.
2938 
2939 void
do_export(Export_function_body * efb) const2940 Float_expression::do_export(Export_function_body* efb) const
2941 {
2942   bool added_type = false;
2943   if (this->type_ != NULL
2944       && !this->type_->is_abstract()
2945       && this->type_ != efb->type_context())
2946     {
2947       efb->write_c_string("$convert(");
2948       efb->write_type(this->type_);
2949       efb->write_c_string(", ");
2950       added_type = true;
2951     }
2952 
2953   Float_expression::export_float(efb, this->val_);
2954   // A trailing space lets us reliably identify the end of the number.
2955   efb->write_c_string(" ");
2956 
2957   if (added_type)
2958     efb->write_c_string(")");
2959 }
2960 
2961 // Dump a floating point number to the dump file.
2962 
2963 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2964 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2965 {
2966   Float_expression::export_float(ast_dump_context, this->val_);
2967 }
2968 
2969 // Make a float expression.
2970 
2971 Expression*
make_float(const mpfr_t * val,Type * type,Location location)2972 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2973 {
2974   return new Float_expression(val, type, location);
2975 }
2976 
2977 // Complex numbers.
2978 
2979 class Complex_expression : public Expression
2980 {
2981  public:
Complex_expression(const mpc_t * val,Type * type,Location location)2982   Complex_expression(const mpc_t* val, Type* type, Location location)
2983     : Expression(EXPRESSION_COMPLEX, location),
2984       type_(type)
2985   {
2986     mpc_init2(this->val_, mpc_precision);
2987     mpc_set(this->val_, *val, MPC_RNDNN);
2988   }
2989 
2990   // Write VAL to string dump.
2991   static void
2992   export_complex(String_dump* exp, const mpc_t val);
2993 
2994   // Write REAL/IMAG to dump context.
2995   static void
2996   dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2997 
2998  protected:
2999   int
3000   do_traverse(Traverse*);
3001 
3002   bool
do_is_constant() const3003   do_is_constant() const
3004   { return true; }
3005 
3006   bool
do_is_zero_value() const3007   do_is_zero_value() const
3008   {
3009     return mpfr_zero_p(mpc_realref(this->val_)) != 0
3010            && mpfr_signbit(mpc_realref(this->val_)) == 0
3011            && mpfr_zero_p(mpc_imagref(this->val_)) != 0
3012            && mpfr_signbit(mpc_imagref(this->val_)) == 0;
3013   }
3014 
3015   bool
do_is_static_initializer() const3016   do_is_static_initializer() const
3017   { return true; }
3018 
3019   bool
do_numeric_constant_value(Numeric_constant * nc) const3020   do_numeric_constant_value(Numeric_constant* nc) const
3021   {
3022     nc->set_complex(this->type_, this->val_);
3023     return true;
3024   }
3025 
3026   Type*
3027   do_type();
3028 
3029   void
3030   do_determine_type(const Type_context*);
3031 
3032   void
3033   do_check_types(Gogo*);
3034 
3035   Expression*
do_copy()3036   do_copy()
3037   {
3038     return Expression::make_complex(&this->val_,
3039 				    (this->type_ == NULL
3040 				     ? NULL
3041 				     : this->type_->copy_expressions()),
3042 				    this->location());
3043   }
3044 
3045   Bexpression*
3046   do_get_backend(Translate_context*);
3047 
3048   int
do_inlining_cost() const3049   do_inlining_cost() const
3050   { return 2; }
3051 
3052   void
3053   do_export(Export_function_body*) const;
3054 
3055   void
3056   do_dump_expression(Ast_dump_context*) const;
3057 
3058  private:
3059   // The complex value.
3060   mpc_t val_;
3061   // The type if known.
3062   Type* type_;
3063 };
3064 
3065 // Traverse a complex expression.  We just need to traverse the type
3066 // if there is one.
3067 
3068 int
do_traverse(Traverse * traverse)3069 Complex_expression::do_traverse(Traverse* traverse)
3070 {
3071   if (this->type_ != NULL)
3072     return Type::traverse(this->type_, traverse);
3073   return TRAVERSE_CONTINUE;
3074 }
3075 
3076 // Return the current type.  If we haven't set the type yet, we return
3077 // an abstract complex type.
3078 
3079 Type*
do_type()3080 Complex_expression::do_type()
3081 {
3082   if (this->type_ == NULL)
3083     this->type_ = Type::make_abstract_complex_type();
3084   return this->type_;
3085 }
3086 
3087 // Set the type of the complex value.  Here we may switch from an
3088 // abstract type to a real type.
3089 
3090 void
do_determine_type(const Type_context * context)3091 Complex_expression::do_determine_type(const Type_context* context)
3092 {
3093   if (this->type_ != NULL && !this->type_->is_abstract())
3094     ;
3095   else if (context->type != NULL && context->type->is_numeric_type())
3096     this->type_ = context->type;
3097   else if (!context->may_be_abstract)
3098     this->type_ = Type::lookup_complex_type("complex128");
3099 }
3100 
3101 // Check the type of a complex value.
3102 
3103 void
do_check_types(Gogo *)3104 Complex_expression::do_check_types(Gogo*)
3105 {
3106   Type* type = this->type_;
3107   if (type == NULL)
3108     return;
3109   Numeric_constant nc;
3110   nc.set_complex(NULL, this->val_);
3111   if (!nc.set_type(this->type_, true, this->location()))
3112     this->set_is_error();
3113 }
3114 
3115 // Get the backend representation for a complex constant.
3116 
3117 Bexpression*
do_get_backend(Translate_context * context)3118 Complex_expression::do_get_backend(Translate_context* context)
3119 {
3120   if (this->is_error_expression()
3121       || (this->type_ != NULL && this->type_->is_error_type()))
3122     {
3123       go_assert(saw_errors());
3124       return context->gogo()->backend()->error_expression();
3125     }
3126 
3127   Type* resolved_type;
3128   if (this->type_ != NULL && !this->type_->is_abstract())
3129     resolved_type = this->type_;
3130   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3131     {
3132       // We are converting to an abstract integer type.
3133       resolved_type = Type::lookup_integer_type("int");
3134     }
3135   else if (this->type_ != NULL && this->type_->float_type() != NULL)
3136     {
3137       // We are converting to an abstract float type.
3138       resolved_type = Type::lookup_float_type("float64");
3139     }
3140   else
3141     {
3142       // If we still have an abstract type here, this is being
3143       // used in a constant expression which didn't get reduced.  We
3144       // just use complex128 and hope for the best.
3145       resolved_type = Type::lookup_complex_type("complex128");
3146     }
3147 
3148   Numeric_constant nc;
3149   nc.set_complex(resolved_type, this->val_);
3150   return Expression::backend_numeric_constant_expression(context, &nc);
3151 }
3152 
3153 // Write REAL/IMAG to export data.
3154 
3155 void
export_complex(String_dump * exp,const mpc_t val)3156 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
3157 {
3158   if (!mpfr_zero_p(mpc_realref(val)))
3159     {
3160       Float_expression::export_float(exp, mpc_realref(val));
3161       if (mpfr_sgn(mpc_imagref(val)) >= 0)
3162 	exp->write_c_string("+");
3163     }
3164   Float_expression::export_float(exp, mpc_imagref(val));
3165   exp->write_c_string("i");
3166 }
3167 
3168 // Export a complex number in a constant expression.
3169 
3170 void
do_export(Export_function_body * efb) const3171 Complex_expression::do_export(Export_function_body* efb) const
3172 {
3173   bool added_type = false;
3174   if (this->type_ != NULL
3175       && !this->type_->is_abstract()
3176       && this->type_ != efb->type_context())
3177     {
3178       efb->write_c_string("$convert(");
3179       efb->write_type(this->type_);
3180       efb->write_c_string(", ");
3181       added_type = true;
3182     }
3183 
3184   Complex_expression::export_complex(efb, this->val_);
3185   // A trailing space lets us reliably identify the end of the number.
3186   efb->write_c_string(" ");
3187 
3188   if (added_type)
3189     efb->write_c_string(")");
3190 }
3191 
3192 // Dump a complex expression to the dump file.
3193 
3194 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3195 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3196 {
3197   Complex_expression::export_complex(ast_dump_context, this->val_);
3198 }
3199 
3200 // Make a complex expression.
3201 
3202 Expression*
make_complex(const mpc_t * val,Type * type,Location location)3203 Expression::make_complex(const mpc_t* val, Type* type, Location location)
3204 {
3205   return new Complex_expression(val, type, location);
3206 }
3207 
3208 // Find a named object in an expression.
3209 
3210 class Find_named_object : public Traverse
3211 {
3212  public:
Find_named_object(Named_object * no)3213   Find_named_object(Named_object* no)
3214     : Traverse(traverse_expressions),
3215       no_(no), found_(false)
3216   { }
3217 
3218   // Whether we found the object.
3219   bool
found() const3220   found() const
3221   { return this->found_; }
3222 
3223  protected:
3224   int
3225   expression(Expression**);
3226 
3227  private:
3228   // The object we are looking for.
3229   Named_object* no_;
3230   // Whether we found it.
3231   bool found_;
3232 };
3233 
3234 // A reference to a const in an expression.
3235 
3236 class Const_expression : public Expression
3237 {
3238  public:
Const_expression(Named_object * constant,Location location)3239   Const_expression(Named_object* constant, Location location)
3240     : Expression(EXPRESSION_CONST_REFERENCE, location),
3241       constant_(constant), type_(NULL), seen_(false)
3242   { }
3243 
3244   Named_object*
named_object()3245   named_object()
3246   { return this->constant_; }
3247 
3248   const Named_object*
named_object() const3249   named_object() const
3250   { return this->constant_; }
3251 
3252   // Check that the initializer does not refer to the constant itself.
3253   void
3254   check_for_init_loop();
3255 
3256  protected:
3257   int
3258   do_traverse(Traverse*);
3259 
3260   Expression*
3261   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3262 
3263   bool
do_is_constant() const3264   do_is_constant() const
3265   { return true; }
3266 
3267   bool
do_is_zero_value() const3268   do_is_zero_value() const
3269   { return this->constant_->const_value()->expr()->is_zero_value(); }
3270 
3271   bool
do_is_static_initializer() const3272   do_is_static_initializer() const
3273   { return true; }
3274 
3275   bool
3276   do_numeric_constant_value(Numeric_constant* nc) const;
3277 
3278   bool
3279   do_string_constant_value(std::string* val) const;
3280 
3281   bool
3282   do_boolean_constant_value(bool* val) const;
3283 
3284   Type*
3285   do_type();
3286 
3287   // The type of a const is set by the declaration, not the use.
3288   void
3289   do_determine_type(const Type_context*);
3290 
3291   void
3292   do_check_types(Gogo*);
3293 
3294   Expression*
do_copy()3295   do_copy()
3296   { return this; }
3297 
3298   Bexpression*
3299   do_get_backend(Translate_context* context);
3300 
3301   int
do_inlining_cost() const3302   do_inlining_cost() const
3303   { return 1; }
3304 
3305   // When exporting a reference to a const as part of a const
3306   // expression, we export the value.  We ignore the fact that it has
3307   // a name.
3308   void
do_export(Export_function_body * efb) const3309   do_export(Export_function_body* efb) const
3310   { this->constant_->const_value()->expr()->export_expression(efb); }
3311 
3312   void
3313   do_dump_expression(Ast_dump_context*) const;
3314 
3315  private:
3316   // The constant.
3317   Named_object* constant_;
3318   // The type of this reference.  This is used if the constant has an
3319   // abstract type.
3320   Type* type_;
3321   // Used to prevent infinite recursion when a constant incorrectly
3322   // refers to itself.
3323   mutable bool seen_;
3324 };
3325 
3326 // Traversal.
3327 
3328 int
do_traverse(Traverse * traverse)3329 Const_expression::do_traverse(Traverse* traverse)
3330 {
3331   if (this->type_ != NULL)
3332     return Type::traverse(this->type_, traverse);
3333   return TRAVERSE_CONTINUE;
3334 }
3335 
3336 // Lower a constant expression.  This is where we convert the
3337 // predeclared constant iota into an integer value.
3338 
3339 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)3340 Const_expression::do_lower(Gogo* gogo, Named_object*,
3341 			   Statement_inserter*, int iota_value)
3342 {
3343   if (this->constant_->const_value()->expr()->classification()
3344       == EXPRESSION_IOTA)
3345     {
3346       if (iota_value == -1)
3347 	{
3348 	  go_error_at(this->location(),
3349 		      "iota is only defined in const declarations");
3350 	  iota_value = 0;
3351 	}
3352       return Expression::make_integer_ul(iota_value, NULL, this->location());
3353     }
3354 
3355   // Make sure that the constant itself has been lowered.
3356   gogo->lower_constant(this->constant_);
3357 
3358   return this;
3359 }
3360 
3361 // Return a numeric constant value.
3362 
3363 bool
do_numeric_constant_value(Numeric_constant * nc) const3364 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
3365 {
3366   if (this->seen_)
3367     return false;
3368 
3369   Expression* e = this->constant_->const_value()->expr();
3370 
3371   this->seen_ = true;
3372 
3373   bool r = e->numeric_constant_value(nc);
3374 
3375   this->seen_ = false;
3376 
3377   Type* ctype;
3378   if (this->type_ != NULL)
3379     ctype = this->type_;
3380   else
3381     ctype = this->constant_->const_value()->type();
3382   if (r && ctype != NULL)
3383     {
3384       if (!nc->set_type(ctype, false, this->location()))
3385 	return false;
3386     }
3387 
3388   return r;
3389 }
3390 
3391 bool
do_string_constant_value(std::string * val) const3392 Const_expression::do_string_constant_value(std::string* val) const
3393 {
3394   if (this->seen_)
3395     return false;
3396 
3397   Expression* e = this->constant_->const_value()->expr();
3398 
3399   this->seen_ = true;
3400   bool ok = e->string_constant_value(val);
3401   this->seen_ = false;
3402 
3403   return ok;
3404 }
3405 
3406 bool
do_boolean_constant_value(bool * val) const3407 Const_expression::do_boolean_constant_value(bool* val) const
3408 {
3409   if (this->seen_)
3410     return false;
3411 
3412   Expression* e = this->constant_->const_value()->expr();
3413 
3414   this->seen_ = true;
3415   bool ok = e->boolean_constant_value(val);
3416   this->seen_ = false;
3417 
3418   return ok;
3419 }
3420 
3421 // Return the type of the const reference.
3422 
3423 Type*
do_type()3424 Const_expression::do_type()
3425 {
3426   if (this->type_ != NULL)
3427     return this->type_;
3428 
3429   Named_constant* nc = this->constant_->const_value();
3430 
3431   if (this->seen_ || nc->lowering())
3432     {
3433       if (nc->type() == NULL || !nc->type()->is_error_type())
3434 	{
3435 	  Location loc = this->location();
3436 	  if (!this->seen_)
3437 	    loc = nc->location();
3438 	  go_error_at(loc, "constant refers to itself");
3439 	}
3440       this->set_is_error();
3441       this->type_ = Type::make_error_type();
3442       nc->set_type(this->type_);
3443       return this->type_;
3444     }
3445 
3446   this->seen_ = true;
3447 
3448   Type* ret = nc->type();
3449 
3450   if (ret != NULL)
3451     {
3452       this->seen_ = false;
3453       return ret;
3454     }
3455 
3456   // During parsing, a named constant may have a NULL type, but we
3457   // must not return a NULL type here.
3458   ret = nc->expr()->type();
3459 
3460   this->seen_ = false;
3461 
3462   if (ret->is_error_type())
3463     nc->set_type(ret);
3464 
3465   return ret;
3466 }
3467 
3468 // Set the type of the const reference.
3469 
3470 void
do_determine_type(const Type_context * context)3471 Const_expression::do_determine_type(const Type_context* context)
3472 {
3473   Type* ctype = this->constant_->const_value()->type();
3474   Type* cetype = (ctype != NULL
3475 		  ? ctype
3476 		  : this->constant_->const_value()->expr()->type());
3477   if (ctype != NULL && !ctype->is_abstract())
3478     ;
3479   else if (context->type != NULL
3480 	   && context->type->is_numeric_type()
3481 	   && cetype->is_numeric_type())
3482     this->type_ = context->type;
3483   else if (context->type != NULL
3484 	   && context->type->is_string_type()
3485 	   && cetype->is_string_type())
3486     this->type_ = context->type;
3487   else if (context->type != NULL
3488 	   && context->type->is_boolean_type()
3489 	   && cetype->is_boolean_type())
3490     this->type_ = context->type;
3491   else if (!context->may_be_abstract)
3492     {
3493       if (cetype->is_abstract())
3494 	cetype = cetype->make_non_abstract_type();
3495       this->type_ = cetype;
3496     }
3497 }
3498 
3499 // Check for a loop in which the initializer of a constant refers to
3500 // the constant itself.
3501 
3502 void
check_for_init_loop()3503 Const_expression::check_for_init_loop()
3504 {
3505   if (this->type_ != NULL && this->type_->is_error())
3506     return;
3507 
3508   if (this->seen_)
3509     {
3510       this->report_error(_("constant refers to itself"));
3511       this->type_ = Type::make_error_type();
3512       return;
3513     }
3514 
3515   Expression* init = this->constant_->const_value()->expr();
3516   Find_named_object find_named_object(this->constant_);
3517 
3518   this->seen_ = true;
3519   Expression::traverse(&init, &find_named_object);
3520   this->seen_ = false;
3521 
3522   if (find_named_object.found())
3523     {
3524       if (this->type_ == NULL || !this->type_->is_error())
3525 	{
3526 	  this->report_error(_("constant refers to itself"));
3527 	  this->type_ = Type::make_error_type();
3528 	}
3529       return;
3530     }
3531 }
3532 
3533 // Check types of a const reference.
3534 
3535 void
do_check_types(Gogo *)3536 Const_expression::do_check_types(Gogo*)
3537 {
3538   if (this->type_ != NULL && this->type_->is_error())
3539     return;
3540 
3541   this->check_for_init_loop();
3542 
3543   // Check that numeric constant fits in type.
3544   if (this->type_ != NULL && this->type_->is_numeric_type())
3545     {
3546       Numeric_constant nc;
3547       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
3548 	{
3549 	  if (!nc.set_type(this->type_, true, this->location()))
3550 	    this->set_is_error();
3551 	}
3552     }
3553 }
3554 
3555 // Return the backend representation for a const reference.
3556 
3557 Bexpression*
do_get_backend(Translate_context * context)3558 Const_expression::do_get_backend(Translate_context* context)
3559 {
3560   if (this->is_error_expression()
3561       || (this->type_ != NULL && this->type_->is_error()))
3562     {
3563       go_assert(saw_errors());
3564       return context->backend()->error_expression();
3565     }
3566 
3567   // If the type has been set for this expression, but the underlying
3568   // object is an abstract int or float, we try to get the abstract
3569   // value.  Otherwise we may lose something in the conversion.
3570   Expression* expr = this->constant_->const_value()->expr();
3571   if (this->type_ != NULL
3572       && this->type_->is_numeric_type()
3573       && (this->constant_->const_value()->type() == NULL
3574 	  || this->constant_->const_value()->type()->is_abstract()))
3575     {
3576       Numeric_constant nc;
3577       if (expr->numeric_constant_value(&nc)
3578 	  && nc.set_type(this->type_, false, this->location()))
3579 	{
3580 	  Expression* e = nc.expression(this->location());
3581 	  return e->get_backend(context);
3582 	}
3583     }
3584 
3585   if (this->type_ != NULL)
3586     expr = Expression::make_cast(this->type_, expr, this->location());
3587   return expr->get_backend(context);
3588 }
3589 
3590 // Dump ast representation for constant expression.
3591 
3592 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3593 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3594 {
3595   ast_dump_context->ostream() << this->constant_->name();
3596 }
3597 
3598 // Make a reference to a constant in an expression.
3599 
3600 Expression*
make_const_reference(Named_object * constant,Location location)3601 Expression::make_const_reference(Named_object* constant,
3602 				 Location location)
3603 {
3604   return new Const_expression(constant, location);
3605 }
3606 
3607 // Find a named object in an expression.
3608 
3609 int
expression(Expression ** pexpr)3610 Find_named_object::expression(Expression** pexpr)
3611 {
3612   switch ((*pexpr)->classification())
3613     {
3614     case Expression::EXPRESSION_CONST_REFERENCE:
3615       {
3616 	Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3617 	if (ce->named_object() == this->no_)
3618 	  break;
3619 
3620 	// We need to check a constant initializer explicitly, as
3621 	// loops here will not be caught by the loop checking for
3622 	// variable initializers.
3623 	ce->check_for_init_loop();
3624 
3625 	return TRAVERSE_CONTINUE;
3626       }
3627 
3628     case Expression::EXPRESSION_VAR_REFERENCE:
3629       if ((*pexpr)->var_expression()->named_object() == this->no_)
3630 	break;
3631       return TRAVERSE_CONTINUE;
3632     case Expression::EXPRESSION_FUNC_REFERENCE:
3633       if ((*pexpr)->func_expression()->named_object() == this->no_)
3634 	break;
3635       return TRAVERSE_CONTINUE;
3636     default:
3637       return TRAVERSE_CONTINUE;
3638     }
3639   this->found_ = true;
3640   return TRAVERSE_EXIT;
3641 }
3642 
3643 // The nil value.
3644 
3645 class Nil_expression : public Expression
3646 {
3647  public:
Nil_expression(Location location)3648   Nil_expression(Location location)
3649     : Expression(EXPRESSION_NIL, location)
3650   { }
3651 
3652   static Expression*
3653   do_import(Import_expression*, Location);
3654 
3655  protected:
3656   bool
do_is_constant() const3657   do_is_constant() const
3658   { return true; }
3659 
3660   bool
do_is_zero_value() const3661   do_is_zero_value() const
3662   { return true; }
3663 
3664   bool
do_is_static_initializer() const3665   do_is_static_initializer() const
3666   { return true; }
3667 
3668   Type*
do_type()3669   do_type()
3670   { return Type::make_nil_type(); }
3671 
3672   void
do_determine_type(const Type_context *)3673   do_determine_type(const Type_context*)
3674   { }
3675 
3676   Expression*
do_copy()3677   do_copy()
3678   { return this; }
3679 
3680   Bexpression*
do_get_backend(Translate_context * context)3681   do_get_backend(Translate_context* context)
3682   { return context->backend()->nil_pointer_expression(); }
3683 
3684   int
do_inlining_cost() const3685   do_inlining_cost() const
3686   { return 1; }
3687 
3688   void
do_export(Export_function_body * efb) const3689   do_export(Export_function_body* efb) const
3690   { efb->write_c_string("$nil"); }
3691 
3692   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3693   do_dump_expression(Ast_dump_context* ast_dump_context) const
3694   { ast_dump_context->ostream() << "nil"; }
3695 };
3696 
3697 // Import a nil expression.
3698 
3699 Expression*
do_import(Import_expression * imp,Location loc)3700 Nil_expression::do_import(Import_expression* imp, Location loc)
3701 {
3702   if (imp->version() >= EXPORT_FORMAT_V3)
3703     imp->require_c_string("$");
3704   imp->require_c_string("nil");
3705   return Expression::make_nil(loc);
3706 }
3707 
3708 // Make a nil expression.
3709 
3710 Expression*
make_nil(Location location)3711 Expression::make_nil(Location location)
3712 {
3713   return new Nil_expression(location);
3714 }
3715 
3716 // The value of the predeclared constant iota.  This is little more
3717 // than a marker.  This will be lowered to an integer in
3718 // Const_expression::do_lower, which is where we know the value that
3719 // it should have.
3720 
3721 class Iota_expression : public Parser_expression
3722 {
3723  public:
Iota_expression(Location location)3724   Iota_expression(Location location)
3725     : Parser_expression(EXPRESSION_IOTA, location)
3726   { }
3727 
3728  protected:
3729   Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3730   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3731   { go_unreachable(); }
3732 
3733   // There should only ever be one of these.
3734   Expression*
do_copy()3735   do_copy()
3736   { go_unreachable(); }
3737 
3738   void
do_dump_expression(Ast_dump_context * ast_dump_context) const3739   do_dump_expression(Ast_dump_context* ast_dump_context) const
3740   { ast_dump_context->ostream() << "iota"; }
3741 };
3742 
3743 // Make an iota expression.  This is only called for one case: the
3744 // value of the predeclared constant iota.
3745 
3746 Expression*
make_iota()3747 Expression::make_iota()
3748 {
3749   static Iota_expression iota_expression(Linemap::unknown_location());
3750   return &iota_expression;
3751 }
3752 
3753 // Class Type_conversion_expression.
3754 
3755 // Traversal.
3756 
3757 int
do_traverse(Traverse * traverse)3758 Type_conversion_expression::do_traverse(Traverse* traverse)
3759 {
3760   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3761       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3762     return TRAVERSE_EXIT;
3763   return TRAVERSE_CONTINUE;
3764 }
3765 
3766 // Convert to a constant at lowering time.
3767 
3768 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3769 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3770 				     Statement_inserter*, int)
3771 {
3772   Type* type = this->type_;
3773   Expression* val = this->expr_;
3774   Location location = this->location();
3775 
3776   if (type->is_numeric_type())
3777     {
3778       Numeric_constant nc;
3779       if (val->numeric_constant_value(&nc))
3780 	{
3781 	  if (!nc.set_type(type, true, location))
3782 	    return Expression::make_error(location);
3783 	  return nc.expression(location);
3784 	}
3785     }
3786 
3787   // According to the language specification on string conversions
3788   // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3789   // When converting an integer into a string, the string will be a UTF-8
3790   // representation of the integer and integers "outside the range of valid
3791   // Unicode code points are converted to '\uFFFD'."
3792   if (type->is_string_type())
3793     {
3794       Numeric_constant nc;
3795       if (val->numeric_constant_value(&nc) && nc.is_int())
3796         {
3797           // An integer value doesn't fit in the Unicode code point range if it
3798           // overflows the Go "int" type or is negative.
3799           unsigned long ul;
3800           if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3801               || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3802             return Expression::make_string("\ufffd", location);
3803         }
3804     }
3805 
3806   if (type->is_slice_type())
3807     {
3808       Type* element_type = type->array_type()->element_type()->forwarded();
3809       bool is_byte = (element_type->integer_type() != NULL
3810 		      && element_type->integer_type()->is_byte());
3811       bool is_rune = (element_type->integer_type() != NULL
3812 		      && element_type->integer_type()->is_rune());
3813       if (is_byte || is_rune)
3814 	{
3815 	  std::string s;
3816 	  if (val->string_constant_value(&s))
3817 	    {
3818 	      Expression_list* vals = new Expression_list();
3819 	      if (is_byte)
3820 		{
3821 		  for (std::string::const_iterator p = s.begin();
3822 		       p != s.end();
3823 		       p++)
3824 		    {
3825 		      unsigned char c = static_cast<unsigned char>(*p);
3826 		      vals->push_back(Expression::make_integer_ul(c,
3827 								  element_type,
3828 								  location));
3829 		    }
3830 		}
3831 	      else
3832 		{
3833 		  const char *p = s.data();
3834 		  const char *pend = s.data() + s.length();
3835 		  while (p < pend)
3836 		    {
3837 		      unsigned int c;
3838 		      int adv = Lex::fetch_char(p, &c);
3839 		      if (adv == 0)
3840 			{
3841 			  go_warning_at(this->location(), 0,
3842 				     "invalid UTF-8 encoding");
3843 			  adv = 1;
3844 			}
3845 		      p += adv;
3846 		      vals->push_back(Expression::make_integer_ul(c,
3847 								  element_type,
3848 								  location));
3849 		    }
3850 		}
3851 
3852 	      return Expression::make_slice_composite_literal(type, vals,
3853 							      location);
3854 	    }
3855 	}
3856     }
3857 
3858   return this;
3859 }
3860 
3861 // Flatten a type conversion by using a temporary variable for the slice
3862 // in slice to string conversions.
3863 
3864 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)3865 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3866                                        Statement_inserter* inserter)
3867 {
3868   if (this->type()->is_error_type() || this->expr_->is_error_expression())
3869     {
3870       go_assert(saw_errors());
3871       return Expression::make_error(this->location());
3872     }
3873 
3874   if (((this->type()->is_string_type()
3875         && this->expr_->type()->is_slice_type())
3876        || this->expr_->type()->interface_type() != NULL)
3877       && !this->expr_->is_variable())
3878     {
3879       Temporary_statement* temp =
3880           Statement::make_temporary(NULL, this->expr_, this->location());
3881       inserter->insert(temp);
3882       this->expr_ = Expression::make_temporary_reference(temp, this->location());
3883     }
3884 
3885   // For interface conversion and string to/from slice conversions,
3886   // decide if we can allocate on stack.
3887   if (this->type()->interface_type() != NULL
3888       || this->type()->is_string_type()
3889       || this->expr_->type()->is_string_type())
3890     {
3891       Node* n = Node::make_node(this);
3892       if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
3893         this->no_escape_ = true;
3894     }
3895   return this;
3896 }
3897 
3898 // Return whether a type conversion is a constant.
3899 
3900 bool
do_is_constant() const3901 Type_conversion_expression::do_is_constant() const
3902 {
3903   if (!this->expr_->is_constant())
3904     return false;
3905 
3906   // A conversion to a type that may not be used as a constant is not
3907   // a constant.  For example, []byte(nil).
3908   Type* type = this->type_;
3909   if (type->integer_type() == NULL
3910       && type->float_type() == NULL
3911       && type->complex_type() == NULL
3912       && !type->is_boolean_type()
3913       && !type->is_string_type())
3914     return false;
3915 
3916   return true;
3917 }
3918 
3919 // Return whether a type conversion is a zero value.
3920 
3921 bool
do_is_zero_value() const3922 Type_conversion_expression::do_is_zero_value() const
3923 {
3924   if (!this->expr_->is_zero_value())
3925     return false;
3926 
3927   // Some type conversion from zero value is still not zero value.
3928   // For example, []byte("") or interface{}(0).
3929   // Conservatively, only report true if the RHS is nil.
3930   Type* type = this->type_;
3931   if (type->integer_type() == NULL
3932       && type->float_type() == NULL
3933       && type->complex_type() == NULL
3934       && !type->is_boolean_type()
3935       && !type->is_string_type())
3936     return this->expr_->is_nil_expression();
3937 
3938   return true;
3939 }
3940 
3941 // Return whether a type conversion can be used in a constant
3942 // initializer.
3943 
3944 bool
do_is_static_initializer() const3945 Type_conversion_expression::do_is_static_initializer() const
3946 {
3947   Type* type = this->type_;
3948   Type* expr_type = this->expr_->type();
3949 
3950   if (type->interface_type() != NULL
3951       || expr_type->interface_type() != NULL)
3952     return false;
3953 
3954   if (!this->expr_->is_static_initializer())
3955     return false;
3956 
3957   if (Type::are_identical(type, expr_type,
3958 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
3959 			  NULL))
3960     return true;
3961 
3962   if (type->is_string_type() && expr_type->is_string_type())
3963     return true;
3964 
3965   if ((type->is_numeric_type()
3966        || type->is_boolean_type()
3967        || type->points_to() != NULL)
3968       && (expr_type->is_numeric_type()
3969 	  || expr_type->is_boolean_type()
3970 	  || expr_type->points_to() != NULL))
3971     return true;
3972 
3973   return false;
3974 }
3975 
3976 // Return the constant numeric value if there is one.
3977 
3978 bool
do_numeric_constant_value(Numeric_constant * nc) const3979 Type_conversion_expression::do_numeric_constant_value(
3980     Numeric_constant* nc) const
3981 {
3982   if (!this->type_->is_numeric_type())
3983     return false;
3984   if (!this->expr_->numeric_constant_value(nc))
3985     return false;
3986   return nc->set_type(this->type_, false, this->location());
3987 }
3988 
3989 // Return the constant string value if there is one.
3990 
3991 bool
do_string_constant_value(std::string * val) const3992 Type_conversion_expression::do_string_constant_value(std::string* val) const
3993 {
3994   if (this->type_->is_string_type()
3995       && this->expr_->type()->integer_type() != NULL)
3996     {
3997       Numeric_constant nc;
3998       if (this->expr_->numeric_constant_value(&nc))
3999 	{
4000 	  unsigned long ival;
4001 	  if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
4002 	    {
4003 	      val->clear();
4004 	      Lex::append_char(ival, true, val, this->location());
4005 	      return true;
4006 	    }
4007 	}
4008     }
4009 
4010   // FIXME: Could handle conversion from const []int here.
4011 
4012   return false;
4013 }
4014 
4015 // Return the constant boolean value if there is one.
4016 
4017 bool
do_boolean_constant_value(bool * val) const4018 Type_conversion_expression::do_boolean_constant_value(bool* val) const
4019 {
4020   if (!this->type_->is_boolean_type())
4021     return false;
4022   return this->expr_->boolean_constant_value(val);
4023 }
4024 
4025 // Determine the resulting type of the conversion.
4026 
4027 void
do_determine_type(const Type_context *)4028 Type_conversion_expression::do_determine_type(const Type_context*)
4029 {
4030   Type_context subcontext(this->type_, false);
4031   this->expr_->determine_type(&subcontext);
4032 }
4033 
4034 // Check that types are convertible.
4035 
4036 void
do_check_types(Gogo *)4037 Type_conversion_expression::do_check_types(Gogo*)
4038 {
4039   Type* type = this->type_;
4040   Type* expr_type = this->expr_->type();
4041   std::string reason;
4042 
4043   if (type->is_error() || expr_type->is_error())
4044     {
4045       this->set_is_error();
4046       return;
4047     }
4048 
4049   if (this->may_convert_function_types_
4050       && type->function_type() != NULL
4051       && expr_type->function_type() != NULL)
4052     return;
4053 
4054   if (Type::are_convertible(type, expr_type, &reason))
4055     return;
4056 
4057   go_error_at(this->location(), "%s", reason.c_str());
4058   this->set_is_error();
4059 }
4060 
4061 // Copy.
4062 
4063 Expression*
do_copy()4064 Type_conversion_expression::do_copy()
4065 {
4066   Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
4067                                                    this->expr_->copy(),
4068                                                    this->location());
4069   ret->conversion_expression()->set_no_copy(this->no_copy_);
4070   return ret;
4071 }
4072 
4073 // Get the backend representation for a type conversion.
4074 
4075 Bexpression*
do_get_backend(Translate_context * context)4076 Type_conversion_expression::do_get_backend(Translate_context* context)
4077 {
4078   Type* type = this->type_;
4079   Type* expr_type = this->expr_->type();
4080 
4081   Gogo* gogo = context->gogo();
4082   Btype* btype = type->get_backend(gogo);
4083   Location loc = this->location();
4084 
4085   if (Type::are_identical(type, expr_type,
4086 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4087 			  NULL))
4088     {
4089       Bexpression* bexpr = this->expr_->get_backend(context);
4090       return gogo->backend()->convert_expression(btype, bexpr, loc);
4091     }
4092   else if (type->interface_type() != NULL
4093            && expr_type->interface_type() == NULL)
4094     {
4095       Expression* conversion =
4096           Expression::convert_type_to_interface(type, this->expr_,
4097                                                 this->no_escape_, loc);
4098       return conversion->get_backend(context);
4099     }
4100   else if (type->interface_type() != NULL
4101 	   || expr_type->interface_type() != NULL)
4102     {
4103       Expression* conversion =
4104           Expression::convert_for_assignment(gogo, type, this->expr_,
4105                                              loc);
4106       return conversion->get_backend(context);
4107     }
4108   else if (type->is_string_type()
4109 	   && expr_type->integer_type() != NULL)
4110     {
4111       mpz_t intval;
4112       Numeric_constant nc;
4113       if (this->expr_->numeric_constant_value(&nc)
4114 	  && nc.to_int(&intval))
4115 	{
4116 	  std::string s;
4117           unsigned int x;
4118           if (mpz_fits_uint_p(intval))
4119             x = mpz_get_ui(intval);
4120           else
4121             {
4122               char* ms = mpz_get_str(NULL, 16, intval);
4123               go_warning_at(loc, 0,
4124                             "unicode code point 0x%s out of range in string",
4125                             ms);
4126               free(ms);
4127               x = 0xfffd;
4128             }
4129 	  Lex::append_char(x, true, &s, loc);
4130 	  mpz_clear(intval);
4131 	  Expression* se = Expression::make_string(s, loc);
4132 	  return se->get_backend(context);
4133 	}
4134 
4135       Expression* buf;
4136       if (this->no_escape_)
4137         {
4138           Type* byte_type = Type::lookup_integer_type("uint8");
4139           Expression* buflen =
4140             Expression::make_integer_ul(4, NULL, loc);
4141           Type* array_type = Type::make_array_type(byte_type, buflen);
4142           buf = Expression::make_allocation(array_type, loc);
4143           buf->allocation_expression()->set_allocate_on_stack();
4144           buf->allocation_expression()->set_no_zero();
4145         }
4146       else
4147         buf = Expression::make_nil(loc);
4148       Expression* i2s_expr =
4149         Runtime::make_call(Runtime::INTSTRING, loc, 2, buf, this->expr_);
4150       return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
4151     }
4152   else if (type->is_string_type() && expr_type->is_slice_type())
4153     {
4154       Array_type* a = expr_type->array_type();
4155       Type* e = a->element_type()->forwarded();
4156       go_assert(e->integer_type() != NULL);
4157       go_assert(this->expr_->is_variable());
4158 
4159       Runtime::Function code;
4160       if (e->integer_type()->is_byte())
4161         {
4162           if (this->no_copy_)
4163             {
4164               if (gogo->debug_optimization())
4165                 go_debug(loc, "no copy string([]byte)");
4166               Expression* ptr = Expression::make_slice_info(this->expr_,
4167                                                             SLICE_INFO_VALUE_POINTER,
4168                                                             loc);
4169               Expression* len = Expression::make_slice_info(this->expr_,
4170                                                             SLICE_INFO_LENGTH,
4171                                                             loc);
4172               Expression* str = Expression::make_string_value(ptr, len, loc);
4173               return str->get_backend(context);
4174             }
4175           code = Runtime::SLICEBYTETOSTRING;
4176         }
4177       else
4178         {
4179           go_assert(e->integer_type()->is_rune());
4180           code = Runtime::SLICERUNETOSTRING;
4181         }
4182 
4183       Expression* buf;
4184       if (this->no_escape_)
4185         {
4186           Type* byte_type = Type::lookup_integer_type("uint8");
4187           Expression* buflen =
4188             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4189           Type* array_type = Type::make_array_type(byte_type, buflen);
4190           buf = Expression::make_allocation(array_type, loc);
4191           buf->allocation_expression()->set_allocate_on_stack();
4192           buf->allocation_expression()->set_no_zero();
4193         }
4194       else
4195         buf = Expression::make_nil(loc);
4196       return Runtime::make_call(code, loc, 2, buf,
4197 				this->expr_)->get_backend(context);
4198     }
4199   else if (type->is_slice_type() && expr_type->is_string_type())
4200     {
4201       Type* e = type->array_type()->element_type()->forwarded();
4202       go_assert(e->integer_type() != NULL);
4203 
4204       Runtime::Function code;
4205       if (e->integer_type()->is_byte())
4206 	code = Runtime::STRINGTOSLICEBYTE;
4207       else
4208 	{
4209 	  go_assert(e->integer_type()->is_rune());
4210 	  code = Runtime::STRINGTOSLICERUNE;
4211 	}
4212 
4213       Expression* buf;
4214       if (this->no_escape_)
4215         {
4216           Expression* buflen =
4217             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4218           Type* array_type = Type::make_array_type(e, buflen);
4219           buf = Expression::make_allocation(array_type, loc);
4220           buf->allocation_expression()->set_allocate_on_stack();
4221           buf->allocation_expression()->set_no_zero();
4222         }
4223       else
4224         buf = Expression::make_nil(loc);
4225       Expression* s2a = Runtime::make_call(code, loc, 2, buf, this->expr_);
4226       return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
4227     }
4228   else if (type->is_numeric_type())
4229     {
4230       go_assert(Type::are_convertible(type, expr_type, NULL));
4231       Bexpression* bexpr = this->expr_->get_backend(context);
4232       return gogo->backend()->convert_expression(btype, bexpr, loc);
4233     }
4234   else if ((type->is_unsafe_pointer_type()
4235 	    && (expr_type->points_to() != NULL
4236                 || expr_type->integer_type()))
4237            || (expr_type->is_unsafe_pointer_type()
4238 	       && type->points_to() != NULL)
4239            || (this->may_convert_function_types_
4240                && type->function_type() != NULL
4241                && expr_type->function_type() != NULL))
4242     {
4243       Bexpression* bexpr = this->expr_->get_backend(context);
4244       return gogo->backend()->convert_expression(btype, bexpr, loc);
4245     }
4246   else
4247     {
4248       Expression* conversion =
4249           Expression::convert_for_assignment(gogo, type, this->expr_, loc);
4250       return conversion->get_backend(context);
4251     }
4252 }
4253 
4254 // Cost of inlining a type conversion.
4255 
4256 int
do_inlining_cost() const4257 Type_conversion_expression::do_inlining_cost() const
4258 {
4259   Type* type = this->type_;
4260   Type* expr_type = this->expr_->type();
4261   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
4262     return 10;
4263   else if (type->is_string_type() && expr_type->integer_type() != NULL)
4264     return 10;
4265   else if (type->is_string_type() && expr_type->is_slice_type())
4266     return 10;
4267   else if (type->is_slice_type() && expr_type->is_string_type())
4268     return 10;
4269   else
4270     return 1;
4271 }
4272 
4273 // Output a type conversion in a constant expression.
4274 
4275 void
do_export(Export_function_body * efb) const4276 Type_conversion_expression::do_export(Export_function_body* efb) const
4277 {
4278   efb->write_c_string("$convert(");
4279   efb->write_type(this->type_);
4280   efb->write_c_string(", ");
4281 
4282   Type* old_context = efb->type_context();
4283   efb->set_type_context(this->type_);
4284 
4285   this->expr_->export_expression(efb);
4286 
4287   efb->set_type_context(old_context);
4288 
4289   efb->write_c_string(")");
4290 }
4291 
4292 // Import a type conversion or a struct construction.
4293 
4294 Expression*
do_import(Import_expression * imp,Location loc)4295 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
4296 {
4297   imp->require_c_string("$convert(");
4298   Type* type = imp->read_type();
4299   imp->require_c_string(", ");
4300   Expression* val = Expression::import_expression(imp, loc);
4301   imp->require_c_string(")");
4302   return Expression::make_cast(type, val, loc);
4303 }
4304 
4305 // Dump ast representation for a type conversion expression.
4306 
4307 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4308 Type_conversion_expression::do_dump_expression(
4309     Ast_dump_context* ast_dump_context) const
4310 {
4311   ast_dump_context->dump_type(this->type_);
4312   ast_dump_context->ostream() << "(";
4313   ast_dump_context->dump_expression(this->expr_);
4314   ast_dump_context->ostream() << ") ";
4315 }
4316 
4317 // Make a type cast expression.
4318 
4319 Expression*
make_cast(Type * type,Expression * val,Location location)4320 Expression::make_cast(Type* type, Expression* val, Location location)
4321 {
4322   if (type->is_error_type() || val->is_error_expression())
4323     return Expression::make_error(location);
4324   return new Type_conversion_expression(type, val, location);
4325 }
4326 
4327 // Class Unsafe_type_conversion_expression.
4328 
4329 // Traversal.
4330 
4331 int
do_traverse(Traverse * traverse)4332 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
4333 {
4334   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4335       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4336     return TRAVERSE_EXIT;
4337   return TRAVERSE_CONTINUE;
4338 }
4339 
4340 // Return whether an unsafe type conversion can be used as a constant
4341 // initializer.
4342 
4343 bool
do_is_static_initializer() const4344 Unsafe_type_conversion_expression::do_is_static_initializer() const
4345 {
4346   Type* type = this->type_;
4347   Type* expr_type = this->expr_->type();
4348 
4349   if (type->interface_type() != NULL
4350       || expr_type->interface_type() != NULL)
4351     return false;
4352 
4353   if (!this->expr_->is_static_initializer())
4354     return false;
4355 
4356   if (Type::are_convertible(type, expr_type, NULL))
4357     return true;
4358 
4359   if (type->is_string_type() && expr_type->is_string_type())
4360     return true;
4361 
4362   if ((type->is_numeric_type()
4363        || type->is_boolean_type()
4364        || type->points_to() != NULL)
4365       && (expr_type->is_numeric_type()
4366 	  || expr_type->is_boolean_type()
4367 	  || expr_type->points_to() != NULL))
4368     return true;
4369 
4370   return false;
4371 }
4372 
4373 // Copy.
4374 
4375 Expression*
do_copy()4376 Unsafe_type_conversion_expression::do_copy()
4377 {
4378   return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
4379 					       this->expr_->copy(),
4380 					       this->location());
4381 }
4382 
4383 // Convert to backend representation.
4384 
4385 Bexpression*
do_get_backend(Translate_context * context)4386 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
4387 {
4388   // We are only called for a limited number of cases.
4389 
4390   Type* t = this->type_;
4391   Type* et = this->expr_->type();
4392 
4393   if (t->is_error_type()
4394       || this->expr_->is_error_expression()
4395       || et->is_error_type())
4396     {
4397       go_assert(saw_errors());
4398       return context->backend()->error_expression();
4399     }
4400 
4401   if (t->array_type() != NULL)
4402     go_assert(et->array_type() != NULL
4403               && t->is_slice_type() == et->is_slice_type());
4404   else if (t->struct_type() != NULL)
4405     {
4406       if (t->named_type() != NULL
4407           && et->named_type() != NULL
4408           && !Type::are_convertible(t, et, NULL))
4409 	{
4410 	  go_assert(saw_errors());
4411 	  return context->backend()->error_expression();
4412 	}
4413 
4414       go_assert(et->struct_type() != NULL
4415                 && Type::are_convertible(t, et, NULL));
4416     }
4417   else if (t->map_type() != NULL)
4418     go_assert(et->map_type() != NULL || et->points_to() != NULL);
4419   else if (t->channel_type() != NULL)
4420     go_assert(et->channel_type() != NULL || et->points_to() != NULL);
4421   else if (t->points_to() != NULL)
4422     go_assert(et->points_to() != NULL
4423               || et->channel_type() != NULL
4424               || et->map_type() != NULL
4425               || et->function_type() != NULL
4426 	      || et->integer_type() != NULL
4427               || et->is_nil_type());
4428   else if (t->function_type() != NULL)
4429     go_assert(et->points_to() != NULL);
4430   else if (et->is_unsafe_pointer_type())
4431     go_assert(t->points_to() != NULL
4432 	      || (t->integer_type() != NULL
4433 		  && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
4434   else if (t->interface_type() != NULL)
4435     {
4436       bool empty_iface = t->interface_type()->is_empty();
4437       go_assert(et->interface_type() != NULL
4438                 && et->interface_type()->is_empty() == empty_iface);
4439     }
4440   else if (t->integer_type() != NULL)
4441     go_assert(et->is_boolean_type()
4442               || et->integer_type() != NULL
4443               || et->function_type() != NULL
4444               || et->points_to() != NULL
4445               || et->map_type() != NULL
4446               || et->channel_type() != NULL
4447 	      || et->is_nil_type());
4448   else
4449     go_unreachable();
4450 
4451   Gogo* gogo = context->gogo();
4452   Btype* btype = t->get_backend(gogo);
4453   Bexpression* bexpr = this->expr_->get_backend(context);
4454   Location loc = this->location();
4455   return gogo->backend()->convert_expression(btype, bexpr, loc);
4456 }
4457 
4458 // Dump ast representation for an unsafe type conversion expression.
4459 
4460 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4461 Unsafe_type_conversion_expression::do_dump_expression(
4462     Ast_dump_context* ast_dump_context) const
4463 {
4464   ast_dump_context->dump_type(this->type_);
4465   ast_dump_context->ostream() << "(";
4466   ast_dump_context->dump_expression(this->expr_);
4467   ast_dump_context->ostream() << ") ";
4468 }
4469 
4470 // Make an unsafe type conversion expression.
4471 
4472 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)4473 Expression::make_unsafe_cast(Type* type, Expression* expr,
4474 			     Location location)
4475 {
4476   return new Unsafe_type_conversion_expression(type, expr, location);
4477 }
4478 
4479 // Class Unary_expression.
4480 
4481 // Call the address_taken method of the operand if needed.  This is
4482 // called after escape analysis but before inserting write barriers.
4483 
4484 void
check_operand_address_taken(Gogo *)4485 Unary_expression::check_operand_address_taken(Gogo*)
4486 {
4487   if (this->op_ != OPERATOR_AND)
4488     return;
4489 
4490   // If this->escapes_ is false at this point, then it was set to
4491   // false by an explicit call to set_does_not_escape, and the value
4492   // does not escape.  If this->escapes_ is true, we may be able to
4493   // set it to false based on the escape analysis pass.
4494   if (this->escapes_)
4495     {
4496       Node* n = Node::make_node(this);
4497       if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
4498 	this->escapes_ = false;
4499     }
4500 
4501   this->expr_->address_taken(this->escapes_);
4502 }
4503 
4504 // If we are taking the address of a composite literal, and the
4505 // contents are not constant, then we want to make a heap expression
4506 // instead.
4507 
4508 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)4509 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4510 {
4511   Location loc = this->location();
4512   Operator op = this->op_;
4513   Expression* expr = this->expr_;
4514 
4515   if (op == OPERATOR_MULT && expr->is_type_expression())
4516     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4517 
4518   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
4519   // moving x to the heap.  FIXME: Is it worth doing a real escape
4520   // analysis here?  This case is found in math/unsafe.go and is
4521   // therefore worth special casing.
4522   if (op == OPERATOR_MULT)
4523     {
4524       Expression* e = expr;
4525       while (e->classification() == EXPRESSION_CONVERSION)
4526 	{
4527 	  Type_conversion_expression* te
4528 	    = static_cast<Type_conversion_expression*>(e);
4529 	  e = te->expr();
4530 	}
4531 
4532       if (e->classification() == EXPRESSION_UNARY)
4533 	{
4534 	  Unary_expression* ue = static_cast<Unary_expression*>(e);
4535 	  if (ue->op_ == OPERATOR_AND)
4536 	    {
4537 	      if (e == expr)
4538 		{
4539 		  // *&x == x.
4540 		  if (!ue->expr_->is_addressable() && !ue->create_temp_)
4541 		    {
4542 		      go_error_at(ue->location(),
4543 				  "invalid operand for unary %<&%>");
4544 		      this->set_is_error();
4545 		    }
4546 		  return ue->expr_;
4547 		}
4548 	      ue->set_does_not_escape();
4549 	    }
4550 	}
4551     }
4552 
4553   // Catching an invalid indirection of unsafe.Pointer here avoid
4554   // having to deal with TYPE_VOID in other places.
4555   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4556     {
4557       go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4558       return Expression::make_error(this->location());
4559     }
4560 
4561   // Check for an invalid pointer dereference.  We need to do this
4562   // here because Unary_expression::do_type will return an error type
4563   // in this case.  That can cause code to appear erroneous, and
4564   // therefore disappear at lowering time, without any error message.
4565   if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
4566     {
4567       this->report_error(_("expected pointer"));
4568       return Expression::make_error(this->location());
4569     }
4570 
4571   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
4572     {
4573       Numeric_constant nc;
4574       if (expr->numeric_constant_value(&nc))
4575 	{
4576 	  Numeric_constant result;
4577 	  bool issued_error;
4578 	  if (Unary_expression::eval_constant(op, &nc, loc, &result,
4579 					      &issued_error))
4580 	    return result.expression(loc);
4581 	  else if (issued_error)
4582 	    return Expression::make_error(this->location());
4583 	}
4584     }
4585 
4586   return this;
4587 }
4588 
4589 // Flatten expression if a nil check must be performed and create temporary
4590 // variables if necessary.
4591 
4592 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)4593 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
4594                              Statement_inserter* inserter)
4595 {
4596   if (this->is_error_expression()
4597       || this->expr_->is_error_expression()
4598       || this->expr_->type()->is_error_type())
4599     {
4600       go_assert(saw_errors());
4601       return Expression::make_error(this->location());
4602     }
4603 
4604   Location location = this->location();
4605   if (this->op_ == OPERATOR_MULT
4606       && !this->expr_->is_variable())
4607     {
4608       go_assert(this->expr_->type()->points_to() != NULL);
4609       switch (this->requires_nil_check(gogo))
4610         {
4611           case NIL_CHECK_ERROR_ENCOUNTERED:
4612             {
4613               go_assert(saw_errors());
4614               return Expression::make_error(this->location());
4615             }
4616           case NIL_CHECK_NOT_NEEDED:
4617             break;
4618           case NIL_CHECK_NEEDED:
4619             this->create_temp_ = true;
4620             break;
4621           case NIL_CHECK_DEFAULT:
4622             go_unreachable();
4623         }
4624     }
4625 
4626   if (this->create_temp_ && !this->expr_->is_variable())
4627     {
4628       Temporary_statement* temp =
4629           Statement::make_temporary(NULL, this->expr_, location);
4630       inserter->insert(temp);
4631       this->expr_ = Expression::make_temporary_reference(temp, location);
4632     }
4633 
4634   return this;
4635 }
4636 
4637 // Return whether a unary expression is a constant.
4638 
4639 bool
do_is_constant() const4640 Unary_expression::do_is_constant() const
4641 {
4642   if (this->op_ == OPERATOR_MULT)
4643     {
4644       // Indirecting through a pointer is only constant if the object
4645       // to which the expression points is constant, but we currently
4646       // have no way to determine that.
4647       return false;
4648     }
4649   else if (this->op_ == OPERATOR_AND)
4650     {
4651       // Taking the address of a variable is constant if it is a
4652       // global variable, not constant otherwise.  In other cases taking the
4653       // address is probably not a constant.
4654       Var_expression* ve = this->expr_->var_expression();
4655       if (ve != NULL)
4656 	{
4657 	  Named_object* no = ve->named_object();
4658 	  return no->is_variable() && no->var_value()->is_global();
4659 	}
4660       return false;
4661     }
4662   else
4663     return this->expr_->is_constant();
4664 }
4665 
4666 // Return whether a unary expression can be used as a constant
4667 // initializer.
4668 
4669 bool
do_is_static_initializer() const4670 Unary_expression::do_is_static_initializer() const
4671 {
4672   if (this->op_ == OPERATOR_MULT)
4673     return false;
4674   else if (this->op_ == OPERATOR_AND)
4675     return Unary_expression::base_is_static_initializer(this->expr_);
4676   else
4677     return this->expr_->is_static_initializer();
4678 }
4679 
4680 // Return whether the address of EXPR can be used as a static
4681 // initializer.
4682 
4683 bool
base_is_static_initializer(Expression * expr)4684 Unary_expression::base_is_static_initializer(Expression* expr)
4685 {
4686   // The address of a field reference can be a static initializer if
4687   // the base can be a static initializer.
4688   Field_reference_expression* fre = expr->field_reference_expression();
4689   if (fre != NULL)
4690     return Unary_expression::base_is_static_initializer(fre->expr());
4691 
4692   // The address of an index expression can be a static initializer if
4693   // the base can be a static initializer and the index is constant.
4694   Array_index_expression* aind = expr->array_index_expression();
4695   if (aind != NULL)
4696     return (aind->end() == NULL
4697 	    && aind->start()->is_constant()
4698 	    && Unary_expression::base_is_static_initializer(aind->array()));
4699 
4700   // The address of a global variable can be a static initializer.
4701   Var_expression* ve = expr->var_expression();
4702   if (ve != NULL)
4703     {
4704       Named_object* no = ve->named_object();
4705       return no->is_variable() && no->var_value()->is_global();
4706     }
4707 
4708   // The address of a composite literal can be used as a static
4709   // initializer if the composite literal is itself usable as a
4710   // static initializer.
4711   if (expr->is_composite_literal() && expr->is_static_initializer())
4712     return true;
4713 
4714   // The address of a string constant can be used as a static
4715   // initializer.  This can not be written in Go itself but this is
4716   // used when building a type descriptor.
4717   if (expr->string_expression() != NULL)
4718     return true;
4719 
4720   return false;
4721 }
4722 
4723 // Return whether this dereference expression requires an explicit nil
4724 // check. If we are dereferencing the pointer to a large struct
4725 // (greater than the specified size threshold), we need to check for
4726 // nil. We don't bother to check for small structs because we expect
4727 // the system to crash on a nil pointer dereference. However, if we
4728 // know the address of this expression is being taken, we must always
4729 // check for nil.
4730 Unary_expression::Nil_check_classification
requires_nil_check(Gogo * gogo)4731 Unary_expression::requires_nil_check(Gogo* gogo)
4732 {
4733   go_assert(this->op_ == OPERATOR_MULT);
4734   go_assert(this->expr_->type()->points_to() != NULL);
4735 
4736   if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4737     return NIL_CHECK_NEEDED;
4738   else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4739     return NIL_CHECK_NOT_NEEDED;
4740 
4741   Type* ptype = this->expr_->type()->points_to();
4742   int64_t type_size = -1;
4743   if (!ptype->is_void_type())
4744     {
4745       bool ok = ptype->backend_type_size(gogo, &type_size);
4746       if (!ok)
4747         return NIL_CHECK_ERROR_ENCOUNTERED;
4748     }
4749 
4750   int64_t size_cutoff = gogo->nil_check_size_threshold();
4751   if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4752     this->issue_nil_check_ = NIL_CHECK_NEEDED;
4753   else
4754     this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4755   return this->issue_nil_check_;
4756 }
4757 
4758 // Apply unary opcode OP to UNC, setting NC.  Return true if this
4759 // could be done, false if not.  On overflow, issues an error and sets
4760 // *ISSUED_ERROR.
4761 
4762 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)4763 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4764 				Location location, Numeric_constant* nc,
4765 				bool* issued_error)
4766 {
4767   *issued_error = false;
4768   switch (op)
4769     {
4770     case OPERATOR_PLUS:
4771       *nc = *unc;
4772       return true;
4773 
4774     case OPERATOR_MINUS:
4775       if (unc->is_int() || unc->is_rune())
4776 	break;
4777       else if (unc->is_float())
4778 	{
4779 	  mpfr_t uval;
4780 	  unc->get_float(&uval);
4781 	  mpfr_t val;
4782 	  mpfr_init(val);
4783 	  mpfr_neg(val, uval, MPFR_RNDN);
4784 	  nc->set_float(unc->type(), val);
4785 	  mpfr_clear(uval);
4786 	  mpfr_clear(val);
4787 	  return true;
4788 	}
4789       else if (unc->is_complex())
4790 	{
4791 	  mpc_t uval;
4792 	  unc->get_complex(&uval);
4793 	  mpc_t val;
4794 	  mpc_init2(val, mpc_precision);
4795 	  mpc_neg(val, uval, MPC_RNDNN);
4796 	  nc->set_complex(unc->type(), val);
4797 	  mpc_clear(uval);
4798 	  mpc_clear(val);
4799 	  return true;
4800 	}
4801       else
4802 	go_unreachable();
4803 
4804     case OPERATOR_XOR:
4805       break;
4806 
4807     case OPERATOR_NOT:
4808     case OPERATOR_AND:
4809     case OPERATOR_MULT:
4810       return false;
4811 
4812     default:
4813       go_unreachable();
4814     }
4815 
4816   if (!unc->is_int() && !unc->is_rune())
4817     return false;
4818 
4819   mpz_t uval;
4820   if (unc->is_rune())
4821     unc->get_rune(&uval);
4822   else
4823     unc->get_int(&uval);
4824   mpz_t val;
4825   mpz_init(val);
4826 
4827   switch (op)
4828     {
4829     case OPERATOR_MINUS:
4830       mpz_neg(val, uval);
4831       break;
4832 
4833     case OPERATOR_NOT:
4834       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4835       break;
4836 
4837     case OPERATOR_XOR:
4838       {
4839 	Type* utype = unc->type();
4840 	if (utype->integer_type() == NULL
4841 	    || utype->integer_type()->is_abstract())
4842 	  mpz_com(val, uval);
4843 	else
4844 	  {
4845 	    // The number of HOST_WIDE_INTs that it takes to represent
4846 	    // UVAL.
4847 	    size_t count = ((mpz_sizeinbase(uval, 2)
4848 			     + HOST_BITS_PER_WIDE_INT
4849 			     - 1)
4850 			    / HOST_BITS_PER_WIDE_INT);
4851 
4852 	    unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4853 	    memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4854 
4855 	    size_t obits = utype->integer_type()->bits();
4856 
4857 	    if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4858 	      {
4859 		mpz_t adj;
4860 		mpz_init_set_ui(adj, 1);
4861 		mpz_mul_2exp(adj, adj, obits);
4862 		mpz_add(uval, uval, adj);
4863 		mpz_clear(adj);
4864 	      }
4865 
4866 	    size_t ecount;
4867 	    mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4868 	    go_assert(ecount <= count);
4869 
4870 	    // Trim down to the number of words required by the type.
4871 	    size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4872 			     / HOST_BITS_PER_WIDE_INT);
4873 	    go_assert(ocount <= count);
4874 
4875 	    for (size_t i = 0; i < ocount; ++i)
4876 	      phwi[i] = ~phwi[i];
4877 
4878 	    size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4879 	    if (clearbits != 0)
4880 	      phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4881 				   >> clearbits);
4882 
4883 	    mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4884 
4885 	    if (!utype->integer_type()->is_unsigned()
4886 		&& mpz_tstbit(val, obits - 1))
4887 	      {
4888 		mpz_t adj;
4889 		mpz_init_set_ui(adj, 1);
4890 		mpz_mul_2exp(adj, adj, obits);
4891 		mpz_sub(val, val, adj);
4892 		mpz_clear(adj);
4893 	      }
4894 
4895 	    delete[] phwi;
4896 	  }
4897       }
4898       break;
4899 
4900     default:
4901       go_unreachable();
4902     }
4903 
4904   if (unc->is_rune())
4905     nc->set_rune(NULL, val);
4906   else
4907     nc->set_int(NULL, val);
4908 
4909   mpz_clear(uval);
4910   mpz_clear(val);
4911 
4912   if (!nc->set_type(unc->type(), true, location))
4913     {
4914       *issued_error = true;
4915       return false;
4916     }
4917   return true;
4918 }
4919 
4920 // Return the integral constant value of a unary expression, if it has one.
4921 
4922 bool
do_numeric_constant_value(Numeric_constant * nc) const4923 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4924 {
4925   Numeric_constant unc;
4926   if (!this->expr_->numeric_constant_value(&unc))
4927     return false;
4928   bool issued_error;
4929   return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4930 					 nc, &issued_error);
4931 }
4932 
4933 // Return the boolean constant value of a unary expression, if it has one.
4934 
4935 bool
do_boolean_constant_value(bool * val) const4936 Unary_expression::do_boolean_constant_value(bool* val) const
4937 {
4938   if (this->op_ == OPERATOR_NOT
4939       && this->expr_->boolean_constant_value(val))
4940     {
4941       *val = !*val;
4942       return true;
4943     }
4944   return false;
4945 }
4946 
4947 // Return the type of a unary expression.
4948 
4949 Type*
do_type()4950 Unary_expression::do_type()
4951 {
4952   switch (this->op_)
4953     {
4954     case OPERATOR_PLUS:
4955     case OPERATOR_MINUS:
4956     case OPERATOR_NOT:
4957     case OPERATOR_XOR:
4958       return this->expr_->type();
4959 
4960     case OPERATOR_AND:
4961       return Type::make_pointer_type(this->expr_->type());
4962 
4963     case OPERATOR_MULT:
4964       {
4965 	Type* subtype = this->expr_->type();
4966 	Type* points_to = subtype->points_to();
4967 	if (points_to == NULL)
4968 	  return Type::make_error_type();
4969 	return points_to;
4970       }
4971 
4972     default:
4973       go_unreachable();
4974     }
4975 }
4976 
4977 // Determine abstract types for a unary expression.
4978 
4979 void
do_determine_type(const Type_context * context)4980 Unary_expression::do_determine_type(const Type_context* context)
4981 {
4982   switch (this->op_)
4983     {
4984     case OPERATOR_PLUS:
4985     case OPERATOR_MINUS:
4986     case OPERATOR_NOT:
4987     case OPERATOR_XOR:
4988       this->expr_->determine_type(context);
4989       break;
4990 
4991     case OPERATOR_AND:
4992       // Taking the address of something.
4993       {
4994 	Type* subtype = (context->type == NULL
4995 			 ? NULL
4996 			 : context->type->points_to());
4997 	Type_context subcontext(subtype, false);
4998 	this->expr_->determine_type(&subcontext);
4999       }
5000       break;
5001 
5002     case OPERATOR_MULT:
5003       // Indirecting through a pointer.
5004       {
5005 	Type* subtype = (context->type == NULL
5006 			 ? NULL
5007 			 : Type::make_pointer_type(context->type));
5008 	Type_context subcontext(subtype, false);
5009 	this->expr_->determine_type(&subcontext);
5010       }
5011       break;
5012 
5013     default:
5014       go_unreachable();
5015     }
5016 }
5017 
5018 // Check types for a unary expression.
5019 
5020 void
do_check_types(Gogo *)5021 Unary_expression::do_check_types(Gogo*)
5022 {
5023   Type* type = this->expr_->type();
5024   if (type->is_error())
5025     {
5026       this->set_is_error();
5027       return;
5028     }
5029 
5030   switch (this->op_)
5031     {
5032     case OPERATOR_PLUS:
5033     case OPERATOR_MINUS:
5034       if (type->integer_type() == NULL
5035 	  && type->float_type() == NULL
5036 	  && type->complex_type() == NULL)
5037 	this->report_error(_("expected numeric type"));
5038       break;
5039 
5040     case OPERATOR_NOT:
5041       if (!type->is_boolean_type())
5042 	this->report_error(_("expected boolean type"));
5043       break;
5044 
5045     case OPERATOR_XOR:
5046       if (type->integer_type() == NULL)
5047 	this->report_error(_("expected integer"));
5048       break;
5049 
5050     case OPERATOR_AND:
5051       if (!this->expr_->is_addressable())
5052 	{
5053 	  if (!this->create_temp_)
5054 	    {
5055 	      go_error_at(this->location(), "invalid operand for unary %<&%>");
5056 	      this->set_is_error();
5057 	    }
5058 	}
5059       else
5060 	this->expr_->issue_nil_check();
5061       break;
5062 
5063     case OPERATOR_MULT:
5064       // Indirecting through a pointer.
5065       if (type->points_to() == NULL)
5066 	this->report_error(_("expected pointer"));
5067       if (type->points_to()->is_error())
5068 	this->set_is_error();
5069       break;
5070 
5071     default:
5072       go_unreachable();
5073     }
5074 }
5075 
5076 // Get the backend representation for a unary expression.
5077 
5078 Bexpression*
do_get_backend(Translate_context * context)5079 Unary_expression::do_get_backend(Translate_context* context)
5080 {
5081   Gogo* gogo = context->gogo();
5082   Location loc = this->location();
5083 
5084   // Taking the address of a set-and-use-temporary expression requires
5085   // setting the temporary and then taking the address.
5086   if (this->op_ == OPERATOR_AND)
5087     {
5088       Set_and_use_temporary_expression* sut =
5089 	this->expr_->set_and_use_temporary_expression();
5090       if (sut != NULL)
5091 	{
5092 	  Temporary_statement* temp = sut->temporary();
5093 	  Bvariable* bvar = temp->get_backend_variable(context);
5094           Bexpression* bvar_expr =
5095               gogo->backend()->var_expression(bvar, loc);
5096           Bexpression* bval = sut->expression()->get_backend(context);
5097 
5098           Named_object* fn = context->function();
5099           go_assert(fn != NULL);
5100           Bfunction* bfn =
5101               fn->func_value()->get_or_make_decl(gogo, fn);
5102           Bstatement* bassign =
5103               gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
5104           Bexpression* bvar_addr =
5105               gogo->backend()->address_expression(bvar_expr, loc);
5106 	  return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
5107 	}
5108     }
5109 
5110   Bexpression* ret;
5111   Bexpression* bexpr = this->expr_->get_backend(context);
5112   Btype* btype = this->expr_->type()->get_backend(gogo);
5113   switch (this->op_)
5114     {
5115     case OPERATOR_PLUS:
5116       ret = bexpr;
5117       break;
5118 
5119     case OPERATOR_MINUS:
5120       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5121       ret = gogo->backend()->convert_expression(btype, ret, loc);
5122       break;
5123 
5124     case OPERATOR_NOT:
5125     case OPERATOR_XOR:
5126       ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5127       break;
5128 
5129     case OPERATOR_AND:
5130       if (!this->create_temp_)
5131 	{
5132 	  // We should not see a non-constant constructor here; cases
5133 	  // where we would see one should have been moved onto the
5134 	  // heap at parse time.  Taking the address of a nonconstant
5135 	  // constructor will not do what the programmer expects.
5136 
5137           go_assert(!this->expr_->is_composite_literal()
5138                     || this->expr_->is_static_initializer());
5139 	  if (this->expr_->classification() == EXPRESSION_UNARY)
5140 	    {
5141 	      Unary_expression* ue =
5142 		static_cast<Unary_expression*>(this->expr_);
5143 	      go_assert(ue->op() != OPERATOR_AND);
5144 	    }
5145 	}
5146 
5147       if (this->is_gc_root_ || this->is_slice_init_)
5148 	{
5149 	  std::string var_name;
5150 	  bool copy_to_heap = false;
5151 	  if (this->is_gc_root_)
5152 	    {
5153 	      // Build a decl for a GC root variable.  GC roots are mutable, so
5154 	      // they cannot be represented as an immutable_struct in the
5155 	      // backend.
5156 	      var_name = gogo->gc_root_name();
5157 	    }
5158 	  else
5159 	    {
5160 	      // Build a decl for a slice value initializer.  An immutable slice
5161 	      // value initializer may have to be copied to the heap if it
5162 	      // contains pointers in a non-constant context.
5163 	      var_name = gogo->initializer_name();
5164 
5165 	      Array_type* at = this->expr_->type()->array_type();
5166 	      go_assert(at != NULL);
5167 
5168 	      // If we are not copying the value to the heap, we will only
5169 	      // initialize the value once, so we can use this directly
5170 	      // rather than copying it.  In that case we can't make it
5171 	      // read-only, because the program is permitted to change it.
5172 	      copy_to_heap = (context->function() != NULL
5173                               || context->is_const());
5174 	    }
5175 	  std::string asm_name(go_selectively_encode_id(var_name));
5176 	  Bvariable* implicit =
5177               gogo->backend()->implicit_variable(var_name, asm_name,
5178                                                  btype, true, copy_to_heap,
5179                                                  false, 0);
5180 	  gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
5181 						      true, copy_to_heap, false,
5182 						      bexpr);
5183 	  bexpr = gogo->backend()->var_expression(implicit, loc);
5184 
5185 	  // If we are not copying a slice initializer to the heap,
5186 	  // then it can be changed by the program, so if it can
5187 	  // contain pointers we must register it as a GC root.
5188 	  if (this->is_slice_init_
5189 	      && !copy_to_heap
5190 	      && this->expr_->type()->has_pointer())
5191 	    {
5192 	      Bexpression* root =
5193                   gogo->backend()->var_expression(implicit, loc);
5194 	      root = gogo->backend()->address_expression(root, loc);
5195 	      Type* type = Type::make_pointer_type(this->expr_->type());
5196 	      gogo->add_gc_root(Expression::make_backend(root, type, loc));
5197 	    }
5198 	}
5199       else if ((this->expr_->is_composite_literal()
5200 		|| this->expr_->string_expression() != NULL)
5201 	       && this->expr_->is_static_initializer())
5202         {
5203 	  std::string var_name(gogo->initializer_name());
5204 	  std::string asm_name(go_selectively_encode_id(var_name));
5205           Bvariable* decl =
5206               gogo->backend()->immutable_struct(var_name, asm_name,
5207                                                 true, false, btype, loc);
5208           gogo->backend()->immutable_struct_set_init(decl, var_name, true,
5209 						     false, btype, loc, bexpr);
5210           bexpr = gogo->backend()->var_expression(decl, loc);
5211         }
5212       else if (this->expr_->is_constant())
5213         {
5214           std::string var_name(gogo->initializer_name());
5215           std::string asm_name(go_selectively_encode_id(var_name));
5216           Bvariable* decl =
5217               gogo->backend()->implicit_variable(var_name, asm_name, btype,
5218                                                  true, true, false, 0);
5219           gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
5220                                                       true, true, false,
5221                                                       bexpr);
5222           bexpr = gogo->backend()->var_expression(decl, loc);
5223         }
5224 
5225       go_assert(!this->create_temp_ || this->expr_->is_variable());
5226       ret = gogo->backend()->address_expression(bexpr, loc);
5227       break;
5228 
5229     case OPERATOR_MULT:
5230       {
5231         go_assert(this->expr_->type()->points_to() != NULL);
5232 
5233         bool known_valid = false;
5234         Type* ptype = this->expr_->type()->points_to();
5235         Btype* pbtype = ptype->get_backend(gogo);
5236         switch (this->requires_nil_check(gogo))
5237           {
5238             case NIL_CHECK_NOT_NEEDED:
5239               break;
5240             case NIL_CHECK_ERROR_ENCOUNTERED:
5241               {
5242                 go_assert(saw_errors());
5243                 return gogo->backend()->error_expression();
5244               }
5245             case NIL_CHECK_NEEDED:
5246               {
5247                 go_assert(this->expr_->is_variable());
5248 
5249                 // If we're nil-checking the result of a set-and-use-temporary
5250                 // expression, then pick out the target temp and use that
5251                 // for the final result of the conditional.
5252                 Bexpression* tbexpr = bexpr;
5253                 Bexpression* ubexpr = bexpr;
5254                 Set_and_use_temporary_expression* sut =
5255                     this->expr_->set_and_use_temporary_expression();
5256                 if (sut != NULL) {
5257                   Temporary_statement* temp = sut->temporary();
5258                   Bvariable* bvar = temp->get_backend_variable(context);
5259                   ubexpr = gogo->backend()->var_expression(bvar, loc);
5260                 }
5261                 Bexpression* nil =
5262                     Expression::make_nil(loc)->get_backend(context);
5263                 Bexpression* compare =
5264                     gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
5265                                                        nil, loc);
5266 		Expression* crash = Runtime::make_call(Runtime::PANIC_MEM,
5267 						       loc, 0);
5268 		Bexpression* bcrash = crash->get_backend(context);
5269                 Bfunction* bfn = context->function()->func_value()->get_decl();
5270                 bexpr = gogo->backend()->conditional_expression(bfn, btype,
5271                                                                 compare,
5272                                                                 bcrash, ubexpr,
5273                                                                 loc);
5274                 known_valid = true;
5275                 break;
5276               }
5277             case NIL_CHECK_DEFAULT:
5278               go_unreachable();
5279           }
5280         ret = gogo->backend()->indirect_expression(pbtype, bexpr,
5281                                                    known_valid, loc);
5282       }
5283       break;
5284 
5285     default:
5286       go_unreachable();
5287     }
5288 
5289   return ret;
5290 }
5291 
5292 // Export a unary expression.
5293 
5294 void
do_export(Export_function_body * efb) const5295 Unary_expression::do_export(Export_function_body* efb) const
5296 {
5297   switch (this->op_)
5298     {
5299     case OPERATOR_PLUS:
5300       efb->write_c_string("+");
5301       break;
5302     case OPERATOR_MINUS:
5303       efb->write_c_string("-");
5304       break;
5305     case OPERATOR_NOT:
5306       efb->write_c_string("!");
5307       break;
5308     case OPERATOR_XOR:
5309       efb->write_c_string("^");
5310       break;
5311     case OPERATOR_AND:
5312       efb->write_c_string("&");
5313       break;
5314     case OPERATOR_MULT:
5315       efb->write_c_string("*");
5316       break;
5317     default:
5318       go_unreachable();
5319     }
5320   this->expr_->export_expression(efb);
5321 }
5322 
5323 // Import a unary expression.
5324 
5325 Expression*
do_import(Import_expression * imp,Location loc)5326 Unary_expression::do_import(Import_expression* imp, Location loc)
5327 {
5328   Operator op;
5329   switch (imp->get_char())
5330     {
5331     case '+':
5332       op = OPERATOR_PLUS;
5333       break;
5334     case '-':
5335       op = OPERATOR_MINUS;
5336       break;
5337     case '!':
5338       op = OPERATOR_NOT;
5339       break;
5340     case '^':
5341       op = OPERATOR_XOR;
5342       break;
5343     case '&':
5344       op = OPERATOR_AND;
5345       break;
5346     case '*':
5347       op = OPERATOR_MULT;
5348       break;
5349     default:
5350       go_unreachable();
5351     }
5352   if (imp->version() < EXPORT_FORMAT_V3)
5353     imp->require_c_string(" ");
5354   Expression* expr = Expression::import_expression(imp, loc);
5355   return Expression::make_unary(op, expr, loc);
5356 }
5357 
5358 // Dump ast representation of an unary expression.
5359 
5360 void
do_dump_expression(Ast_dump_context * ast_dump_context) const5361 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5362 {
5363   ast_dump_context->dump_operator(this->op_);
5364   ast_dump_context->ostream() << "(";
5365   ast_dump_context->dump_expression(this->expr_);
5366   ast_dump_context->ostream() << ") ";
5367 }
5368 
5369 // Make a unary expression.
5370 
5371 Expression*
make_unary(Operator op,Expression * expr,Location location)5372 Expression::make_unary(Operator op, Expression* expr, Location location)
5373 {
5374   return new Unary_expression(op, expr, location);
5375 }
5376 
5377 Expression*
make_dereference(Expression * ptr,Nil_check_classification docheck,Location location)5378 Expression::make_dereference(Expression* ptr,
5379                              Nil_check_classification docheck,
5380                              Location location)
5381 {
5382   Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
5383   if (docheck == NIL_CHECK_NEEDED)
5384     deref->unary_expression()->set_requires_nil_check(true);
5385   else if (docheck == NIL_CHECK_NOT_NEEDED)
5386     deref->unary_expression()->set_requires_nil_check(false);
5387   return deref;
5388 }
5389 
5390 // If this is an indirection through a pointer, return the expression
5391 // being pointed through.  Otherwise return this.
5392 
5393 Expression*
deref()5394 Expression::deref()
5395 {
5396   if (this->classification_ == EXPRESSION_UNARY)
5397     {
5398       Unary_expression* ue = static_cast<Unary_expression*>(this);
5399       if (ue->op() == OPERATOR_MULT)
5400 	return ue->operand();
5401     }
5402   return this;
5403 }
5404 
5405 // Class Binary_expression.
5406 
5407 // Traversal.
5408 
5409 int
do_traverse(Traverse * traverse)5410 Binary_expression::do_traverse(Traverse* traverse)
5411 {
5412   int t = Expression::traverse(&this->left_, traverse);
5413   if (t == TRAVERSE_EXIT)
5414     return TRAVERSE_EXIT;
5415   return Expression::traverse(&this->right_, traverse);
5416 }
5417 
5418 // Return whether this expression may be used as a static initializer.
5419 
5420 bool
do_is_static_initializer() const5421 Binary_expression::do_is_static_initializer() const
5422 {
5423   if (!this->left_->is_static_initializer()
5424       || !this->right_->is_static_initializer())
5425     return false;
5426 
5427   // Addresses can be static initializers, but we can't implement
5428   // arbitray binary expressions of them.
5429   Unary_expression* lu = this->left_->unary_expression();
5430   Unary_expression* ru = this->right_->unary_expression();
5431   if (lu != NULL && lu->op() == OPERATOR_AND)
5432     {
5433       if (ru != NULL && ru->op() == OPERATOR_AND)
5434 	return this->op_ == OPERATOR_MINUS;
5435       else
5436 	return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5437     }
5438   else if (ru != NULL && ru->op() == OPERATOR_AND)
5439     return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5440 
5441   // Other cases should resolve in the backend.
5442   return true;
5443 }
5444 
5445 // Return the type to use for a binary operation on operands of
5446 // LEFT_TYPE and RIGHT_TYPE.  These are the types of constants and as
5447 // such may be NULL or abstract.
5448 
5449 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)5450 Binary_expression::operation_type(Operator op, Type* left_type,
5451 				  Type* right_type, Type** result_type)
5452 {
5453   if (left_type != right_type
5454       && !left_type->is_abstract()
5455       && !right_type->is_abstract()
5456       && left_type->base() != right_type->base()
5457       && op != OPERATOR_LSHIFT
5458       && op != OPERATOR_RSHIFT)
5459     {
5460       // May be a type error--let it be diagnosed elsewhere.
5461       return false;
5462     }
5463 
5464   if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5465     {
5466       if (left_type->integer_type() != NULL)
5467 	*result_type = left_type;
5468       else
5469 	*result_type = Type::make_abstract_integer_type();
5470     }
5471   else if (!left_type->is_abstract() && left_type->named_type() != NULL)
5472     *result_type = left_type;
5473   else if (!right_type->is_abstract() && right_type->named_type() != NULL)
5474     *result_type = right_type;
5475   else if (!left_type->is_abstract())
5476     *result_type = left_type;
5477   else if (!right_type->is_abstract())
5478     *result_type = right_type;
5479   else if (left_type->complex_type() != NULL)
5480     *result_type = left_type;
5481   else if (right_type->complex_type() != NULL)
5482     *result_type = right_type;
5483   else if (left_type->float_type() != NULL)
5484     *result_type = left_type;
5485   else if (right_type->float_type() != NULL)
5486     *result_type = right_type;
5487   else if (left_type->integer_type() != NULL
5488 	   && left_type->integer_type()->is_rune())
5489     *result_type = left_type;
5490   else if (right_type->integer_type() != NULL
5491 	   && right_type->integer_type()->is_rune())
5492     *result_type = right_type;
5493   else
5494     *result_type = left_type;
5495 
5496   return true;
5497 }
5498 
5499 // Convert an integer comparison code and an operator to a boolean
5500 // value.
5501 
5502 bool
cmp_to_bool(Operator op,int cmp)5503 Binary_expression::cmp_to_bool(Operator op, int cmp)
5504 {
5505   switch (op)
5506     {
5507     case OPERATOR_EQEQ:
5508       return cmp == 0;
5509       break;
5510     case OPERATOR_NOTEQ:
5511       return cmp != 0;
5512       break;
5513     case OPERATOR_LT:
5514       return cmp < 0;
5515       break;
5516     case OPERATOR_LE:
5517       return cmp <= 0;
5518     case OPERATOR_GT:
5519       return cmp > 0;
5520     case OPERATOR_GE:
5521       return cmp >= 0;
5522     default:
5523       go_unreachable();
5524     }
5525 }
5526 
5527 // Compare constants according to OP.
5528 
5529 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)5530 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
5531 				    Numeric_constant* right_nc,
5532 				    Location location, bool* result)
5533 {
5534   Type* left_type = left_nc->type();
5535   Type* right_type = right_nc->type();
5536 
5537   Type* type;
5538   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5539     return false;
5540 
5541   // When comparing an untyped operand to a typed operand, we are
5542   // effectively coercing the untyped operand to the other operand's
5543   // type, so make sure that is valid.
5544   if (!left_nc->set_type(type, true, location)
5545       || !right_nc->set_type(type, true, location))
5546     return false;
5547 
5548   bool ret;
5549   int cmp;
5550   if (type->complex_type() != NULL)
5551     {
5552       if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
5553 	return false;
5554       ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
5555     }
5556   else if (type->float_type() != NULL)
5557     ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
5558   else
5559     ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
5560 
5561   if (ret)
5562     *result = Binary_expression::cmp_to_bool(op, cmp);
5563 
5564   return ret;
5565 }
5566 
5567 // Compare integer constants.
5568 
5569 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5570 Binary_expression::compare_integer(const Numeric_constant* left_nc,
5571 				   const Numeric_constant* right_nc,
5572 				   int* cmp)
5573 {
5574   mpz_t left_val;
5575   if (!left_nc->to_int(&left_val))
5576     return false;
5577   mpz_t right_val;
5578   if (!right_nc->to_int(&right_val))
5579     {
5580       mpz_clear(left_val);
5581       return false;
5582     }
5583 
5584   *cmp = mpz_cmp(left_val, right_val);
5585 
5586   mpz_clear(left_val);
5587   mpz_clear(right_val);
5588 
5589   return true;
5590 }
5591 
5592 // Compare floating point constants.
5593 
5594 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5595 Binary_expression::compare_float(const Numeric_constant* left_nc,
5596 				 const Numeric_constant* right_nc,
5597 				 int* cmp)
5598 {
5599   mpfr_t left_val;
5600   if (!left_nc->to_float(&left_val))
5601     return false;
5602   mpfr_t right_val;
5603   if (!right_nc->to_float(&right_val))
5604     {
5605       mpfr_clear(left_val);
5606       return false;
5607     }
5608 
5609   // We already coerced both operands to the same type.  If that type
5610   // is not an abstract type, we need to round the values accordingly.
5611   Type* type = left_nc->type();
5612   if (!type->is_abstract() && type->float_type() != NULL)
5613     {
5614       int bits = type->float_type()->bits();
5615       mpfr_prec_round(left_val, bits, MPFR_RNDN);
5616       mpfr_prec_round(right_val, bits, MPFR_RNDN);
5617     }
5618 
5619   *cmp = mpfr_cmp(left_val, right_val);
5620 
5621   mpfr_clear(left_val);
5622   mpfr_clear(right_val);
5623 
5624   return true;
5625 }
5626 
5627 // Compare complex constants.  Complex numbers may only be compared
5628 // for equality.
5629 
5630 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5631 Binary_expression::compare_complex(const Numeric_constant* left_nc,
5632 				   const Numeric_constant* right_nc,
5633 				   int* cmp)
5634 {
5635   mpc_t left_val;
5636   if (!left_nc->to_complex(&left_val))
5637     return false;
5638   mpc_t right_val;
5639   if (!right_nc->to_complex(&right_val))
5640     {
5641       mpc_clear(left_val);
5642       return false;
5643     }
5644 
5645   // We already coerced both operands to the same type.  If that type
5646   // is not an abstract type, we need to round the values accordingly.
5647   Type* type = left_nc->type();
5648   if (!type->is_abstract() && type->complex_type() != NULL)
5649     {
5650       int bits = type->complex_type()->bits();
5651       mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
5652       mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
5653       mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
5654       mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
5655     }
5656 
5657   *cmp = mpc_cmp(left_val, right_val) != 0;
5658 
5659   mpc_clear(left_val);
5660   mpc_clear(right_val);
5661 
5662   return true;
5663 }
5664 
5665 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC.  Return
5666 // true if this could be done, false if not.  Issue errors at LOCATION
5667 // as appropriate, and sets *ISSUED_ERROR if it did.
5668 
5669 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)5670 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
5671 				 Numeric_constant* right_nc,
5672 				 Location location, Numeric_constant* nc,
5673 				 bool* issued_error)
5674 {
5675   *issued_error = false;
5676   switch (op)
5677     {
5678     case OPERATOR_OROR:
5679     case OPERATOR_ANDAND:
5680     case OPERATOR_EQEQ:
5681     case OPERATOR_NOTEQ:
5682     case OPERATOR_LT:
5683     case OPERATOR_LE:
5684     case OPERATOR_GT:
5685     case OPERATOR_GE:
5686       // These return boolean values, not numeric.
5687       return false;
5688     default:
5689       break;
5690     }
5691 
5692   Type* left_type = left_nc->type();
5693   Type* right_type = right_nc->type();
5694 
5695   Type* type;
5696   if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5697     return false;
5698 
5699   bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
5700 
5701   // When combining an untyped operand with a typed operand, we are
5702   // effectively coercing the untyped operand to the other operand's
5703   // type, so make sure that is valid.
5704   if (!left_nc->set_type(type, true, location))
5705     return false;
5706   if (!is_shift && !right_nc->set_type(type, true, location))
5707     return false;
5708   if (is_shift
5709       && ((left_type->integer_type() == NULL
5710            && !left_type->is_abstract())
5711           || (right_type->integer_type() == NULL
5712               && !right_type->is_abstract())))
5713     return false;
5714 
5715   bool r;
5716   if (type->complex_type() != NULL)
5717     r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
5718   else if (type->float_type() != NULL)
5719     r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
5720   else
5721     r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
5722 
5723   if (r)
5724     {
5725       r = nc->set_type(type, true, location);
5726       if (!r)
5727 	*issued_error = true;
5728     }
5729 
5730   return r;
5731 }
5732 
5733 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5734 // integer operations.  Return true if this could be done, false if
5735 // not.
5736 
5737 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5738 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
5739 				const Numeric_constant* right_nc,
5740 				Location location, Numeric_constant* nc)
5741 {
5742   mpz_t left_val;
5743   if (!left_nc->to_int(&left_val))
5744     return false;
5745   mpz_t right_val;
5746   if (!right_nc->to_int(&right_val))
5747     {
5748       mpz_clear(left_val);
5749       return false;
5750     }
5751 
5752   mpz_t val;
5753   mpz_init(val);
5754 
5755   switch (op)
5756     {
5757     case OPERATOR_PLUS:
5758       mpz_add(val, left_val, right_val);
5759       if (mpz_sizeinbase(val, 2) > 0x100000)
5760 	{
5761 	  go_error_at(location, "constant addition overflow");
5762           nc->set_invalid();
5763 	  mpz_set_ui(val, 1);
5764 	}
5765       break;
5766     case OPERATOR_MINUS:
5767       mpz_sub(val, left_val, right_val);
5768       if (mpz_sizeinbase(val, 2) > 0x100000)
5769 	{
5770 	  go_error_at(location, "constant subtraction overflow");
5771           nc->set_invalid();
5772 	  mpz_set_ui(val, 1);
5773 	}
5774       break;
5775     case OPERATOR_OR:
5776       mpz_ior(val, left_val, right_val);
5777       break;
5778     case OPERATOR_XOR:
5779       mpz_xor(val, left_val, right_val);
5780       break;
5781     case OPERATOR_MULT:
5782       mpz_mul(val, left_val, right_val);
5783       if (mpz_sizeinbase(val, 2) > 0x100000)
5784 	{
5785 	  go_error_at(location, "constant multiplication overflow");
5786           nc->set_invalid();
5787 	  mpz_set_ui(val, 1);
5788 	}
5789       break;
5790     case OPERATOR_DIV:
5791       if (mpz_sgn(right_val) != 0)
5792 	mpz_tdiv_q(val, left_val, right_val);
5793       else
5794 	{
5795 	  go_error_at(location, "division by zero");
5796           nc->set_invalid();
5797 	  mpz_set_ui(val, 0);
5798 	}
5799       break;
5800     case OPERATOR_MOD:
5801       if (mpz_sgn(right_val) != 0)
5802 	mpz_tdiv_r(val, left_val, right_val);
5803       else
5804 	{
5805 	  go_error_at(location, "division by zero");
5806           nc->set_invalid();
5807 	  mpz_set_ui(val, 0);
5808 	}
5809       break;
5810     case OPERATOR_LSHIFT:
5811       {
5812 	unsigned long shift = mpz_get_ui(right_val);
5813 	if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5814 	  mpz_mul_2exp(val, left_val, shift);
5815 	else
5816 	  {
5817 	    go_error_at(location, "shift count overflow");
5818             nc->set_invalid();
5819 	    mpz_set_ui(val, 1);
5820 	  }
5821 	break;
5822       }
5823       break;
5824     case OPERATOR_RSHIFT:
5825       {
5826 	unsigned long shift = mpz_get_ui(right_val);
5827 	if (mpz_cmp_ui(right_val, shift) != 0)
5828 	  {
5829 	    go_error_at(location, "shift count overflow");
5830             nc->set_invalid();
5831 	    mpz_set_ui(val, 1);
5832 	  }
5833 	else
5834 	  {
5835 	    if (mpz_cmp_ui(left_val, 0) >= 0)
5836 	      mpz_tdiv_q_2exp(val, left_val, shift);
5837 	    else
5838 	      mpz_fdiv_q_2exp(val, left_val, shift);
5839 	  }
5840 	break;
5841       }
5842       break;
5843     case OPERATOR_AND:
5844       mpz_and(val, left_val, right_val);
5845       break;
5846     case OPERATOR_BITCLEAR:
5847       {
5848 	mpz_t tval;
5849 	mpz_init(tval);
5850 	mpz_com(tval, right_val);
5851 	mpz_and(val, left_val, tval);
5852 	mpz_clear(tval);
5853       }
5854       break;
5855     default:
5856       go_unreachable();
5857     }
5858 
5859   mpz_clear(left_val);
5860   mpz_clear(right_val);
5861 
5862   if (left_nc->is_rune()
5863       || (op != OPERATOR_LSHIFT
5864 	  && op != OPERATOR_RSHIFT
5865 	  && right_nc->is_rune()))
5866     nc->set_rune(NULL, val);
5867   else
5868     nc->set_int(NULL, val);
5869 
5870   mpz_clear(val);
5871 
5872   return true;
5873 }
5874 
5875 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5876 // floating point operations.  Return true if this could be done,
5877 // false if not.
5878 
5879 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5880 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5881 			      const Numeric_constant* right_nc,
5882 			      Location location, Numeric_constant* nc)
5883 {
5884   mpfr_t left_val;
5885   if (!left_nc->to_float(&left_val))
5886     return false;
5887   mpfr_t right_val;
5888   if (!right_nc->to_float(&right_val))
5889     {
5890       mpfr_clear(left_val);
5891       return false;
5892     }
5893 
5894   mpfr_t val;
5895   mpfr_init(val);
5896 
5897   bool ret = true;
5898   switch (op)
5899     {
5900     case OPERATOR_PLUS:
5901       mpfr_add(val, left_val, right_val, MPFR_RNDN);
5902       break;
5903     case OPERATOR_MINUS:
5904       mpfr_sub(val, left_val, right_val, MPFR_RNDN);
5905       break;
5906     case OPERATOR_OR:
5907     case OPERATOR_XOR:
5908     case OPERATOR_AND:
5909     case OPERATOR_BITCLEAR:
5910     case OPERATOR_MOD:
5911     case OPERATOR_LSHIFT:
5912     case OPERATOR_RSHIFT:
5913       mpfr_set_ui(val, 0, MPFR_RNDN);
5914       ret = false;
5915       break;
5916     case OPERATOR_MULT:
5917       mpfr_mul(val, left_val, right_val, MPFR_RNDN);
5918       break;
5919     case OPERATOR_DIV:
5920       if (!mpfr_zero_p(right_val))
5921 	mpfr_div(val, left_val, right_val, MPFR_RNDN);
5922       else
5923 	{
5924 	  go_error_at(location, "division by zero");
5925           nc->set_invalid();
5926 	  mpfr_set_ui(val, 0, MPFR_RNDN);
5927 	}
5928       break;
5929     default:
5930       go_unreachable();
5931     }
5932 
5933   mpfr_clear(left_val);
5934   mpfr_clear(right_val);
5935 
5936   nc->set_float(NULL, val);
5937   mpfr_clear(val);
5938 
5939   return ret;
5940 }
5941 
5942 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5943 // complex operations.  Return true if this could be done, false if
5944 // not.
5945 
5946 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5947 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5948 				const Numeric_constant* right_nc,
5949 				Location location, Numeric_constant* nc)
5950 {
5951   mpc_t left_val;
5952   if (!left_nc->to_complex(&left_val))
5953     return false;
5954   mpc_t right_val;
5955   if (!right_nc->to_complex(&right_val))
5956     {
5957       mpc_clear(left_val);
5958       return false;
5959     }
5960 
5961   mpc_t val;
5962   mpc_init2(val, mpc_precision);
5963 
5964   bool ret = true;
5965   switch (op)
5966     {
5967     case OPERATOR_PLUS:
5968       mpc_add(val, left_val, right_val, MPC_RNDNN);
5969       break;
5970     case OPERATOR_MINUS:
5971       mpc_sub(val, left_val, right_val, MPC_RNDNN);
5972       break;
5973     case OPERATOR_OR:
5974     case OPERATOR_XOR:
5975     case OPERATOR_AND:
5976     case OPERATOR_BITCLEAR:
5977     case OPERATOR_MOD:
5978     case OPERATOR_LSHIFT:
5979     case OPERATOR_RSHIFT:
5980       mpc_set_ui(val, 0, MPC_RNDNN);
5981       ret = false;
5982       break;
5983     case OPERATOR_MULT:
5984       mpc_mul(val, left_val, right_val, MPC_RNDNN);
5985       break;
5986     case OPERATOR_DIV:
5987       if (mpc_cmp_si(right_val, 0) == 0)
5988 	{
5989 	  go_error_at(location, "division by zero");
5990           nc->set_invalid();
5991 	  mpc_set_ui(val, 0, MPC_RNDNN);
5992 	  break;
5993 	}
5994       mpc_div(val, left_val, right_val, MPC_RNDNN);
5995       break;
5996     default:
5997       go_unreachable();
5998     }
5999 
6000   mpc_clear(left_val);
6001   mpc_clear(right_val);
6002 
6003   nc->set_complex(NULL, val);
6004   mpc_clear(val);
6005 
6006   return ret;
6007 }
6008 
6009 // Lower a binary expression.  We have to evaluate constant
6010 // expressions now, in order to implement Go's unlimited precision
6011 // constants.
6012 
6013 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)6014 Binary_expression::do_lower(Gogo* gogo, Named_object*,
6015 			    Statement_inserter* inserter, int)
6016 {
6017   Location location = this->location();
6018   Operator op = this->op_;
6019   Expression* left = this->left_;
6020   Expression* right = this->right_;
6021 
6022   const bool is_comparison = (op == OPERATOR_EQEQ
6023 			      || op == OPERATOR_NOTEQ
6024 			      || op == OPERATOR_LT
6025 			      || op == OPERATOR_LE
6026 			      || op == OPERATOR_GT
6027 			      || op == OPERATOR_GE);
6028 
6029   // Numeric constant expressions.
6030   {
6031     Numeric_constant left_nc;
6032     Numeric_constant right_nc;
6033     if (left->numeric_constant_value(&left_nc)
6034 	&& right->numeric_constant_value(&right_nc))
6035       {
6036 	if (is_comparison)
6037 	  {
6038 	    bool result;
6039 	    if (!Binary_expression::compare_constant(op, &left_nc,
6040 						     &right_nc, location,
6041 						     &result))
6042 	      return this;
6043 	    return Expression::make_cast(Type::make_boolean_type(),
6044 					 Expression::make_boolean(result,
6045 								  location),
6046 					 location);
6047 	  }
6048 	else
6049 	  {
6050 	    Numeric_constant nc;
6051 	    bool issued_error;
6052 	    if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
6053 						  location, &nc,
6054 						  &issued_error))
6055 	      {
6056 		if (issued_error)
6057 		  return Expression::make_error(location);
6058                 return this;
6059 	      }
6060 	    return nc.expression(location);
6061 	  }
6062       }
6063   }
6064 
6065   // String constant expressions.
6066   //
6067   // Avoid constant folding here if the left and right types are incompatible
6068   // (leave the operation intact so that the type checker can complain about it
6069   // later on). If concatenating an abstract string with a named string type,
6070   // result type needs to be of the named type (see issue 31412).
6071   if (left->type()->is_string_type()
6072       && right->type()->is_string_type()
6073       && (left->type()->named_type() == NULL
6074           || right->type()->named_type() == NULL
6075           || left->type()->named_type() == right->type()->named_type()))
6076     {
6077       std::string left_string;
6078       std::string right_string;
6079       if (left->string_constant_value(&left_string)
6080 	  && right->string_constant_value(&right_string))
6081 	{
6082 	  if (op == OPERATOR_PLUS)
6083             {
6084               Type* result_type = (left->type()->named_type() != NULL
6085                                    ? left->type()
6086                                    : right->type());
6087               return Expression::make_string_typed(left_string + right_string,
6088                                                    result_type, location);
6089             }
6090 	  else if (is_comparison)
6091 	    {
6092 	      int cmp = left_string.compare(right_string);
6093 	      bool r = Binary_expression::cmp_to_bool(op, cmp);
6094 	      return Expression::make_boolean(r, location);
6095 	    }
6096 	}
6097     }
6098 
6099   // Lower struct, array, and some interface comparisons.
6100   if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6101     {
6102       if (left->type()->struct_type() != NULL
6103 	  && right->type()->struct_type() != NULL)
6104 	return this->lower_struct_comparison(gogo, inserter);
6105       else if (left->type()->array_type() != NULL
6106 	       && !left->type()->is_slice_type()
6107 	       && right->type()->array_type() != NULL
6108 	       && !right->type()->is_slice_type())
6109 	return this->lower_array_comparison(gogo, inserter);
6110       else if ((left->type()->interface_type() != NULL
6111                 && right->type()->interface_type() == NULL)
6112                || (left->type()->interface_type() == NULL
6113                    && right->type()->interface_type() != NULL))
6114 	return this->lower_interface_value_comparison(gogo, inserter);
6115     }
6116 
6117   // Lower string concatenation to String_concat_expression, so that
6118   // we can group sequences of string additions.
6119   if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
6120     {
6121       Expression_list* exprs;
6122       String_concat_expression* left_sce =
6123 	this->left_->string_concat_expression();
6124       if (left_sce != NULL)
6125 	exprs = left_sce->exprs();
6126       else
6127 	{
6128 	  exprs = new Expression_list();
6129 	  exprs->push_back(this->left_);
6130 	}
6131 
6132       String_concat_expression* right_sce =
6133 	this->right_->string_concat_expression();
6134       if (right_sce != NULL)
6135 	exprs->append(right_sce->exprs());
6136       else
6137 	exprs->push_back(this->right_);
6138 
6139       return Expression::make_string_concat(exprs);
6140     }
6141 
6142   return this;
6143 }
6144 
6145 // Lower a struct comparison.
6146 
6147 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)6148 Binary_expression::lower_struct_comparison(Gogo* gogo,
6149 					   Statement_inserter* inserter)
6150 {
6151   Struct_type* st = this->left_->type()->struct_type();
6152   Struct_type* st2 = this->right_->type()->struct_type();
6153   if (st2 == NULL)
6154     return this;
6155   if (st != st2
6156       && !Type::are_identical(st, st2,
6157 			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6158 			      NULL))
6159     return this;
6160   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6161 					   this->right_->type(), NULL))
6162     return this;
6163 
6164   // See if we can compare using memcmp.  As a heuristic, we use
6165   // memcmp rather than field references and comparisons if there are
6166   // more than two fields.
6167   if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
6168     return this->lower_compare_to_memcmp(gogo, inserter);
6169 
6170   Location loc = this->location();
6171 
6172   Expression* left = this->left_;
6173   Temporary_statement* left_temp = NULL;
6174   if (left->var_expression() == NULL
6175       && left->temporary_reference_expression() == NULL)
6176     {
6177       left_temp = Statement::make_temporary(left->type(), NULL, loc);
6178       inserter->insert(left_temp);
6179       left = Expression::make_set_and_use_temporary(left_temp, left, loc);
6180     }
6181 
6182   Expression* right = this->right_;
6183   Temporary_statement* right_temp = NULL;
6184   if (right->var_expression() == NULL
6185       && right->temporary_reference_expression() == NULL)
6186     {
6187       right_temp = Statement::make_temporary(right->type(), NULL, loc);
6188       inserter->insert(right_temp);
6189       right = Expression::make_set_and_use_temporary(right_temp, right, loc);
6190     }
6191 
6192   Expression* ret = Expression::make_boolean(true, loc);
6193   const Struct_field_list* fields = st->fields();
6194   unsigned int field_index = 0;
6195   for (Struct_field_list::const_iterator pf = fields->begin();
6196        pf != fields->end();
6197        ++pf, ++field_index)
6198     {
6199       if (Gogo::is_sink_name(pf->field_name()))
6200 	continue;
6201 
6202       if (field_index > 0)
6203 	{
6204 	  if (left_temp == NULL)
6205 	    left = left->copy();
6206 	  else
6207 	    left = Expression::make_temporary_reference(left_temp, loc);
6208 	  if (right_temp == NULL)
6209 	    right = right->copy();
6210 	  else
6211 	    right = Expression::make_temporary_reference(right_temp, loc);
6212 	}
6213       Expression* f1 = Expression::make_field_reference(left, field_index,
6214 							loc);
6215       Expression* f2 = Expression::make_field_reference(right, field_index,
6216 							loc);
6217       Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6218       ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6219     }
6220 
6221   if (this->op_ == OPERATOR_NOTEQ)
6222     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6223 
6224   return ret;
6225 }
6226 
6227 // Lower an array comparison.
6228 
6229 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)6230 Binary_expression::lower_array_comparison(Gogo* gogo,
6231 					  Statement_inserter* inserter)
6232 {
6233   Array_type* at = this->left_->type()->array_type();
6234   Array_type* at2 = this->right_->type()->array_type();
6235   if (at2 == NULL)
6236     return this;
6237   if (at != at2
6238       && !Type::are_identical(at, at2,
6239 			      Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6240 			      NULL))
6241     return this;
6242   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6243 					   this->right_->type(), NULL))
6244     return this;
6245 
6246   // Call memcmp directly if possible.  This may let the middle-end
6247   // optimize the call.
6248   if (at->compare_is_identity(gogo))
6249     return this->lower_compare_to_memcmp(gogo, inserter);
6250 
6251   // Call the array comparison function.
6252   Named_object* equal_fn =
6253     at->equal_function(gogo, this->left_->type()->named_type(), NULL);
6254 
6255   Location loc = this->location();
6256 
6257   Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6258 
6259   Expression_list* args = new Expression_list();
6260   args->push_back(this->operand_address(inserter, this->left_));
6261   args->push_back(this->operand_address(inserter, this->right_));
6262 
6263   Expression* ret = Expression::make_call(func, args, false, loc);
6264 
6265   if (this->op_ == OPERATOR_NOTEQ)
6266     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6267 
6268   return ret;
6269 }
6270 
6271 // Lower an interface to value comparison.
6272 
6273 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)6274 Binary_expression::lower_interface_value_comparison(Gogo*,
6275                                                     Statement_inserter* inserter)
6276 {
6277   Type* left_type = this->left_->type();
6278   Type* right_type = this->right_->type();
6279   Interface_type* ift;
6280   if (left_type->interface_type() != NULL)
6281     {
6282       ift = left_type->interface_type();
6283       if (!ift->implements_interface(right_type, NULL))
6284         return this;
6285     }
6286   else
6287     {
6288       ift = right_type->interface_type();
6289       if (!ift->implements_interface(left_type, NULL))
6290         return this;
6291     }
6292   if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
6293     return this;
6294 
6295   Location loc = this->location();
6296 
6297   if (left_type->interface_type() == NULL
6298       && left_type->points_to() == NULL
6299       && !this->left_->is_addressable())
6300     {
6301       Temporary_statement* temp =
6302           Statement::make_temporary(left_type, NULL, loc);
6303       inserter->insert(temp);
6304       this->left_ =
6305           Expression::make_set_and_use_temporary(temp, this->left_, loc);
6306     }
6307 
6308   if (right_type->interface_type() == NULL
6309       && right_type->points_to() == NULL
6310       && !this->right_->is_addressable())
6311     {
6312       Temporary_statement* temp =
6313           Statement::make_temporary(right_type, NULL, loc);
6314       inserter->insert(temp);
6315       this->right_ =
6316           Expression::make_set_and_use_temporary(temp, this->right_, loc);
6317     }
6318 
6319   return this;
6320 }
6321 
6322 // Lower a struct or array comparison to a call to memcmp.
6323 
6324 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)6325 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6326 {
6327   Location loc = this->location();
6328 
6329   Expression* a1 = this->operand_address(inserter, this->left_);
6330   Expression* a2 = this->operand_address(inserter, this->right_);
6331   Expression* len = Expression::make_type_info(this->left_->type(),
6332 					       TYPE_INFO_SIZE);
6333 
6334   Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6335   Type* int32_type = Type::lookup_integer_type("int32");
6336   Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
6337   return Expression::make_binary(this->op_, call, zero, loc);
6338 }
6339 
6340 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)6341 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
6342                               Statement_inserter* inserter)
6343 {
6344   Location loc = this->location();
6345   if (this->left_->type()->is_error_type()
6346       || this->right_->type()->is_error_type()
6347       || this->left_->is_error_expression()
6348       || this->right_->is_error_expression())
6349     {
6350       go_assert(saw_errors());
6351       return Expression::make_error(loc);
6352     }
6353 
6354   Temporary_statement* temp;
6355 
6356   Type* left_type = this->left_->type();
6357   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6358                       || this->op_ == OPERATOR_RSHIFT);
6359   bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
6360                       left_type->integer_type() != NULL)
6361                      || this->op_ == OPERATOR_MOD);
6362   bool is_string_op = (left_type->is_string_type()
6363                        && this->right_->type()->is_string_type());
6364 
6365   if (is_string_op)
6366     {
6367       // Mark string([]byte) operands to reuse the backing store.
6368       // String comparison does not keep the reference, so it is safe.
6369       Type_conversion_expression* lce =
6370         this->left_->conversion_expression();
6371       if (lce != NULL && lce->expr()->type()->is_slice_type())
6372         lce->set_no_copy(true);
6373       Type_conversion_expression* rce =
6374         this->right_->conversion_expression();
6375       if (rce != NULL && rce->expr()->type()->is_slice_type())
6376         rce->set_no_copy(true);
6377     }
6378 
6379   if (is_shift_op
6380       || (is_idiv_op
6381 	  && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
6382       || is_string_op)
6383     {
6384       if (!this->left_->is_variable() && !this->left_->is_constant())
6385         {
6386           temp = Statement::make_temporary(NULL, this->left_, loc);
6387           inserter->insert(temp);
6388           this->left_ = Expression::make_temporary_reference(temp, loc);
6389         }
6390       if (!this->right_->is_variable() && !this->right_->is_constant())
6391         {
6392           temp =
6393               Statement::make_temporary(NULL, this->right_, loc);
6394           this->right_ = Expression::make_temporary_reference(temp, loc);
6395           inserter->insert(temp);
6396         }
6397     }
6398   return this;
6399 }
6400 
6401 
6402 // Return the address of EXPR, cast to unsafe.Pointer.
6403 
6404 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)6405 Binary_expression::operand_address(Statement_inserter* inserter,
6406 				   Expression* expr)
6407 {
6408   Location loc = this->location();
6409 
6410   if (!expr->is_addressable())
6411     {
6412       Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6413 							    loc);
6414       inserter->insert(temp);
6415       expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6416     }
6417   expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6418   static_cast<Unary_expression*>(expr)->set_does_not_escape();
6419   Type* void_type = Type::make_void_type();
6420   Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6421   return Expression::make_cast(unsafe_pointer_type, expr, loc);
6422 }
6423 
6424 // Return the numeric constant value, if it has one.
6425 
6426 bool
do_numeric_constant_value(Numeric_constant * nc) const6427 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
6428 {
6429   Numeric_constant left_nc;
6430   if (!this->left_->numeric_constant_value(&left_nc))
6431     return false;
6432   Numeric_constant right_nc;
6433   if (!this->right_->numeric_constant_value(&right_nc))
6434     return false;
6435   bool issued_error;
6436   return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
6437 					  this->location(), nc, &issued_error);
6438 }
6439 
6440 // Return the boolean constant value, if it has one.
6441 
6442 bool
do_boolean_constant_value(bool * val) const6443 Binary_expression::do_boolean_constant_value(bool* val) const
6444 {
6445   bool is_comparison = false;
6446   switch (this->op_)
6447     {
6448     case OPERATOR_EQEQ:
6449     case OPERATOR_NOTEQ:
6450     case OPERATOR_LT:
6451     case OPERATOR_LE:
6452     case OPERATOR_GT:
6453     case OPERATOR_GE:
6454       is_comparison = true;
6455       break;
6456     case OPERATOR_ANDAND:
6457     case OPERATOR_OROR:
6458       break;
6459     default:
6460       return false;
6461     }
6462 
6463   Numeric_constant left_nc, right_nc;
6464   if (is_comparison
6465       && this->left_->numeric_constant_value(&left_nc)
6466       && this->right_->numeric_constant_value(&right_nc))
6467     return Binary_expression::compare_constant(this->op_, &left_nc,
6468                                                &right_nc,
6469                                                this->location(),
6470                                                val);
6471 
6472   std::string left_str, right_str;
6473   if (is_comparison
6474       && this->left_->string_constant_value(&left_str)
6475       && this->right_->string_constant_value(&right_str))
6476     {
6477       *val = Binary_expression::cmp_to_bool(this->op_,
6478                                             left_str.compare(right_str));
6479       return true;
6480     }
6481 
6482   bool left_bval;
6483   if (this->left_->boolean_constant_value(&left_bval))
6484     {
6485       if (this->op_ == OPERATOR_ANDAND && !left_bval)
6486         {
6487           *val = false;
6488           return true;
6489         }
6490       else if (this->op_ == OPERATOR_OROR && left_bval)
6491         {
6492           *val = true;
6493           return true;
6494         }
6495 
6496       bool right_bval;
6497       if (this->right_->boolean_constant_value(&right_bval))
6498         {
6499           switch (this->op_)
6500             {
6501             case OPERATOR_EQEQ:
6502               *val = (left_bval == right_bval);
6503               return true;
6504             case OPERATOR_NOTEQ:
6505               *val = (left_bval != right_bval);
6506               return true;
6507             case OPERATOR_ANDAND:
6508             case OPERATOR_OROR:
6509               *val = right_bval;
6510               return true;
6511             default:
6512               go_unreachable();
6513             }
6514         }
6515     }
6516 
6517   return false;
6518 }
6519 
6520 // Note that the value is being discarded.
6521 
6522 bool
do_discarding_value()6523 Binary_expression::do_discarding_value()
6524 {
6525   if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6526     return this->right_->discarding_value();
6527   else
6528     {
6529       this->unused_value_error();
6530       return false;
6531     }
6532 }
6533 
6534 // Get type.
6535 
6536 Type*
do_type()6537 Binary_expression::do_type()
6538 {
6539   if (this->classification() == EXPRESSION_ERROR)
6540     return Type::make_error_type();
6541 
6542   switch (this->op_)
6543     {
6544     case OPERATOR_EQEQ:
6545     case OPERATOR_NOTEQ:
6546     case OPERATOR_LT:
6547     case OPERATOR_LE:
6548     case OPERATOR_GT:
6549     case OPERATOR_GE:
6550       if (this->type_ == NULL)
6551 	this->type_ = Type::make_boolean_type();
6552       return this->type_;
6553 
6554     case OPERATOR_PLUS:
6555     case OPERATOR_MINUS:
6556     case OPERATOR_OR:
6557     case OPERATOR_XOR:
6558     case OPERATOR_MULT:
6559     case OPERATOR_DIV:
6560     case OPERATOR_MOD:
6561     case OPERATOR_AND:
6562     case OPERATOR_BITCLEAR:
6563     case OPERATOR_OROR:
6564     case OPERATOR_ANDAND:
6565       {
6566 	Type* type;
6567 	if (!Binary_expression::operation_type(this->op_,
6568 					       this->left_->type(),
6569 					       this->right_->type(),
6570 					       &type))
6571 	  return Type::make_error_type();
6572 	return type;
6573       }
6574 
6575     case OPERATOR_LSHIFT:
6576     case OPERATOR_RSHIFT:
6577       return this->left_->type();
6578 
6579     default:
6580       go_unreachable();
6581     }
6582 }
6583 
6584 // Set type for a binary expression.
6585 
6586 void
do_determine_type(const Type_context * context)6587 Binary_expression::do_determine_type(const Type_context* context)
6588 {
6589   Type* tleft = this->left_->type();
6590   Type* tright = this->right_->type();
6591 
6592   // Both sides should have the same type, except for the shift
6593   // operations.  For a comparison, we should ignore the incoming
6594   // type.
6595 
6596   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6597 		      || this->op_ == OPERATOR_RSHIFT);
6598 
6599   bool is_comparison = (this->op_ == OPERATOR_EQEQ
6600 			|| this->op_ == OPERATOR_NOTEQ
6601 			|| this->op_ == OPERATOR_LT
6602 			|| this->op_ == OPERATOR_LE
6603 			|| this->op_ == OPERATOR_GT
6604 			|| this->op_ == OPERATOR_GE);
6605 
6606   // For constant expressions, the context of the result is not useful in
6607   // determining the types of the operands.  It is only legal to use abstract
6608   // boolean, numeric, and string constants as operands where it is legal to
6609   // use non-abstract boolean, numeric, and string constants, respectively.
6610   // Any issues with the operation will be resolved in the check_types pass.
6611   bool is_constant_expr = (this->left_->is_constant()
6612                            && this->right_->is_constant());
6613 
6614   Type_context subcontext(*context);
6615 
6616   if (is_constant_expr && !is_shift_op)
6617     {
6618       subcontext.type = NULL;
6619       subcontext.may_be_abstract = true;
6620     }
6621   else if (is_comparison)
6622     {
6623       // In a comparison, the context does not determine the types of
6624       // the operands.
6625       subcontext.type = NULL;
6626     }
6627 
6628   // Set the context for the left hand operand.
6629   if (is_shift_op)
6630     {
6631       // The right hand operand of a shift plays no role in
6632       // determining the type of the left hand operand.
6633     }
6634   else if (!tleft->is_abstract())
6635     subcontext.type = tleft;
6636   else if (!tright->is_abstract())
6637     subcontext.type = tright;
6638   else if (subcontext.type == NULL)
6639     {
6640       if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6641 	  || (tleft->float_type() != NULL && tright->float_type() != NULL)
6642 	  || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6643 	{
6644 	  // Both sides have an abstract integer, abstract float, or
6645 	  // abstract complex type.  Just let CONTEXT determine
6646 	  // whether they may remain abstract or not.
6647 	}
6648       else if (tleft->complex_type() != NULL)
6649 	subcontext.type = tleft;
6650       else if (tright->complex_type() != NULL)
6651 	subcontext.type = tright;
6652       else if (tleft->float_type() != NULL)
6653 	subcontext.type = tleft;
6654       else if (tright->float_type() != NULL)
6655 	subcontext.type = tright;
6656       else
6657 	subcontext.type = tleft;
6658 
6659       if (subcontext.type != NULL && !context->may_be_abstract)
6660 	subcontext.type = subcontext.type->make_non_abstract_type();
6661     }
6662 
6663   this->left_->determine_type(&subcontext);
6664 
6665   if (is_shift_op)
6666     {
6667       // We may have inherited an unusable type for the shift operand.
6668       // Give a useful error if that happened.
6669       if (tleft->is_abstract()
6670 	  && subcontext.type != NULL
6671 	  && !subcontext.may_be_abstract
6672 	  && subcontext.type->interface_type() == NULL
6673 	  && subcontext.type->integer_type() == NULL)
6674 	this->report_error(("invalid context-determined non-integer type "
6675 			    "for left operand of shift"));
6676 
6677       // The context for the right hand operand is the same as for the
6678       // left hand operand, except for a shift operator.
6679       subcontext.type = Type::lookup_integer_type("uint");
6680       subcontext.may_be_abstract = false;
6681     }
6682 
6683   this->right_->determine_type(&subcontext);
6684 
6685   if (is_comparison)
6686     {
6687       if (this->type_ != NULL && !this->type_->is_abstract())
6688 	;
6689       else if (context->type != NULL && context->type->is_boolean_type())
6690 	this->type_ = context->type;
6691       else if (!context->may_be_abstract)
6692 	this->type_ = Type::lookup_bool_type();
6693     }
6694 }
6695 
6696 // Report an error if the binary operator OP does not support TYPE.
6697 // OTYPE is the type of the other operand.  Return whether the
6698 // operation is OK.  This should not be used for shift.
6699 
6700 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)6701 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6702 				       Location location)
6703 {
6704   switch (op)
6705     {
6706     case OPERATOR_OROR:
6707     case OPERATOR_ANDAND:
6708       if (!type->is_boolean_type()
6709           || !otype->is_boolean_type())
6710 	{
6711 	  go_error_at(location, "expected boolean type");
6712 	  return false;
6713 	}
6714       break;
6715 
6716     case OPERATOR_EQEQ:
6717     case OPERATOR_NOTEQ:
6718       {
6719 	std::string reason;
6720 	if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6721 	  {
6722 	    go_error_at(location, "%s", reason.c_str());
6723 	    return false;
6724 	  }
6725       }
6726       break;
6727 
6728     case OPERATOR_LT:
6729     case OPERATOR_LE:
6730     case OPERATOR_GT:
6731     case OPERATOR_GE:
6732       {
6733 	std::string reason;
6734 	if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6735 	  {
6736 	    go_error_at(location, "%s", reason.c_str());
6737 	    return false;
6738 	  }
6739       }
6740       break;
6741 
6742     case OPERATOR_PLUS:
6743     case OPERATOR_PLUSEQ:
6744       if ((!type->is_numeric_type() && !type->is_string_type())
6745           || (!otype->is_numeric_type() && !otype->is_string_type()))
6746 	{
6747 	  go_error_at(location,
6748 		   "expected integer, floating, complex, or string type");
6749 	  return false;
6750 	}
6751       break;
6752 
6753     case OPERATOR_MINUS:
6754     case OPERATOR_MINUSEQ:
6755     case OPERATOR_MULT:
6756     case OPERATOR_MULTEQ:
6757     case OPERATOR_DIV:
6758     case OPERATOR_DIVEQ:
6759       if (!type->is_numeric_type() || !otype->is_numeric_type())
6760 	{
6761 	  go_error_at(location, "expected integer, floating, or complex type");
6762 	  return false;
6763 	}
6764       break;
6765 
6766     case OPERATOR_MOD:
6767     case OPERATOR_MODEQ:
6768     case OPERATOR_OR:
6769     case OPERATOR_OREQ:
6770     case OPERATOR_AND:
6771     case OPERATOR_ANDEQ:
6772     case OPERATOR_XOR:
6773     case OPERATOR_XOREQ:
6774     case OPERATOR_BITCLEAR:
6775     case OPERATOR_BITCLEAREQ:
6776       if (type->integer_type() == NULL || otype->integer_type() == NULL)
6777 	{
6778 	  go_error_at(location, "expected integer type");
6779 	  return false;
6780 	}
6781       break;
6782 
6783     default:
6784       go_unreachable();
6785     }
6786 
6787   return true;
6788 }
6789 
6790 // Check types.
6791 
6792 void
do_check_types(Gogo *)6793 Binary_expression::do_check_types(Gogo*)
6794 {
6795   if (this->classification() == EXPRESSION_ERROR)
6796     return;
6797 
6798   Type* left_type = this->left_->type();
6799   Type* right_type = this->right_->type();
6800   if (left_type->is_error() || right_type->is_error())
6801     {
6802       this->set_is_error();
6803       return;
6804     }
6805 
6806   if (this->op_ == OPERATOR_EQEQ
6807       || this->op_ == OPERATOR_NOTEQ
6808       || this->op_ == OPERATOR_LT
6809       || this->op_ == OPERATOR_LE
6810       || this->op_ == OPERATOR_GT
6811       || this->op_ == OPERATOR_GE)
6812     {
6813       if (left_type->is_nil_type() && right_type->is_nil_type())
6814 	{
6815 	  this->report_error(_("invalid comparison of nil with nil"));
6816 	  return;
6817 	}
6818       if (!Type::are_assignable(left_type, right_type, NULL)
6819 	  && !Type::are_assignable(right_type, left_type, NULL))
6820 	{
6821 	  this->report_error(_("incompatible types in binary expression"));
6822 	  return;
6823 	}
6824       if (!Binary_expression::check_operator_type(this->op_, left_type,
6825 						  right_type,
6826 						  this->location())
6827 	  || !Binary_expression::check_operator_type(this->op_, right_type,
6828 						     left_type,
6829 						     this->location()))
6830 	{
6831 	  this->set_is_error();
6832 	  return;
6833 	}
6834     }
6835   else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6836     {
6837       if (!Type::are_compatible_for_binop(left_type, right_type))
6838 	{
6839 	  this->report_error(_("incompatible types in binary expression"));
6840 	  return;
6841 	}
6842       if (!Binary_expression::check_operator_type(this->op_, left_type,
6843 						  right_type,
6844 						  this->location()))
6845 	{
6846 	  this->set_is_error();
6847 	  return;
6848 	}
6849       if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
6850 	{
6851 	  // Division by a zero integer constant is an error.
6852 	  Numeric_constant rconst;
6853 	  unsigned long rval;
6854 	  if (left_type->integer_type() != NULL
6855 	      && this->right_->numeric_constant_value(&rconst)
6856 	      && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6857 	      && rval == 0)
6858 	    {
6859 	      this->report_error(_("integer division by zero"));
6860 	      return;
6861 	    }
6862 	}
6863     }
6864   else
6865     {
6866       if (left_type->integer_type() == NULL)
6867 	this->report_error(_("shift of non-integer operand"));
6868 
6869       if (right_type->is_string_type())
6870         this->report_error(_("shift count not integer"));
6871       else if (!right_type->is_abstract()
6872 	       && right_type->integer_type() == NULL)
6873 	this->report_error(_("shift count not integer"));
6874       else
6875 	{
6876 	  Numeric_constant nc;
6877 	  if (this->right_->numeric_constant_value(&nc))
6878 	    {
6879 	      mpz_t val;
6880 	      if (!nc.to_int(&val))
6881 		this->report_error(_("shift count not integer"));
6882 	      else
6883 		{
6884 		  if (mpz_sgn(val) < 0)
6885 		    {
6886 		      this->report_error(_("negative shift count"));
6887 		      Location rloc = this->right_->location();
6888 		      this->right_ = Expression::make_integer_ul(0, right_type,
6889 								 rloc);
6890 		    }
6891 		  mpz_clear(val);
6892 		}
6893 	    }
6894 	}
6895     }
6896 }
6897 
6898 // Get the backend representation for a binary expression.
6899 
6900 Bexpression*
do_get_backend(Translate_context * context)6901 Binary_expression::do_get_backend(Translate_context* context)
6902 {
6903   Gogo* gogo = context->gogo();
6904   Location loc = this->location();
6905   Type* left_type = this->left_->type();
6906   Type* right_type = this->right_->type();
6907 
6908   bool use_left_type = true;
6909   bool is_shift_op = false;
6910   bool is_idiv_op = false;
6911   switch (this->op_)
6912     {
6913     case OPERATOR_EQEQ:
6914     case OPERATOR_NOTEQ:
6915     case OPERATOR_LT:
6916     case OPERATOR_LE:
6917     case OPERATOR_GT:
6918     case OPERATOR_GE:
6919       return Expression::comparison(context, this->type_, this->op_,
6920 				    this->left_, this->right_, loc);
6921 
6922     case OPERATOR_OROR:
6923     case OPERATOR_ANDAND:
6924       use_left_type = false;
6925       break;
6926     case OPERATOR_PLUS:
6927     case OPERATOR_MINUS:
6928     case OPERATOR_OR:
6929     case OPERATOR_XOR:
6930     case OPERATOR_MULT:
6931       break;
6932     case OPERATOR_DIV:
6933       if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6934         break;
6935       // Fall through.
6936     case OPERATOR_MOD:
6937       is_idiv_op = true;
6938       break;
6939     case OPERATOR_LSHIFT:
6940     case OPERATOR_RSHIFT:
6941       is_shift_op = true;
6942       break;
6943     case OPERATOR_BITCLEAR:
6944       this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6945     case OPERATOR_AND:
6946       break;
6947     default:
6948       go_unreachable();
6949     }
6950 
6951   // The only binary operation for string is +, and that should have
6952   // been converted to a String_concat_expression in do_lower.
6953   go_assert(!left_type->is_string_type());
6954 
6955   // For complex division Go might want slightly different results than the
6956   // backend implementation provides, so we have our own runtime routine.
6957   if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6958     {
6959       Runtime::Function complex_code;
6960       switch (this->left_->type()->complex_type()->bits())
6961 	{
6962 	case 64:
6963           complex_code = Runtime::COMPLEX64_DIV;
6964 	  break;
6965 	case 128:
6966           complex_code = Runtime::COMPLEX128_DIV;
6967 	  break;
6968 	default:
6969 	  go_unreachable();
6970 	}
6971       Expression* complex_div =
6972           Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6973       return complex_div->get_backend(context);
6974     }
6975 
6976   Bexpression* left = this->left_->get_backend(context);
6977   Bexpression* right = this->right_->get_backend(context);
6978 
6979   Type* type = use_left_type ? left_type : right_type;
6980   Btype* btype = type->get_backend(gogo);
6981 
6982   Bexpression* ret =
6983       gogo->backend()->binary_expression(this->op_, left, right, loc);
6984   ret = gogo->backend()->convert_expression(btype, ret, loc);
6985 
6986   // Initialize overflow constants.
6987   Bexpression* overflow;
6988   mpz_t zero;
6989   mpz_init_set_ui(zero, 0UL);
6990   mpz_t one;
6991   mpz_init_set_ui(one, 1UL);
6992   mpz_t neg_one;
6993   mpz_init_set_si(neg_one, -1);
6994 
6995   Btype* left_btype = left_type->get_backend(gogo);
6996   Btype* right_btype = right_type->get_backend(gogo);
6997 
6998   // In Go, a shift larger than the size of the type is well-defined.
6999   // This is not true in C, so we need to insert a conditional.
7000   // We also need to check for a negative shift count.
7001   if (is_shift_op)
7002     {
7003       go_assert(left_type->integer_type() != NULL);
7004       go_assert(right_type->integer_type() != NULL);
7005 
7006       int bits = left_type->integer_type()->bits();
7007 
7008       Numeric_constant nc;
7009       unsigned long ul;
7010       if (!this->right_->numeric_constant_value(&nc)
7011 	  || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
7012 	  || ul >= static_cast<unsigned long>(bits))
7013 	{
7014 	  mpz_t bitsval;
7015 	  mpz_init_set_ui(bitsval, bits);
7016 	  Bexpression* bits_expr =
7017 	    gogo->backend()->integer_constant_expression(right_btype, bitsval);
7018 	  Bexpression* compare =
7019 	    gogo->backend()->binary_expression(OPERATOR_LT,
7020 					       right, bits_expr, loc);
7021 
7022 	  Bexpression* zero_expr =
7023 	    gogo->backend()->integer_constant_expression(left_btype, zero);
7024 	  overflow = zero_expr;
7025 	  Bfunction* bfn = context->function()->func_value()->get_decl();
7026 	  if (this->op_ == OPERATOR_RSHIFT
7027 	      && !left_type->integer_type()->is_unsigned())
7028 	    {
7029 	      Bexpression* neg_expr =
7030 		gogo->backend()->binary_expression(OPERATOR_LT, left,
7031 						   zero_expr, loc);
7032 	      Bexpression* neg_one_expr =
7033 		gogo->backend()->integer_constant_expression(left_btype,
7034 							     neg_one);
7035 	      overflow = gogo->backend()->conditional_expression(bfn,
7036 								 btype,
7037 								 neg_expr,
7038 								 neg_one_expr,
7039 								 zero_expr,
7040 								 loc);
7041 	    }
7042 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7043 							ret, overflow, loc);
7044 	  mpz_clear(bitsval);
7045 	}
7046 
7047       if (!right_type->integer_type()->is_unsigned()
7048 	  && (!this->right_->numeric_constant_value(&nc)
7049 	      || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
7050 	{
7051 	  Bexpression* zero_expr =
7052 	    gogo->backend()->integer_constant_expression(right_btype, zero);
7053 	  Bexpression* compare =
7054 	    gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
7055 					       loc);
7056 	  Expression* crash = Runtime::make_call(Runtime::PANIC_SHIFT,
7057 						 loc, 0);
7058 	  Bexpression* bcrash = crash->get_backend(context);
7059 	  Bfunction* bfn = context->function()->func_value()->get_decl();
7060 	  ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7061 							bcrash, ret, loc);
7062 	}
7063     }
7064 
7065   // Add checks for division by zero and division overflow as needed.
7066   if (is_idiv_op)
7067     {
7068       if (gogo->check_divide_by_zero())
7069 	{
7070 	  // right == 0
7071           Bexpression* zero_expr =
7072               gogo->backend()->integer_constant_expression(right_btype, zero);
7073           Bexpression* check =
7074               gogo->backend()->binary_expression(OPERATOR_EQEQ,
7075                                                  right, zero_expr, loc);
7076 
7077 	  Expression* crash = Runtime::make_call(Runtime::PANIC_DIVIDE,
7078 						 loc, 0);
7079 	  Bexpression* bcrash = crash->get_backend(context);
7080 
7081 	  // right == 0 ? (panicdivide(), 0) : ret
7082           Bfunction* bfn = context->function()->func_value()->get_decl();
7083           ret = gogo->backend()->conditional_expression(bfn, btype,
7084                                                         check, bcrash,
7085 							ret, loc);
7086 	}
7087 
7088       if (gogo->check_divide_overflow())
7089 	{
7090 	  // right == -1
7091 	  // FIXME: It would be nice to say that this test is expected
7092 	  // to return false.
7093 
7094           Bexpression* neg_one_expr =
7095               gogo->backend()->integer_constant_expression(right_btype, neg_one);
7096           Bexpression* check =
7097               gogo->backend()->binary_expression(OPERATOR_EQEQ,
7098                                                  right, neg_one_expr, loc);
7099 
7100           Bexpression* zero_expr =
7101               gogo->backend()->integer_constant_expression(btype, zero);
7102           Bexpression* one_expr =
7103               gogo->backend()->integer_constant_expression(btype, one);
7104           Bfunction* bfn = context->function()->func_value()->get_decl();
7105 
7106 	  if (type->integer_type()->is_unsigned())
7107 	    {
7108 	      // An unsigned -1 is the largest possible number, so
7109 	      // dividing is always 1 or 0.
7110 
7111               Bexpression* cmp =
7112                   gogo->backend()->binary_expression(OPERATOR_EQEQ,
7113                                                      left, right, loc);
7114 	      if (this->op_ == OPERATOR_DIV)
7115                 overflow =
7116                     gogo->backend()->conditional_expression(bfn, btype, cmp,
7117                                                             one_expr, zero_expr,
7118                                                             loc);
7119 	      else
7120                 overflow =
7121                     gogo->backend()->conditional_expression(bfn, btype, cmp,
7122                                                             zero_expr, left,
7123                                                             loc);
7124 	    }
7125 	  else
7126 	    {
7127 	      // Computing left / -1 is the same as computing - left,
7128 	      // which does not overflow since Go sets -fwrapv.
7129 	      if (this->op_ == OPERATOR_DIV)
7130                 {
7131                   Expression* negate_expr =
7132                       Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
7133                   overflow = negate_expr->get_backend(context);
7134                 }
7135 	      else
7136                 overflow = zero_expr;
7137 	    }
7138           overflow = gogo->backend()->convert_expression(btype, overflow, loc);
7139 
7140 	  // right == -1 ? - left : ret
7141           ret = gogo->backend()->conditional_expression(bfn, btype,
7142                                                         check, overflow,
7143                                                         ret, loc);
7144 	}
7145     }
7146 
7147   mpz_clear(zero);
7148   mpz_clear(one);
7149   mpz_clear(neg_one);
7150   return ret;
7151 }
7152 
7153 // Export a binary expression.
7154 
7155 void
do_export(Export_function_body * efb) const7156 Binary_expression::do_export(Export_function_body* efb) const
7157 {
7158   efb->write_c_string("(");
7159   this->left_->export_expression(efb);
7160   switch (this->op_)
7161     {
7162     case OPERATOR_OROR:
7163       efb->write_c_string(" || ");
7164       break;
7165     case OPERATOR_ANDAND:
7166       efb->write_c_string(" && ");
7167       break;
7168     case OPERATOR_EQEQ:
7169       efb->write_c_string(" == ");
7170       break;
7171     case OPERATOR_NOTEQ:
7172       efb->write_c_string(" != ");
7173       break;
7174     case OPERATOR_LT:
7175       efb->write_c_string(" < ");
7176       break;
7177     case OPERATOR_LE:
7178       efb->write_c_string(" <= ");
7179       break;
7180     case OPERATOR_GT:
7181       efb->write_c_string(" > ");
7182       break;
7183     case OPERATOR_GE:
7184       efb->write_c_string(" >= ");
7185       break;
7186     case OPERATOR_PLUS:
7187       efb->write_c_string(" + ");
7188       break;
7189     case OPERATOR_MINUS:
7190       efb->write_c_string(" - ");
7191       break;
7192     case OPERATOR_OR:
7193       efb->write_c_string(" | ");
7194       break;
7195     case OPERATOR_XOR:
7196       efb->write_c_string(" ^ ");
7197       break;
7198     case OPERATOR_MULT:
7199       efb->write_c_string(" * ");
7200       break;
7201     case OPERATOR_DIV:
7202       efb->write_c_string(" / ");
7203       break;
7204     case OPERATOR_MOD:
7205       efb->write_c_string(" % ");
7206       break;
7207     case OPERATOR_LSHIFT:
7208       efb->write_c_string(" << ");
7209       break;
7210     case OPERATOR_RSHIFT:
7211       efb->write_c_string(" >> ");
7212       break;
7213     case OPERATOR_AND:
7214       efb->write_c_string(" & ");
7215       break;
7216     case OPERATOR_BITCLEAR:
7217       efb->write_c_string(" &^ ");
7218       break;
7219     default:
7220       go_unreachable();
7221     }
7222   this->right_->export_expression(efb);
7223   efb->write_c_string(")");
7224 }
7225 
7226 // Import a binary expression.
7227 
7228 Expression*
do_import(Import_expression * imp,Location loc)7229 Binary_expression::do_import(Import_expression* imp, Location loc)
7230 {
7231   imp->require_c_string("(");
7232 
7233   Expression* left = Expression::import_expression(imp, loc);
7234 
7235   Operator op;
7236   if (imp->match_c_string(" || "))
7237     {
7238       op = OPERATOR_OROR;
7239       imp->advance(4);
7240     }
7241   else if (imp->match_c_string(" && "))
7242     {
7243       op = OPERATOR_ANDAND;
7244       imp->advance(4);
7245     }
7246   else if (imp->match_c_string(" == "))
7247     {
7248       op = OPERATOR_EQEQ;
7249       imp->advance(4);
7250     }
7251   else if (imp->match_c_string(" != "))
7252     {
7253       op = OPERATOR_NOTEQ;
7254       imp->advance(4);
7255     }
7256   else if (imp->match_c_string(" < "))
7257     {
7258       op = OPERATOR_LT;
7259       imp->advance(3);
7260     }
7261   else if (imp->match_c_string(" <= "))
7262     {
7263       op = OPERATOR_LE;
7264       imp->advance(4);
7265     }
7266   else if (imp->match_c_string(" > "))
7267     {
7268       op = OPERATOR_GT;
7269       imp->advance(3);
7270     }
7271   else if (imp->match_c_string(" >= "))
7272     {
7273       op = OPERATOR_GE;
7274       imp->advance(4);
7275     }
7276   else if (imp->match_c_string(" + "))
7277     {
7278       op = OPERATOR_PLUS;
7279       imp->advance(3);
7280     }
7281   else if (imp->match_c_string(" - "))
7282     {
7283       op = OPERATOR_MINUS;
7284       imp->advance(3);
7285     }
7286   else if (imp->match_c_string(" | "))
7287     {
7288       op = OPERATOR_OR;
7289       imp->advance(3);
7290     }
7291   else if (imp->match_c_string(" ^ "))
7292     {
7293       op = OPERATOR_XOR;
7294       imp->advance(3);
7295     }
7296   else if (imp->match_c_string(" * "))
7297     {
7298       op = OPERATOR_MULT;
7299       imp->advance(3);
7300     }
7301   else if (imp->match_c_string(" / "))
7302     {
7303       op = OPERATOR_DIV;
7304       imp->advance(3);
7305     }
7306   else if (imp->match_c_string(" % "))
7307     {
7308       op = OPERATOR_MOD;
7309       imp->advance(3);
7310     }
7311   else if (imp->match_c_string(" << "))
7312     {
7313       op = OPERATOR_LSHIFT;
7314       imp->advance(4);
7315     }
7316   else if (imp->match_c_string(" >> "))
7317     {
7318       op = OPERATOR_RSHIFT;
7319       imp->advance(4);
7320     }
7321   else if (imp->match_c_string(" & "))
7322     {
7323       op = OPERATOR_AND;
7324       imp->advance(3);
7325     }
7326   else if (imp->match_c_string(" &^ "))
7327     {
7328       op = OPERATOR_BITCLEAR;
7329       imp->advance(4);
7330     }
7331   else if (imp->match_c_string(")"))
7332     {
7333       // Not a binary operator after all.
7334       imp->advance(1);
7335       return left;
7336     }
7337   else
7338     {
7339       go_error_at(imp->location(), "unrecognized binary operator");
7340       return Expression::make_error(loc);
7341     }
7342 
7343   Expression* right = Expression::import_expression(imp, loc);
7344 
7345   imp->require_c_string(")");
7346 
7347   return Expression::make_binary(op, left, right, loc);
7348 }
7349 
7350 // Dump ast representation of a binary expression.
7351 
7352 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7353 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
7354 {
7355   ast_dump_context->ostream() << "(";
7356   ast_dump_context->dump_expression(this->left_);
7357   ast_dump_context->ostream() << " ";
7358   ast_dump_context->dump_operator(this->op_);
7359   ast_dump_context->ostream() << " ";
7360   ast_dump_context->dump_expression(this->right_);
7361   ast_dump_context->ostream() << ") ";
7362 }
7363 
7364 // Make a binary expression.
7365 
7366 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)7367 Expression::make_binary(Operator op, Expression* left, Expression* right,
7368 			Location location)
7369 {
7370   return new Binary_expression(op, left, right, location);
7371 }
7372 
7373 // Implement a comparison.
7374 
7375 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)7376 Expression::comparison(Translate_context* context, Type* result_type,
7377 		       Operator op, Expression* left, Expression* right,
7378 		       Location location)
7379 {
7380   Type* left_type = left->type();
7381   Type* right_type = right->type();
7382 
7383   Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
7384 
7385   if (left_type->is_string_type() && right_type->is_string_type())
7386     {
7387       go_assert(left->is_variable() || left->is_constant());
7388       go_assert(right->is_variable() || right->is_constant());
7389 
7390       if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
7391 	{
7392           // (l.len == r.len
7393           //  ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
7394           //  : false)
7395           Expression* llen = Expression::make_string_info(left,
7396                                                           STRING_INFO_LENGTH,
7397                                                           location);
7398           Expression* rlen = Expression::make_string_info(right,
7399                                                           STRING_INFO_LENGTH,
7400                                                           location);
7401           Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
7402                                                       location);
7403           Expression* lptr = Expression::make_string_info(left->copy(),
7404                                                           STRING_INFO_DATA,
7405                                                           location);
7406           Expression* rptr = Expression::make_string_info(right->copy(),
7407                                                           STRING_INFO_DATA,
7408                                                           location);
7409           Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
7410                                                       location);
7411           Expression* btrue = Expression::make_boolean(true, location);
7412           Expression* call = Runtime::make_call(Runtime::MEMCMP, location, 3,
7413                                                 lptr->copy(), rptr->copy(),
7414                                                 rlen->copy());
7415           Type* int32_type = Type::lookup_integer_type("int32");
7416           Expression* zero = Expression::make_integer_ul(0, int32_type, location);
7417           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
7418                                                     location);
7419           Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
7420                                                           location);
7421           Expression* bfalse = Expression::make_boolean(false, location);
7422           left = Expression::make_conditional(leneq, cond, bfalse, location);
7423 	  right = Expression::make_boolean(true, location);
7424 	}
7425       else
7426 	{
7427 	  left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
7428 				    left, right);
7429 	  right = zexpr;
7430 	}
7431     }
7432   else if ((left_type->interface_type() != NULL
7433 	    && right_type->interface_type() == NULL
7434 	    && !right_type->is_nil_type())
7435 	   || (left_type->interface_type() == NULL
7436 	       && !left_type->is_nil_type()
7437 	       && right_type->interface_type() != NULL))
7438     {
7439       // Comparing an interface value to a non-interface value.
7440       if (left_type->interface_type() == NULL)
7441 	{
7442 	  std::swap(left_type, right_type);
7443 	  std::swap(left, right);
7444 	}
7445 
7446       // The right operand is not an interface.  We need to take its
7447       // address if it is not a direct interface type.
7448       Expression* pointer_arg = NULL;
7449       if (right_type->is_direct_iface_type())
7450         pointer_arg = Expression::unpack_direct_iface(right, location);
7451       else
7452 	{
7453           go_assert(right->is_addressable());
7454           pointer_arg = Expression::make_unary(OPERATOR_AND, right,
7455                                                location);
7456 	}
7457 
7458       Expression* descriptor =
7459           Expression::make_type_descriptor(right_type, location);
7460       left =
7461           Runtime::make_call((left_type->interface_type()->is_empty()
7462                               ? Runtime::EFACEVALEQ
7463                               : Runtime::IFACEVALEQ),
7464                              location, 3, left, descriptor,
7465                              pointer_arg);
7466       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7467       right = Expression::make_boolean(true, location);
7468     }
7469   else if (left_type->interface_type() != NULL
7470 	   && right_type->interface_type() != NULL)
7471     {
7472       Runtime::Function compare_function;
7473       if (left_type->interface_type()->is_empty()
7474 	  && right_type->interface_type()->is_empty())
7475 	compare_function = Runtime::EFACEEQ;
7476       else if (!left_type->interface_type()->is_empty()
7477 	       && !right_type->interface_type()->is_empty())
7478 	compare_function = Runtime::IFACEEQ;
7479       else
7480 	{
7481 	  if (left_type->interface_type()->is_empty())
7482 	    {
7483 	      std::swap(left_type, right_type);
7484 	      std::swap(left, right);
7485 	    }
7486 	  go_assert(!left_type->interface_type()->is_empty());
7487 	  go_assert(right_type->interface_type()->is_empty());
7488 	  compare_function = Runtime::IFACEEFACEEQ;
7489 	}
7490 
7491       left = Runtime::make_call(compare_function, location, 2, left, right);
7492       go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7493       right = Expression::make_boolean(true, location);
7494     }
7495 
7496   if (left_type->is_nil_type()
7497       && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7498     {
7499       std::swap(left_type, right_type);
7500       std::swap(left, right);
7501     }
7502 
7503   if (right_type->is_nil_type())
7504     {
7505       right = Expression::make_nil(location);
7506       if (left_type->array_type() != NULL
7507 	  && left_type->array_type()->length() == NULL)
7508 	{
7509 	  Array_type* at = left_type->array_type();
7510           bool is_lvalue = false;
7511           left = at->get_value_pointer(context->gogo(), left, is_lvalue);
7512 	}
7513       else if (left_type->interface_type() != NULL)
7514 	{
7515 	  // An interface is nil if the first field is nil.
7516           left = Expression::make_field_reference(left, 0, location);
7517 	}
7518     }
7519 
7520   Bexpression* left_bexpr = left->get_backend(context);
7521   Bexpression* right_bexpr = right->get_backend(context);
7522 
7523   Gogo* gogo = context->gogo();
7524   Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
7525                                                         right_bexpr, location);
7526   if (result_type != NULL)
7527     ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
7528                                               ret, location);
7529   return ret;
7530 }
7531 
7532 // Class String_concat_expression.
7533 
7534 bool
do_is_constant() const7535 String_concat_expression::do_is_constant() const
7536 {
7537   for (Expression_list::const_iterator pe = this->exprs_->begin();
7538        pe != this->exprs_->end();
7539        ++pe)
7540     {
7541       if (!(*pe)->is_constant())
7542 	return false;
7543     }
7544   return true;
7545 }
7546 
7547 bool
do_is_zero_value() const7548 String_concat_expression::do_is_zero_value() const
7549 {
7550   for (Expression_list::const_iterator pe = this->exprs_->begin();
7551        pe != this->exprs_->end();
7552        ++pe)
7553     {
7554       if (!(*pe)->is_zero_value())
7555 	return false;
7556     }
7557   return true;
7558 }
7559 
7560 bool
do_is_static_initializer() const7561 String_concat_expression::do_is_static_initializer() const
7562 {
7563   for (Expression_list::const_iterator pe = this->exprs_->begin();
7564        pe != this->exprs_->end();
7565        ++pe)
7566     {
7567       if (!(*pe)->is_static_initializer())
7568 	return false;
7569     }
7570   return true;
7571 }
7572 
7573 Type*
do_type()7574 String_concat_expression::do_type()
7575 {
7576   Type* t = this->exprs_->front()->type();
7577   Expression_list::iterator pe = this->exprs_->begin();
7578   ++pe;
7579   for (; pe != this->exprs_->end(); ++pe)
7580     {
7581       Type* t1;
7582       if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
7583 					     (*pe)->type(),
7584 					     &t1))
7585 	return Type::make_error_type();
7586       t = t1;
7587     }
7588   return t;
7589 }
7590 
7591 void
do_determine_type(const Type_context * context)7592 String_concat_expression::do_determine_type(const Type_context* context)
7593 {
7594   Type_context subcontext(*context);
7595   for (Expression_list::iterator pe = this->exprs_->begin();
7596        pe != this->exprs_->end();
7597        ++pe)
7598     {
7599       Type* t = (*pe)->type();
7600       if (!t->is_abstract())
7601 	{
7602 	  subcontext.type = t;
7603 	  break;
7604 	}
7605     }
7606   if (subcontext.type == NULL)
7607     subcontext.type = this->exprs_->front()->type();
7608   for (Expression_list::iterator pe = this->exprs_->begin();
7609        pe != this->exprs_->end();
7610        ++pe)
7611     (*pe)->determine_type(&subcontext);
7612 }
7613 
7614 void
do_check_types(Gogo *)7615 String_concat_expression::do_check_types(Gogo*)
7616 {
7617   if (this->is_error_expression())
7618     return;
7619   Type* t = this->exprs_->front()->type();
7620   if (t->is_error())
7621     {
7622       this->set_is_error();
7623       return;
7624     }
7625   Expression_list::iterator pe = this->exprs_->begin();
7626   ++pe;
7627   for (; pe != this->exprs_->end(); ++pe)
7628     {
7629       Type* t1 = (*pe)->type();
7630       if (!Type::are_compatible_for_binop(t, t1))
7631 	{
7632 	  this->report_error("incompatible types in binary expression");
7633 	  return;
7634 	}
7635       if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
7636 						  this->location()))
7637 	{
7638 	  this->set_is_error();
7639 	  return;
7640 	}
7641     }
7642 }
7643 
7644 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)7645 String_concat_expression::do_flatten(Gogo*, Named_object*,
7646 				     Statement_inserter* inserter)
7647 {
7648   if (this->is_error_expression())
7649     return this;
7650   Location loc = this->location();
7651   Type* type = this->type();
7652 
7653   // Mark string([]byte) operands to reuse the backing store.
7654   // runtime.concatstrings does not keep the reference.
7655   //
7656   // Note: in the gc runtime, if all but one inputs are empty,
7657   // concatstrings returns the only nonempty input without copy.
7658   // So it is not safe to reuse the backing store if it is a
7659   // string([]byte) conversion. So the gc compiler does the
7660   // no-copy optimization only when there is at least one
7661   // constant nonempty input. Currently the gccgo runtime
7662   // doesn't do this, so we don't do the check.
7663   for (Expression_list::iterator p = this->exprs_->begin();
7664        p != this->exprs_->end();
7665        ++p)
7666     {
7667       Type_conversion_expression* tce = (*p)->conversion_expression();
7668       if (tce != NULL)
7669         tce->set_no_copy(true);
7670     }
7671 
7672   Expression* buf = NULL;
7673   Node* n = Node::make_node(this);
7674   if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7675     {
7676       size_t size = 0;
7677       for (Expression_list::iterator p = this->exprs_->begin();
7678            p != this->exprs_->end();
7679            ++p)
7680         {
7681           std::string s;
7682           if ((*p)->string_constant_value(&s))
7683             size += s.length();
7684         }
7685       // Make a buffer on stack if the result does not escape.
7686       // But don't do this if we know it won't fit.
7687       if (size < (size_t)tmp_string_buf_size)
7688         {
7689           Type* byte_type = Type::lookup_integer_type("uint8");
7690           Expression* buflen =
7691             Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7692           Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7693           Type* array_type = Type::make_array_type(byte_type, buflen);
7694           buf = Expression::make_allocation(array_type, loc);
7695           buf->allocation_expression()->set_allocate_on_stack();
7696           buf->allocation_expression()->set_no_zero();
7697         }
7698     }
7699   if (buf == NULL)
7700     buf = Expression::make_nil(loc);
7701   go_assert(this->exprs_->size() > 1);
7702   Expression* len =
7703     Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
7704   Array_type* array_type = Type::make_array_type(type, len);
7705   array_type->set_is_array_incomparable();
7706   Expression* array =
7707     Expression::make_array_composite_literal(array_type, this->exprs_,
7708                                              loc);
7709   Temporary_statement* ts =
7710     Statement::make_temporary(array_type, array, loc);
7711   inserter->insert(ts);
7712   Expression* ref = Expression::make_temporary_reference(ts, loc);
7713   ref = Expression::make_unary(OPERATOR_AND, ref, loc);
7714 	Expression* call =
7715     Runtime::make_call(Runtime::CONCATSTRINGS, loc, 3, buf,
7716                        ref, len->copy());
7717   return Expression::make_cast(type, call, loc);
7718 }
7719 
7720 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7721 String_concat_expression::do_dump_expression(
7722     Ast_dump_context* ast_dump_context) const
7723 {
7724   ast_dump_context->ostream() << "concat(";
7725   ast_dump_context->dump_expression_list(this->exprs_, false);
7726   ast_dump_context->ostream() << ")";
7727 }
7728 
7729 Expression*
make_string_concat(Expression_list * exprs)7730 Expression::make_string_concat(Expression_list* exprs)
7731 {
7732   return new String_concat_expression(exprs);
7733 }
7734 
7735 // Class Bound_method_expression.
7736 
7737 // Traversal.
7738 
7739 int
do_traverse(Traverse * traverse)7740 Bound_method_expression::do_traverse(Traverse* traverse)
7741 {
7742   return Expression::traverse(&this->expr_, traverse);
7743 }
7744 
7745 // Return the type of a bound method expression.  The type of this
7746 // object is simply the type of the method with no receiver.
7747 
7748 Type*
do_type()7749 Bound_method_expression::do_type()
7750 {
7751   Named_object* fn = this->method_->named_object();
7752   Function_type* fntype;
7753   if (fn->is_function())
7754     fntype = fn->func_value()->type();
7755   else if (fn->is_function_declaration())
7756     fntype = fn->func_declaration_value()->type();
7757   else
7758     return Type::make_error_type();
7759   return fntype->copy_without_receiver();
7760 }
7761 
7762 // Determine the types of a method expression.
7763 
7764 void
do_determine_type(const Type_context *)7765 Bound_method_expression::do_determine_type(const Type_context*)
7766 {
7767   Named_object* fn = this->method_->named_object();
7768   Function_type* fntype;
7769   if (fn->is_function())
7770     fntype = fn->func_value()->type();
7771   else if (fn->is_function_declaration())
7772     fntype = fn->func_declaration_value()->type();
7773   else
7774     fntype = NULL;
7775   if (fntype == NULL || !fntype->is_method())
7776     this->expr_->determine_type_no_context();
7777   else
7778     {
7779       Type_context subcontext(fntype->receiver()->type(), false);
7780       this->expr_->determine_type(&subcontext);
7781     }
7782 }
7783 
7784 // Check the types of a method expression.
7785 
7786 void
do_check_types(Gogo *)7787 Bound_method_expression::do_check_types(Gogo*)
7788 {
7789   Named_object* fn = this->method_->named_object();
7790   if (!fn->is_function() && !fn->is_function_declaration())
7791     {
7792       this->report_error(_("object is not a method"));
7793       return;
7794     }
7795 
7796   Function_type* fntype;
7797   if (fn->is_function())
7798     fntype = fn->func_value()->type();
7799   else if (fn->is_function_declaration())
7800     fntype = fn->func_declaration_value()->type();
7801   else
7802     go_unreachable();
7803   Type* rtype = fntype->receiver()->type()->deref();
7804   Type* etype = (this->expr_type_ != NULL
7805 		 ? this->expr_type_
7806 		 : this->expr_->type());
7807   etype = etype->deref();
7808   if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
7809     this->report_error(_("method type does not match object type"));
7810 }
7811 
7812 // If a bound method expression is not simply called, then it is
7813 // represented as a closure.  The closure will hold a single variable,
7814 // the receiver to pass to the method.  The function will be a simple
7815 // thunk that pulls that value from the closure and calls the method
7816 // with the remaining arguments.
7817 //
7818 // Because method values are not common, we don't build all thunks for
7819 // every methods, but instead only build them as we need them.  In
7820 // particular, we even build them on demand for methods defined in
7821 // other packages.
7822 
7823 Bound_method_expression::Method_value_thunks
7824   Bound_method_expression::method_value_thunks;
7825 
7826 // Find or create the thunk for METHOD.
7827 
7828 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)7829 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
7830 				      Named_object* fn)
7831 {
7832   std::pair<Named_object*, Named_object*> val(fn, NULL);
7833   std::pair<Method_value_thunks::iterator, bool> ins =
7834     Bound_method_expression::method_value_thunks.insert(val);
7835   if (!ins.second)
7836     {
7837       // We have seen this method before.
7838       go_assert(ins.first->second != NULL);
7839       return ins.first->second;
7840     }
7841 
7842   Location loc = fn->location();
7843 
7844   Function_type* orig_fntype;
7845   if (fn->is_function())
7846     orig_fntype = fn->func_value()->type();
7847   else if (fn->is_function_declaration())
7848     orig_fntype = fn->func_declaration_value()->type();
7849   else
7850     orig_fntype = NULL;
7851 
7852   if (orig_fntype == NULL || !orig_fntype->is_method())
7853     {
7854       ins.first->second =
7855 	Named_object::make_erroneous_name(gogo->thunk_name());
7856       return ins.first->second;
7857     }
7858 
7859   Struct_field_list* sfl = new Struct_field_list();
7860   // The type here is wrong--it should be the C function type.  But it
7861   // doesn't really matter.
7862   Type* vt = Type::make_pointer_type(Type::make_void_type());
7863   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
7864   sfl->push_back(Struct_field(Typed_identifier("val",
7865 					       orig_fntype->receiver()->type(),
7866 					       loc)));
7867   Struct_type* st = Type::make_struct_type(sfl, loc);
7868   st->set_is_struct_incomparable();
7869   Type* closure_type = Type::make_pointer_type(st);
7870 
7871   Function_type* new_fntype = orig_fntype->copy_with_names();
7872 
7873   std::string thunk_name = gogo->thunk_name();
7874   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
7875 					      false, loc);
7876 
7877   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
7878   cvar->set_is_used();
7879   cvar->set_is_closure();
7880   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
7881 						 NULL, cvar);
7882   new_no->func_value()->set_closure_var(cp);
7883 
7884   gogo->start_block(loc);
7885 
7886   // Field 0 of the closure is the function code pointer, field 1 is
7887   // the value on which to invoke the method.
7888   Expression* arg = Expression::make_var_reference(cp, loc);
7889   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
7890   arg = Expression::make_field_reference(arg, 1, loc);
7891 
7892   Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
7893 
7894   const Typed_identifier_list* orig_params = orig_fntype->parameters();
7895   Expression_list* args;
7896   if (orig_params == NULL || orig_params->empty())
7897     args = NULL;
7898   else
7899     {
7900       const Typed_identifier_list* new_params = new_fntype->parameters();
7901       args = new Expression_list();
7902       for (Typed_identifier_list::const_iterator p = new_params->begin();
7903 	   p != new_params->end();
7904 	   ++p)
7905 	{
7906 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
7907 	  go_assert(p_no != NULL
7908 		    && p_no->is_variable()
7909 		    && p_no->var_value()->is_parameter());
7910 	  args->push_back(Expression::make_var_reference(p_no, loc));
7911 	}
7912     }
7913 
7914   Call_expression* call = Expression::make_call(bme, args,
7915 						orig_fntype->is_varargs(),
7916 						loc);
7917   call->set_varargs_are_lowered();
7918 
7919   Statement* s = Statement::make_return_from_call(call, loc);
7920   gogo->add_statement(s);
7921   Block* b = gogo->finish_block(loc);
7922   gogo->add_block(b, loc);
7923   gogo->lower_block(new_no, b);
7924   gogo->flatten_block(new_no, b);
7925   gogo->finish_function(loc);
7926 
7927   ins.first->second = new_no;
7928   return new_no;
7929 }
7930 
7931 // Return an expression to check *REF for nil while dereferencing
7932 // according to FIELD_INDEXES.  Update *REF to build up the field
7933 // reference.  This is a static function so that we don't have to
7934 // worry about declaring Field_indexes in expressions.h.
7935 
7936 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)7937 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
7938 	      Expression** ref)
7939 {
7940   if (field_indexes == NULL)
7941     return Expression::make_boolean(false, loc);
7942   Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
7943   Struct_type* stype = (*ref)->type()->deref()->struct_type();
7944   go_assert(stype != NULL
7945 	    && field_indexes->field_index < stype->field_count());
7946   if ((*ref)->type()->struct_type() == NULL)
7947     {
7948       go_assert((*ref)->type()->points_to() != NULL);
7949       Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
7950 					      Expression::make_nil(loc),
7951 					      loc);
7952       cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
7953       *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
7954                                           loc);
7955       go_assert((*ref)->type()->struct_type() == stype);
7956     }
7957   *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
7958 					  loc);
7959   return cond;
7960 }
7961 
7962 // Flatten a method value into a struct with nil checks.  We can't do
7963 // this in the lowering phase, because if the method value is called
7964 // directly we don't need a thunk.  That case will have been handled
7965 // by Call_expression::do_lower, so if we get here then we do need a
7966 // thunk.
7967 
7968 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)7969 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
7970 				    Statement_inserter* inserter)
7971 {
7972   Location loc = this->location();
7973 
7974   Named_object* thunk = Bound_method_expression::create_thunk(gogo,
7975 							      this->method_,
7976 							      this->function_);
7977   if (thunk->is_erroneous())
7978     {
7979       go_assert(saw_errors());
7980       return Expression::make_error(loc);
7981     }
7982 
7983   // Force the expression into a variable.  This is only necessary if
7984   // we are going to do nil checks below, but it's easy enough to
7985   // always do it.
7986   Expression* expr = this->expr_;
7987   if (!expr->is_variable())
7988     {
7989       Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
7990       inserter->insert(etemp);
7991       expr = Expression::make_temporary_reference(etemp, loc);
7992     }
7993 
7994   // If the method expects a value, and we have a pointer, we need to
7995   // dereference the pointer.
7996 
7997   Named_object* fn = this->method_->named_object();
7998   Function_type *fntype;
7999   if (fn->is_function())
8000     fntype = fn->func_value()->type();
8001   else if (fn->is_function_declaration())
8002     fntype = fn->func_declaration_value()->type();
8003   else
8004     go_unreachable();
8005 
8006   Expression* val = expr;
8007   if (fntype->receiver()->type()->points_to() == NULL
8008       && val->type()->points_to() != NULL)
8009     val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
8010 
8011   // Note that we are ignoring this->expr_type_ here.  The thunk will
8012   // expect a closure whose second field has type this->expr_type_ (if
8013   // that is not NULL).  We are going to pass it a closure whose
8014   // second field has type this->expr_->type().  Since
8015   // this->expr_type_ is only not-NULL for pointer types, we can get
8016   // away with this.
8017 
8018   Struct_field_list* fields = new Struct_field_list();
8019   fields->push_back(Struct_field(Typed_identifier("fn",
8020 						  thunk->func_value()->type(),
8021 						  loc)));
8022   fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
8023   Struct_type* st = Type::make_struct_type(fields, loc);
8024   st->set_is_struct_incomparable();
8025 
8026   Expression_list* vals = new Expression_list();
8027   vals->push_back(Expression::make_func_code_reference(thunk, loc));
8028   vals->push_back(val);
8029 
8030   Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
8031   ret = Expression::make_heap_expression(ret, loc);
8032 
8033   Node* node = Node::make_node(this);
8034   if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8035     ret->heap_expression()->set_allocate_on_stack();
8036   else if (gogo->compiling_runtime()
8037 	   && gogo->package_name() == "runtime"
8038 	   && !saw_errors())
8039     go_error_at(loc, "%s escapes to heap, not allowed in runtime",
8040                 node->ast_format(gogo).c_str());
8041 
8042   // If necessary, check whether the expression or any embedded
8043   // pointers are nil.
8044 
8045   Expression* nil_check = NULL;
8046   if (this->method_->field_indexes() != NULL)
8047     {
8048       Expression* ref = expr;
8049       nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
8050       expr = ref;
8051     }
8052 
8053   if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
8054     {
8055       Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
8056 					      Expression::make_nil(loc),
8057 					      loc);
8058       if (nil_check == NULL)
8059 	nil_check = n;
8060       else
8061 	nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
8062     }
8063 
8064   if (nil_check != NULL)
8065     {
8066       Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
8067       // Fix the type of the conditional expression by pretending to
8068       // evaluate to RET either way through the conditional.
8069       crash = Expression::make_compound(crash, ret, loc);
8070       ret = Expression::make_conditional(nil_check, crash, ret, loc);
8071     }
8072 
8073   // RET is a pointer to a struct, but we want a function type.
8074   ret = Expression::make_unsafe_cast(this->type(), ret, loc);
8075 
8076   return ret;
8077 }
8078 
8079 // Dump ast representation of a bound method expression.
8080 
8081 void
do_dump_expression(Ast_dump_context * ast_dump_context) const8082 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
8083     const
8084 {
8085   if (this->expr_type_ != NULL)
8086     ast_dump_context->ostream() << "(";
8087   ast_dump_context->dump_expression(this->expr_);
8088   if (this->expr_type_ != NULL)
8089     {
8090       ast_dump_context->ostream() << ":";
8091       ast_dump_context->dump_type(this->expr_type_);
8092       ast_dump_context->ostream() << ")";
8093     }
8094 
8095   ast_dump_context->ostream() << "." << this->function_->name();
8096 }
8097 
8098 // Make a method expression.
8099 
8100 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)8101 Expression::make_bound_method(Expression* expr, const Method* method,
8102 			      Named_object* function, Location location)
8103 {
8104   return new Bound_method_expression(expr, method, function, location);
8105 }
8106 
8107 // Class Builtin_call_expression.  This is used for a call to a
8108 // builtin function.
8109 
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)8110 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
8111 						 Expression* fn,
8112 						 Expression_list* args,
8113 						 bool is_varargs,
8114 						 Location location)
8115   : Call_expression(fn, args, is_varargs, location),
8116     gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
8117     recover_arg_is_set_(false)
8118 {
8119   Func_expression* fnexp = this->fn()->func_expression();
8120   if (fnexp == NULL)
8121     {
8122       this->code_ = BUILTIN_INVALID;
8123       return;
8124     }
8125   const std::string& name(fnexp->named_object()->name());
8126   if (name == "append")
8127     this->code_ = BUILTIN_APPEND;
8128   else if (name == "cap")
8129     this->code_ = BUILTIN_CAP;
8130   else if (name == "close")
8131     this->code_ = BUILTIN_CLOSE;
8132   else if (name == "complex")
8133     this->code_ = BUILTIN_COMPLEX;
8134   else if (name == "copy")
8135     this->code_ = BUILTIN_COPY;
8136   else if (name == "delete")
8137     this->code_ = BUILTIN_DELETE;
8138   else if (name == "imag")
8139     this->code_ = BUILTIN_IMAG;
8140   else if (name == "len")
8141     this->code_ = BUILTIN_LEN;
8142   else if (name == "make")
8143     this->code_ = BUILTIN_MAKE;
8144   else if (name == "new")
8145     this->code_ = BUILTIN_NEW;
8146   else if (name == "panic")
8147     this->code_ = BUILTIN_PANIC;
8148   else if (name == "print")
8149     this->code_ = BUILTIN_PRINT;
8150   else if (name == "println")
8151     this->code_ = BUILTIN_PRINTLN;
8152   else if (name == "real")
8153     this->code_ = BUILTIN_REAL;
8154   else if (name == "recover")
8155     this->code_ = BUILTIN_RECOVER;
8156   else if (name == "Alignof")
8157     this->code_ = BUILTIN_ALIGNOF;
8158   else if (name == "Offsetof")
8159     this->code_ = BUILTIN_OFFSETOF;
8160   else if (name == "Sizeof")
8161     this->code_ = BUILTIN_SIZEOF;
8162   else
8163     go_unreachable();
8164 }
8165 
8166 // Return whether this is a call to recover.  This is a virtual
8167 // function called from the parent class.
8168 
8169 bool
do_is_recover_call() const8170 Builtin_call_expression::do_is_recover_call() const
8171 {
8172   if (this->classification() == EXPRESSION_ERROR)
8173     return false;
8174   return this->code_ == BUILTIN_RECOVER;
8175 }
8176 
8177 // Set the argument for a call to recover.
8178 
8179 void
do_set_recover_arg(Expression * arg)8180 Builtin_call_expression::do_set_recover_arg(Expression* arg)
8181 {
8182   const Expression_list* args = this->args();
8183   go_assert(args == NULL || args->empty());
8184   Expression_list* new_args = new Expression_list();
8185   new_args->push_back(arg);
8186   this->set_args(new_args);
8187   this->recover_arg_is_set_ = true;
8188 }
8189 
8190 // Lower a builtin call expression.  This turns new and make into
8191 // specific expressions.  We also convert to a constant if we can.
8192 
8193 Expression*
do_lower(Gogo *,Named_object * function,Statement_inserter * inserter,int)8194 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
8195 				  Statement_inserter* inserter, int)
8196 {
8197   if (this->is_error_expression())
8198     return this;
8199 
8200   Location loc = this->location();
8201 
8202   if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
8203     {
8204       this->report_error(_("invalid use of %<...%> with builtin function"));
8205       return Expression::make_error(loc);
8206     }
8207 
8208   if (this->code_ == BUILTIN_OFFSETOF)
8209     {
8210       Expression* arg = this->one_arg();
8211 
8212       if (arg->bound_method_expression() != NULL
8213 	  || arg->interface_field_reference_expression() != NULL)
8214 	{
8215 	  this->report_error(_("invalid use of method value as argument "
8216 			       "of Offsetof"));
8217 	  return this;
8218 	}
8219 
8220       Field_reference_expression* farg = arg->field_reference_expression();
8221       while (farg != NULL)
8222 	{
8223 	  if (!farg->implicit())
8224 	    break;
8225 	  // When the selector refers to an embedded field,
8226 	  // it must not be reached through pointer indirections.
8227 	  if (farg->expr()->deref() != farg->expr())
8228 	    {
8229 	      this->report_error(_("argument of Offsetof implies "
8230 				   "indirection of an embedded field"));
8231 	      return this;
8232 	    }
8233 	  // Go up until we reach the original base.
8234 	  farg = farg->expr()->field_reference_expression();
8235 	}
8236     }
8237 
8238   if (this->is_constant())
8239     {
8240       Numeric_constant nc;
8241       if (this->numeric_constant_value(&nc))
8242 	return nc.expression(loc);
8243     }
8244 
8245   switch (this->code_)
8246     {
8247     default:
8248       break;
8249 
8250     case BUILTIN_NEW:
8251       {
8252 	const Expression_list* args = this->args();
8253 	if (args == NULL || args->size() < 1)
8254 	  this->report_error(_("not enough arguments"));
8255 	else if (args->size() > 1)
8256 	  this->report_error(_("too many arguments"));
8257 	else
8258 	  {
8259 	    Expression* arg = args->front();
8260 	    if (!arg->is_type_expression())
8261 	      {
8262 		go_error_at(arg->location(), "expected type");
8263 		this->set_is_error();
8264 	      }
8265 	    else
8266 	      return Expression::make_allocation(arg->type(), loc);
8267 	  }
8268       }
8269       break;
8270 
8271     case BUILTIN_MAKE:
8272       return this->lower_make(inserter);
8273 
8274     case BUILTIN_RECOVER:
8275       if (function != NULL)
8276 	function->func_value()->set_calls_recover();
8277       else
8278 	{
8279 	  // Calling recover outside of a function always returns the
8280 	  // nil empty interface.
8281 	  Type* eface = Type::make_empty_interface_type(loc);
8282 	  return Expression::make_cast(eface, Expression::make_nil(loc), loc);
8283 	}
8284       break;
8285 
8286     case BUILTIN_DELETE:
8287       {
8288         const Expression_list* args = this->args();
8289         if (args == NULL || args->size() < 2)
8290           this->report_error(_("not enough arguments"));
8291         else if (args->size() > 2)
8292           this->report_error(_("too many arguments"));
8293         else if (args->front()->type()->map_type() == NULL)
8294           this->report_error(_("argument 1 must be a map"));
8295         else
8296           {
8297             Type* key_type =
8298               args->front()->type()->map_type()->key_type();
8299             Expression_list::iterator pa = this->args()->begin();
8300             pa++;
8301             Type* arg_type = (*pa)->type();
8302             std::string reason;
8303             if (!Type::are_assignable(key_type, arg_type, &reason))
8304               {
8305                 if (reason.empty())
8306                   go_error_at(loc, "argument 2 has incompatible type");
8307                 else
8308                   go_error_at(loc, "argument 2 has incompatible type (%s)",
8309                               reason.c_str());
8310                 this->set_is_error();
8311               }
8312             else if (!Type::are_identical(key_type, arg_type, 0, NULL))
8313               *pa = Expression::make_cast(key_type, *pa, loc);
8314           }
8315       }
8316       break;
8317 
8318     case BUILTIN_PRINT:
8319     case BUILTIN_PRINTLN:
8320       // Force all the arguments into temporary variables, so that we
8321       // don't try to evaluate something while holding the print lock.
8322       if (this->args() == NULL)
8323 	break;
8324       for (Expression_list::iterator pa = this->args()->begin();
8325 	   pa != this->args()->end();
8326 	   ++pa)
8327 	{
8328 	  if (!(*pa)->is_variable() && !(*pa)->is_constant())
8329 	    {
8330 	      Temporary_statement* temp =
8331 		Statement::make_temporary(NULL, *pa, loc);
8332 	      inserter->insert(temp);
8333 	      *pa = Expression::make_temporary_reference(temp, loc);
8334 	    }
8335 	}
8336       break;
8337     }
8338 
8339   return this;
8340 }
8341 
8342 // Flatten a builtin call expression.  This turns the arguments of some
8343 // builtin calls into temporary expressions.  Also expand copy and append
8344 // to runtime calls.
8345 
8346 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)8347 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
8348                                     Statement_inserter* inserter)
8349 {
8350   if (this->is_error_expression())
8351     {
8352       go_assert(saw_errors());
8353       return this;
8354     }
8355 
8356   Location loc = this->location();
8357 
8358   switch (this->code_)
8359     {
8360     default:
8361       break;
8362 
8363     case BUILTIN_APPEND:
8364       return this->flatten_append(gogo, function, inserter, NULL, NULL);
8365 
8366     case BUILTIN_COPY:
8367       {
8368 	Type* at = this->args()->front()->type();
8369 	for (Expression_list::iterator pa = this->args()->begin();
8370 	     pa != this->args()->end();
8371 	     ++pa)
8372 	  {
8373 	    if ((*pa)->is_nil_expression())
8374 	      {
8375 		Expression* nil = Expression::make_nil(loc);
8376 		Expression* zero = Expression::make_integer_ul(0, NULL, loc);
8377 		*pa = Expression::make_slice_value(at, nil, zero, zero, loc);
8378 	      }
8379 	    if (!(*pa)->is_variable())
8380 	      {
8381 		Temporary_statement* temp =
8382                   Statement::make_temporary(NULL, *pa, loc);
8383 		inserter->insert(temp);
8384 		*pa = Expression::make_temporary_reference(temp, loc);
8385 	      }
8386 	  }
8387 
8388         // Lower to runtime call.
8389         const Expression_list* args = this->args();
8390         go_assert(args != NULL && args->size() == 2);
8391         Expression* arg1 = args->front();
8392         Expression* arg2 = args->back();
8393         go_assert(arg1->is_variable());
8394         go_assert(arg2->is_variable());
8395         bool arg2_is_string = arg2->type()->is_string_type();
8396 
8397         Expression* ret;
8398         Type* et = at->array_type()->element_type();
8399         if (et->has_pointer())
8400           {
8401             Expression* td = Expression::make_type_descriptor(et, loc);
8402             ret = Runtime::make_call(Runtime::TYPEDSLICECOPY, loc,
8403                                      3, td, arg1, arg2);
8404           }
8405         else
8406           {
8407             Type* int_type = Type::lookup_integer_type("int");
8408             Type* uintptr_type = Type::lookup_integer_type("uintptr");
8409 
8410             // l1 = len(arg1)
8411             Named_object* lenfn = gogo->lookup_global("len");
8412             Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8413             Expression_list* len_args = new Expression_list();
8414             len_args->push_back(arg1->copy());
8415             Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
8416             gogo->lower_expression(function, inserter, &len1);
8417             gogo->flatten_expression(function, inserter, &len1);
8418             Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
8419             inserter->insert(l1tmp);
8420 
8421             // l2 = len(arg2)
8422             len_args = new Expression_list();
8423             len_args->push_back(arg2->copy());
8424             Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
8425             gogo->lower_expression(function, inserter, &len2);
8426             gogo->flatten_expression(function, inserter, &len2);
8427             Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
8428             inserter->insert(l2tmp);
8429 
8430             // n = (l1 < l2 ? l1 : l2)
8431             Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
8432             Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
8433             Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
8434             Expression* n = Expression::make_conditional(cond,
8435                                                          l1ref->copy(),
8436                                                          l2ref->copy(),
8437                                                          loc);
8438             Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
8439             inserter->insert(ntmp);
8440 
8441             // sz = n * sizeof(elem_type)
8442             Expression* nref = Expression::make_temporary_reference(ntmp, loc);
8443             nref = Expression::make_cast(uintptr_type, nref, loc);
8444             Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
8445             sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
8446 
8447             // memmove(arg1.ptr, arg2.ptr, sz)
8448             Expression* p1 = Expression::make_slice_info(arg1,
8449                                                          SLICE_INFO_VALUE_POINTER,
8450                                                          loc);
8451             Expression* p2 = (arg2_is_string
8452                               ? Expression::make_string_info(arg2,
8453                                                              STRING_INFO_DATA,
8454                                                              loc)
8455                               : Expression::make_slice_info(arg2,
8456                                                             SLICE_INFO_VALUE_POINTER,
8457                                                             loc));
8458             Expression* call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
8459                                                   p1, p2, sz);
8460 
8461             // n is the return value of copy
8462             nref = Expression::make_temporary_reference(ntmp, loc);
8463             ret = Expression::make_compound(call, nref, loc);
8464           }
8465         return ret;
8466       }
8467       break;
8468 
8469     case BUILTIN_PANIC:
8470       for (Expression_list::iterator pa = this->args()->begin();
8471 	   pa != this->args()->end();
8472 	   ++pa)
8473 	{
8474 	  if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
8475 	    {
8476 	      Temporary_statement* temp =
8477 		Statement::make_temporary(NULL, *pa, loc);
8478 	      inserter->insert(temp);
8479 	      *pa = Expression::make_temporary_reference(temp, loc);
8480 	    }
8481 	}
8482       break;
8483 
8484     case BUILTIN_LEN:
8485     case BUILTIN_CAP:
8486       {
8487 	Expression_list::iterator pa = this->args()->begin();
8488 	if (!(*pa)->is_variable()
8489 	    && ((*pa)->type()->map_type() != NULL
8490 		|| (*pa)->type()->channel_type() != NULL))
8491 	  {
8492 	    Temporary_statement* temp =
8493 	      Statement::make_temporary(NULL, *pa, loc);
8494 	    inserter->insert(temp);
8495 	    *pa = Expression::make_temporary_reference(temp, loc);
8496 	  }
8497       }
8498       break;
8499 
8500     case BUILTIN_DELETE:
8501       {
8502         // Lower to a runtime function call.
8503         const Expression_list* args = this->args();
8504 
8505         // Since this function returns no value it must appear in
8506         // a statement by itself, so we don't have to worry about
8507         // order of evaluation of values around it.  Evaluate the
8508         // map first to get order of evaluation right.
8509         Map_type* mt = args->front()->type()->map_type();
8510         Temporary_statement* map_temp =
8511           Statement::make_temporary(mt, args->front(), loc);
8512         inserter->insert(map_temp);
8513 
8514         Temporary_statement* key_temp =
8515           Statement::make_temporary(mt->key_type(), args->back(), loc);
8516         inserter->insert(key_temp);
8517 
8518         Expression* e1 = Expression::make_type_descriptor(mt, loc);
8519         Expression* e2 = Expression::make_temporary_reference(map_temp,
8520                                                               loc);
8521         Expression* e3 = Expression::make_temporary_reference(key_temp,
8522                                                               loc);
8523 
8524         Runtime::Function code;
8525         switch (mt->algorithm(gogo))
8526           {
8527             case Map_type::MAP_ALG_FAST32:
8528             case Map_type::MAP_ALG_FAST32PTR:
8529               {
8530                 code = Runtime::MAPDELETE_FAST32;
8531                 Type* uint32_type = Type::lookup_integer_type("uint32");
8532                 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
8533                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8534                 e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
8535                                                   loc);
8536                 e3 = Expression::make_dereference(e3,
8537                                                   Expression::NIL_CHECK_NOT_NEEDED,
8538                                                   loc);
8539                 break;
8540               }
8541             case Map_type::MAP_ALG_FAST64:
8542             case Map_type::MAP_ALG_FAST64PTR:
8543               {
8544                 code = Runtime::MAPDELETE_FAST64;
8545                 Type* uint64_type = Type::lookup_integer_type("uint64");
8546                 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
8547                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8548                 e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
8549                                                   loc);
8550                 e3 = Expression::make_dereference(e3,
8551                                                   Expression::NIL_CHECK_NOT_NEEDED,
8552                                                   loc);
8553                 break;
8554               }
8555             case Map_type::MAP_ALG_FASTSTR:
8556               code = Runtime::MAPDELETE_FASTSTR;
8557               break;
8558             default:
8559               code = Runtime::MAPDELETE;
8560 
8561               // If the call to delete is deferred, and is in a loop,
8562               // then the loop will only have a single instance of the
8563               // temporary variable.  Passing the address of the
8564               // temporary variable here means that the deferred call
8565               // will see the last value in the loop, not the current
8566               // value.  So for this unusual case copy the value into
8567               // the heap.
8568               if (!this->is_deferred())
8569                 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8570               else
8571                 {
8572                   Expression* a = Expression::make_allocation(mt->key_type(),
8573                                                               loc);
8574                   Temporary_statement* atemp =
8575                     Statement::make_temporary(NULL, a, loc);
8576                   inserter->insert(atemp);
8577 
8578                   a = Expression::make_temporary_reference(atemp, loc);
8579                   a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
8580                   Statement* s = Statement::make_assignment(a, e3, loc);
8581                   inserter->insert(s);
8582 
8583                   e3 = Expression::make_temporary_reference(atemp, loc);
8584                 }
8585           }
8586 
8587         return Runtime::make_call(code, loc, 3, e1, e2, e3);
8588       }
8589     }
8590 
8591   return this;
8592 }
8593 
8594 // Lower a make expression.
8595 
8596 Expression*
lower_make(Statement_inserter * inserter)8597 Builtin_call_expression::lower_make(Statement_inserter* inserter)
8598 {
8599   Location loc = this->location();
8600 
8601   const Expression_list* args = this->args();
8602   if (args == NULL || args->size() < 1)
8603     {
8604       this->report_error(_("not enough arguments"));
8605       return Expression::make_error(this->location());
8606     }
8607 
8608   Expression_list::const_iterator parg = args->begin();
8609 
8610   Expression* first_arg = *parg;
8611   if (!first_arg->is_type_expression())
8612     {
8613       go_error_at(first_arg->location(), "expected type");
8614       this->set_is_error();
8615       return Expression::make_error(this->location());
8616     }
8617   Type* type = first_arg->type();
8618 
8619   if (!type->in_heap())
8620     go_error_at(first_arg->location(),
8621 		"cannot make slice of go:notinheap type");
8622 
8623   bool is_slice = false;
8624   bool is_map = false;
8625   bool is_chan = false;
8626   if (type->is_slice_type())
8627     is_slice = true;
8628   else if (type->map_type() != NULL)
8629     is_map = true;
8630   else if (type->channel_type() != NULL)
8631     is_chan = true;
8632   else
8633     {
8634       this->report_error(_("invalid type for make function"));
8635       return Expression::make_error(this->location());
8636     }
8637 
8638   Type_context int_context(Type::lookup_integer_type("int"), false);
8639 
8640   ++parg;
8641   Expression* len_arg;
8642   bool len_small = false;
8643   if (parg == args->end())
8644     {
8645       if (is_slice)
8646 	{
8647 	  this->report_error(_("length required when allocating a slice"));
8648 	  return Expression::make_error(this->location());
8649 	}
8650       len_arg = Expression::make_integer_ul(0, NULL, loc);
8651       len_small = true;
8652     }
8653   else
8654     {
8655       len_arg = *parg;
8656       len_arg->determine_type(&int_context);
8657       if (len_arg->type()->integer_type() == NULL)
8658 	{
8659 	  go_error_at(len_arg->location(), "non-integer len argument in make");
8660 	  return Expression::make_error(this->location());
8661 	}
8662       if (!this->check_int_value(len_arg, true, &len_small))
8663 	return Expression::make_error(this->location());
8664       ++parg;
8665     }
8666 
8667   Expression* cap_arg = NULL;
8668   bool cap_small = false;
8669   Numeric_constant nclen;
8670   Numeric_constant nccap;
8671   unsigned long vlen;
8672   unsigned long vcap;
8673   if (is_slice && parg != args->end())
8674     {
8675       cap_arg = *parg;
8676       cap_arg->determine_type(&int_context);
8677       if (cap_arg->type()->integer_type() == NULL)
8678 	{
8679 	  go_error_at(cap_arg->location(), "non-integer cap argument in make");
8680 	  return Expression::make_error(this->location());
8681 	}
8682       if (!this->check_int_value(cap_arg, false, &cap_small))
8683 	return Expression::make_error(this->location());
8684 
8685       if (len_arg->numeric_constant_value(&nclen)
8686 	  && cap_arg->numeric_constant_value(&nccap)
8687 	  && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8688 	  && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
8689 	  && vlen > vcap)
8690 	{
8691 	  this->report_error(_("len larger than cap"));
8692 	  return Expression::make_error(this->location());
8693 	}
8694 
8695       ++parg;
8696     }
8697 
8698   if (parg != args->end())
8699     {
8700       this->report_error(_("too many arguments to make"));
8701       return Expression::make_error(this->location());
8702     }
8703 
8704   Location type_loc = first_arg->location();
8705 
8706   Expression* call;
8707   if (is_slice)
8708     {
8709       Temporary_statement* len_temp = NULL;
8710       if (!len_arg->is_constant())
8711 	{
8712 	  len_temp = Statement::make_temporary(NULL, len_arg, loc);
8713 	  inserter->insert(len_temp);
8714 	  len_arg = Expression::make_temporary_reference(len_temp, loc);
8715 	}
8716 
8717       if (cap_arg == NULL)
8718 	{
8719           cap_small = len_small;
8720 	  if (len_temp == NULL)
8721 	    cap_arg = len_arg->copy();
8722 	  else
8723 	    cap_arg = Expression::make_temporary_reference(len_temp, loc);
8724 	}
8725       else if (!cap_arg->is_constant())
8726 	{
8727 	  Temporary_statement* cap_temp = Statement::make_temporary(NULL,
8728 								    cap_arg,
8729 								    loc);
8730 	  inserter->insert(cap_temp);
8731 	  cap_arg = Expression::make_temporary_reference(cap_temp, loc);
8732 	}
8733 
8734       Type* et = type->array_type()->element_type();
8735       Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
8736       Runtime::Function code = Runtime::MAKESLICE;
8737       if (!len_small || !cap_small)
8738 	code = Runtime::MAKESLICE64;
8739       Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
8740 					   cap_arg);
8741       mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
8742 					 loc);
8743       Type* int_type = Type::lookup_integer_type("int");
8744       len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
8745       cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
8746       call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
8747     }
8748   else if (is_map)
8749     {
8750       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8751       if (!len_small)
8752 	call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
8753 				  len_arg,
8754 				  Expression::make_nil(loc));
8755       else
8756 	{
8757 	  if (len_arg->numeric_constant_value(&nclen)
8758 	      && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8759 	      && vlen <= Map_type::bucket_size)
8760 	    call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
8761 	  else
8762 	    call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
8763 				      len_arg,
8764 				      Expression::make_nil(loc));
8765 	}
8766     }
8767   else if (is_chan)
8768     {
8769       Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8770       Runtime::Function code = Runtime::MAKECHAN;
8771       if (!len_small)
8772 	code = Runtime::MAKECHAN64;
8773       call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
8774     }
8775   else
8776     go_unreachable();
8777 
8778   return Expression::make_unsafe_cast(type, call, loc);
8779 }
8780 
8781 // Flatten a call to the predeclared append function.  We do this in
8782 // the flatten phase, not the lowering phase, so that we run after
8783 // type checking and after order_evaluations.  If ASSIGN_LHS is not
8784 // NULL, this append is the right-hand-side of an assignment and
8785 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
8786 // rather than returning a slice.  This lets us omit a write barrier
8787 // in common cases like a = append(a, ...) when the slice does not
8788 // need to grow.  ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
8789 
8790 Expression*
flatten_append(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Expression * assign_lhs,Block * enclosing)8791 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
8792 					Statement_inserter* inserter,
8793 					Expression* assign_lhs,
8794 					Block* enclosing)
8795 {
8796   if (this->is_error_expression())
8797     return this;
8798 
8799   Location loc = this->location();
8800 
8801   const Expression_list* args = this->args();
8802   go_assert(args != NULL && !args->empty());
8803 
8804   Type* slice_type = args->front()->type();
8805   go_assert(slice_type->is_slice_type());
8806   Type* element_type = slice_type->array_type()->element_type();
8807 
8808   if (args->size() == 1)
8809     {
8810       // append(s) evaluates to s.
8811       if (assign_lhs != NULL)
8812 	return NULL;
8813       return args->front();
8814     }
8815 
8816   Type* int_type = Type::lookup_integer_type("int");
8817   Type* uint_type = Type::lookup_integer_type("uint");
8818 
8819   // Implementing
8820   //   append(s1, s2...)
8821   // or
8822   //   append(s1, a1, a2, a3, ...)
8823 
8824   // s1tmp := s1
8825   Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
8826 							 loc);
8827   inserter->insert(s1tmp);
8828 
8829   // l1tmp := len(s1tmp)
8830   Named_object* lenfn = gogo->lookup_global("len");
8831   Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8832   Expression_list* call_args = new Expression_list();
8833   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8834   Expression* len = Expression::make_call(lenref, call_args, false, loc);
8835   gogo->lower_expression(function, inserter, &len);
8836   gogo->flatten_expression(function, inserter, &len);
8837   Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
8838   inserter->insert(l1tmp);
8839 
8840   Temporary_statement* s2tmp = NULL;
8841   Temporary_statement* l2tmp = NULL;
8842   Expression_list* add = NULL;
8843   Expression* len2;
8844   Call_expression* makecall = NULL;
8845   if (this->is_varargs())
8846     {
8847       go_assert(args->size() == 2);
8848 
8849       std::pair<Call_expression*, Temporary_statement*> p =
8850         Expression::find_makeslice_call(args->back());
8851       makecall = p.first;
8852       if (makecall != NULL)
8853         {
8854           // We are handling
8855           // 	append(s, make([]T, len[, cap])...))
8856           // which has already been lowered to
8857           // 	append(s, runtime.makeslice(T, len, cap)).
8858           // We will optimize this to directly zeroing the tail,
8859           // instead of allocating a new slice then copy.
8860 
8861           // Retrieve the length. Cannot reference s2 as we will remove
8862           // the makeslice call.
8863           Expression* len_arg = makecall->args()->at(1);
8864           len_arg = Expression::make_cast(int_type, len_arg, loc);
8865           l2tmp = Statement::make_temporary(int_type, len_arg, loc);
8866           inserter->insert(l2tmp);
8867 
8868           Expression* cap_arg = makecall->args()->at(2);
8869           cap_arg = Expression::make_cast(int_type, cap_arg, loc);
8870           Temporary_statement* c2tmp =
8871             Statement::make_temporary(int_type, cap_arg, loc);
8872           inserter->insert(c2tmp);
8873 
8874           // Check bad len/cap here.
8875           // if len2 < 0 { panicmakeslicelen(); }
8876           len2 = Expression::make_temporary_reference(l2tmp, loc);
8877           Expression* zero = Expression::make_integer_ul(0, int_type, loc);
8878           Expression* cond = Expression::make_binary(OPERATOR_LT, len2,
8879                                                      zero, loc);
8880 	  Expression* call = Runtime::make_call(Runtime::PANIC_MAKE_SLICE_LEN,
8881 						loc, 0);
8882           cond = Expression::make_conditional(cond, call, zero->copy(), loc);
8883           gogo->lower_expression(function, inserter, &cond);
8884           gogo->flatten_expression(function, inserter, &cond);
8885           Statement* s = Statement::make_statement(cond, false);
8886           inserter->insert(s);
8887 
8888           // if cap2 < 0 { panicmakeslicecap(); }
8889           Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
8890           cond = Expression::make_binary(OPERATOR_LT, cap2,
8891                                          zero->copy(), loc);
8892 	  call = Runtime::make_call(Runtime::PANIC_MAKE_SLICE_CAP, loc, 0);
8893           cond = Expression::make_conditional(cond, call, zero->copy(), loc);
8894           gogo->lower_expression(function, inserter, &cond);
8895           gogo->flatten_expression(function, inserter, &cond);
8896           s = Statement::make_statement(cond, false);
8897           inserter->insert(s);
8898 
8899           // Remove the original makeslice call.
8900           Temporary_statement* ts = p.second;
8901           if (ts != NULL && ts->uses() == 1)
8902             ts->set_init(Expression::make_nil(loc));
8903         }
8904       else
8905         {
8906           // s2tmp := s2
8907           s2tmp = Statement::make_temporary(NULL, args->back(), loc);
8908           inserter->insert(s2tmp);
8909 
8910           // l2tmp := len(s2tmp)
8911           lenref = Expression::make_func_reference(lenfn, NULL, loc);
8912           call_args = new Expression_list();
8913           call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
8914           len = Expression::make_call(lenref, call_args, false, loc);
8915           gogo->lower_expression(function, inserter, &len);
8916           gogo->flatten_expression(function, inserter, &len);
8917           l2tmp = Statement::make_temporary(int_type, len, loc);
8918           inserter->insert(l2tmp);
8919         }
8920 
8921       // len2 = l2tmp
8922       len2 = Expression::make_temporary_reference(l2tmp, loc);
8923     }
8924   else
8925     {
8926       // We have to ensure that all the arguments are in variables
8927       // now, because otherwise if one of them is an index expression
8928       // into the current slice we could overwrite it before we fetch
8929       // it.
8930       add = new Expression_list();
8931       Expression_list::const_iterator pa = args->begin();
8932       for (++pa; pa != args->end(); ++pa)
8933 	{
8934 	  if ((*pa)->is_variable())
8935 	    add->push_back(*pa);
8936 	  else
8937 	    {
8938 	      Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
8939 								   loc);
8940 	      inserter->insert(tmp);
8941 	      add->push_back(Expression::make_temporary_reference(tmp, loc));
8942 	    }
8943 	}
8944 
8945       // len2 = len(add)
8946       len2 = Expression::make_integer_ul(add->size(), int_type, loc);
8947     }
8948 
8949   // ntmp := l1tmp + len2
8950   Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
8951   Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
8952   gogo->lower_expression(function, inserter, &sum);
8953   gogo->flatten_expression(function, inserter, &sum);
8954   Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
8955   inserter->insert(ntmp);
8956 
8957   // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
8958   //   growslice(type, s1tmp, ntmp) :
8959   //   s1tmp[:ntmp]
8960   // Using uint here means that if the computation of ntmp overflowed,
8961   // we will call growslice which will panic.
8962 
8963   Named_object* capfn = gogo->lookup_global("cap");
8964   Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
8965   call_args = new Expression_list();
8966   call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8967   Expression* cap = Expression::make_call(capref, call_args, false, loc);
8968   gogo->lower_expression(function, inserter, &cap);
8969   gogo->flatten_expression(function, inserter, &cap);
8970   Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
8971   inserter->insert(c1tmp);
8972 
8973   Expression* left = Expression::make_temporary_reference(ntmp, loc);
8974   left = Expression::make_cast(uint_type, left, loc);
8975   Expression* right = Expression::make_temporary_reference(c1tmp, loc);
8976   right = Expression::make_cast(uint_type, right, loc);
8977 
8978   Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
8979 
8980   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8981   Expression* a1 = Expression::make_type_descriptor(element_type, loc);
8982   Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
8983   a2 = slice_type->array_type()->get_value_pointer(gogo, a2, false);
8984   a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
8985   Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
8986   Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
8987   Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
8988   Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
8989 					a1, a2, a3, a4, a5);
8990   call = Expression::make_unsafe_cast(slice_type, call, loc);
8991 
8992   ref = Expression::make_temporary_reference(s1tmp, loc);
8993   Expression* zero = Expression::make_integer_ul(0, int_type, loc);
8994   Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
8995   ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
8996   ref->array_index_expression()->set_needs_bounds_check(false);
8997 
8998   if (assign_lhs == NULL)
8999     {
9000       Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
9001 
9002       gogo->lower_expression(function, inserter, &rhs);
9003       gogo->flatten_expression(function, inserter, &rhs);
9004 
9005       ref = Expression::make_temporary_reference(s1tmp, loc);
9006       Statement* assign = Statement::make_assignment(ref, rhs, loc);
9007       inserter->insert(assign);
9008     }
9009   else
9010     {
9011       gogo->lower_expression(function, inserter, &cond);
9012       gogo->flatten_expression(function, inserter, &cond);
9013       gogo->lower_expression(function, inserter, &call);
9014       gogo->flatten_expression(function, inserter, &call);
9015       gogo->lower_expression(function, inserter, &ref);
9016       gogo->flatten_expression(function, inserter, &ref);
9017 
9018       Block* then_block = new Block(enclosing, loc);
9019       Assignment_statement* assign =
9020 	Statement::make_assignment(assign_lhs, call, loc);
9021       then_block->add_statement(assign);
9022 
9023       Block* else_block = new Block(enclosing, loc);
9024       assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
9025       // This assignment will not change the pointer value, so it does
9026       // not need a write barrier.
9027       assign->set_omit_write_barrier();
9028       else_block->add_statement(assign);
9029 
9030       Statement* s = Statement::make_if_statement(cond, then_block,
9031 						  else_block, loc);
9032       inserter->insert(s);
9033 
9034       ref = Expression::make_temporary_reference(s1tmp, loc);
9035       assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
9036       inserter->insert(assign);
9037     }
9038 
9039   Type* uintptr_type = Type::lookup_integer_type("uintptr");
9040 
9041   if (this->is_varargs())
9042     {
9043       if (makecall != NULL)
9044         {
9045           // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
9046           a1 = Expression::make_temporary_reference(s1tmp, loc);
9047           ref = Expression::make_temporary_reference(l1tmp, loc);
9048           a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9049           a1->array_index_expression()->set_needs_bounds_check(false);
9050           a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9051 
9052           ref = Expression::make_temporary_reference(l2tmp, loc);
9053           ref = Expression::make_cast(uintptr_type, ref, loc);
9054           a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9055           a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
9056 
9057           if (element_type->has_pointer())
9058             call = Runtime::make_call(Runtime::MEMCLRHASPTR, loc, 2, a1, a2);
9059           else
9060             {
9061               Type* int32_type = Type::lookup_integer_type("int32");
9062               zero = Expression::make_integer_ul(0, int32_type, loc);
9063               call = Runtime::make_call(Runtime::BUILTIN_MEMSET, loc, 3, a1,
9064                                         zero, a2);
9065             }
9066 
9067           if (element_type->has_pointer())
9068             {
9069               // For a slice containing pointers, growslice already zeroed
9070               // the memory. We only need to zero in non-growing case.
9071               // Note: growslice does not zero the memory in non-pointer case.
9072               ref = Expression::make_temporary_reference(ntmp, loc);
9073               ref = Expression::make_cast(uint_type, ref, loc);
9074               ref2 = Expression::make_temporary_reference(c1tmp, loc);
9075               ref2 = Expression::make_cast(uint_type, ref2, loc);
9076               cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
9077               zero = Expression::make_integer_ul(0, int_type, loc);
9078               call = Expression::make_conditional(cond, zero, call, loc);
9079             }
9080         }
9081       else
9082         {
9083           if (element_type->has_pointer())
9084             {
9085               // copy(s1tmp[l1tmp:], s2tmp)
9086               a1 = Expression::make_temporary_reference(s1tmp, loc);
9087               ref = Expression::make_temporary_reference(l1tmp, loc);
9088               Expression* nil = Expression::make_nil(loc);
9089               a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
9090               a1->array_index_expression()->set_needs_bounds_check(false);
9091 
9092               a2 = Expression::make_temporary_reference(s2tmp, loc);
9093 
9094               Named_object* copyfn = gogo->lookup_global("copy");
9095               Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
9096               call_args = new Expression_list();
9097               call_args->push_back(a1);
9098               call_args->push_back(a2);
9099               call = Expression::make_call(copyref, call_args, false, loc);
9100             }
9101           else
9102             {
9103               // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
9104               a1 = Expression::make_temporary_reference(s1tmp, loc);
9105               ref = Expression::make_temporary_reference(l1tmp, loc);
9106               a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9107               a1->array_index_expression()->set_needs_bounds_check(false);
9108               a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9109 
9110               a2 = Expression::make_temporary_reference(s2tmp, loc);
9111               a2 = (a2->type()->is_string_type()
9112                     ? Expression::make_string_info(a2,
9113                                                    STRING_INFO_DATA,
9114                                                    loc)
9115                     : Expression::make_slice_info(a2,
9116                                                   SLICE_INFO_VALUE_POINTER,
9117                                                   loc));
9118 
9119               ref = Expression::make_temporary_reference(l2tmp, loc);
9120               ref = Expression::make_cast(uintptr_type, ref, loc);
9121               a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9122               a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
9123 
9124               call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
9125                                         a1, a2, a3);
9126             }
9127         }
9128       gogo->lower_expression(function, inserter, &call);
9129       gogo->flatten_expression(function, inserter, &call);
9130       inserter->insert(Statement::make_statement(call, false));
9131     }
9132   else
9133     {
9134       // For each argument:
9135       //  s1tmp[l1tmp+i] = a
9136       unsigned long i = 0;
9137       for (Expression_list::const_iterator pa = add->begin();
9138 	   pa != add->end();
9139 	   ++pa, ++i)
9140 	{
9141 	  ref = Expression::make_temporary_reference(s1tmp, loc);
9142 	  ref2 = Expression::make_temporary_reference(l1tmp, loc);
9143 	  Expression* off = Expression::make_integer_ul(i, int_type, loc);
9144 	  ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
9145 	  Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
9146                                                          NULL, loc);
9147           lhs->array_index_expression()->set_needs_bounds_check(false);
9148 	  gogo->lower_expression(function, inserter, &lhs);
9149 	  gogo->flatten_expression(function, inserter, &lhs);
9150       Expression* elem = *pa;
9151       if (!Type::are_identical(element_type, elem->type(), 0, NULL)
9152           && element_type->interface_type() != NULL)
9153         elem = Expression::make_cast(element_type, elem, loc);
9154 	  // The flatten pass runs after the write barrier pass, so we
9155 	  // need to insert a write barrier here if necessary.
9156 	  // However, if ASSIGN_LHS is not NULL, we have been called
9157 	  // directly before the write barrier pass.
9158 	  Statement* assign;
9159 	  if (assign_lhs != NULL
9160 	      || !gogo->assign_needs_write_barrier(lhs, NULL))
9161 	    assign = Statement::make_assignment(lhs, elem, loc);
9162 	  else
9163 	    {
9164 	      Function* f = function == NULL ? NULL : function->func_value();
9165 	      assign = gogo->assign_with_write_barrier(f, NULL, inserter,
9166 						       lhs, elem, loc);
9167 	    }
9168 	  inserter->insert(assign);
9169 	}
9170     }
9171 
9172   if (assign_lhs != NULL)
9173     return NULL;
9174 
9175   return Expression::make_temporary_reference(s1tmp, loc);
9176 }
9177 
9178 // Return whether an expression has an integer value.  Report an error
9179 // if not.  This is used when handling calls to the predeclared make
9180 // function.  Set *SMALL if the value is known to fit in type "int".
9181 
9182 bool
check_int_value(Expression * e,bool is_length,bool * small)9183 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
9184 					 bool *small)
9185 {
9186   *small = false;
9187 
9188   Numeric_constant nc;
9189   if (e->numeric_constant_value(&nc))
9190     {
9191       unsigned long v;
9192       switch (nc.to_unsigned_long(&v))
9193 	{
9194 	case Numeric_constant::NC_UL_VALID:
9195 	  break;
9196 	case Numeric_constant::NC_UL_NOTINT:
9197 	  go_error_at(e->location(), "non-integer %s argument to make",
9198 		      is_length ? "len" : "cap");
9199 	  return false;
9200 	case Numeric_constant::NC_UL_NEGATIVE:
9201 	  go_error_at(e->location(), "negative %s argument to make",
9202 		      is_length ? "len" : "cap");
9203 	  return false;
9204 	case Numeric_constant::NC_UL_BIG:
9205 	  // We don't want to give a compile-time error for a 64-bit
9206 	  // value on a 32-bit target.
9207 	  break;
9208 	}
9209 
9210       mpz_t val;
9211       if (!nc.to_int(&val))
9212 	go_unreachable();
9213       int bits = mpz_sizeinbase(val, 2);
9214       mpz_clear(val);
9215       Type* int_type = Type::lookup_integer_type("int");
9216       if (bits >= int_type->integer_type()->bits())
9217 	{
9218 	  go_error_at(e->location(), "%s argument too large for make",
9219 		      is_length ? "len" : "cap");
9220 	  return false;
9221 	}
9222 
9223       *small = true;
9224       return true;
9225     }
9226 
9227   if (e->type()->integer_type() != NULL)
9228     {
9229       int ebits = e->type()->integer_type()->bits();
9230       int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
9231 
9232       // We can treat ebits == intbits as small even for an unsigned
9233       // integer type, because we will convert the value to int and
9234       // then reject it in the runtime if it is negative.
9235       *small = ebits <= intbits;
9236 
9237       return true;
9238     }
9239 
9240   go_error_at(e->location(), "non-integer %s argument to make",
9241 	      is_length ? "len" : "cap");
9242   return false;
9243 }
9244 
9245 // Return the type of the real or imag functions, given the type of
9246 // the argument.  We need to map complex64 to float32 and complex128
9247 // to float64, so it has to be done by name.  This returns NULL if it
9248 // can't figure out the type.
9249 
9250 Type*
real_imag_type(Type * arg_type)9251 Builtin_call_expression::real_imag_type(Type* arg_type)
9252 {
9253   if (arg_type == NULL || arg_type->is_abstract())
9254     return NULL;
9255   Named_type* nt = arg_type->named_type();
9256   if (nt == NULL)
9257     return NULL;
9258   while (nt->real_type()->named_type() != NULL)
9259     nt = nt->real_type()->named_type();
9260   if (nt->name() == "complex64")
9261     return Type::lookup_float_type("float32");
9262   else if (nt->name() == "complex128")
9263     return Type::lookup_float_type("float64");
9264   else
9265     return NULL;
9266 }
9267 
9268 // Return the type of the complex function, given the type of one of the
9269 // argments.  Like real_imag_type, we have to map by name.
9270 
9271 Type*
complex_type(Type * arg_type)9272 Builtin_call_expression::complex_type(Type* arg_type)
9273 {
9274   if (arg_type == NULL || arg_type->is_abstract())
9275     return NULL;
9276   Named_type* nt = arg_type->named_type();
9277   if (nt == NULL)
9278     return NULL;
9279   while (nt->real_type()->named_type() != NULL)
9280     nt = nt->real_type()->named_type();
9281   if (nt->name() == "float32")
9282     return Type::lookup_complex_type("complex64");
9283   else if (nt->name() == "float64")
9284     return Type::lookup_complex_type("complex128");
9285   else
9286     return NULL;
9287 }
9288 
9289 // Return a single argument, or NULL if there isn't one.
9290 
9291 Expression*
one_arg() const9292 Builtin_call_expression::one_arg() const
9293 {
9294   const Expression_list* args = this->args();
9295   if (args == NULL || args->size() != 1)
9296     return NULL;
9297   return args->front();
9298 }
9299 
9300 // A traversal class which looks for a call or receive expression.
9301 
9302 class Find_call_expression : public Traverse
9303 {
9304  public:
Find_call_expression()9305   Find_call_expression()
9306     : Traverse(traverse_expressions),
9307       found_(false)
9308   { }
9309 
9310   int
9311   expression(Expression**);
9312 
9313   bool
found()9314   found()
9315   { return this->found_; }
9316 
9317  private:
9318   bool found_;
9319 };
9320 
9321 int
expression(Expression ** pexpr)9322 Find_call_expression::expression(Expression** pexpr)
9323 {
9324   Expression* expr = *pexpr;
9325   if (!expr->is_constant()
9326       && (expr->call_expression() != NULL
9327 	  || expr->receive_expression() != NULL))
9328     {
9329       this->found_ = true;
9330       return TRAVERSE_EXIT;
9331     }
9332   return TRAVERSE_CONTINUE;
9333 }
9334 
9335 // Return whether calling len or cap on EXPR, of array type, is a
9336 // constant.  The language spec says "the expressions len(s) and
9337 // cap(s) are constants if the type of s is an array or pointer to an
9338 // array and the expression s does not contain channel receives or
9339 // (non-constant) function calls."
9340 
9341 bool
array_len_is_constant(Expression * expr)9342 Builtin_call_expression::array_len_is_constant(Expression* expr)
9343 {
9344   go_assert(expr->type()->deref()->array_type() != NULL
9345 	    && !expr->type()->deref()->is_slice_type());
9346   if (expr->is_constant())
9347     return true;
9348   Find_call_expression find_call;
9349   Expression::traverse(&expr, &find_call);
9350   return !find_call.found();
9351 }
9352 
9353 // Return whether this is constant: len of a string constant, or len
9354 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
9355 // unsafe.Alignof.
9356 
9357 bool
do_is_constant() const9358 Builtin_call_expression::do_is_constant() const
9359 {
9360   if (this->is_error_expression())
9361     return true;
9362   switch (this->code_)
9363     {
9364     case BUILTIN_LEN:
9365     case BUILTIN_CAP:
9366       {
9367 	if (this->seen_)
9368 	  return false;
9369 
9370 	Expression* arg = this->one_arg();
9371 	if (arg == NULL)
9372 	  return false;
9373 	Type* arg_type = arg->type();
9374 
9375 	if (arg_type->points_to() != NULL
9376 	    && arg_type->points_to()->array_type() != NULL
9377 	    && !arg_type->points_to()->is_slice_type())
9378 	  arg_type = arg_type->points_to();
9379 
9380 	if (arg_type->array_type() != NULL
9381 	    && arg_type->array_type()->length() != NULL)
9382           {
9383 	    this->seen_ = true;
9384 	    bool ret = Builtin_call_expression::array_len_is_constant(arg);
9385 	    this->seen_ = false;
9386 	    return ret;
9387           }
9388 
9389 	if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9390 	  {
9391 	    this->seen_ = true;
9392 	    bool ret = arg->is_constant();
9393 	    this->seen_ = false;
9394 	    return ret;
9395 	  }
9396       }
9397       break;
9398 
9399     case BUILTIN_SIZEOF:
9400     case BUILTIN_ALIGNOF:
9401       return this->one_arg() != NULL;
9402 
9403     case BUILTIN_OFFSETOF:
9404       {
9405 	Expression* arg = this->one_arg();
9406 	if (arg == NULL)
9407 	  return false;
9408 	return arg->field_reference_expression() != NULL;
9409       }
9410 
9411     case BUILTIN_COMPLEX:
9412       {
9413 	const Expression_list* args = this->args();
9414 	if (args != NULL && args->size() == 2)
9415 	  return args->front()->is_constant() && args->back()->is_constant();
9416       }
9417       break;
9418 
9419     case BUILTIN_REAL:
9420     case BUILTIN_IMAG:
9421       {
9422 	Expression* arg = this->one_arg();
9423 	return arg != NULL && arg->is_constant();
9424       }
9425 
9426     default:
9427       break;
9428     }
9429 
9430   return false;
9431 }
9432 
9433 // Return a numeric constant if possible.
9434 
9435 bool
do_numeric_constant_value(Numeric_constant * nc) const9436 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
9437 {
9438   if (this->code_ == BUILTIN_LEN
9439       || this->code_ == BUILTIN_CAP)
9440     {
9441       Expression* arg = this->one_arg();
9442       if (arg == NULL)
9443 	return false;
9444       Type* arg_type = arg->type();
9445 
9446       if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9447 	{
9448 	  std::string sval;
9449 	  if (arg->string_constant_value(&sval))
9450 	    {
9451 	      nc->set_unsigned_long(Type::lookup_integer_type("int"),
9452 				    sval.length());
9453 	      return true;
9454 	    }
9455 	}
9456 
9457       if (arg_type->points_to() != NULL
9458 	  && arg_type->points_to()->array_type() != NULL
9459 	  && !arg_type->points_to()->is_slice_type())
9460 	arg_type = arg_type->points_to();
9461 
9462       if (arg_type->array_type() != NULL
9463 	  && arg_type->array_type()->length() != NULL)
9464 	{
9465 	  if (this->seen_)
9466 	    return false;
9467 	  Expression* e = arg_type->array_type()->length();
9468 	  this->seen_ = true;
9469 	  bool r = e->numeric_constant_value(nc);
9470 	  this->seen_ = false;
9471 	  if (r)
9472 	    {
9473 	      if (!nc->set_type(Type::lookup_integer_type("int"), false,
9474 				this->location()))
9475 		r = false;
9476 	    }
9477 	  return r;
9478 	}
9479     }
9480   else if (this->code_ == BUILTIN_SIZEOF
9481 	   || this->code_ == BUILTIN_ALIGNOF)
9482     {
9483       Expression* arg = this->one_arg();
9484       if (arg == NULL)
9485 	return false;
9486       Type* arg_type = arg->type();
9487       if (arg_type->is_error())
9488 	return false;
9489       if (arg_type->is_abstract())
9490 	arg_type = arg_type->make_non_abstract_type();
9491       if (this->seen_)
9492         return false;
9493 
9494       int64_t ret;
9495       if (this->code_ == BUILTIN_SIZEOF)
9496 	{
9497           this->seen_ = true;
9498 	  bool ok = arg_type->backend_type_size(this->gogo_, &ret);
9499           this->seen_ = false;
9500 	  if (!ok)
9501 	    return false;
9502 	}
9503       else if (this->code_ == BUILTIN_ALIGNOF)
9504 	{
9505 	  bool ok;
9506           this->seen_ = true;
9507 	  if (arg->field_reference_expression() == NULL)
9508 	    ok = arg_type->backend_type_align(this->gogo_, &ret);
9509 	  else
9510 	    {
9511 	      // Calling unsafe.Alignof(s.f) returns the alignment of
9512 	      // the type of f when it is used as a field in a struct.
9513 	      ok = arg_type->backend_type_field_align(this->gogo_, &ret);
9514 	    }
9515           this->seen_ = false;
9516 	  if (!ok)
9517 	    return false;
9518 	}
9519       else
9520 	go_unreachable();
9521 
9522       mpz_t zval;
9523       set_mpz_from_int64(&zval, ret);
9524       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9525       mpz_clear(zval);
9526       return true;
9527     }
9528   else if (this->code_ == BUILTIN_OFFSETOF)
9529     {
9530       Expression* arg = this->one_arg();
9531       if (arg == NULL)
9532 	return false;
9533       Field_reference_expression* farg = arg->field_reference_expression();
9534       if (farg == NULL)
9535 	return false;
9536       if (this->seen_)
9537         return false;
9538 
9539       int64_t total_offset = 0;
9540       while (true)
9541         {
9542           Expression* struct_expr = farg->expr();
9543           Type* st = struct_expr->type();
9544           if (st->struct_type() == NULL)
9545             return false;
9546           if (st->named_type() != NULL)
9547             st->named_type()->convert(this->gogo_);
9548           if (st->is_error_type())
9549             {
9550               go_assert(saw_errors());
9551               return false;
9552             }
9553           int64_t offset;
9554           this->seen_ = true;
9555           bool ok = st->struct_type()->backend_field_offset(this->gogo_,
9556 							    farg->field_index(),
9557 							    &offset);
9558           this->seen_ = false;
9559 	  if (!ok)
9560 	    return false;
9561           total_offset += offset;
9562           if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
9563             {
9564               // Go up until we reach the original base.
9565               farg = struct_expr->field_reference_expression();
9566               continue;
9567             }
9568           break;
9569         }
9570       mpz_t zval;
9571       set_mpz_from_int64(&zval, total_offset);
9572       nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9573       mpz_clear(zval);
9574       return true;
9575     }
9576   else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
9577     {
9578       Expression* arg = this->one_arg();
9579       if (arg == NULL)
9580 	return false;
9581 
9582       Numeric_constant argnc;
9583       if (!arg->numeric_constant_value(&argnc))
9584 	return false;
9585 
9586       mpc_t val;
9587       if (!argnc.to_complex(&val))
9588 	return false;
9589 
9590       Type* type = Builtin_call_expression::real_imag_type(argnc.type());
9591       if (this->code_ == BUILTIN_REAL)
9592 	nc->set_float(type, mpc_realref(val));
9593       else
9594 	nc->set_float(type, mpc_imagref(val));
9595       mpc_clear(val);
9596       return true;
9597     }
9598   else if (this->code_ == BUILTIN_COMPLEX)
9599     {
9600       const Expression_list* args = this->args();
9601       if (args == NULL || args->size() != 2)
9602 	return false;
9603 
9604       Numeric_constant rnc;
9605       if (!args->front()->numeric_constant_value(&rnc))
9606 	return false;
9607       Numeric_constant inc;
9608       if (!args->back()->numeric_constant_value(&inc))
9609 	return false;
9610 
9611       if (rnc.type() != NULL
9612 	  && !rnc.type()->is_abstract()
9613 	  && inc.type() != NULL
9614 	  && !inc.type()->is_abstract()
9615 	  && !Type::are_identical(rnc.type(), inc.type(),
9616 				  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
9617 				  NULL))
9618 	return false;
9619 
9620       mpfr_t r;
9621       if (!rnc.to_float(&r))
9622 	return false;
9623       mpfr_t i;
9624       if (!inc.to_float(&i))
9625 	{
9626 	  mpfr_clear(r);
9627 	  return false;
9628 	}
9629 
9630       Type* arg_type = rnc.type();
9631       if (arg_type == NULL || arg_type->is_abstract())
9632 	arg_type = inc.type();
9633 
9634       mpc_t val;
9635       mpc_init2(val, mpc_precision);
9636       mpc_set_fr_fr(val, r, i, MPC_RNDNN);
9637       mpfr_clear(r);
9638       mpfr_clear(i);
9639 
9640       Type* type = Builtin_call_expression::complex_type(arg_type);
9641       nc->set_complex(type, val);
9642 
9643       mpc_clear(val);
9644 
9645       return true;
9646     }
9647 
9648   return false;
9649 }
9650 
9651 // Give an error if we are discarding the value of an expression which
9652 // should not normally be discarded.  We don't give an error for
9653 // discarding the value of an ordinary function call, but we do for
9654 // builtin functions, purely for consistency with the gc compiler.
9655 
9656 bool
do_discarding_value()9657 Builtin_call_expression::do_discarding_value()
9658 {
9659   switch (this->code_)
9660     {
9661     case BUILTIN_INVALID:
9662     default:
9663       go_unreachable();
9664 
9665     case BUILTIN_APPEND:
9666     case BUILTIN_CAP:
9667     case BUILTIN_COMPLEX:
9668     case BUILTIN_IMAG:
9669     case BUILTIN_LEN:
9670     case BUILTIN_MAKE:
9671     case BUILTIN_NEW:
9672     case BUILTIN_REAL:
9673     case BUILTIN_ALIGNOF:
9674     case BUILTIN_OFFSETOF:
9675     case BUILTIN_SIZEOF:
9676       this->unused_value_error();
9677       return false;
9678 
9679     case BUILTIN_CLOSE:
9680     case BUILTIN_COPY:
9681     case BUILTIN_DELETE:
9682     case BUILTIN_PANIC:
9683     case BUILTIN_PRINT:
9684     case BUILTIN_PRINTLN:
9685     case BUILTIN_RECOVER:
9686       return true;
9687     }
9688 }
9689 
9690 // Return the type.
9691 
9692 Type*
do_type()9693 Builtin_call_expression::do_type()
9694 {
9695   if (this->is_error_expression())
9696     return Type::make_error_type();
9697   switch (this->code_)
9698     {
9699     case BUILTIN_INVALID:
9700     default:
9701       return Type::make_error_type();
9702 
9703     case BUILTIN_NEW:
9704       {
9705 	const Expression_list* args = this->args();
9706 	if (args == NULL || args->empty())
9707 	  return Type::make_error_type();
9708 	return Type::make_pointer_type(args->front()->type());
9709       }
9710 
9711     case BUILTIN_MAKE:
9712       {
9713 	const Expression_list* args = this->args();
9714 	if (args == NULL || args->empty())
9715 	  return Type::make_error_type();
9716 	return args->front()->type();
9717       }
9718 
9719     case BUILTIN_CAP:
9720     case BUILTIN_COPY:
9721     case BUILTIN_LEN:
9722       return Type::lookup_integer_type("int");
9723 
9724     case BUILTIN_ALIGNOF:
9725     case BUILTIN_OFFSETOF:
9726     case BUILTIN_SIZEOF:
9727       return Type::lookup_integer_type("uintptr");
9728 
9729     case BUILTIN_CLOSE:
9730     case BUILTIN_DELETE:
9731     case BUILTIN_PANIC:
9732     case BUILTIN_PRINT:
9733     case BUILTIN_PRINTLN:
9734       return Type::make_void_type();
9735 
9736     case BUILTIN_RECOVER:
9737       return Type::make_empty_interface_type(Linemap::predeclared_location());
9738 
9739     case BUILTIN_APPEND:
9740       {
9741 	const Expression_list* args = this->args();
9742 	if (args == NULL || args->empty())
9743 	  return Type::make_error_type();
9744 	Type *ret = args->front()->type();
9745 	if (!ret->is_slice_type())
9746 	  return Type::make_error_type();
9747 	return ret;
9748       }
9749 
9750     case BUILTIN_REAL:
9751     case BUILTIN_IMAG:
9752       {
9753 	Expression* arg = this->one_arg();
9754 	if (arg == NULL)
9755 	  return Type::make_error_type();
9756 	Type* t = arg->type();
9757 	if (t->is_abstract())
9758 	  t = t->make_non_abstract_type();
9759 	t = Builtin_call_expression::real_imag_type(t);
9760 	if (t == NULL)
9761 	  t = Type::make_error_type();
9762 	return t;
9763       }
9764 
9765     case BUILTIN_COMPLEX:
9766       {
9767 	const Expression_list* args = this->args();
9768 	if (args == NULL || args->size() != 2)
9769 	  return Type::make_error_type();
9770 	Type* t = args->front()->type();
9771 	if (t->is_abstract())
9772 	  {
9773 	    t = args->back()->type();
9774 	    if (t->is_abstract())
9775 	      t = t->make_non_abstract_type();
9776 	  }
9777 	t = Builtin_call_expression::complex_type(t);
9778 	if (t == NULL)
9779 	  t = Type::make_error_type();
9780 	return t;
9781       }
9782     }
9783 }
9784 
9785 // Determine the type.
9786 
9787 void
do_determine_type(const Type_context * context)9788 Builtin_call_expression::do_determine_type(const Type_context* context)
9789 {
9790   if (!this->determining_types())
9791     return;
9792 
9793   this->fn()->determine_type_no_context();
9794 
9795   const Expression_list* args = this->args();
9796 
9797   bool is_print;
9798   Type* arg_type = NULL;
9799   Type* trailing_arg_types = NULL;
9800   switch (this->code_)
9801     {
9802     case BUILTIN_PRINT:
9803     case BUILTIN_PRINTLN:
9804       // Do not force a large integer constant to "int".
9805       is_print = true;
9806       break;
9807 
9808     case BUILTIN_REAL:
9809     case BUILTIN_IMAG:
9810       arg_type = Builtin_call_expression::complex_type(context->type);
9811       if (arg_type == NULL)
9812 	arg_type = Type::lookup_complex_type("complex128");
9813       is_print = false;
9814       break;
9815 
9816     case BUILTIN_COMPLEX:
9817       {
9818 	// For the complex function the type of one operand can
9819 	// determine the type of the other, as in a binary expression.
9820 	arg_type = Builtin_call_expression::real_imag_type(context->type);
9821 	if (arg_type == NULL)
9822 	  arg_type = Type::lookup_float_type("float64");
9823 	if (args != NULL && args->size() == 2)
9824 	  {
9825 	    Type* t1 = args->front()->type();
9826 	    Type* t2 = args->back()->type();
9827 	    if (!t1->is_abstract())
9828 	      arg_type = t1;
9829 	    else if (!t2->is_abstract())
9830 	      arg_type = t2;
9831 	  }
9832 	is_print = false;
9833       }
9834       break;
9835 
9836     case BUILTIN_APPEND:
9837       if (!this->is_varargs()
9838 	  && args != NULL
9839 	  && !args->empty()
9840 	  && args->front()->type()->is_slice_type())
9841 	trailing_arg_types =
9842 	  args->front()->type()->array_type()->element_type();
9843       is_print = false;
9844       break;
9845 
9846     default:
9847       is_print = false;
9848       break;
9849     }
9850 
9851   if (args != NULL)
9852     {
9853       for (Expression_list::const_iterator pa = args->begin();
9854 	   pa != args->end();
9855 	   ++pa)
9856 	{
9857 	  Type_context subcontext;
9858 	  subcontext.type = arg_type;
9859 
9860 	  if (is_print)
9861 	    {
9862 	      // We want to print large constants, we so can't just
9863 	      // use the appropriate nonabstract type.  Use uint64 for
9864 	      // an integer if we know it is nonnegative, otherwise
9865 	      // use int64 for a integer, otherwise use float64 for a
9866 	      // float or complex128 for a complex.
9867 	      Type* want_type = NULL;
9868 	      Type* atype = (*pa)->type();
9869 	      if (atype->is_abstract())
9870 		{
9871 		  if (atype->integer_type() != NULL)
9872 		    {
9873 		      Numeric_constant nc;
9874 		      if (this->numeric_constant_value(&nc))
9875 			{
9876 			  mpz_t val;
9877 			  if (nc.to_int(&val))
9878 			    {
9879 			      if (mpz_sgn(val) >= 0)
9880 				want_type = Type::lookup_integer_type("uint64");
9881 			      mpz_clear(val);
9882 			    }
9883 			}
9884 		      if (want_type == NULL)
9885 			want_type = Type::lookup_integer_type("int64");
9886 		    }
9887 		  else if (atype->float_type() != NULL)
9888 		    want_type = Type::lookup_float_type("float64");
9889 		  else if (atype->complex_type() != NULL)
9890 		    want_type = Type::lookup_complex_type("complex128");
9891 		  else if (atype->is_abstract_string_type())
9892 		    want_type = Type::lookup_string_type();
9893 		  else if (atype->is_abstract_boolean_type())
9894 		    want_type = Type::lookup_bool_type();
9895 		  else
9896 		    go_unreachable();
9897 		  subcontext.type = want_type;
9898 		}
9899 	    }
9900 
9901 	  (*pa)->determine_type(&subcontext);
9902 
9903 	  if (trailing_arg_types != NULL)
9904 	    {
9905 	      arg_type = trailing_arg_types;
9906 	      trailing_arg_types = NULL;
9907 	    }
9908 	}
9909     }
9910 }
9911 
9912 // If there is exactly one argument, return true.  Otherwise give an
9913 // error message and return false.
9914 
9915 bool
check_one_arg()9916 Builtin_call_expression::check_one_arg()
9917 {
9918   const Expression_list* args = this->args();
9919   if (args == NULL || args->size() < 1)
9920     {
9921       this->report_error(_("not enough arguments"));
9922       return false;
9923     }
9924   else if (args->size() > 1)
9925     {
9926       this->report_error(_("too many arguments"));
9927       return false;
9928     }
9929   if (args->front()->is_error_expression()
9930       || args->front()->type()->is_error())
9931     {
9932       this->set_is_error();
9933       return false;
9934     }
9935   return true;
9936 }
9937 
9938 // Check argument types for a builtin function.
9939 
9940 void
do_check_types(Gogo *)9941 Builtin_call_expression::do_check_types(Gogo*)
9942 {
9943   if (this->is_error_expression())
9944     return;
9945   switch (this->code_)
9946     {
9947     case BUILTIN_INVALID:
9948     case BUILTIN_NEW:
9949     case BUILTIN_MAKE:
9950     case BUILTIN_DELETE:
9951       return;
9952 
9953     case BUILTIN_LEN:
9954     case BUILTIN_CAP:
9955       {
9956 	// The single argument may be either a string or an array or a
9957 	// map or a channel, or a pointer to a closed array.
9958 	if (this->check_one_arg())
9959 	  {
9960 	    Type* arg_type = this->one_arg()->type();
9961 	    if (arg_type->points_to() != NULL
9962 		&& arg_type->points_to()->array_type() != NULL
9963 		&& !arg_type->points_to()->is_slice_type())
9964 	      arg_type = arg_type->points_to();
9965 	    if (this->code_ == BUILTIN_CAP)
9966 	      {
9967 		if (!arg_type->is_error()
9968 		    && arg_type->array_type() == NULL
9969 		    && arg_type->channel_type() == NULL)
9970 		  this->report_error(_("argument must be array or slice "
9971 				       "or channel"));
9972 	      }
9973 	    else
9974 	      {
9975 		if (!arg_type->is_error()
9976 		    && !arg_type->is_string_type()
9977 		    && arg_type->array_type() == NULL
9978 		    && arg_type->map_type() == NULL
9979 		    && arg_type->channel_type() == NULL)
9980 		  this->report_error(_("argument must be string or "
9981 				       "array or slice or map or channel"));
9982 	      }
9983 	  }
9984       }
9985       break;
9986 
9987     case BUILTIN_PRINT:
9988     case BUILTIN_PRINTLN:
9989       {
9990 	const Expression_list* args = this->args();
9991 	if (args == NULL)
9992 	  {
9993 	    if (this->code_ == BUILTIN_PRINT)
9994 	      go_warning_at(this->location(), 0,
9995 			 "no arguments for built-in function %<%s%>",
9996 			 (this->code_ == BUILTIN_PRINT
9997 			  ? "print"
9998 			  : "println"));
9999 	  }
10000 	else
10001 	  {
10002 	    for (Expression_list::const_iterator p = args->begin();
10003 		 p != args->end();
10004 		 ++p)
10005 	      {
10006 		Type* type = (*p)->type();
10007 		if (type->is_error()
10008 		    || type->is_string_type()
10009 		    || type->integer_type() != NULL
10010 		    || type->float_type() != NULL
10011 		    || type->complex_type() != NULL
10012 		    || type->is_boolean_type()
10013 		    || type->points_to() != NULL
10014 		    || type->interface_type() != NULL
10015 		    || type->channel_type() != NULL
10016 		    || type->map_type() != NULL
10017 		    || type->function_type() != NULL
10018 		    || type->is_slice_type())
10019 		  ;
10020 		else if ((*p)->is_type_expression())
10021 		  {
10022 		    // If this is a type expression it's going to give
10023 		    // an error anyhow, so we don't need one here.
10024 		  }
10025 		else
10026 		  this->report_error(_("unsupported argument type to "
10027 				       "builtin function"));
10028 	      }
10029 	  }
10030       }
10031       break;
10032 
10033     case BUILTIN_CLOSE:
10034       if (this->check_one_arg())
10035 	{
10036 	  if (this->one_arg()->type()->channel_type() == NULL)
10037 	    this->report_error(_("argument must be channel"));
10038 	  else if (!this->one_arg()->type()->channel_type()->may_send())
10039 	    this->report_error(_("cannot close receive-only channel"));
10040 	}
10041       break;
10042 
10043     case BUILTIN_PANIC:
10044     case BUILTIN_SIZEOF:
10045     case BUILTIN_ALIGNOF:
10046       this->check_one_arg();
10047       break;
10048 
10049     case BUILTIN_RECOVER:
10050       if (this->args() != NULL
10051 	  && !this->args()->empty()
10052 	  && !this->recover_arg_is_set_)
10053 	this->report_error(_("too many arguments"));
10054       break;
10055 
10056     case BUILTIN_OFFSETOF:
10057       if (this->check_one_arg())
10058 	{
10059 	  Expression* arg = this->one_arg();
10060 	  if (arg->field_reference_expression() == NULL)
10061 	    this->report_error(_("argument must be a field reference"));
10062 	}
10063       break;
10064 
10065     case BUILTIN_COPY:
10066       {
10067 	const Expression_list* args = this->args();
10068 	if (args == NULL || args->size() < 2)
10069 	  {
10070 	    this->report_error(_("not enough arguments"));
10071 	    break;
10072 	  }
10073 	else if (args->size() > 2)
10074 	  {
10075 	    this->report_error(_("too many arguments"));
10076 	    break;
10077 	  }
10078 	Type* arg1_type = args->front()->type();
10079 	Type* arg2_type = args->back()->type();
10080 	if (arg1_type->is_error() || arg2_type->is_error())
10081 	  {
10082 	    this->set_is_error();
10083 	    break;
10084 	  }
10085 
10086 	Type* e1;
10087 	if (arg1_type->is_slice_type())
10088 	  e1 = arg1_type->array_type()->element_type();
10089 	else
10090 	  {
10091 	    this->report_error(_("left argument must be a slice"));
10092 	    break;
10093 	  }
10094 
10095 	if (arg2_type->is_slice_type())
10096 	  {
10097 	    Type* e2 = arg2_type->array_type()->element_type();
10098 	    if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
10099 	      this->report_error(_("element types must be the same"));
10100 	  }
10101 	else if (arg2_type->is_string_type())
10102 	  {
10103 	    if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
10104 	      this->report_error(_("first argument must be []byte"));
10105 	  }
10106 	else
10107 	    this->report_error(_("second argument must be slice or string"));
10108       }
10109       break;
10110 
10111     case BUILTIN_APPEND:
10112       {
10113 	const Expression_list* args = this->args();
10114 	if (args == NULL || args->empty())
10115 	  {
10116 	    this->report_error(_("not enough arguments"));
10117 	    break;
10118 	  }
10119 
10120 	Type* slice_type = args->front()->type();
10121 	if (!slice_type->is_slice_type())
10122 	  {
10123 	    if (slice_type->is_error_type())
10124 	      break;
10125 	    if (slice_type->is_nil_type())
10126 	      go_error_at(args->front()->location(), "use of untyped nil");
10127 	    else
10128 	      go_error_at(args->front()->location(),
10129 			  "argument 1 must be a slice");
10130 	    this->set_is_error();
10131 	    break;
10132 	  }
10133 
10134 	Type* element_type = slice_type->array_type()->element_type();
10135 	if (!element_type->in_heap())
10136 	  go_error_at(args->front()->location(),
10137 		      "cannot append to slice of go:notinheap type");
10138 	if (this->is_varargs())
10139 	  {
10140 	    if (!args->back()->type()->is_slice_type()
10141 		&& !args->back()->type()->is_string_type())
10142 	      {
10143 		go_error_at(args->back()->location(),
10144 			    "invalid use of %<...%> with non-slice/non-string");
10145 		this->set_is_error();
10146 		break;
10147 	      }
10148 
10149 	    if (args->size() < 2)
10150 	      {
10151 		this->report_error(_("not enough arguments"));
10152 		break;
10153 	      }
10154 	    if (args->size() > 2)
10155 	      {
10156 		this->report_error(_("too many arguments"));
10157 		break;
10158 	      }
10159 
10160 	    if (args->back()->type()->is_string_type()
10161 		&& element_type->integer_type() != NULL
10162 		&& element_type->integer_type()->is_byte())
10163 	      {
10164 		// Permit append(s1, s2...) when s1 is a slice of
10165 		// bytes and s2 is a string type.
10166 	      }
10167 	    else
10168 	      {
10169 		// We have to test for assignment compatibility to a
10170 		// slice of the element type, which is not necessarily
10171 		// the same as the type of the first argument: the
10172 		// first argument might have a named type.
10173 		Type* check_type = Type::make_array_type(element_type, NULL);
10174 		std::string reason;
10175 		if (!Type::are_assignable(check_type, args->back()->type(),
10176 					  &reason))
10177 		  {
10178 		    if (reason.empty())
10179 		      go_error_at(args->back()->location(),
10180 				  "argument 2 has invalid type");
10181 		    else
10182 		      go_error_at(args->back()->location(),
10183 				  "argument 2 has invalid type (%s)",
10184 				  reason.c_str());
10185 		    this->set_is_error();
10186 		    break;
10187 		  }
10188 	      }
10189 	  }
10190 	else
10191 	  {
10192 	    Expression_list::const_iterator pa = args->begin();
10193 	    int i = 2;
10194 	    for (++pa; pa != args->end(); ++pa, ++i)
10195 	      {
10196 		std::string reason;
10197 		if (!Type::are_assignable(element_type, (*pa)->type(),
10198 					  &reason))
10199 		  {
10200 		    if (reason.empty())
10201 		      go_error_at((*pa)->location(),
10202 				  "argument %d has incompatible type", i);
10203 		    else
10204 		      go_error_at((*pa)->location(),
10205 				  "argument %d has incompatible type (%s)",
10206 				  i, reason.c_str());
10207 		    this->set_is_error();
10208 		  }
10209 	      }
10210 	  }
10211       }
10212       break;
10213 
10214     case BUILTIN_REAL:
10215     case BUILTIN_IMAG:
10216       if (this->check_one_arg())
10217 	{
10218 	  if (this->one_arg()->type()->complex_type() == NULL)
10219 	    this->report_error(_("argument must have complex type"));
10220 	}
10221       break;
10222 
10223     case BUILTIN_COMPLEX:
10224       {
10225 	const Expression_list* args = this->args();
10226 	if (args == NULL || args->size() < 2)
10227 	  this->report_error(_("not enough arguments"));
10228 	else if (args->size() > 2)
10229 	  this->report_error(_("too many arguments"));
10230 	else if (args->front()->is_error_expression()
10231 		 || args->front()->type()->is_error()
10232 		 || args->back()->is_error_expression()
10233 		 || args->back()->type()->is_error())
10234 	  this->set_is_error();
10235 	else if (!Type::are_identical(args->front()->type(),
10236 				      args->back()->type(),
10237 				      Type::COMPARE_TAGS, NULL))
10238 	  this->report_error(_("complex arguments must have identical types"));
10239 	else if (args->front()->type()->float_type() == NULL)
10240 	  this->report_error(_("complex arguments must have "
10241 			       "floating-point type"));
10242       }
10243       break;
10244 
10245     default:
10246       go_unreachable();
10247     }
10248 }
10249 
10250 Expression*
do_copy()10251 Builtin_call_expression::do_copy()
10252 {
10253   Call_expression* bce =
10254     new Builtin_call_expression(this->gogo_, this->fn()->copy(),
10255 				(this->args() == NULL
10256 				 ? NULL
10257 				 : this->args()->copy()),
10258 				this->is_varargs(),
10259 				this->location());
10260 
10261   if (this->varargs_are_lowered())
10262     bce->set_varargs_are_lowered();
10263   if (this->is_deferred())
10264     bce->set_is_deferred();
10265   if (this->is_concurrent())
10266     bce->set_is_concurrent();
10267   return bce;
10268 }
10269 
10270 // Return the backend representation for a builtin function.
10271 
10272 Bexpression*
do_get_backend(Translate_context * context)10273 Builtin_call_expression::do_get_backend(Translate_context* context)
10274 {
10275   Gogo* gogo = context->gogo();
10276   Location location = this->location();
10277 
10278   if (this->is_erroneous_call())
10279     {
10280       go_assert(saw_errors());
10281       return gogo->backend()->error_expression();
10282     }
10283 
10284   switch (this->code_)
10285     {
10286     case BUILTIN_INVALID:
10287     case BUILTIN_NEW:
10288     case BUILTIN_MAKE:
10289       go_unreachable();
10290 
10291     case BUILTIN_LEN:
10292     case BUILTIN_CAP:
10293       {
10294 	const Expression_list* args = this->args();
10295 	go_assert(args != NULL && args->size() == 1);
10296 	Expression* arg = args->front();
10297 	Type* arg_type = arg->type();
10298 
10299 	if (this->seen_)
10300 	  {
10301 	    go_assert(saw_errors());
10302 	    return context->backend()->error_expression();
10303 	  }
10304 	this->seen_ = true;
10305 	this->seen_ = false;
10306 	if (arg_type->points_to() != NULL)
10307 	  {
10308 	    arg_type = arg_type->points_to();
10309 	    go_assert(arg_type->array_type() != NULL
10310 		       && !arg_type->is_slice_type());
10311             arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
10312                                                location);
10313 	  }
10314 
10315 	Type* int_type = Type::lookup_integer_type("int");
10316         Expression* val;
10317 	if (this->code_ == BUILTIN_LEN)
10318 	  {
10319 	    if (arg_type->is_string_type())
10320 	      val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
10321 						 location);
10322 	    else if (arg_type->array_type() != NULL)
10323 	      {
10324 		if (this->seen_)
10325 		  {
10326 		    go_assert(saw_errors());
10327 		    return context->backend()->error_expression();
10328 		  }
10329 		this->seen_ = true;
10330 	        val = arg_type->array_type()->get_length(gogo, arg);
10331 		this->seen_ = false;
10332 	      }
10333 	    else if (arg_type->map_type() != NULL
10334 		     || arg_type->channel_type() != NULL)
10335 	      {
10336 		// The first field is the length.  If the pointer is
10337 		// nil, the length is zero.
10338 		Type* pint_type = Type::make_pointer_type(int_type);
10339 		arg = Expression::make_unsafe_cast(pint_type, arg, location);
10340 		Expression* nil = Expression::make_nil(location);
10341 		nil = Expression::make_cast(pint_type, nil, location);
10342 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10343 							  arg, nil, location);
10344 		Expression* zero = Expression::make_integer_ul(0, int_type,
10345 							       location);
10346                 Expression* indir =
10347                     Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
10348                                                  location);
10349 		val = Expression::make_conditional(cmp, zero, indir, location);
10350 	      }
10351 	    else
10352 	      go_unreachable();
10353 	  }
10354 	else
10355 	  {
10356 	    if (arg_type->array_type() != NULL)
10357 	      {
10358 		if (this->seen_)
10359 		  {
10360 		    go_assert(saw_errors());
10361 		    return context->backend()->error_expression();
10362 		  }
10363 		this->seen_ = true;
10364                 val = arg_type->array_type()->get_capacity(gogo, arg);
10365 		this->seen_ = false;
10366 	      }
10367 	    else if (arg_type->channel_type() != NULL)
10368 	      {
10369 		// The second field is the capacity.  If the pointer
10370 		// is nil, the capacity is zero.
10371 		Type* uintptr_type = Type::lookup_integer_type("uintptr");
10372 		Type* pint_type = Type::make_pointer_type(int_type);
10373 		Expression* parg = Expression::make_unsafe_cast(uintptr_type,
10374 								arg,
10375 								location);
10376 		int off = int_type->integer_type()->bits() / 8;
10377 		Expression* eoff = Expression::make_integer_ul(off,
10378 							       uintptr_type,
10379 							       location);
10380 		parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
10381 					       location);
10382 		parg = Expression::make_unsafe_cast(pint_type, parg, location);
10383 		Expression* nil = Expression::make_nil(location);
10384 		nil = Expression::make_cast(pint_type, nil, location);
10385 		Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10386 							  arg, nil, location);
10387 		Expression* zero = Expression::make_integer_ul(0, int_type,
10388 							       location);
10389                 Expression* indir =
10390                     Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
10391                                                  location);
10392 		val = Expression::make_conditional(cmp, zero, indir, location);
10393 	      }
10394 	    else
10395 	      go_unreachable();
10396 	  }
10397 
10398 	return Expression::make_cast(int_type, val,
10399 				     location)->get_backend(context);
10400       }
10401 
10402     case BUILTIN_PRINT:
10403     case BUILTIN_PRINTLN:
10404       {
10405 	const bool is_ln = this->code_ == BUILTIN_PRINTLN;
10406 
10407 	Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
10408 						     location, 0);
10409 
10410 	const Expression_list* call_args = this->args();
10411 	if (call_args != NULL)
10412 	  {
10413 	    for (Expression_list::const_iterator p = call_args->begin();
10414 		 p != call_args->end();
10415 		 ++p)
10416 	      {
10417 		if (is_ln && p != call_args->begin())
10418 		  {
10419                     Expression* print_space =
10420 		      Runtime::make_call(Runtime::PRINTSP, location, 0);
10421 
10422                     print_stmts =
10423                         Expression::make_compound(print_stmts, print_space,
10424                                                   location);
10425 		  }
10426 
10427                 Expression* arg = *p;
10428 		Type* type = arg->type();
10429                 Runtime::Function code;
10430 		if (type->is_string_type())
10431                   code = Runtime::PRINTSTRING;
10432 		else if (type->integer_type() != NULL
10433 			 && type->integer_type()->is_unsigned())
10434 		  {
10435 		    Type* itype = Type::lookup_integer_type("uint64");
10436 		    arg = Expression::make_cast(itype, arg, location);
10437                     if (gogo->compiling_runtime()
10438                         && type->named_type() != NULL
10439                         && gogo->unpack_hidden_name(type->named_type()->name())
10440                            == "hex")
10441                       code = Runtime::PRINTHEX;
10442                     else
10443                       code = Runtime::PRINTUINT;
10444 		  }
10445 		else if (type->integer_type() != NULL)
10446 		  {
10447 		    Type* itype = Type::lookup_integer_type("int64");
10448 		    arg = Expression::make_cast(itype, arg, location);
10449                     code = Runtime::PRINTINT;
10450 		  }
10451 		else if (type->float_type() != NULL)
10452 		  {
10453                     Type* dtype = Type::lookup_float_type("float64");
10454                     arg = Expression::make_cast(dtype, arg, location);
10455                     code = Runtime::PRINTFLOAT;
10456 		  }
10457 		else if (type->complex_type() != NULL)
10458 		  {
10459                     Type* ctype = Type::lookup_complex_type("complex128");
10460                     arg = Expression::make_cast(ctype, arg, location);
10461                     code = Runtime::PRINTCOMPLEX;
10462 		  }
10463 		else if (type->is_boolean_type())
10464                   code = Runtime::PRINTBOOL;
10465 		else if (type->points_to() != NULL
10466 			 || type->channel_type() != NULL
10467 			 || type->map_type() != NULL
10468 			 || type->function_type() != NULL)
10469 		  {
10470                     arg = Expression::make_cast(type, arg, location);
10471                     code = Runtime::PRINTPOINTER;
10472 		  }
10473 		else if (type->interface_type() != NULL)
10474 		  {
10475 		    if (type->interface_type()->is_empty())
10476                       code = Runtime::PRINTEFACE;
10477 		    else
10478                       code = Runtime::PRINTIFACE;
10479 		  }
10480 		else if (type->is_slice_type())
10481                   code = Runtime::PRINTSLICE;
10482 		else
10483 		  {
10484 		    go_assert(saw_errors());
10485 		    return context->backend()->error_expression();
10486 		  }
10487 
10488                 Expression* call = Runtime::make_call(code, location, 1, arg);
10489 		print_stmts = Expression::make_compound(print_stmts, call,
10490 							location);
10491 	      }
10492 	  }
10493 
10494 	if (is_ln)
10495 	  {
10496             Expression* print_nl =
10497                 Runtime::make_call(Runtime::PRINTNL, location, 0);
10498 	    print_stmts = Expression::make_compound(print_stmts, print_nl,
10499 						    location);
10500 	  }
10501 
10502 	Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
10503 						location, 0);
10504 	print_stmts = Expression::make_compound(print_stmts, unlock, location);
10505 
10506         return print_stmts->get_backend(context);
10507       }
10508 
10509     case BUILTIN_PANIC:
10510       {
10511 	const Expression_list* args = this->args();
10512 	go_assert(args != NULL && args->size() == 1);
10513 	Expression* arg = args->front();
10514 	Type *empty =
10515 	  Type::make_empty_interface_type(Linemap::predeclared_location());
10516         arg = Expression::convert_for_assignment(gogo, empty, arg, location);
10517 
10518         Expression* panic =
10519             Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
10520         return panic->get_backend(context);
10521       }
10522 
10523     case BUILTIN_RECOVER:
10524       {
10525 	// The argument is set when building recover thunks.  It's a
10526 	// boolean value which is true if we can recover a value now.
10527 	const Expression_list* args = this->args();
10528 	go_assert(args != NULL && args->size() == 1);
10529 	Expression* arg = args->front();
10530 	Type *empty =
10531 	  Type::make_empty_interface_type(Linemap::predeclared_location());
10532 
10533 	Expression* nil = Expression::make_nil(location);
10534         nil = Expression::make_interface_value(empty, nil, nil, location);
10535 
10536 	// We need to handle a deferred call to recover specially,
10537 	// because it changes whether it can recover a panic or not.
10538 	// See test7 in test/recover1.go.
10539         Expression* recover = Runtime::make_call((this->is_deferred()
10540                                                   ? Runtime::DEFERREDRECOVER
10541                                                   : Runtime::GORECOVER),
10542                                                  location, 0);
10543         Expression* cond =
10544             Expression::make_conditional(arg, recover, nil, location);
10545         return cond->get_backend(context);
10546       }
10547 
10548     case BUILTIN_CLOSE:
10549       {
10550 	const Expression_list* args = this->args();
10551 	go_assert(args != NULL && args->size() == 1);
10552 	Expression* arg = args->front();
10553         Expression* close = Runtime::make_call(Runtime::CLOSE, location,
10554 					       1, arg);
10555         return close->get_backend(context);
10556       }
10557 
10558     case BUILTIN_SIZEOF:
10559     case BUILTIN_OFFSETOF:
10560     case BUILTIN_ALIGNOF:
10561       {
10562 	Numeric_constant nc;
10563 	unsigned long val;
10564 	if (!this->numeric_constant_value(&nc)
10565 	    || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
10566 	  {
10567 	    go_assert(saw_errors());
10568 	    return context->backend()->error_expression();
10569 	  }
10570 	Type* uintptr_type = Type::lookup_integer_type("uintptr");
10571         mpz_t ival;
10572         nc.get_int(&ival);
10573         Expression* int_cst =
10574             Expression::make_integer_z(&ival, uintptr_type, location);
10575         mpz_clear(ival);
10576         return int_cst->get_backend(context);
10577       }
10578 
10579     case BUILTIN_COPY:
10580       // Handled in Builtin_call_expression::do_flatten.
10581       go_unreachable();
10582 
10583     case BUILTIN_APPEND:
10584       // Handled in Builtin_call_expression::flatten_append.
10585       go_unreachable();
10586 
10587     case BUILTIN_REAL:
10588     case BUILTIN_IMAG:
10589       {
10590 	const Expression_list* args = this->args();
10591 	go_assert(args != NULL && args->size() == 1);
10592 
10593         Bexpression* ret;
10594         Bexpression* bcomplex = args->front()->get_backend(context);
10595         if (this->code_ == BUILTIN_REAL)
10596           ret = gogo->backend()->real_part_expression(bcomplex, location);
10597         else
10598           ret = gogo->backend()->imag_part_expression(bcomplex, location);
10599         return ret;
10600       }
10601 
10602     case BUILTIN_COMPLEX:
10603       {
10604 	const Expression_list* args = this->args();
10605 	go_assert(args != NULL && args->size() == 2);
10606 	Bexpression* breal = args->front()->get_backend(context);
10607 	Bexpression* bimag = args->back()->get_backend(context);
10608 	return gogo->backend()->complex_expression(breal, bimag, location);
10609       }
10610 
10611     default:
10612       go_unreachable();
10613     }
10614 }
10615 
10616 // We have to support exporting a builtin call expression, because
10617 // code can set a constant to the result of a builtin expression.
10618 
10619 void
do_export(Export_function_body * efb) const10620 Builtin_call_expression::do_export(Export_function_body* efb) const
10621 {
10622   Numeric_constant nc;
10623   if (this->numeric_constant_value(&nc))
10624     {
10625       if (nc.is_int())
10626 	{
10627 	  mpz_t val;
10628 	  nc.get_int(&val);
10629 	  Integer_expression::export_integer(efb, val);
10630 	  mpz_clear(val);
10631 	}
10632       else if (nc.is_float())
10633 	{
10634 	  mpfr_t fval;
10635 	  nc.get_float(&fval);
10636 	  Float_expression::export_float(efb, fval);
10637 	  mpfr_clear(fval);
10638 	}
10639       else if (nc.is_complex())
10640 	{
10641 	  mpc_t cval;
10642 	  nc.get_complex(&cval);
10643 	  Complex_expression::export_complex(efb, cval);
10644 	  mpc_clear(cval);
10645 	}
10646       else
10647 	go_unreachable();
10648 
10649       // A trailing space lets us reliably identify the end of the number.
10650       efb->write_c_string(" ");
10651     }
10652   else
10653     {
10654       const char *s = NULL;
10655       switch (this->code_)
10656 	{
10657 	default:
10658 	  go_unreachable();
10659 	case BUILTIN_APPEND:
10660 	  s = "append";
10661 	  break;
10662 	case BUILTIN_COPY:
10663 	  s = "copy";
10664 	  break;
10665 	case BUILTIN_LEN:
10666 	  s = "len";
10667 	  break;
10668 	case BUILTIN_CAP:
10669 	  s = "cap";
10670 	  break;
10671 	case BUILTIN_DELETE:
10672 	  s = "delete";
10673 	  break;
10674 	case BUILTIN_PRINT:
10675 	  s = "print";
10676 	  break;
10677 	case BUILTIN_PRINTLN:
10678 	  s = "println";
10679 	  break;
10680 	case BUILTIN_PANIC:
10681 	  s = "panic";
10682 	  break;
10683 	case BUILTIN_RECOVER:
10684 	  s = "recover";
10685 	  break;
10686 	case BUILTIN_CLOSE:
10687 	  s = "close";
10688 	  break;
10689 	case BUILTIN_REAL:
10690 	  s = "real";
10691 	  break;
10692 	case BUILTIN_IMAG:
10693 	  s = "imag";
10694 	  break;
10695 	case BUILTIN_COMPLEX:
10696 	  s = "complex";
10697 	  break;
10698 	}
10699       efb->write_c_string(s);
10700       this->export_arguments(efb);
10701     }
10702 }
10703 
10704 // Class Call_expression.
10705 
10706 // A Go function can be viewed in a couple of different ways.  The
10707 // code of a Go function becomes a backend function with parameters
10708 // whose types are simply the backend representation of the Go types.
10709 // If there are multiple results, they are returned as a backend
10710 // struct.
10711 
10712 // However, when Go code refers to a function other than simply
10713 // calling it, the backend type of that function is actually a struct.
10714 // The first field of the struct points to the Go function code
10715 // (sometimes a wrapper as described below).  The remaining fields
10716 // hold addresses of closed-over variables.  This struct is called a
10717 // closure.
10718 
10719 // There are a few cases to consider.
10720 
10721 // A direct function call of a known function in package scope.  In
10722 // this case there are no closed-over variables, and we know the name
10723 // of the function code.  We can simply produce a backend call to the
10724 // function directly, and not worry about the closure.
10725 
10726 // A direct function call of a known function literal.  In this case
10727 // we know the function code and we know the closure.  We generate the
10728 // function code such that it expects an additional final argument of
10729 // the closure type.  We pass the closure as the last argument, after
10730 // the other arguments.
10731 
10732 // An indirect function call.  In this case we have a closure.  We
10733 // load the pointer to the function code from the first field of the
10734 // closure.  We pass the address of the closure as the last argument.
10735 
10736 // A call to a method of an interface.  Type methods are always at
10737 // package scope, so we call the function directly, and don't worry
10738 // about the closure.
10739 
10740 // This means that for a function at package scope we have two cases.
10741 // One is the direct call, which has no closure.  The other is the
10742 // indirect call, which does have a closure.  We can't simply ignore
10743 // the closure, even though it is the last argument, because that will
10744 // fail on targets where the function pops its arguments.  So when
10745 // generating a closure for a package-scope function we set the
10746 // function code pointer in the closure to point to a wrapper
10747 // function.  This wrapper function accepts a final argument that
10748 // points to the closure, ignores it, and calls the real function as a
10749 // direct function call.  This wrapper will normally be efficient, and
10750 // can often simply be a tail call to the real function.
10751 
10752 // We don't use GCC's static chain pointer because 1) we don't need
10753 // it; 2) GCC only permits using a static chain to call a known
10754 // function, so we can't use it for an indirect call anyhow.  Since we
10755 // can't use it for an indirect call, we may as well not worry about
10756 // using it for a direct call either.
10757 
10758 // We pass the closure last rather than first because it means that
10759 // the function wrapper we put into a closure for a package-scope
10760 // function can normally just be a tail call to the real function.
10761 
10762 // For method expressions we generate a wrapper that loads the
10763 // receiver from the closure and then calls the method.  This
10764 // unfortunately forces reshuffling the arguments, since there is a
10765 // new first argument, but we can't avoid reshuffling either for
10766 // method expressions or for indirect calls of package-scope
10767 // functions, and since the latter are more common we reshuffle for
10768 // method expressions.
10769 
10770 // Note that the Go code retains the Go types.  The extra final
10771 // argument only appears when we convert to the backend
10772 // representation.
10773 
10774 // Traversal.
10775 
10776 int
do_traverse(Traverse * traverse)10777 Call_expression::do_traverse(Traverse* traverse)
10778 {
10779   // If we are calling a function in a different package that returns
10780   // an unnamed type, this may be the only chance we get to traverse
10781   // that type.  We don't traverse this->type_ because it may be a
10782   // Call_multiple_result_type that will just lead back here.
10783   if (this->type_ != NULL && !this->type_->is_error_type())
10784     {
10785       Function_type *fntype = this->get_function_type();
10786       if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
10787 	return TRAVERSE_EXIT;
10788     }
10789   if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
10790     return TRAVERSE_EXIT;
10791   if (this->args_ != NULL)
10792     {
10793       if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
10794 	return TRAVERSE_EXIT;
10795     }
10796   return TRAVERSE_CONTINUE;
10797 }
10798 
10799 // Lower a call statement.
10800 
10801 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)10802 Call_expression::do_lower(Gogo* gogo, Named_object* function,
10803 			  Statement_inserter* inserter, int)
10804 {
10805   Location loc = this->location();
10806 
10807   // A type cast can look like a function call.
10808   if (this->fn_->is_type_expression()
10809       && this->args_ != NULL
10810       && this->args_->size() == 1)
10811     return Expression::make_cast(this->fn_->type(), this->args_->front(),
10812 				 loc);
10813 
10814   // Because do_type will return an error type and thus prevent future
10815   // errors, check for that case now to ensure that the error gets
10816   // reported.
10817   Function_type* fntype = this->get_function_type();
10818   if (fntype == NULL)
10819     {
10820       if (!this->fn_->type()->is_error())
10821 	this->report_error(_("expected function"));
10822       this->set_is_error();
10823       return this;
10824     }
10825 
10826   // Handle an argument which is a call to a function which returns
10827   // multiple results.
10828   if (this->args_ != NULL
10829       && this->args_->size() == 1
10830       && this->args_->front()->call_expression() != NULL)
10831     {
10832       size_t rc = this->args_->front()->call_expression()->result_count();
10833       if (rc > 1
10834 	  && ((fntype->parameters() != NULL
10835                && (fntype->parameters()->size() == rc
10836                    || (fntype->is_varargs()
10837                        && fntype->parameters()->size() - 1 <= rc)))
10838               || fntype->is_builtin()))
10839 	{
10840 	  Call_expression* call = this->args_->front()->call_expression();
10841 	  call->set_is_multi_value_arg();
10842 	  if (this->is_varargs_)
10843 	    {
10844 	      // It is not clear which result of a multiple result call
10845 	      // the ellipsis operator should be applied to.  If we unpack the
10846 	      // the call into its individual results here, the ellipsis will be
10847 	      // applied to the last result.
10848 	      go_error_at(call->location(),
10849 			  _("multiple-value argument in single-value context"));
10850 	      return Expression::make_error(call->location());
10851 	    }
10852 
10853 	  Expression_list* args = new Expression_list;
10854 	  for (size_t i = 0; i < rc; ++i)
10855 	    args->push_back(Expression::make_call_result(call, i));
10856 	  // We can't return a new call expression here, because this
10857 	  // one may be referenced by Call_result expressions.  We
10858 	  // also can't delete the old arguments, because we may still
10859 	  // traverse them somewhere up the call stack.  FIXME.
10860 	  this->args_ = args;
10861 	}
10862     }
10863 
10864   // Recognize a call to a builtin function.
10865   if (fntype->is_builtin())
10866     {
10867       Builtin_call_expression* bce =
10868 	new Builtin_call_expression(gogo, this->fn_, this->args_,
10869 				    this->is_varargs_, loc);
10870       if (this->is_deferred_)
10871 	bce->set_is_deferred();
10872       if (this->is_concurrent_)
10873 	bce->set_is_concurrent();
10874       return bce;
10875     }
10876 
10877   // If this call returns multiple results, create a temporary
10878   // variable to hold them.
10879   if (this->result_count() > 1 && this->call_temp_ == NULL)
10880     {
10881       Struct_field_list* sfl = new Struct_field_list();
10882       const Typed_identifier_list* results = fntype->results();
10883 
10884       int i = 0;
10885       char buf[20];
10886       for (Typed_identifier_list::const_iterator p = results->begin();
10887            p != results->end();
10888            ++p, ++i)
10889         {
10890           snprintf(buf, sizeof buf, "res%d", i);
10891           sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
10892         }
10893 
10894       Struct_type* st = Type::make_struct_type(sfl, loc);
10895       st->set_is_struct_incomparable();
10896       this->call_temp_ = Statement::make_temporary(st, NULL, loc);
10897       inserter->insert(this->call_temp_);
10898     }
10899 
10900   // Handle a call to a varargs function by packaging up the extra
10901   // parameters.
10902   if (fntype->is_varargs())
10903     {
10904       const Typed_identifier_list* parameters = fntype->parameters();
10905       go_assert(parameters != NULL && !parameters->empty());
10906       Type* varargs_type = parameters->back().type();
10907       this->lower_varargs(gogo, function, inserter, varargs_type,
10908 			  parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
10909     }
10910 
10911   // If this is call to a method, call the method directly passing the
10912   // object as the first parameter.
10913   Bound_method_expression* bme = this->fn_->bound_method_expression();
10914   if (bme != NULL)
10915     {
10916       Named_object* methodfn = bme->function();
10917       Function_type* mft = (methodfn->is_function()
10918                             ? methodfn->func_value()->type()
10919                             : methodfn->func_declaration_value()->type());
10920       Expression* first_arg = bme->first_argument();
10921 
10922       // We always pass a pointer when calling a method, except for
10923       // direct interface types when calling a value method.
10924       if (!first_arg->type()->is_error()
10925           && !first_arg->type()->is_direct_iface_type())
10926 	{
10927 	  first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
10928 	  // We may need to create a temporary variable so that we can
10929 	  // take the address.  We can't do that here because it will
10930 	  // mess up the order of evaluation.
10931 	  Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
10932 	  ue->set_create_temp();
10933 	}
10934       else if (mft->receiver()->type()->points_to() == NULL
10935                && first_arg->type()->points_to() != NULL
10936                && first_arg->type()->points_to()->is_direct_iface_type())
10937         first_arg = Expression::make_dereference(first_arg,
10938                                                  Expression::NIL_CHECK_DEFAULT,
10939                                                  loc);
10940 
10941       // If we are calling a method which was inherited from an
10942       // embedded struct, and the method did not get a stub, then the
10943       // first type may be wrong.
10944       Type* fatype = bme->first_argument_type();
10945       if (fatype != NULL)
10946 	{
10947 	  if (fatype->points_to() == NULL)
10948 	    fatype = Type::make_pointer_type(fatype);
10949 	  first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
10950 	}
10951 
10952       Expression_list* new_args = new Expression_list();
10953       new_args->push_back(first_arg);
10954       if (this->args_ != NULL)
10955 	{
10956 	  for (Expression_list::const_iterator p = this->args_->begin();
10957 	       p != this->args_->end();
10958 	       ++p)
10959 	    new_args->push_back(*p);
10960 	}
10961 
10962       // We have to change in place because this structure may be
10963       // referenced by Call_result_expressions.  We can't delete the
10964       // old arguments, because we may be traversing them up in some
10965       // caller.  FIXME.
10966       this->args_ = new_args;
10967       this->fn_ = Expression::make_func_reference(methodfn, NULL,
10968 						  bme->location());
10969     }
10970 
10971   // If this is a call to an imported function for which we have an
10972   // inlinable function body, add it to the list of functions to give
10973   // to the backend as inlining opportunities.
10974   Func_expression* fe = this->fn_->func_expression();
10975   if (fe != NULL
10976       && fe->named_object()->is_function_declaration()
10977       && fe->named_object()->func_declaration_value()->has_imported_body())
10978     gogo->add_imported_inlinable_function(fe->named_object());
10979 
10980   return this;
10981 }
10982 
10983 // Lower a call to a varargs function.  FUNCTION is the function in
10984 // which the call occurs--it's not the function we are calling.
10985 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
10986 // PARAM_COUNT is the number of parameters of the function we are
10987 // calling; the last of these parameters will be the varargs
10988 // parameter.
10989 
10990 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count,Slice_storage_escape_disp escape_disp)10991 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
10992 			       Statement_inserter* inserter,
10993 			       Type* varargs_type, size_t param_count,
10994                                Slice_storage_escape_disp escape_disp)
10995 {
10996   if (this->varargs_are_lowered_)
10997     return;
10998 
10999   Location loc = this->location();
11000 
11001   go_assert(param_count > 0);
11002   go_assert(varargs_type->is_slice_type());
11003 
11004   size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
11005   if (arg_count < param_count - 1)
11006     {
11007       // Not enough arguments; will be caught in check_types.
11008       return;
11009     }
11010 
11011   Expression_list* old_args = this->args_;
11012   Expression_list* new_args = new Expression_list();
11013   bool push_empty_arg = false;
11014   if (old_args == NULL || old_args->empty())
11015     {
11016       go_assert(param_count == 1);
11017       push_empty_arg = true;
11018     }
11019   else
11020     {
11021       Expression_list::const_iterator pa;
11022       int i = 1;
11023       for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
11024 	{
11025 	  if (static_cast<size_t>(i) == param_count)
11026 	    break;
11027 	  new_args->push_back(*pa);
11028 	}
11029 
11030       // We have reached the varargs parameter.
11031 
11032       bool issued_error = false;
11033       if (pa == old_args->end())
11034 	push_empty_arg = true;
11035       else if (pa + 1 == old_args->end() && this->is_varargs_)
11036 	new_args->push_back(*pa);
11037       else if (this->is_varargs_)
11038 	{
11039 	  if ((*pa)->type()->is_slice_type())
11040 	    this->report_error(_("too many arguments"));
11041 	  else
11042 	    {
11043 	      go_error_at(this->location(),
11044 			  _("invalid use of %<...%> with non-slice"));
11045 	      this->set_is_error();
11046 	    }
11047 	  return;
11048 	}
11049       else
11050 	{
11051 	  Type* element_type = varargs_type->array_type()->element_type();
11052 	  Expression_list* vals = new Expression_list;
11053 	  for (; pa != old_args->end(); ++pa, ++i)
11054 	    {
11055 	      // Check types here so that we get a better message.
11056 	      Type* patype = (*pa)->type();
11057 	      Location paloc = (*pa)->location();
11058 	      if (!this->check_argument_type(i, element_type, patype,
11059 					     paloc, issued_error))
11060 		continue;
11061 	      vals->push_back(*pa);
11062 	    }
11063 	  Slice_construction_expression* sce =
11064 	    Expression::make_slice_composite_literal(varargs_type, vals, loc);
11065 	  if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
11066 	      sce->set_storage_does_not_escape();
11067           Expression* val = sce;
11068 	  gogo->lower_expression(function, inserter, &val);
11069 	  new_args->push_back(val);
11070 	}
11071     }
11072 
11073   if (push_empty_arg)
11074     new_args->push_back(Expression::make_nil(loc));
11075 
11076   // We can't return a new call expression here, because this one may
11077   // be referenced by Call_result expressions.  FIXME.  We can't
11078   // delete OLD_ARGS because we may have both a Call_expression and a
11079   // Builtin_call_expression which refer to them.  FIXME.
11080   this->args_ = new_args;
11081   this->varargs_are_lowered_ = true;
11082 }
11083 
11084 // Flatten a call with multiple results into a temporary.
11085 
11086 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)11087 Call_expression::do_flatten(Gogo* gogo, Named_object*,
11088 			    Statement_inserter* inserter)
11089 {
11090   if (this->is_erroneous_call())
11091     {
11092       go_assert(saw_errors());
11093       return Expression::make_error(this->location());
11094     }
11095 
11096   if (this->is_flattened_)
11097     return this;
11098   this->is_flattened_ = true;
11099 
11100   // Add temporary variables for all arguments that require type
11101   // conversion.
11102   Function_type* fntype = this->get_function_type();
11103   if (fntype == NULL)
11104     {
11105       go_assert(saw_errors());
11106       return this;
11107     }
11108   if (this->args_ != NULL && !this->args_->empty()
11109       && fntype->parameters() != NULL && !fntype->parameters()->empty())
11110     {
11111       bool is_interface_method =
11112 	this->fn_->interface_field_reference_expression() != NULL;
11113 
11114       Expression_list *args = new Expression_list();
11115       Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11116       Expression_list::const_iterator pa = this->args_->begin();
11117       if (!is_interface_method && fntype->is_method())
11118 	{
11119 	  // The receiver argument.
11120 	  args->push_back(*pa);
11121 	  ++pa;
11122 	}
11123       for (; pa != this->args_->end(); ++pa, ++pp)
11124 	{
11125 	  go_assert(pp != fntype->parameters()->end());
11126 	  if (Type::are_identical(pp->type(), (*pa)->type(),
11127 				  Type::COMPARE_TAGS, NULL))
11128 	    args->push_back(*pa);
11129 	  else
11130 	    {
11131 	      Location loc = (*pa)->location();
11132 	      Expression* arg = *pa;
11133 	      if (!arg->is_variable())
11134 		{
11135 		  Temporary_statement *temp =
11136 		    Statement::make_temporary(NULL, arg, loc);
11137 		  inserter->insert(temp);
11138 		  arg = Expression::make_temporary_reference(temp, loc);
11139 		}
11140 	      arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
11141 						       loc);
11142 	      args->push_back(arg);
11143 	    }
11144 	}
11145       delete this->args_;
11146       this->args_ = args;
11147     }
11148 
11149   // Lower to compiler intrinsic if possible.
11150   Func_expression* fe = this->fn_->func_expression();
11151   if (!this->is_concurrent_ && !this->is_deferred_
11152       && fe != NULL
11153       && (fe->named_object()->is_function_declaration()
11154           || fe->named_object()->is_function()))
11155     {
11156       Expression* ret = this->intrinsify(gogo, inserter);
11157       if (ret != NULL)
11158         return ret;
11159     }
11160 
11161   return this;
11162 }
11163 
11164 // Lower a call to a compiler intrinsic if possible.
11165 // Returns NULL if it is not an intrinsic.
11166 
11167 Expression*
intrinsify(Gogo * gogo,Statement_inserter * inserter)11168 Call_expression::intrinsify(Gogo* gogo,
11169                             Statement_inserter* inserter)
11170 {
11171   Func_expression* fe = this->fn_->func_expression();
11172   Named_object* no = fe->named_object();
11173   std::string name = Gogo::unpack_hidden_name(no->name());
11174   std::string package = (no->package() != NULL
11175                          ? no->package()->pkgpath()
11176                          : gogo->pkgpath());
11177   Location loc = this->location();
11178 
11179   Type* int_type = Type::lookup_integer_type("int");
11180   Type* int32_type = Type::lookup_integer_type("int32");
11181   Type* int64_type = Type::lookup_integer_type("int64");
11182   Type* uint_type = Type::lookup_integer_type("uint");
11183   Type* uint32_type = Type::lookup_integer_type("uint32");
11184   Type* uint64_type = Type::lookup_integer_type("uint64");
11185   Type* uintptr_type = Type::lookup_integer_type("uintptr");
11186   Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
11187 
11188   int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
11189   int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
11190 
11191   if (package == "sync/atomic")
11192     {
11193       // sync/atomic functions and runtime/internal/atomic functions
11194       // are very similar. In order not to duplicate code, we just
11195       // redirect to the latter and let the code below to handle them.
11196       // In case there is no equivalent functions (slight variance
11197       // in types), we just make an artificial name (begin with '$').
11198       // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
11199       // as they need write barriers.
11200       if (name == "LoadInt32")
11201         name = "$Loadint32";
11202       else if (name == "LoadInt64")
11203         name = "Loadint64";
11204       else if (name == "LoadUint32")
11205         name = "Load";
11206       else if (name == "LoadUint64")
11207         name = "Load64";
11208       else if (name == "LoadUintptr")
11209         name = "Loaduintptr";
11210       else if (name == "LoadPointer")
11211         name = "Loadp";
11212       else if (name == "StoreInt32")
11213         name = "$Storeint32";
11214       else if (name == "StoreInt64")
11215         name = "$Storeint64";
11216       else if (name == "StoreUint32")
11217         name = "Store";
11218       else if (name == "StoreUint64")
11219         name = "Store64";
11220       else if (name == "StoreUintptr")
11221         name = "Storeuintptr";
11222       else if (name == "AddInt32")
11223         name = "$Xaddint32";
11224       else if (name == "AddInt64")
11225         name = "Xaddint64";
11226       else if (name == "AddUint32")
11227         name = "Xadd";
11228       else if (name == "AddUint64")
11229         name = "Xadd64";
11230       else if (name == "AddUintptr")
11231         name = "Xadduintptr";
11232       else if (name == "SwapInt32")
11233         name = "$Xchgint32";
11234       else if (name == "SwapInt64")
11235         name = "$Xchgint64";
11236       else if (name == "SwapUint32")
11237         name = "Xchg";
11238       else if (name == "SwapUint64")
11239         name = "Xchg64";
11240       else if (name == "SwapUintptr")
11241         name = "Xchguintptr";
11242       else if (name == "CompareAndSwapInt32")
11243         name = "$Casint32";
11244       else if (name == "CompareAndSwapInt64")
11245         name = "$Casint64";
11246       else if (name == "CompareAndSwapUint32")
11247         name = "Cas";
11248       else if (name == "CompareAndSwapUint64")
11249         name = "Cas64";
11250       else if (name == "CompareAndSwapUintptr")
11251         name = "Casuintptr";
11252       else
11253         return NULL;
11254 
11255       package = "runtime/internal/atomic";
11256     }
11257 
11258   if (package == "runtime/internal/sys")
11259     {
11260       // runtime/internal/sys functions and math/bits functions
11261       // are very similar. In order not to duplicate code, we just
11262       // redirect to the latter and let the code below to handle them.
11263       if (name == "Bswap32")
11264         name = "ReverseBytes32";
11265       else if (name == "Bswap64")
11266         name = "ReverseBytes64";
11267       else if (name == "Ctz32")
11268         name = "TrailingZeros32";
11269       else if (name == "Ctz64")
11270         name = "TrailingZeros64";
11271       else
11272         return NULL;
11273 
11274       package = "math/bits";
11275     }
11276 
11277   if (package == "runtime")
11278     {
11279       // Handle a couple of special runtime functions.  In the runtime
11280       // package, getcallerpc returns the PC of the caller, and
11281       // getcallersp returns the frame pointer of the caller.  Implement
11282       // these by turning them into calls to GCC builtin functions.  We
11283       // could implement them in normal code, but then we would have to
11284       // explicitly unwind the stack.  These functions are intended to be
11285       // efficient.  Note that this technique obviously only works for
11286       // direct calls, but that is the only way they are used.
11287       if (name == "getcallerpc"
11288           && (this->args_ == NULL || this->args_->size() == 0))
11289         {
11290           Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
11291           Expression* call =
11292             Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, loc,
11293                                1, arg);
11294           // The builtin functions return void*, but the Go functions return uintptr.
11295           return Expression::make_cast(uintptr_type, call, loc);
11296         }
11297       else if (name == "getcallersp"
11298                && (this->args_ == NULL || this->args_->size() == 0))
11299 
11300         {
11301           Expression* call =
11302             Runtime::make_call(Runtime::BUILTIN_DWARF_CFA, loc, 0);
11303           // The builtin functions return void*, but the Go functions return uintptr.
11304           return Expression::make_cast(uintptr_type, call, loc);
11305         }
11306     }
11307   else if (package == "math/bits")
11308     {
11309       if ((name == "ReverseBytes16" || name == "ReverseBytes32"
11310            || name == "ReverseBytes64" || name == "ReverseBytes")
11311           && this->args_ != NULL && this->args_->size() == 1)
11312         {
11313           Runtime::Function code;
11314           if (name == "ReverseBytes16")
11315             code = Runtime::BUILTIN_BSWAP16;
11316           else if (name == "ReverseBytes32")
11317             code = Runtime::BUILTIN_BSWAP32;
11318           else if (name == "ReverseBytes64")
11319             code = Runtime::BUILTIN_BSWAP64;
11320           else if (name == "ReverseBytes")
11321             code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
11322           else
11323             go_unreachable();
11324           Expression* arg = this->args_->front();
11325           Expression* call = Runtime::make_call(code, loc, 1, arg);
11326           if (name == "ReverseBytes")
11327             return Expression::make_cast(uint_type, call, loc);
11328           return call;
11329         }
11330       else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
11331                && this->args_ != NULL && this->args_->size() == 1)
11332         {
11333           // GCC does not have a ctz8 or ctz16 intrinsic. We do
11334           // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
11335           Expression* arg = this->args_->front();
11336           arg = Expression::make_cast(uint32_type, arg, loc);
11337           unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
11338           Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
11339           arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11340           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg);
11341           return Expression::make_cast(int_type, call, loc);
11342         }
11343       else if ((name == "TrailingZeros32"
11344                 || (name == "TrailingZeros" && int_size == 4))
11345                && this->args_ != NULL && this->args_->size() == 1)
11346         {
11347           Expression* arg = this->args_->front();
11348           if (!arg->is_variable())
11349             {
11350               Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11351               inserter->insert(ts);
11352               arg = Expression::make_temporary_reference(ts, loc);
11353             }
11354           // arg == 0 ? 32 : __builtin_ctz(arg)
11355           Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11356           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11357           Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11358           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg->copy());
11359           call = Expression::make_cast(int_type, call, loc);
11360           return Expression::make_conditional(cmp, c32, call, loc);
11361         }
11362       else if ((name == "TrailingZeros64"
11363                 || (name == "TrailingZeros" && int_size == 8))
11364                && this->args_ != NULL && this->args_->size() == 1)
11365         {
11366           Expression* arg = this->args_->front();
11367           if (!arg->is_variable())
11368             {
11369               Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11370               inserter->insert(ts);
11371               arg = Expression::make_temporary_reference(ts, loc);
11372             }
11373           // arg == 0 ? 64 : __builtin_ctzll(arg)
11374           Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11375           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11376           Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11377           Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZLL, loc, 1, arg->copy());
11378           call = Expression::make_cast(int_type, call, loc);
11379           return Expression::make_conditional(cmp, c64, call, loc);
11380         }
11381       else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
11382                 || name == "Len8" || name == "Len16")
11383                && this->args_ != NULL && this->args_->size() == 1)
11384         {
11385           // GCC does not have a clz8 ir clz16 intrinsic. We do
11386           // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
11387           Expression* arg = this->args_->front();
11388           arg = Expression::make_cast(uint32_type, arg, loc);
11389           unsigned long shift =
11390             ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
11391           Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
11392           arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
11393           unsigned long mask =
11394             ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
11395           c = Expression::make_integer_ul(mask, uint32_type, loc);
11396           arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11397           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg);
11398           call = Expression::make_cast(int_type, call, loc);
11399           // len = width - clz
11400           if (name == "Len8")
11401             {
11402               c = Expression::make_integer_ul(8, int_type, loc);
11403               return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11404             }
11405           else if (name == "Len16")
11406             {
11407               c = Expression::make_integer_ul(16, int_type, loc);
11408               return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11409             }
11410           return call;
11411         }
11412       else if ((name == "LeadingZeros32" || name == "Len32"
11413                 || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
11414                && this->args_ != NULL && this->args_->size() == 1)
11415         {
11416           Expression* arg = this->args_->front();
11417           if (!arg->is_variable())
11418             {
11419               Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11420               inserter->insert(ts);
11421               arg = Expression::make_temporary_reference(ts, loc);
11422             }
11423           // arg == 0 ? 32 : __builtin_clz(arg)
11424           Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11425           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11426           Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11427           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg->copy());
11428           call = Expression::make_cast(int_type, call, loc);
11429           Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
11430           // len = 32 - clz
11431           if (name == "Len32" || name == "Len")
11432             return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
11433           return cond;
11434         }
11435       else if ((name == "LeadingZeros64" || name == "Len64"
11436                 || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
11437                && this->args_ != NULL && this->args_->size() == 1)
11438         {
11439           Expression* arg = this->args_->front();
11440           if (!arg->is_variable())
11441             {
11442               Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11443               inserter->insert(ts);
11444               arg = Expression::make_temporary_reference(ts, loc);
11445             }
11446           // arg == 0 ? 64 : __builtin_clzll(arg)
11447           Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11448           Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11449           Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11450           Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZLL, loc, 1, arg->copy());
11451           call = Expression::make_cast(int_type, call, loc);
11452           Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
11453           // len = 64 - clz
11454           if (name == "Len64" || name == "Len")
11455             return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
11456           return cond;
11457         }
11458       else if ((name == "OnesCount8" || name == "OnesCount16"
11459            || name == "OnesCount32" || name == "OnesCount64"
11460            || name == "OnesCount")
11461           && this->args_ != NULL && this->args_->size() == 1)
11462         {
11463           Runtime::Function code;
11464           if (name == "OnesCount64")
11465             code = Runtime::BUILTIN_POPCOUNTLL;
11466           else if (name == "OnesCount")
11467             code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
11468           else
11469             code = Runtime::BUILTIN_POPCOUNT;
11470           Expression* arg = this->args_->front();
11471           Expression* call = Runtime::make_call(code, loc, 1, arg);
11472           return Expression::make_cast(int_type, call, loc);
11473         }
11474     }
11475   else if (package == "runtime/internal/atomic")
11476     {
11477       int memorder = __ATOMIC_SEQ_CST;
11478 
11479       if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
11480            || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
11481            || name == "$Loadint32")
11482           && this->args_ != NULL && this->args_->size() == 1)
11483         {
11484           if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
11485             // On 32-bit architectures we need to check alignment.
11486             // Not intrinsify for now.
11487             return NULL;
11488 
11489           Runtime::Function code;
11490           Type* res_type;
11491           if (name == "Load")
11492             {
11493               code = Runtime::ATOMIC_LOAD_4;
11494               res_type = uint32_type;
11495             }
11496           else if (name == "Load64")
11497             {
11498               code = Runtime::ATOMIC_LOAD_8;
11499               res_type = uint64_type;
11500             }
11501           else if (name == "$Loadint32")
11502             {
11503               code = Runtime::ATOMIC_LOAD_4;
11504               res_type = int32_type;
11505             }
11506           else if (name == "Loadint64")
11507             {
11508               code = Runtime::ATOMIC_LOAD_8;
11509               res_type = int64_type;
11510             }
11511           else if (name == "Loaduint")
11512             {
11513               code = (int_size == 8
11514                       ? Runtime::ATOMIC_LOAD_8
11515                       : Runtime::ATOMIC_LOAD_4);
11516               res_type = uint_type;
11517             }
11518           else if (name == "Loaduintptr")
11519             {
11520               code = (ptr_size == 8
11521                       ? Runtime::ATOMIC_LOAD_8
11522                       : Runtime::ATOMIC_LOAD_4);
11523               res_type = uintptr_type;
11524             }
11525           else if (name == "Loadp")
11526             {
11527               code = (ptr_size == 8
11528                       ? Runtime::ATOMIC_LOAD_8
11529                       : Runtime::ATOMIC_LOAD_4);
11530               res_type = pointer_type;
11531             }
11532           else if (name == "LoadAcq")
11533             {
11534               code = Runtime::ATOMIC_LOAD_4;
11535               res_type = uint32_type;
11536               memorder = __ATOMIC_ACQUIRE;
11537             }
11538           else
11539             go_unreachable();
11540           Expression* a1 = this->args_->front();
11541           Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
11542           Expression* call = Runtime::make_call(code, loc, 2, a1, a2);
11543           return Expression::make_unsafe_cast(res_type, call, loc);
11544         }
11545 
11546       if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
11547            || name == "Storeuintptr" || name == "StoreRel"
11548            || name == "$Storeint32" || name == "$Storeint64")
11549           && this->args_ != NULL && this->args_->size() == 2)
11550         {
11551           if (int_size < 8 && (name == "Store64" || name == "$Storeint64"))
11552             return NULL;
11553 
11554           Runtime::Function code;
11555           Expression* a1 = this->args_->at(0);
11556           Expression* a2 = this->args_->at(1);
11557           if (name == "Store")
11558             code = Runtime::ATOMIC_STORE_4;
11559           else if (name == "Store64")
11560             code = Runtime::ATOMIC_STORE_8;
11561           else if (name == "$Storeint32")
11562             code = Runtime::ATOMIC_STORE_4;
11563           else if (name == "$Storeint64")
11564             code = Runtime::ATOMIC_STORE_8;
11565           else if (name == "Storeuintptr")
11566             code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11567           else if (name == "StorepNoWB")
11568             {
11569               code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11570               a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
11571               a2 = Expression::make_cast(uint64_type, a2, loc);
11572             }
11573           else if (name == "StoreRel")
11574             {
11575               code = Runtime::ATOMIC_STORE_4;
11576               memorder = __ATOMIC_RELEASE;
11577             }
11578           else
11579             go_unreachable();
11580           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11581           return Runtime::make_call(code, loc, 3, a1, a2, a3);
11582         }
11583 
11584       if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
11585            || name == "$Xchgint32" || name == "$Xchgint64")
11586           && this->args_ != NULL && this->args_->size() == 2)
11587         {
11588           if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
11589             return NULL;
11590 
11591           Runtime::Function code;
11592           Type* res_type;
11593           if (name == "Xchg")
11594             {
11595               code = Runtime::ATOMIC_EXCHANGE_4;
11596               res_type = uint32_type;
11597             }
11598           else if (name == "Xchg64")
11599             {
11600               code = Runtime::ATOMIC_EXCHANGE_8;
11601               res_type = uint64_type;
11602             }
11603           else if (name == "$Xchgint32")
11604             {
11605               code = Runtime::ATOMIC_EXCHANGE_4;
11606               res_type = int32_type;
11607             }
11608           else if (name == "$Xchgint64")
11609             {
11610               code = Runtime::ATOMIC_EXCHANGE_8;
11611               res_type = int64_type;
11612             }
11613           else if (name == "Xchguintptr")
11614             {
11615               code = (ptr_size == 8
11616                       ? Runtime::ATOMIC_EXCHANGE_8
11617                       : Runtime::ATOMIC_EXCHANGE_4);
11618               res_type = uintptr_type;
11619             }
11620           else
11621             go_unreachable();
11622           Expression* a1 = this->args_->at(0);
11623           Expression* a2 = this->args_->at(1);
11624           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11625           Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11626           return Expression::make_cast(res_type, call, loc);
11627         }
11628 
11629       if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
11630            || name == "Casp1" || name == "CasRel"
11631            || name == "$Casint32" || name == "$Casint64")
11632           && this->args_ != NULL && this->args_->size() == 3)
11633         {
11634           if (int_size < 8 && (name == "Cas64" || name == "$Casint64"))
11635             return NULL;
11636 
11637           Runtime::Function code;
11638           Expression* a1 = this->args_->at(0);
11639 
11640           // Builtin cas takes a pointer to the old value.
11641           // Store it in a temporary and take the address.
11642           Expression* a2 = this->args_->at(1);
11643           Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
11644           inserter->insert(ts);
11645           a2 = Expression::make_temporary_reference(ts, loc);
11646           a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
11647 
11648           Expression* a3 = this->args_->at(2);
11649           if (name == "Cas")
11650             code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11651           else if (name == "Cas64")
11652             code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11653           else if (name == "$Casint32")
11654             code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11655           else if (name == "$Casint64")
11656             code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11657           else if (name == "Casuintptr")
11658             code = (ptr_size == 8
11659                     ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11660                     : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11661           else if (name == "Casp1")
11662             {
11663               code = (ptr_size == 8
11664                       ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11665                       : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11666               a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
11667               a3 = Expression::make_cast(uint64_type, a3, loc);
11668             }
11669           else if (name == "CasRel")
11670             {
11671               code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11672               memorder = __ATOMIC_RELEASE;
11673             }
11674           else
11675             go_unreachable();
11676           Expression* a4 = Expression::make_boolean(false, loc);
11677           Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
11678           Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
11679           return Runtime::make_call(code, loc, 6, a1, a2, a3, a4, a5, a6);
11680         }
11681 
11682       if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
11683            || name == "Xadduintptr" || name == "$Xaddint32")
11684           && this->args_ != NULL && this->args_->size() == 2)
11685         {
11686           if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
11687             return NULL;
11688 
11689           Runtime::Function code;
11690           Type* res_type;
11691           if (name == "Xadd")
11692             {
11693               code = Runtime::ATOMIC_ADD_FETCH_4;
11694               res_type = uint32_type;
11695             }
11696           else if (name == "Xadd64")
11697             {
11698               code = Runtime::ATOMIC_ADD_FETCH_8;
11699               res_type = uint64_type;
11700             }
11701           else if (name == "$Xaddint32")
11702             {
11703               code = Runtime::ATOMIC_ADD_FETCH_4;
11704               res_type = int32_type;
11705             }
11706           else if (name == "Xaddint64")
11707             {
11708               code = Runtime::ATOMIC_ADD_FETCH_8;
11709               res_type = int64_type;
11710             }
11711           else if (name == "Xadduintptr")
11712             {
11713               code = (ptr_size == 8
11714                       ? Runtime::ATOMIC_ADD_FETCH_8
11715                       : Runtime::ATOMIC_ADD_FETCH_4);
11716               res_type = uintptr_type;
11717             }
11718           else
11719             go_unreachable();
11720           Expression* a1 = this->args_->at(0);
11721           Expression* a2 = this->args_->at(1);
11722           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11723           Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11724           return Expression::make_cast(res_type, call, loc);
11725         }
11726 
11727       if ((name == "And8" || name == "Or8")
11728           && this->args_ != NULL && this->args_->size() == 2)
11729         {
11730           Runtime::Function code;
11731           if (name == "And8")
11732             code = Runtime::ATOMIC_AND_FETCH_1;
11733           else if (name == "Or8")
11734             code = Runtime::ATOMIC_OR_FETCH_1;
11735           else
11736             go_unreachable();
11737           Expression* a1 = this->args_->at(0);
11738           Expression* a2 = this->args_->at(1);
11739           Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11740           return Runtime::make_call(code, loc, 3, a1, a2, a3);
11741         }
11742     }
11743 
11744   return NULL;
11745 }
11746 
11747 // Make implicit type conversions explicit.
11748 
11749 void
do_add_conversions()11750 Call_expression::do_add_conversions()
11751 {
11752   // Skip call that requires a thunk. We generate conversions inside the thunk.
11753   if (this->is_concurrent_ || this->is_deferred_)
11754     return;
11755 
11756   if (this->args_ == NULL || this->args_->empty())
11757     return;
11758 
11759   Function_type* fntype = this->get_function_type();
11760   if (fntype == NULL)
11761     {
11762       go_assert(saw_errors());
11763       return;
11764     }
11765   if (fntype->parameters() == NULL || fntype->parameters()->empty())
11766     return;
11767 
11768   Location loc = this->location();
11769   Expression_list::iterator pa = this->args_->begin();
11770   Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11771   bool is_interface_method =
11772     this->fn_->interface_field_reference_expression() != NULL;
11773   size_t argcount = this->args_->size();
11774   if (!is_interface_method && fntype->is_method())
11775     {
11776       // Skip the receiver argument, which cannot be interface.
11777       pa++;
11778       argcount--;
11779     }
11780   if (argcount != fntype->parameters()->size())
11781     {
11782       go_assert(saw_errors());
11783       return;
11784     }
11785   for (; pa != this->args_->end(); ++pa, ++pp)
11786     {
11787       Type* pt = pp->type();
11788       if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
11789           && pt->interface_type() != NULL)
11790         *pa = Expression::make_cast(pt, *pa, loc);
11791     }
11792 }
11793 
11794 // Get the function type.  This can return NULL in error cases.
11795 
11796 Function_type*
get_function_type() const11797 Call_expression::get_function_type() const
11798 {
11799   return this->fn_->type()->function_type();
11800 }
11801 
11802 // Return the number of values which this call will return.
11803 
11804 size_t
result_count() const11805 Call_expression::result_count() const
11806 {
11807   const Function_type* fntype = this->get_function_type();
11808   if (fntype == NULL)
11809     return 0;
11810   if (fntype->results() == NULL)
11811     return 0;
11812   return fntype->results()->size();
11813 }
11814 
11815 // Return the temporary that holds the result for a call with multiple
11816 // results.
11817 
11818 Temporary_statement*
results() const11819 Call_expression::results() const
11820 {
11821   if (this->call_temp_ == NULL)
11822     {
11823       go_assert(saw_errors());
11824       return NULL;
11825     }
11826   return this->call_temp_;
11827 }
11828 
11829 // Set the number of results expected from a call expression.
11830 
11831 void
set_expected_result_count(size_t count)11832 Call_expression::set_expected_result_count(size_t count)
11833 {
11834   go_assert(this->expected_result_count_ == 0);
11835   this->expected_result_count_ = count;
11836 }
11837 
11838 // Return whether this is a call to the predeclared function recover.
11839 
11840 bool
is_recover_call() const11841 Call_expression::is_recover_call() const
11842 {
11843   return this->do_is_recover_call();
11844 }
11845 
11846 // Set the argument to the recover function.
11847 
11848 void
set_recover_arg(Expression * arg)11849 Call_expression::set_recover_arg(Expression* arg)
11850 {
11851   this->do_set_recover_arg(arg);
11852 }
11853 
11854 // Virtual functions also implemented by Builtin_call_expression.
11855 
11856 bool
do_is_recover_call() const11857 Call_expression::do_is_recover_call() const
11858 {
11859   return false;
11860 }
11861 
11862 void
do_set_recover_arg(Expression *)11863 Call_expression::do_set_recover_arg(Expression*)
11864 {
11865   go_unreachable();
11866 }
11867 
11868 // We have found an error with this call expression; return true if
11869 // we should report it.
11870 
11871 bool
issue_error()11872 Call_expression::issue_error()
11873 {
11874   if (this->issued_error_)
11875     return false;
11876   else
11877     {
11878       this->issued_error_ = true;
11879       return true;
11880     }
11881 }
11882 
11883 // Whether or not this call contains errors, either in the call or the
11884 // arguments to the call.
11885 
11886 bool
is_erroneous_call()11887 Call_expression::is_erroneous_call()
11888 {
11889   if (this->is_error_expression() || this->fn()->is_error_expression())
11890     return true;
11891 
11892   if (this->args() == NULL)
11893     return false;
11894   for (Expression_list::iterator pa = this->args()->begin();
11895        pa != this->args()->end();
11896        ++pa)
11897     {
11898       if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
11899         return true;
11900     }
11901   return false;
11902 }
11903 
11904 // Get the type.
11905 
11906 Type*
do_type()11907 Call_expression::do_type()
11908 {
11909   if (this->is_error_expression())
11910     return Type::make_error_type();
11911   if (this->type_ != NULL)
11912     return this->type_;
11913 
11914   Type* ret;
11915   Function_type* fntype = this->get_function_type();
11916   if (fntype == NULL)
11917     return Type::make_error_type();
11918 
11919   const Typed_identifier_list* results = fntype->results();
11920   if (results == NULL)
11921     ret = Type::make_void_type();
11922   else if (results->size() == 1)
11923     ret = results->begin()->type();
11924   else
11925     ret = Type::make_call_multiple_result_type(this);
11926 
11927   this->type_ = ret;
11928 
11929   return this->type_;
11930 }
11931 
11932 // Determine types for a call expression.  We can use the function
11933 // parameter types to set the types of the arguments.
11934 
11935 void
do_determine_type(const Type_context *)11936 Call_expression::do_determine_type(const Type_context*)
11937 {
11938   if (!this->determining_types())
11939     return;
11940 
11941   this->fn_->determine_type_no_context();
11942   Function_type* fntype = this->get_function_type();
11943   const Typed_identifier_list* parameters = NULL;
11944   if (fntype != NULL)
11945     parameters = fntype->parameters();
11946   if (this->args_ != NULL)
11947     {
11948       Typed_identifier_list::const_iterator pt;
11949       if (parameters != NULL)
11950 	pt = parameters->begin();
11951       bool first = true;
11952       for (Expression_list::const_iterator pa = this->args_->begin();
11953 	   pa != this->args_->end();
11954 	   ++pa)
11955 	{
11956 	  if (first)
11957 	    {
11958 	      first = false;
11959 	      // If this is a method, the first argument is the
11960 	      // receiver.
11961 	      if (fntype != NULL && fntype->is_method())
11962 		{
11963 		  Type* rtype = fntype->receiver()->type();
11964 		  // The receiver is always passed as a pointer.
11965 		  if (rtype->points_to() == NULL)
11966 		    rtype = Type::make_pointer_type(rtype);
11967 		  Type_context subcontext(rtype, false);
11968 		  (*pa)->determine_type(&subcontext);
11969 		  continue;
11970 		}
11971 	    }
11972 
11973 	  if (parameters != NULL && pt != parameters->end())
11974 	    {
11975 	      Type_context subcontext(pt->type(), false);
11976 	      (*pa)->determine_type(&subcontext);
11977 	      ++pt;
11978 	    }
11979 	  else
11980 	    (*pa)->determine_type_no_context();
11981 	}
11982     }
11983 }
11984 
11985 // Called when determining types for a Call_expression.  Return true
11986 // if we should go ahead, false if they have already been determined.
11987 
11988 bool
determining_types()11989 Call_expression::determining_types()
11990 {
11991   if (this->types_are_determined_)
11992     return false;
11993   else
11994     {
11995       this->types_are_determined_ = true;
11996       return true;
11997     }
11998 }
11999 
12000 // Check types for parameter I.
12001 
12002 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)12003 Call_expression::check_argument_type(int i, const Type* parameter_type,
12004 				     const Type* argument_type,
12005 				     Location argument_location,
12006 				     bool issued_error)
12007 {
12008   std::string reason;
12009   if (!Type::are_assignable(parameter_type, argument_type, &reason))
12010     {
12011       if (!issued_error)
12012 	{
12013 	  if (reason.empty())
12014 	    go_error_at(argument_location, "argument %d has incompatible type", i);
12015 	  else
12016 	    go_error_at(argument_location,
12017 			"argument %d has incompatible type (%s)",
12018 			i, reason.c_str());
12019 	}
12020       this->set_is_error();
12021       return false;
12022     }
12023   return true;
12024 }
12025 
12026 // Check types.
12027 
12028 void
do_check_types(Gogo *)12029 Call_expression::do_check_types(Gogo*)
12030 {
12031   if (this->classification() == EXPRESSION_ERROR)
12032     return;
12033 
12034   Function_type* fntype = this->get_function_type();
12035   if (fntype == NULL)
12036     {
12037       if (!this->fn_->type()->is_error())
12038 	this->report_error(_("expected function"));
12039       return;
12040     }
12041 
12042   if (this->expected_result_count_ != 0
12043       && this->expected_result_count_ != this->result_count())
12044     {
12045       if (this->issue_error())
12046 	this->report_error(_("function result count mismatch"));
12047       this->set_is_error();
12048       return;
12049     }
12050 
12051   bool is_method = fntype->is_method();
12052   if (is_method)
12053     {
12054       go_assert(this->args_ != NULL && !this->args_->empty());
12055       Type* rtype = fntype->receiver()->type();
12056       Expression* first_arg = this->args_->front();
12057       // We dereference the values since receivers are always passed
12058       // as pointers.
12059       std::string reason;
12060       if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
12061 				&reason))
12062 	{
12063 	  if (reason.empty())
12064 	    this->report_error(_("incompatible type for receiver"));
12065 	  else
12066 	    {
12067 	      go_error_at(this->location(),
12068                           "incompatible type for receiver (%s)",
12069                           reason.c_str());
12070 	      this->set_is_error();
12071 	    }
12072 	}
12073     }
12074 
12075   // Note that varargs was handled by the lower_varargs() method, so
12076   // we don't have to worry about it here unless something is wrong.
12077   if (this->is_varargs_ && !this->varargs_are_lowered_)
12078     {
12079       if (!fntype->is_varargs())
12080 	{
12081 	  go_error_at(this->location(),
12082                       _("invalid use of %<...%> calling non-variadic function"));
12083 	  this->set_is_error();
12084 	  return;
12085 	}
12086     }
12087 
12088   const Typed_identifier_list* parameters = fntype->parameters();
12089   if (this->args_ == NULL || this->args_->size() == 0)
12090     {
12091       if (parameters != NULL && !parameters->empty())
12092 	this->report_error(_("not enough arguments"));
12093     }
12094   else if (parameters == NULL)
12095     {
12096       if (!is_method || this->args_->size() > 1)
12097 	this->report_error(_("too many arguments"));
12098     }
12099   else if (this->args_->size() == 1
12100 	   && this->args_->front()->call_expression() != NULL
12101 	   && this->args_->front()->call_expression()->result_count() > 1)
12102     {
12103       // This is F(G()) when G returns more than one result.  If the
12104       // results can be matched to parameters, it would have been
12105       // lowered in do_lower.  If we get here we know there is a
12106       // mismatch.
12107       if (this->args_->front()->call_expression()->result_count()
12108 	  < parameters->size())
12109 	this->report_error(_("not enough arguments"));
12110       else
12111 	this->report_error(_("too many arguments"));
12112     }
12113   else
12114     {
12115       int i = 0;
12116       Expression_list::const_iterator pa = this->args_->begin();
12117       if (is_method)
12118 	++pa;
12119       for (Typed_identifier_list::const_iterator pt = parameters->begin();
12120 	   pt != parameters->end();
12121 	   ++pt, ++pa, ++i)
12122 	{
12123 	  if (pa == this->args_->end())
12124 	    {
12125 	      this->report_error(_("not enough arguments"));
12126 	      return;
12127 	    }
12128 	  this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
12129 				    (*pa)->location(), false);
12130 	}
12131       if (pa != this->args_->end())
12132 	this->report_error(_("too many arguments"));
12133     }
12134 }
12135 
12136 Expression*
do_copy()12137 Call_expression::do_copy()
12138 {
12139   Call_expression* call =
12140     Expression::make_call(this->fn_->copy(),
12141 			  (this->args_ == NULL
12142 			   ? NULL
12143 			   : this->args_->copy()),
12144 			  this->is_varargs_, this->location());
12145 
12146   if (this->varargs_are_lowered_)
12147     call->set_varargs_are_lowered();
12148   if (this->is_deferred_)
12149     call->set_is_deferred();
12150   if (this->is_concurrent_)
12151     call->set_is_concurrent();
12152   return call;
12153 }
12154 
12155 // Return whether we have to use a temporary variable to ensure that
12156 // we evaluate this call expression in order.  If the call returns no
12157 // results then it will inevitably be executed last.
12158 
12159 bool
do_must_eval_in_order() const12160 Call_expression::do_must_eval_in_order() const
12161 {
12162   return this->result_count() > 0;
12163 }
12164 
12165 // Get the function and the first argument to use when calling an
12166 // interface method.
12167 
12168 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr,Location location)12169 Call_expression::interface_method_function(
12170     Interface_field_reference_expression* interface_method,
12171     Expression** first_arg_ptr,
12172     Location location)
12173 {
12174   Expression* object = interface_method->get_underlying_object();
12175   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
12176   *first_arg_ptr =
12177       Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
12178   return interface_method->get_function();
12179 }
12180 
12181 // Build the call expression.
12182 
12183 Bexpression*
do_get_backend(Translate_context * context)12184 Call_expression::do_get_backend(Translate_context* context)
12185 {
12186   Location location = this->location();
12187 
12188   if (this->call_ != NULL)
12189     {
12190       // If the call returns multiple results, make a new reference to
12191       // the temporary.
12192       if (this->call_temp_ != NULL)
12193 	{
12194 	  Expression* ref =
12195 	    Expression::make_temporary_reference(this->call_temp_, location);
12196 	  return ref->get_backend(context);
12197 	}
12198 
12199       return this->call_;
12200     }
12201 
12202   Function_type* fntype = this->get_function_type();
12203   if (fntype == NULL)
12204     return context->backend()->error_expression();
12205 
12206   if (this->fn_->is_error_expression())
12207     return context->backend()->error_expression();
12208 
12209   Gogo* gogo = context->gogo();
12210 
12211   Func_expression* func = this->fn_->func_expression();
12212   Interface_field_reference_expression* interface_method =
12213     this->fn_->interface_field_reference_expression();
12214   const bool has_closure = func != NULL && func->closure() != NULL;
12215   const bool is_interface_method = interface_method != NULL;
12216 
12217   bool has_closure_arg;
12218   if (has_closure)
12219     has_closure_arg = true;
12220   else if (func != NULL)
12221     has_closure_arg = false;
12222   else if (is_interface_method)
12223     has_closure_arg = false;
12224   else
12225     has_closure_arg = true;
12226 
12227   Expression* first_arg = NULL;
12228   if (!is_interface_method && fntype->is_method())
12229     {
12230       first_arg = this->args_->front();
12231       if (first_arg->type()->points_to() == NULL
12232           && first_arg->type()->is_direct_iface_type())
12233         first_arg = Expression::unpack_direct_iface(first_arg,
12234                                                     first_arg->location());
12235     }
12236 
12237   int nargs;
12238   std::vector<Bexpression*> fn_args;
12239   if (this->args_ == NULL || this->args_->empty())
12240     {
12241       nargs = is_interface_method ? 1 : 0;
12242       if (nargs > 0)
12243         fn_args.resize(1);
12244     }
12245   else if (fntype->parameters() == NULL || fntype->parameters()->empty())
12246     {
12247       // Passing a receiver parameter.
12248       go_assert(!is_interface_method
12249 		&& fntype->is_method()
12250 		&& this->args_->size() == 1);
12251       nargs = 1;
12252       fn_args.resize(1);
12253       fn_args[0] = first_arg->get_backend(context);
12254     }
12255   else
12256     {
12257       const Typed_identifier_list* params = fntype->parameters();
12258 
12259       nargs = this->args_->size();
12260       int i = is_interface_method ? 1 : 0;
12261       nargs += i;
12262       fn_args.resize(nargs);
12263 
12264       Typed_identifier_list::const_iterator pp = params->begin();
12265       Expression_list::const_iterator pe = this->args_->begin();
12266       if (!is_interface_method && fntype->is_method())
12267 	{
12268           fn_args[i] = first_arg->get_backend(context);
12269 	  ++pe;
12270 	  ++i;
12271 	}
12272       for (; pe != this->args_->end(); ++pe, ++pp, ++i)
12273 	{
12274 	  go_assert(pp != params->end());
12275           Expression* arg =
12276               Expression::convert_for_assignment(gogo, pp->type(), *pe,
12277                                                  location);
12278           fn_args[i] = arg->get_backend(context);
12279 	}
12280       go_assert(pp == params->end());
12281       go_assert(i == nargs);
12282     }
12283 
12284   Expression* fn;
12285   Expression* closure = NULL;
12286   if (func != NULL)
12287     {
12288       Named_object* no = func->named_object();
12289       fn = Expression::make_func_code_reference(no, location);
12290       if (has_closure)
12291         closure = func->closure();
12292     }
12293   else if (!is_interface_method)
12294     {
12295       closure = this->fn_;
12296 
12297       // The backend representation of this function type is a pointer
12298       // to a struct whose first field is the actual function to call.
12299       Type* pfntype =
12300           Type::make_pointer_type(
12301               Type::make_pointer_type(Type::make_void_type()));
12302       fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
12303       fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
12304     }
12305   else
12306     {
12307       Expression* arg0;
12308       fn = this->interface_method_function(interface_method, &arg0,
12309                                            location);
12310       fn_args[0] = arg0->get_backend(context);
12311     }
12312 
12313   Bexpression* bclosure = NULL;
12314   if (has_closure_arg)
12315     bclosure = closure->get_backend(context);
12316   else
12317     go_assert(closure == NULL);
12318 
12319   Bexpression* bfn = fn->get_backend(context);
12320 
12321   // When not calling a named function directly, use a type conversion
12322   // in case the type of the function is a recursive type which refers
12323   // to itself.  We don't do this for an interface method because 1)
12324   // an interface method never refers to itself, so we always have a
12325   // function type here; 2) we pass an extra first argument to an
12326   // interface method, so fntype is not correct.
12327   if (func == NULL && !is_interface_method)
12328     {
12329       Btype* bft = fntype->get_backend_fntype(gogo);
12330       bfn = gogo->backend()->convert_expression(bft, bfn, location);
12331     }
12332 
12333   Bfunction* bfunction = NULL;
12334   if (context->function())
12335     bfunction = context->function()->func_value()->get_decl();
12336   Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
12337                                                        fn_args, bclosure,
12338                                                        location);
12339 
12340   if (this->call_temp_ != NULL)
12341     {
12342       // This case occurs when the call returns multiple results.
12343 
12344       Expression* ref = Expression::make_temporary_reference(this->call_temp_,
12345 							     location);
12346       Bexpression* bref = ref->get_backend(context);
12347       Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
12348 								bref, call,
12349 								location);
12350 
12351       ref = Expression::make_temporary_reference(this->call_temp_, location);
12352       this->call_ = ref->get_backend(context);
12353 
12354       return gogo->backend()->compound_expression(bassn, this->call_,
12355 						  location);
12356     }
12357 
12358   this->call_ = call;
12359   return this->call_;
12360 }
12361 
12362 // The cost of inlining a call expression.
12363 
12364 int
do_inlining_cost() const12365 Call_expression::do_inlining_cost() const
12366 {
12367   Func_expression* fn = this->fn_->func_expression();
12368 
12369   // FIXME: We don't yet support all kinds of calls.
12370   if (fn != NULL && fn->closure() != NULL)
12371     return 0x100000;
12372   if (this->fn_->interface_field_reference_expression())
12373     return 0x100000;
12374   if (this->get_function_type()->is_method())
12375     return 0x100000;
12376 
12377   return 5;
12378 }
12379 
12380 // Export a call expression.
12381 
12382 void
do_export(Export_function_body * efb) const12383 Call_expression::do_export(Export_function_body* efb) const
12384 {
12385   bool simple_call = (this->fn_->func_expression() != NULL);
12386   if (!simple_call)
12387     efb->write_c_string("(");
12388   this->fn_->export_expression(efb);
12389   if (!simple_call)
12390     efb->write_c_string(")");
12391   this->export_arguments(efb);
12392 }
12393 
12394 // Export call expression arguments.
12395 
12396 void
export_arguments(Export_function_body * efb) const12397 Call_expression::export_arguments(Export_function_body* efb) const
12398 {
12399   efb->write_c_string("(");
12400   if (this->args_ != NULL && !this->args_->empty())
12401     {
12402       Expression_list::const_iterator pa = this->args_->begin();
12403       (*pa)->export_expression(efb);
12404       for (pa++; pa != this->args_->end(); pa++)
12405 	{
12406 	  efb->write_c_string(", ");
12407 	  (*pa)->export_expression(efb);
12408 	}
12409       if (this->is_varargs_)
12410 	efb->write_c_string("...");
12411     }
12412   efb->write_c_string(")");
12413 }
12414 
12415 // Dump ast representation for a call expression.
12416 
12417 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12418 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12419 {
12420   this->fn_->dump_expression(ast_dump_context);
12421   ast_dump_context->ostream() << "(";
12422   if (args_ != NULL)
12423     ast_dump_context->dump_expression_list(this->args_);
12424 
12425   ast_dump_context->ostream() << ") ";
12426 }
12427 
12428 // Make a call expression.
12429 
12430 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)12431 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
12432 		      Location location)
12433 {
12434   return new Call_expression(fn, args, is_varargs, location);
12435 }
12436 
12437 // Class Call_result_expression.
12438 
12439 // Traverse a call result.
12440 
12441 int
do_traverse(Traverse * traverse)12442 Call_result_expression::do_traverse(Traverse* traverse)
12443 {
12444   if (traverse->remember_expression(this->call_))
12445     {
12446       // We have already traversed the call expression.
12447       return TRAVERSE_CONTINUE;
12448     }
12449   return Expression::traverse(&this->call_, traverse);
12450 }
12451 
12452 // Get the type.
12453 
12454 Type*
do_type()12455 Call_result_expression::do_type()
12456 {
12457   if (this->classification() == EXPRESSION_ERROR)
12458     return Type::make_error_type();
12459 
12460   // THIS->CALL_ can be replaced with a temporary reference due to
12461   // Call_expression::do_must_eval_in_order when there is an error.
12462   Call_expression* ce = this->call_->call_expression();
12463   if (ce == NULL)
12464     {
12465       this->set_is_error();
12466       return Type::make_error_type();
12467     }
12468   Function_type* fntype = ce->get_function_type();
12469   if (fntype == NULL)
12470     {
12471       if (ce->issue_error())
12472 	{
12473 	  if (!ce->fn()->type()->is_error())
12474 	    this->report_error(_("expected function"));
12475 	}
12476       this->set_is_error();
12477       return Type::make_error_type();
12478     }
12479   const Typed_identifier_list* results = fntype->results();
12480   if (results == NULL || results->size() < 2)
12481     {
12482       if (ce->issue_error())
12483 	this->report_error(_("number of results does not match "
12484 			     "number of values"));
12485       return Type::make_error_type();
12486     }
12487   Typed_identifier_list::const_iterator pr = results->begin();
12488   for (unsigned int i = 0; i < this->index_; ++i)
12489     {
12490       if (pr == results->end())
12491 	break;
12492       ++pr;
12493     }
12494   if (pr == results->end())
12495     {
12496       if (ce->issue_error())
12497 	this->report_error(_("number of results does not match "
12498 			     "number of values"));
12499       return Type::make_error_type();
12500     }
12501   return pr->type();
12502 }
12503 
12504 // Check the type.  Just make sure that we trigger the warning in
12505 // do_type.
12506 
12507 void
do_check_types(Gogo *)12508 Call_result_expression::do_check_types(Gogo*)
12509 {
12510   this->type();
12511 }
12512 
12513 // Determine the type.  We have nothing to do here, but the 0 result
12514 // needs to pass down to the caller.
12515 
12516 void
do_determine_type(const Type_context *)12517 Call_result_expression::do_determine_type(const Type_context*)
12518 {
12519   this->call_->determine_type_no_context();
12520 }
12521 
12522 // Return the backend representation.  We just refer to the temporary set by the
12523 // call expression.  We don't do this at lowering time because it makes it
12524 // hard to evaluate the call at the right time.
12525 
12526 Bexpression*
do_get_backend(Translate_context * context)12527 Call_result_expression::do_get_backend(Translate_context* context)
12528 {
12529   Call_expression* ce = this->call_->call_expression();
12530   if (ce == NULL)
12531     {
12532       go_assert(this->call_->is_error_expression());
12533       return context->backend()->error_expression();
12534     }
12535   Temporary_statement* ts = ce->results();
12536   if (ts == NULL)
12537     {
12538       go_assert(saw_errors());
12539       return context->backend()->error_expression();
12540     }
12541   Expression* ref = Expression::make_temporary_reference(ts, this->location());
12542   ref = Expression::make_field_reference(ref, this->index_, this->location());
12543   return ref->get_backend(context);
12544 }
12545 
12546 // Dump ast representation for a call result expression.
12547 
12548 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12549 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12550     const
12551 {
12552   // FIXME: Wouldn't it be better if the call is assigned to a temporary
12553   // (struct) and the fields are referenced instead.
12554   ast_dump_context->ostream() << this->index_ << "@(";
12555   ast_dump_context->dump_expression(this->call_);
12556   ast_dump_context->ostream() << ")";
12557 }
12558 
12559 // Make a reference to a single result of a call which returns
12560 // multiple results.
12561 
12562 Expression*
make_call_result(Call_expression * call,unsigned int index)12563 Expression::make_call_result(Call_expression* call, unsigned int index)
12564 {
12565   return new Call_result_expression(call, index);
12566 }
12567 
12568 // Class Index_expression.
12569 
12570 // Traversal.
12571 
12572 int
do_traverse(Traverse * traverse)12573 Index_expression::do_traverse(Traverse* traverse)
12574 {
12575   if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
12576       || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
12577       || (this->end_ != NULL
12578 	  && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12579       || (this->cap_ != NULL
12580           && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
12581     return TRAVERSE_EXIT;
12582   return TRAVERSE_CONTINUE;
12583 }
12584 
12585 // Lower an index expression.  This converts the generic index
12586 // expression into an array index, a string index, or a map index.
12587 
12588 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)12589 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
12590 {
12591   Location location = this->location();
12592   Expression* left = this->left_;
12593   Expression* start = this->start_;
12594   Expression* end = this->end_;
12595   Expression* cap = this->cap_;
12596 
12597   Type* type = left->type();
12598   if (type->is_error())
12599     {
12600       go_assert(saw_errors());
12601       return Expression::make_error(location);
12602     }
12603   else if (left->is_type_expression())
12604     {
12605       go_error_at(location, "attempt to index type expression");
12606       return Expression::make_error(location);
12607     }
12608   else if (type->array_type() != NULL)
12609     return Expression::make_array_index(left, start, end, cap, location);
12610   else if (type->points_to() != NULL
12611 	   && type->points_to()->array_type() != NULL
12612 	   && !type->points_to()->is_slice_type())
12613     {
12614       Expression* deref =
12615           Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
12616 
12617       // For an ordinary index into the array, the pointer will be
12618       // dereferenced.  For a slice it will not--the resulting slice
12619       // will simply reuse the pointer, which is incorrect if that
12620       // pointer is nil.
12621       if (end != NULL || cap != NULL)
12622 	deref->issue_nil_check();
12623 
12624       return Expression::make_array_index(deref, start, end, cap, location);
12625     }
12626   else if (type->is_string_type())
12627     {
12628       if (cap != NULL)
12629         {
12630           go_error_at(location, "invalid 3-index slice of string");
12631           return Expression::make_error(location);
12632         }
12633       return Expression::make_string_index(left, start, end, location);
12634     }
12635   else if (type->map_type() != NULL)
12636     {
12637       if (end != NULL || cap != NULL)
12638 	{
12639 	  go_error_at(location, "invalid slice of map");
12640 	  return Expression::make_error(location);
12641 	}
12642       return Expression::make_map_index(left, start, location);
12643     }
12644   else if (cap != NULL)
12645     {
12646       go_error_at(location,
12647 		  "invalid 3-index slice of object that is not a slice");
12648       return Expression::make_error(location);
12649     }
12650   else if (end != NULL)
12651     {
12652       go_error_at(location,
12653 		  ("attempt to slice object that is not "
12654 		   "array, slice, or string"));
12655       return Expression::make_error(location);
12656     }
12657   else
12658     {
12659       go_error_at(location,
12660                   ("attempt to index object that is not "
12661 		   "array, slice, string, or map"));
12662       return Expression::make_error(location);
12663     }
12664 }
12665 
12666 // Write an indexed expression
12667 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
12668 
12669 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)12670 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
12671 					const Expression* expr,
12672 					const Expression* start,
12673 					const Expression* end,
12674 					const Expression* cap)
12675 {
12676   expr->dump_expression(ast_dump_context);
12677   ast_dump_context->ostream() << "[";
12678   start->dump_expression(ast_dump_context);
12679   if (end != NULL)
12680     {
12681       ast_dump_context->ostream() << ":";
12682       end->dump_expression(ast_dump_context);
12683     }
12684   if (cap != NULL)
12685     {
12686       ast_dump_context->ostream() << ":";
12687       cap->dump_expression(ast_dump_context);
12688     }
12689   ast_dump_context->ostream() << "]";
12690 }
12691 
12692 // Dump ast representation for an index expression.
12693 
12694 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12695 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12696     const
12697 {
12698   Index_expression::dump_index_expression(ast_dump_context, this->left_,
12699                                           this->start_, this->end_, this->cap_);
12700 }
12701 
12702 // Make an index expression.
12703 
12704 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)12705 Expression::make_index(Expression* left, Expression* start, Expression* end,
12706 		       Expression* cap, Location location)
12707 {
12708   return new Index_expression(left, start, end, cap, location);
12709 }
12710 
12711 // Class Array_index_expression.
12712 
12713 // Array index traversal.
12714 
12715 int
do_traverse(Traverse * traverse)12716 Array_index_expression::do_traverse(Traverse* traverse)
12717 {
12718   if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
12719     return TRAVERSE_EXIT;
12720   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
12721     return TRAVERSE_EXIT;
12722   if (this->end_ != NULL)
12723     {
12724       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12725 	return TRAVERSE_EXIT;
12726     }
12727   if (this->cap_ != NULL)
12728     {
12729       if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
12730         return TRAVERSE_EXIT;
12731     }
12732   return TRAVERSE_CONTINUE;
12733 }
12734 
12735 // Return the type of an array index.
12736 
12737 Type*
do_type()12738 Array_index_expression::do_type()
12739 {
12740   if (this->type_ == NULL)
12741     {
12742      Array_type* type = this->array_->type()->array_type();
12743       if (type == NULL)
12744 	this->type_ = Type::make_error_type();
12745       else if (this->end_ == NULL)
12746 	this->type_ = type->element_type();
12747       else if (type->is_slice_type())
12748 	{
12749 	  // A slice of a slice has the same type as the original
12750 	  // slice.
12751 	  this->type_ = this->array_->type()->deref();
12752 	}
12753       else
12754 	{
12755 	  // A slice of an array is a slice.
12756 	  this->type_ = Type::make_array_type(type->element_type(), NULL);
12757 	}
12758     }
12759   return this->type_;
12760 }
12761 
12762 // Set the type of an array index.
12763 
12764 void
do_determine_type(const Type_context *)12765 Array_index_expression::do_determine_type(const Type_context*)
12766 {
12767   this->array_->determine_type_no_context();
12768 
12769   Type_context index_context(Type::lookup_integer_type("int"), false);
12770   if (this->start_->is_constant())
12771     this->start_->determine_type(&index_context);
12772   else
12773     this->start_->determine_type_no_context();
12774   if (this->end_ != NULL)
12775     {
12776       if (this->end_->is_constant())
12777         this->end_->determine_type(&index_context);
12778       else
12779         this->end_->determine_type_no_context();
12780     }
12781   if (this->cap_ != NULL)
12782     {
12783       if (this->cap_->is_constant())
12784         this->cap_->determine_type(&index_context);
12785       else
12786         this->cap_->determine_type_no_context();
12787     }
12788 }
12789 
12790 // Check types of an array index.
12791 
12792 void
do_check_types(Gogo *)12793 Array_index_expression::do_check_types(Gogo*)
12794 {
12795   Numeric_constant nc;
12796   unsigned long v;
12797   if (this->start_->type()->integer_type() == NULL
12798       && !this->start_->type()->is_error()
12799       && (!this->start_->type()->is_abstract()
12800 	  || !this->start_->numeric_constant_value(&nc)
12801 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12802     this->report_error(_("index must be integer"));
12803   if (this->end_ != NULL
12804       && this->end_->type()->integer_type() == NULL
12805       && !this->end_->type()->is_error()
12806       && !this->end_->is_nil_expression()
12807       && !this->end_->is_error_expression()
12808       && (!this->end_->type()->is_abstract()
12809 	  || !this->end_->numeric_constant_value(&nc)
12810 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12811     this->report_error(_("slice end must be integer"));
12812   if (this->cap_ != NULL
12813       && this->cap_->type()->integer_type() == NULL
12814       && !this->cap_->type()->is_error()
12815       && !this->cap_->is_nil_expression()
12816       && !this->cap_->is_error_expression()
12817       && (!this->cap_->type()->is_abstract()
12818 	  || !this->cap_->numeric_constant_value(&nc)
12819 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12820     this->report_error(_("slice capacity must be integer"));
12821 
12822   Array_type* array_type = this->array_->type()->array_type();
12823   if (array_type == NULL)
12824     {
12825       go_assert(this->array_->type()->is_error());
12826       return;
12827     }
12828 
12829   unsigned int int_bits =
12830     Type::lookup_integer_type("int")->integer_type()->bits();
12831 
12832   Numeric_constant lvalnc;
12833   mpz_t lval;
12834   bool lval_valid = (array_type->length() != NULL
12835 		     && array_type->length()->numeric_constant_value(&lvalnc)
12836 		     && lvalnc.to_int(&lval));
12837   Numeric_constant inc;
12838   mpz_t ival;
12839   bool ival_valid = false;
12840   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
12841     {
12842       ival_valid = true;
12843       if (mpz_sgn(ival) < 0
12844 	  || mpz_sizeinbase(ival, 2) >= int_bits
12845 	  || (lval_valid
12846 	      && (this->end_ == NULL
12847 		  ? mpz_cmp(ival, lval) >= 0
12848 		  : mpz_cmp(ival, lval) > 0)))
12849 	{
12850 	  go_error_at(this->start_->location(), "array index out of bounds");
12851 	  this->set_is_error();
12852 	}
12853     }
12854   if (this->end_ != NULL && !this->end_->is_nil_expression())
12855     {
12856       Numeric_constant enc;
12857       mpz_t eval;
12858       bool eval_valid = false;
12859       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
12860 	{
12861 	  eval_valid = true;
12862 	  if (mpz_sgn(eval) < 0
12863 	      || mpz_sizeinbase(eval, 2) >= int_bits
12864 	      || (lval_valid && mpz_cmp(eval, lval) > 0))
12865 	    {
12866 	      go_error_at(this->end_->location(), "array index out of bounds");
12867 	      this->set_is_error();
12868 	    }
12869 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
12870 	    this->report_error(_("inverted slice range"));
12871 	}
12872 
12873       Numeric_constant cnc;
12874       mpz_t cval;
12875       if (this->cap_ != NULL
12876           && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
12877         {
12878           if (mpz_sgn(cval) < 0
12879               || mpz_sizeinbase(cval, 2) >= int_bits
12880               || (lval_valid && mpz_cmp(cval, lval) > 0))
12881             {
12882               go_error_at(this->cap_->location(), "array index out of bounds");
12883               this->set_is_error();
12884             }
12885 	  else if (ival_valid && mpz_cmp(ival, cval) > 0)
12886 	    {
12887 	      go_error_at(this->cap_->location(),
12888                           "invalid slice index: capacity less than start");
12889 	      this->set_is_error();
12890 	    }
12891           else if (eval_valid && mpz_cmp(eval, cval) > 0)
12892             {
12893               go_error_at(this->cap_->location(),
12894                           "invalid slice index: capacity less than length");
12895               this->set_is_error();
12896             }
12897           mpz_clear(cval);
12898         }
12899 
12900       if (eval_valid)
12901         mpz_clear(eval);
12902     }
12903   if (ival_valid)
12904     mpz_clear(ival);
12905   if (lval_valid)
12906     mpz_clear(lval);
12907 
12908   // A slice of an array requires an addressable array.  A slice of a
12909   // slice is always possible.
12910   if (this->end_ != NULL && !array_type->is_slice_type())
12911     {
12912       if (!this->array_->is_addressable())
12913 	this->report_error(_("slice of unaddressable value"));
12914       else
12915         // Set the array address taken but not escape. The escape
12916         // analysis will make it escape to heap when needed.
12917         this->array_->address_taken(false);
12918     }
12919 }
12920 
12921 // The subexpressions of an array index must be evaluated in order.
12922 // If this is indexing into an array, rather than a slice, then only
12923 // the index should be evaluated.  Since this is called for values on
12924 // the left hand side of an assigment, evaluating the array, meaning
12925 // copying the array, will cause a different array to be modified.
12926 
12927 bool
do_must_eval_subexpressions_in_order(int * skip) const12928 Array_index_expression::do_must_eval_subexpressions_in_order(
12929     int* skip) const
12930 {
12931   *skip = this->array_->type()->is_slice_type() ? 0 : 1;
12932   return true;
12933 }
12934 
12935 // Flatten array indexing: add temporary variables and bounds checks.
12936 
12937 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)12938 Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
12939                                    Statement_inserter* inserter)
12940 {
12941   if (this->is_flattened_)
12942     return this;
12943   this->is_flattened_ = true;
12944 
12945   Location loc = this->location();
12946 
12947   if (this->is_error_expression())
12948     return Expression::make_error(loc);
12949 
12950   Expression* array = this->array_;
12951   Expression* start = this->start_;
12952   Expression* end = this->end_;
12953   Expression* cap = this->cap_;
12954   if (array->is_error_expression()
12955       || array->type()->is_error_type()
12956       || start->is_error_expression()
12957       || start->type()->is_error_type()
12958       || (end != NULL
12959           && (end->is_error_expression() || end->type()->is_error_type()))
12960       || (cap != NULL
12961           && (cap->is_error_expression() || cap->type()->is_error_type())))
12962     {
12963       go_assert(saw_errors());
12964       return Expression::make_error(loc);
12965     }
12966 
12967   Array_type* array_type = this->array_->type()->array_type();
12968   if (array_type == NULL)
12969     {
12970       go_assert(saw_errors());
12971       return Expression::make_error(loc);
12972     }
12973 
12974   Temporary_statement* temp;
12975   if (array_type->is_slice_type() && !array->is_variable())
12976     {
12977       temp = Statement::make_temporary(NULL, array, loc);
12978       inserter->insert(temp);
12979       this->array_ = Expression::make_temporary_reference(temp, loc);
12980       array = this->array_;
12981     }
12982   if (!start->is_variable() && !start->is_constant())
12983     {
12984       temp = Statement::make_temporary(NULL, start, loc);
12985       inserter->insert(temp);
12986       this->start_ = Expression::make_temporary_reference(temp, loc);
12987       start = this->start_;
12988     }
12989   if (end != NULL
12990       && !end->is_nil_expression()
12991       && !end->is_variable()
12992       && !end->is_constant())
12993     {
12994       temp = Statement::make_temporary(NULL, end, loc);
12995       inserter->insert(temp);
12996       this->end_ = Expression::make_temporary_reference(temp, loc);
12997       end = this->end_;
12998     }
12999   if (cap != NULL && !cap->is_variable() && !cap->is_constant())
13000     {
13001       temp = Statement::make_temporary(NULL, cap, loc);
13002       inserter->insert(temp);
13003       this->cap_ = Expression::make_temporary_reference(temp, loc);
13004       cap = this->cap_;
13005     }
13006 
13007   if (!this->needs_bounds_check_)
13008     return this;
13009 
13010   Expression* len;
13011   if (!array_type->is_slice_type())
13012     {
13013       len = array_type->get_length(gogo, this->array_);
13014       go_assert(len->is_constant());
13015     }
13016   else
13017     {
13018       len = array_type->get_length(gogo, this->array_->copy());
13019       temp = Statement::make_temporary(NULL, len, loc);
13020       inserter->insert(temp);
13021       len = Expression::make_temporary_reference(temp, loc);
13022     }
13023 
13024   Expression* scap = NULL;
13025   if (array_type->is_slice_type())
13026     {
13027       scap = array_type->get_capacity(gogo, this->array_->copy());
13028       temp = Statement::make_temporary(NULL, scap, loc);
13029       inserter->insert(temp);
13030       scap = Expression::make_temporary_reference(temp, loc);
13031     }
13032 
13033   // The order of bounds checks here matches the order used by the gc
13034   // compiler, as tested by issue30116[u].go.
13035 
13036   if (cap != NULL)
13037     {
13038       if (array_type->is_slice_type())
13039 	Expression::check_bounds(cap, OPERATOR_LE, scap,
13040 				 Runtime::PANIC_SLICE3_ACAP,
13041 				 Runtime::PANIC_SLICE3_ACAP_U,
13042 				 Runtime::PANIC_EXTEND_SLICE3_ACAP,
13043 				 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
13044 				 inserter, loc);
13045       else
13046 	Expression::check_bounds(cap, OPERATOR_LE, len,
13047 				 Runtime::PANIC_SLICE3_ALEN,
13048 				 Runtime::PANIC_SLICE3_ALEN_U,
13049 				 Runtime::PANIC_EXTEND_SLICE3_ALEN,
13050 				 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
13051 				 inserter, loc);
13052 
13053       Expression* start_bound = cap;
13054       if (end != NULL && !end->is_nil_expression())
13055 	{
13056 	  Expression::check_bounds(end, OPERATOR_LE, cap,
13057 				   Runtime::PANIC_SLICE3_B,
13058 				   Runtime::PANIC_SLICE3_B_U,
13059 				   Runtime::PANIC_EXTEND_SLICE3_B,
13060 				   Runtime::PANIC_EXTEND_SLICE3_B_U,
13061 				   inserter, loc);
13062 	  start_bound = end;
13063 	}
13064 
13065       Expression::check_bounds(start, OPERATOR_LE, start_bound,
13066 			       Runtime::PANIC_SLICE3_C,
13067 			       Runtime::PANIC_SLICE3_C_U,
13068 			       Runtime::PANIC_EXTEND_SLICE3_C,
13069 			       Runtime::PANIC_EXTEND_SLICE3_C_U,
13070 			       inserter, loc);
13071     }
13072   else if (end != NULL && !end->is_nil_expression())
13073     {
13074       if (array_type->is_slice_type())
13075 	Expression::check_bounds(end, OPERATOR_LE, scap,
13076 				 Runtime::PANIC_SLICE_ACAP,
13077 				 Runtime::PANIC_SLICE_ACAP_U,
13078 				 Runtime::PANIC_EXTEND_SLICE_ACAP,
13079 				 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
13080 				 inserter, loc);
13081       else
13082 	Expression::check_bounds(end, OPERATOR_LE, len,
13083 				 Runtime::PANIC_SLICE_ALEN,
13084 				 Runtime::PANIC_SLICE_ALEN_U,
13085 				 Runtime::PANIC_EXTEND_SLICE_ALEN,
13086 				 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13087 				 inserter, loc);
13088 
13089       Expression::check_bounds(start, OPERATOR_LE, end,
13090 			       Runtime::PANIC_SLICE_B,
13091 			       Runtime::PANIC_SLICE_B_U,
13092 			       Runtime::PANIC_EXTEND_SLICE_B,
13093 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13094 			       inserter, loc);
13095     }
13096   else if (end != NULL)
13097     {
13098       Expression* start_bound;
13099       if (array_type->is_slice_type())
13100 	start_bound = scap;
13101       else
13102 	start_bound = len;
13103       Expression::check_bounds(start, OPERATOR_LE, start_bound,
13104 			       Runtime::PANIC_SLICE_B,
13105 			       Runtime::PANIC_SLICE_B_U,
13106 			       Runtime::PANIC_EXTEND_SLICE_B,
13107 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13108 			       inserter, loc);
13109     }
13110   else
13111     Expression::check_bounds(start, OPERATOR_LT, len,
13112 			     Runtime::PANIC_INDEX,
13113 			     Runtime::PANIC_INDEX_U,
13114 			     Runtime::PANIC_EXTEND_INDEX,
13115 			     Runtime::PANIC_EXTEND_INDEX_U,
13116 			     inserter, loc);
13117 
13118   return this;
13119 }
13120 
13121 // Return whether this expression is addressable.
13122 
13123 bool
do_is_addressable() const13124 Array_index_expression::do_is_addressable() const
13125 {
13126   // A slice expression is not addressable.
13127   if (this->end_ != NULL)
13128     return false;
13129 
13130   // An index into a slice is addressable.
13131   if (this->array_->type()->is_slice_type())
13132     return true;
13133 
13134   // An index into an array is addressable if the array is
13135   // addressable.
13136   return this->array_->is_addressable();
13137 }
13138 
13139 void
do_address_taken(bool escapes)13140 Array_index_expression::do_address_taken(bool escapes)
13141 {
13142   // In &x[0], if x is a slice, then x's address is not taken.
13143   if (!this->array_->type()->is_slice_type())
13144     this->array_->address_taken(escapes);
13145 }
13146 
13147 // Get the backend representation for an array index.
13148 
13149 Bexpression*
do_get_backend(Translate_context * context)13150 Array_index_expression::do_get_backend(Translate_context* context)
13151 {
13152   Array_type* array_type = this->array_->type()->array_type();
13153   if (array_type == NULL)
13154     {
13155       go_assert(this->array_->type()->is_error());
13156       return context->backend()->error_expression();
13157     }
13158   go_assert(!array_type->is_slice_type() || this->array_->is_variable());
13159 
13160   Location loc = this->location();
13161   Gogo* gogo = context->gogo();
13162 
13163   Type* int_type = Type::lookup_integer_type("int");
13164   Btype* int_btype = int_type->get_backend(gogo);
13165 
13166   // Convert the length and capacity to "int".  FIXME: Do we need to
13167   // do this?
13168   Bexpression* length = NULL;
13169   if (this->end_ == NULL || this->end_->is_nil_expression())
13170     {
13171       Expression* len = array_type->get_length(gogo, this->array_);
13172       length = len->get_backend(context);
13173       length = gogo->backend()->convert_expression(int_btype, length, loc);
13174     }
13175 
13176   Bexpression* capacity = NULL;
13177   if (this->end_ != NULL)
13178     {
13179       Expression* cap = array_type->get_capacity(gogo, this->array_);
13180       capacity = cap->get_backend(context);
13181       capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
13182     }
13183 
13184   Bexpression* cap_arg = capacity;
13185   if (this->cap_ != NULL)
13186     {
13187       cap_arg = this->cap_->get_backend(context);
13188       cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
13189     }
13190 
13191   if (length == NULL)
13192     length = cap_arg;
13193 
13194   if (this->start_->type()->integer_type() == NULL
13195       && !Type::are_convertible(int_type, this->start_->type(), NULL))
13196     {
13197       go_assert(saw_errors());
13198       return context->backend()->error_expression();
13199     }
13200 
13201   Bexpression* start = this->start_->get_backend(context);
13202   start = gogo->backend()->convert_expression(int_btype, start, loc);
13203 
13204   Bfunction* bfn = context->function()->func_value()->get_decl();
13205   if (this->end_ == NULL)
13206     {
13207       // Simple array indexing.
13208       Bexpression* ret;
13209       if (!array_type->is_slice_type())
13210 	{
13211 	  Bexpression* array = this->array_->get_backend(context);
13212 	  ret = gogo->backend()->array_index_expression(array, start, loc);
13213 	}
13214       else
13215 	{
13216 	  Expression* valptr =
13217               array_type->get_value_pointer(gogo, this->array_,
13218                                             this->is_lvalue_);
13219 	  Bexpression* ptr = valptr->get_backend(context);
13220           ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
13221 
13222 	  Type* ele_type = this->array_->type()->array_type()->element_type();
13223 	  Btype* ele_btype = ele_type->get_backend(gogo);
13224 	  ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
13225 	}
13226       return ret;
13227     }
13228 
13229   // Slice expression.
13230 
13231   Bexpression* end;
13232   if (this->end_->is_nil_expression())
13233     end = length;
13234   else
13235     {
13236       end = this->end_->get_backend(context);
13237       end = gogo->backend()->convert_expression(int_btype, end, loc);
13238     }
13239 
13240   Bexpression* result_length =
13241     gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
13242 
13243   Bexpression* result_capacity =
13244     gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
13245 
13246   // If the new capacity is zero, don't change val.  Otherwise we can
13247   // get a pointer to the next object in memory, keeping it live
13248   // unnecessarily.  When the capacity is zero, the actual pointer
13249   // value doesn't matter.
13250   Bexpression* zero =
13251     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13252   Bexpression* cond =
13253     gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
13254 				       loc);
13255   Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
13256 								cond, zero,
13257 								start, loc);
13258   Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
13259                                                      this->is_lvalue_);
13260   Bexpression* val = valptr->get_backend(context);
13261   val = gogo->backend()->pointer_offset_expression(val, offset, loc);
13262 
13263   Btype* struct_btype = this->type()->get_backend(gogo);
13264   std::vector<Bexpression*> init;
13265   init.push_back(val);
13266   init.push_back(result_length);
13267   init.push_back(result_capacity);
13268 
13269   return gogo->backend()->constructor_expression(struct_btype, init, loc);
13270 }
13271 
13272 // Export an array index expression.
13273 
13274 void
do_export(Export_function_body * efb) const13275 Array_index_expression::do_export(Export_function_body* efb) const
13276 {
13277   efb->write_c_string("(");
13278   this->array_->export_expression(efb);
13279   efb->write_c_string(")[");
13280 
13281   Type* old_context = efb->type_context();
13282   efb->set_type_context(Type::lookup_integer_type("int"));
13283 
13284   this->start_->export_expression(efb);
13285   if (this->end_ == NULL)
13286     go_assert(this->cap_ == NULL);
13287   else
13288     {
13289       efb->write_c_string(":");
13290       if (!this->end_->is_nil_expression())
13291 	this->end_->export_expression(efb);
13292       if (this->cap_ != NULL)
13293 	{
13294 	  efb->write_c_string(":");
13295 	  this->cap_->export_expression(efb);
13296 	}
13297     }
13298 
13299   efb->set_type_context(old_context);
13300 
13301   efb->write_c_string("]");
13302 }
13303 
13304 // Dump ast representation for an array index expression.
13305 
13306 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13307 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13308     const
13309 {
13310   Index_expression::dump_index_expression(ast_dump_context, this->array_,
13311                                           this->start_, this->end_, this->cap_);
13312 }
13313 
13314 // Make an array index expression.  END and CAP may be NULL.
13315 
13316 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)13317 Expression::make_array_index(Expression* array, Expression* start,
13318                              Expression* end, Expression* cap,
13319                              Location location)
13320 {
13321   return new Array_index_expression(array, start, end, cap, location);
13322 }
13323 
13324 // Class String_index_expression.
13325 
13326 // String index traversal.
13327 
13328 int
do_traverse(Traverse * traverse)13329 String_index_expression::do_traverse(Traverse* traverse)
13330 {
13331   if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
13332     return TRAVERSE_EXIT;
13333   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
13334     return TRAVERSE_EXIT;
13335   if (this->end_ != NULL)
13336     {
13337       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13338 	return TRAVERSE_EXIT;
13339     }
13340   return TRAVERSE_CONTINUE;
13341 }
13342 
13343 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13344 String_index_expression::do_flatten(Gogo*, Named_object*,
13345                                     Statement_inserter* inserter)
13346 {
13347   if (this->is_flattened_)
13348     return this;
13349   this->is_flattened_ = true;
13350 
13351   Location loc = this->location();
13352 
13353   if (this->is_error_expression())
13354     return Expression::make_error(loc);
13355 
13356   Expression* string = this->string_;
13357   Expression* start = this->start_;
13358   Expression* end = this->end_;
13359   if (string->is_error_expression()
13360       || string->type()->is_error_type()
13361       || start->is_error_expression()
13362       || start->type()->is_error_type()
13363       || (end != NULL
13364           && (end->is_error_expression() || end->type()->is_error_type())))
13365     {
13366       go_assert(saw_errors());
13367       return Expression::make_error(loc);
13368     }
13369 
13370   Temporary_statement* temp;
13371   if (!string->is_variable())
13372     {
13373       temp = Statement::make_temporary(NULL, string, loc);
13374       inserter->insert(temp);
13375       this->string_ = Expression::make_temporary_reference(temp, loc);
13376       string = this->string_;
13377     }
13378   if (!start->is_variable())
13379     {
13380       temp = Statement::make_temporary(NULL, start, loc);
13381       inserter->insert(temp);
13382       this->start_ = Expression::make_temporary_reference(temp, loc);
13383       start = this->start_;
13384     }
13385   if (end != NULL
13386       && !end->is_nil_expression()
13387       && !end->is_variable())
13388     {
13389       temp = Statement::make_temporary(NULL, end, loc);
13390       inserter->insert(temp);
13391       this->end_ = Expression::make_temporary_reference(temp, loc);
13392       end = this->end_;
13393     }
13394 
13395   Expression* len = Expression::make_string_info(string->copy(),
13396 						 STRING_INFO_LENGTH, loc);
13397   temp = Statement::make_temporary(NULL, len, loc);
13398   inserter->insert(temp);
13399   len = Expression::make_temporary_reference(temp, loc);
13400 
13401   // The order of bounds checks here matches the order used by the gc
13402   // compiler, as tested by issue30116[u].go.
13403 
13404   if (end != NULL && !end->is_nil_expression())
13405     {
13406       Expression::check_bounds(end, OPERATOR_LE, len,
13407 			       Runtime::PANIC_SLICE_ALEN,
13408 			       Runtime::PANIC_SLICE_ALEN_U,
13409 			       Runtime::PANIC_EXTEND_SLICE_ALEN,
13410 			       Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13411 			       inserter, loc);
13412       Expression::check_bounds(start, OPERATOR_LE, end,
13413 			       Runtime::PANIC_SLICE_B,
13414 			       Runtime::PANIC_SLICE_B_U,
13415 			       Runtime::PANIC_EXTEND_SLICE_B,
13416 			       Runtime::PANIC_EXTEND_SLICE_B_U,
13417 			       inserter, loc);
13418     }
13419   else if (end != NULL)
13420     Expression::check_bounds(start, OPERATOR_LE, len,
13421 			     Runtime::PANIC_SLICE_B,
13422 			     Runtime::PANIC_SLICE_B_U,
13423 			     Runtime::PANIC_EXTEND_SLICE_B,
13424 			     Runtime::PANIC_EXTEND_SLICE_B_U,
13425 			     inserter, loc);
13426   else
13427     Expression::check_bounds(start, OPERATOR_LT, len,
13428 			     Runtime::PANIC_INDEX,
13429 			     Runtime::PANIC_INDEX_U,
13430 			     Runtime::PANIC_EXTEND_INDEX,
13431 			     Runtime::PANIC_EXTEND_INDEX_U,
13432 			     inserter, loc);
13433 
13434   return this;
13435 }
13436 
13437 // Return the type of a string index.
13438 
13439 Type*
do_type()13440 String_index_expression::do_type()
13441 {
13442   if (this->end_ == NULL)
13443     return Type::lookup_integer_type("uint8");
13444   else
13445     return this->string_->type();
13446 }
13447 
13448 // Determine the type of a string index.
13449 
13450 void
do_determine_type(const Type_context *)13451 String_index_expression::do_determine_type(const Type_context*)
13452 {
13453   this->string_->determine_type_no_context();
13454 
13455   Type_context index_context(Type::lookup_integer_type("int"), false);
13456   if (this->start_->is_constant())
13457     this->start_->determine_type(&index_context);
13458   else
13459     this->start_->determine_type_no_context();
13460   if (this->end_ != NULL)
13461     {
13462       if (this->end_->is_constant())
13463         this->end_->determine_type(&index_context);
13464       else
13465         this->end_->determine_type_no_context();
13466     }
13467 }
13468 
13469 // Check types of a string index.
13470 
13471 void
do_check_types(Gogo *)13472 String_index_expression::do_check_types(Gogo*)
13473 {
13474   Numeric_constant nc;
13475   unsigned long v;
13476   if (this->start_->type()->integer_type() == NULL
13477       && !this->start_->type()->is_error()
13478       && (!this->start_->type()->is_abstract()
13479 	  || !this->start_->numeric_constant_value(&nc)
13480 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13481     this->report_error(_("index must be integer"));
13482   if (this->end_ != NULL
13483       && this->end_->type()->integer_type() == NULL
13484       && !this->end_->type()->is_error()
13485       && !this->end_->is_nil_expression()
13486       && !this->end_->is_error_expression()
13487       && (!this->end_->type()->is_abstract()
13488 	  || !this->end_->numeric_constant_value(&nc)
13489 	  || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13490     this->report_error(_("slice end must be integer"));
13491 
13492   std::string sval;
13493   bool sval_valid = this->string_->string_constant_value(&sval);
13494 
13495   Numeric_constant inc;
13496   mpz_t ival;
13497   bool ival_valid = false;
13498   if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
13499     {
13500       ival_valid = true;
13501       if (mpz_sgn(ival) < 0
13502 	  || (sval_valid
13503 	      && (this->end_ == NULL
13504 		  ? mpz_cmp_ui(ival, sval.length()) >= 0
13505 		  : mpz_cmp_ui(ival, sval.length()) > 0)))
13506 	{
13507 	  go_error_at(this->start_->location(), "string index out of bounds");
13508 	  this->set_is_error();
13509 	}
13510     }
13511   if (this->end_ != NULL && !this->end_->is_nil_expression())
13512     {
13513       Numeric_constant enc;
13514       mpz_t eval;
13515       if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
13516 	{
13517 	  if (mpz_sgn(eval) < 0
13518 	      || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
13519 	    {
13520 	      go_error_at(this->end_->location(), "string index out of bounds");
13521 	      this->set_is_error();
13522 	    }
13523 	  else if (ival_valid && mpz_cmp(ival, eval) > 0)
13524 	    this->report_error(_("inverted slice range"));
13525 	  mpz_clear(eval);
13526 	}
13527     }
13528   if (ival_valid)
13529     mpz_clear(ival);
13530 }
13531 
13532 // Get the backend representation for a string index.
13533 
13534 Bexpression*
do_get_backend(Translate_context * context)13535 String_index_expression::do_get_backend(Translate_context* context)
13536 {
13537   Location loc = this->location();
13538   Gogo* gogo = context->gogo();
13539 
13540   Type* int_type = Type::lookup_integer_type("int");
13541 
13542   // It is possible that an error occurred earlier because the start index
13543   // cannot be represented as an integer type.  In this case, we shouldn't
13544   // try casting the starting index into an integer since
13545   // Type_conversion_expression will fail to get the backend representation.
13546   // FIXME.
13547   if (this->start_->type()->integer_type() == NULL
13548       && !Type::are_convertible(int_type, this->start_->type(), NULL))
13549     {
13550       go_assert(saw_errors());
13551       return context->backend()->error_expression();
13552     }
13553 
13554   go_assert(this->string_->is_variable());
13555   go_assert(this->start_->is_variable());
13556 
13557   Expression* start = Expression::make_cast(int_type, this->start_, loc);
13558   Bfunction* bfn = context->function()->func_value()->get_decl();
13559 
13560   Expression* length =
13561     Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
13562   Expression* bytes =
13563     Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
13564 
13565   Bexpression* bstart = start->get_backend(context);
13566   Bexpression* ptr = bytes->get_backend(context);
13567 
13568   if (this->end_ == NULL)
13569     {
13570       ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
13571       Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
13572       return gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
13573     }
13574 
13575   Expression* end = NULL;
13576   if (this->end_->is_nil_expression())
13577     end = length;
13578   else
13579     {
13580       go_assert(this->end_->is_variable());
13581       end = Expression::make_cast(int_type, this->end_, loc);
13582     }
13583 
13584   end = end->copy();
13585   Bexpression* bend = end->get_backend(context);
13586   Bexpression* new_length =
13587     gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
13588 
13589   // If the new length is zero, don't change pointer.  Otherwise we can
13590   // get a pointer to the next object in memory, keeping it live
13591   // unnecessarily.  When the length is zero, the actual pointer
13592   // value doesn't matter.
13593   Btype* int_btype = int_type->get_backend(gogo);
13594   Bexpression* zero =
13595     Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13596   Bexpression* cond =
13597     gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
13598                                        loc);
13599   Bexpression* offset =
13600     gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
13601                                             bstart, loc);
13602 
13603   ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
13604 
13605   Btype* str_btype = this->type()->get_backend(gogo);
13606   std::vector<Bexpression*> init;
13607   init.push_back(ptr);
13608   init.push_back(new_length);
13609   return gogo->backend()->constructor_expression(str_btype, init, loc);
13610 }
13611 
13612 // Export a string index expression.
13613 
13614 void
do_export(Export_function_body * efb) const13615 String_index_expression::do_export(Export_function_body* efb) const
13616 {
13617   efb->write_c_string("(");
13618   this->string_->export_expression(efb);
13619   efb->write_c_string(")[");
13620 
13621   Type* old_context = efb->type_context();
13622   efb->set_type_context(Type::lookup_integer_type("int"));
13623 
13624   this->start_->export_expression(efb);
13625   if (this->end_ != NULL)
13626     {
13627       efb->write_c_string(":");
13628       if (!this->end_->is_nil_expression())
13629 	this->end_->export_expression(efb);
13630     }
13631 
13632   efb->set_type_context(old_context);
13633 
13634   efb->write_c_string("]");
13635 }
13636 
13637 // Dump ast representation for a string index expression.
13638 
13639 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13640 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13641     const
13642 {
13643   Index_expression::dump_index_expression(ast_dump_context, this->string_,
13644                                           this->start_, this->end_, NULL);
13645 }
13646 
13647 // Make a string index expression.  END may be NULL.
13648 
13649 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)13650 Expression::make_string_index(Expression* string, Expression* start,
13651 			      Expression* end, Location location)
13652 {
13653   return new String_index_expression(string, start, end, location);
13654 }
13655 
13656 // Class Map_index.
13657 
13658 // Get the type of the map.
13659 
13660 Map_type*
get_map_type() const13661 Map_index_expression::get_map_type() const
13662 {
13663   Map_type* mt = this->map_->type()->map_type();
13664   if (mt == NULL)
13665     go_assert(saw_errors());
13666   return mt;
13667 }
13668 
13669 // Map index traversal.
13670 
13671 int
do_traverse(Traverse * traverse)13672 Map_index_expression::do_traverse(Traverse* traverse)
13673 {
13674   if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
13675     return TRAVERSE_EXIT;
13676   return Expression::traverse(&this->index_, traverse);
13677 }
13678 
13679 // We need to pass in a pointer to the key, so flatten the index into a
13680 // temporary variable if it isn't already.  The value pointer will be
13681 // dereferenced and checked for nil, so flatten into a temporary to avoid
13682 // recomputation.
13683 
13684 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13685 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
13686 				 Statement_inserter* inserter)
13687 {
13688   Location loc = this->location();
13689   Map_type* mt = this->get_map_type();
13690   if (this->index()->is_error_expression()
13691       || this->index()->type()->is_error_type()
13692       || mt->is_error_type())
13693     {
13694       go_assert(saw_errors());
13695       return Expression::make_error(loc);
13696     }
13697 
13698   // Avoid copy for string([]byte) conversions used in map keys.
13699   // mapaccess doesn't keep the reference, so this is safe.
13700   Type_conversion_expression* ce = this->index_->conversion_expression();
13701   if (ce != NULL && ce->type()->is_string_type()
13702       && ce->expr()->type()->is_slice_type())
13703     ce->set_no_copy(true);
13704 
13705   if (!Type::are_identical(mt->key_type(), this->index_->type(),
13706 			   Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
13707 			   NULL))
13708     {
13709       if (this->index_->type()->interface_type() != NULL
13710 	  && !this->index_->is_variable())
13711 	{
13712 	  Temporary_statement* temp =
13713 	    Statement::make_temporary(NULL, this->index_, loc);
13714 	  inserter->insert(temp);
13715 	  this->index_ = Expression::make_temporary_reference(temp, loc);
13716 	}
13717       this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
13718 							this->index_, loc);
13719     }
13720 
13721   if (!this->index_->is_variable())
13722     {
13723       Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
13724                                                             loc);
13725       inserter->insert(temp);
13726       this->index_ = Expression::make_temporary_reference(temp, loc);
13727     }
13728 
13729   if (this->value_pointer_ == NULL)
13730     this->get_value_pointer(gogo);
13731   if (this->value_pointer_->is_error_expression()
13732       || this->value_pointer_->type()->is_error_type())
13733     return Expression::make_error(loc);
13734   if (!this->value_pointer_->is_variable())
13735     {
13736       Temporary_statement* temp =
13737 	Statement::make_temporary(NULL, this->value_pointer_, loc);
13738       inserter->insert(temp);
13739       this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
13740     }
13741 
13742   return this;
13743 }
13744 
13745 // Return the type of a map index.
13746 
13747 Type*
do_type()13748 Map_index_expression::do_type()
13749 {
13750   Map_type* mt = this->get_map_type();
13751   if (mt == NULL)
13752     return Type::make_error_type();
13753   return mt->val_type();
13754 }
13755 
13756 // Fix the type of a map index.
13757 
13758 void
do_determine_type(const Type_context *)13759 Map_index_expression::do_determine_type(const Type_context*)
13760 {
13761   this->map_->determine_type_no_context();
13762   Map_type* mt = this->get_map_type();
13763   Type* key_type = mt == NULL ? NULL : mt->key_type();
13764   Type_context subcontext(key_type, false);
13765   this->index_->determine_type(&subcontext);
13766 }
13767 
13768 // Check types of a map index.
13769 
13770 void
do_check_types(Gogo *)13771 Map_index_expression::do_check_types(Gogo*)
13772 {
13773   std::string reason;
13774   Map_type* mt = this->get_map_type();
13775   if (mt == NULL)
13776     return;
13777   if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
13778     {
13779       if (reason.empty())
13780 	this->report_error(_("incompatible type for map index"));
13781       else
13782 	{
13783 	  go_error_at(this->location(), "incompatible type for map index (%s)",
13784                       reason.c_str());
13785 	  this->set_is_error();
13786 	}
13787     }
13788 }
13789 
13790 // Add explicit type conversions.
13791 
13792 void
do_add_conversions()13793 Map_index_expression::do_add_conversions()
13794 {
13795   Map_type* mt = this->get_map_type();
13796   if (mt == NULL)
13797     return;
13798   Type* lt = mt->key_type();
13799   Type* rt = this->index_->type();
13800   if (!Type::are_identical(lt, rt, 0, NULL)
13801       && lt->interface_type() != NULL)
13802     this->index_ = Expression::make_cast(lt, this->index_, this->location());
13803 }
13804 
13805 // Get the backend representation for a map index.
13806 
13807 Bexpression*
do_get_backend(Translate_context * context)13808 Map_index_expression::do_get_backend(Translate_context* context)
13809 {
13810   Map_type* type = this->get_map_type();
13811   if (type == NULL)
13812     {
13813       go_assert(saw_errors());
13814       return context->backend()->error_expression();
13815     }
13816 
13817   go_assert(this->value_pointer_ != NULL
13818             && this->value_pointer_->is_variable());
13819 
13820   Expression* val = Expression::make_dereference(this->value_pointer_,
13821                                                  NIL_CHECK_NOT_NEEDED,
13822                                                  this->location());
13823   return val->get_backend(context);
13824 }
13825 
13826 // Get an expression for the map index.  This returns an expression
13827 // that evaluates to a pointer to a value.  If the key is not in the
13828 // map, the pointer will point to a zero value.
13829 
13830 Expression*
get_value_pointer(Gogo * gogo)13831 Map_index_expression::get_value_pointer(Gogo* gogo)
13832 {
13833   if (this->value_pointer_ == NULL)
13834     {
13835       Map_type* type = this->get_map_type();
13836       if (type == NULL)
13837 	{
13838 	  go_assert(saw_errors());
13839 	  return Expression::make_error(this->location());
13840 	}
13841 
13842       Location loc = this->location();
13843       Expression* map_ref = this->map_;
13844 
13845       Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
13846 						     this->index_,
13847                                                      loc);
13848 
13849       Expression* type_expr = Expression::make_type_descriptor(type, loc);
13850       Expression* zero = type->fat_zero_value(gogo);
13851       Expression* map_index;
13852       if (zero == NULL)
13853         {
13854           Runtime::Function code;
13855           Expression* key;
13856           switch (type->algorithm(gogo))
13857             {
13858               case Map_type::MAP_ALG_FAST32:
13859               case Map_type::MAP_ALG_FAST32PTR:
13860                 {
13861                   Type* uint32_type = Type::lookup_integer_type("uint32");
13862                   Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
13863                   key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
13864                                                      loc);
13865                   key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13866                                                      loc);
13867                   code = Runtime::MAPACCESS1_FAST32;
13868                   break;
13869                 }
13870               case Map_type::MAP_ALG_FAST64:
13871               case Map_type::MAP_ALG_FAST64PTR:
13872                 {
13873                   Type* uint64_type = Type::lookup_integer_type("uint64");
13874                   Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
13875                   key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
13876                                                      loc);
13877                   key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13878                                                      loc);
13879                   code = Runtime::MAPACCESS1_FAST64;
13880                   break;
13881                 }
13882               case Map_type::MAP_ALG_FASTSTR:
13883                 key = this->index_;
13884                 code = Runtime::MAPACCESS1_FASTSTR;
13885                 break;
13886               default:
13887                 key = index_ptr;
13888                 code = Runtime::MAPACCESS1;
13889                 break;
13890             }
13891           map_index = Runtime::make_call(code, loc, 3,
13892                                          type_expr, map_ref, key);
13893         }
13894       else
13895         map_index = Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
13896                                        type_expr, map_ref, index_ptr, zero);
13897 
13898       Type* val_type = type->val_type();
13899       this->value_pointer_ =
13900           Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
13901                                        map_index, this->location());
13902     }
13903 
13904   return this->value_pointer_;
13905 }
13906 
13907 // Export a map index expression.
13908 
13909 void
do_export(Export_function_body * efb) const13910 Map_index_expression::do_export(Export_function_body* efb) const
13911 {
13912   efb->write_c_string("(");
13913   this->map_->export_expression(efb);
13914   efb->write_c_string(")[");
13915 
13916   Type* old_context = efb->type_context();
13917   efb->set_type_context(this->get_map_type()->key_type());
13918 
13919   this->index_->export_expression(efb);
13920 
13921   efb->set_type_context(old_context);
13922 
13923   efb->write_c_string("]");
13924 }
13925 
13926 // Dump ast representation for a map index expression
13927 
13928 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13929 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13930     const
13931 {
13932   Index_expression::dump_index_expression(ast_dump_context, this->map_,
13933                                           this->index_, NULL, NULL);
13934 }
13935 
13936 // Make a map index expression.
13937 
13938 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)13939 Expression::make_map_index(Expression* map, Expression* index,
13940 			   Location location)
13941 {
13942   return new Map_index_expression(map, index, location);
13943 }
13944 
13945 // Class Field_reference_expression.
13946 
13947 // Lower a field reference expression.  There is nothing to lower, but
13948 // this is where we generate the tracking information for fields with
13949 // the magic go:"track" tag.
13950 
13951 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)13952 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
13953 				     Statement_inserter* inserter, int)
13954 {
13955   Struct_type* struct_type = this->expr_->type()->struct_type();
13956   if (struct_type == NULL)
13957     {
13958       // Error will be reported elsewhere.
13959       return this;
13960     }
13961   const Struct_field* field = struct_type->field(this->field_index_);
13962   if (field == NULL)
13963     return this;
13964   if (!field->has_tag())
13965     return this;
13966   if (field->tag().find("go:\"track\"") == std::string::npos)
13967     return this;
13968 
13969   // References from functions generated by the compiler don't count.
13970   if (function != NULL && function->func_value()->is_type_specific_function())
13971     return this;
13972 
13973   // We have found a reference to a tracked field.  Build a call to
13974   // the runtime function __go_fieldtrack with a string that describes
13975   // the field.  FIXME: We should only call this once per referenced
13976   // field per function, not once for each reference to the field.
13977 
13978   if (this->called_fieldtrack_)
13979     return this;
13980   this->called_fieldtrack_ = true;
13981 
13982   Location loc = this->location();
13983 
13984   std::string s = "fieldtrack \"";
13985   Named_type* nt = this->expr_->type()->unalias()->named_type();
13986   if (nt == NULL || nt->named_object()->package() == NULL)
13987     s.append(gogo->pkgpath());
13988   else
13989     s.append(nt->named_object()->package()->pkgpath());
13990   s.push_back('.');
13991   if (nt != NULL)
13992     s.append(Gogo::unpack_hidden_name(nt->name()));
13993   s.push_back('.');
13994   s.append(Gogo::unpack_hidden_name(field->field_name()));
13995   s.push_back('"');
13996 
13997   // We can't use a string here, because internally a string holds a
13998   // pointer to the actual bytes; when the linker garbage collects the
13999   // string, it won't garbage collect the bytes.  So we use a
14000   // [...]byte.
14001 
14002   Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
14003 
14004   Type* byte_type = gogo->lookup_global("byte")->type_value();
14005   Array_type* array_type = Type::make_array_type(byte_type, length_expr);
14006   array_type->set_is_array_incomparable();
14007 
14008   Expression_list* bytes = new Expression_list();
14009   for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
14010     {
14011       unsigned char c = static_cast<unsigned char>(*p);
14012       bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
14013     }
14014 
14015   Expression* e = Expression::make_composite_literal(array_type, 0, false,
14016 						     bytes, false, loc);
14017 
14018   Variable* var = new Variable(array_type, e, true, false, false, loc);
14019 
14020   static int count;
14021   char buf[50];
14022   snprintf(buf, sizeof buf, "fieldtrack.%d", count);
14023   ++count;
14024 
14025   Named_object* no = gogo->add_variable(buf, var);
14026   e = Expression::make_var_reference(no, loc);
14027   e = Expression::make_unary(OPERATOR_AND, e, loc);
14028 
14029   Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
14030   gogo->lower_expression(function, inserter, &call);
14031   inserter->insert(Statement::make_statement(call, false));
14032 
14033   // Put this function, and the global variable we just created, into
14034   // unique sections.  This will permit the linker to garbage collect
14035   // them if they are not referenced.  The effect is that the only
14036   // strings, indicating field references, that will wind up in the
14037   // executable will be those for functions that are actually needed.
14038   if (function != NULL)
14039     function->func_value()->set_in_unique_section();
14040   var->set_in_unique_section();
14041 
14042   return this;
14043 }
14044 
14045 // Return the type of a field reference.
14046 
14047 Type*
do_type()14048 Field_reference_expression::do_type()
14049 {
14050   Type* type = this->expr_->type();
14051   if (type->is_error())
14052     return type;
14053   Struct_type* struct_type = type->struct_type();
14054   go_assert(struct_type != NULL);
14055   return struct_type->field(this->field_index_)->type();
14056 }
14057 
14058 // Check the types for a field reference.
14059 
14060 void
do_check_types(Gogo *)14061 Field_reference_expression::do_check_types(Gogo*)
14062 {
14063   Type* type = this->expr_->type();
14064   if (type->is_error())
14065     return;
14066   Struct_type* struct_type = type->struct_type();
14067   go_assert(struct_type != NULL);
14068   go_assert(struct_type->field(this->field_index_) != NULL);
14069 }
14070 
14071 // Get the backend representation for a field reference.
14072 
14073 Bexpression*
do_get_backend(Translate_context * context)14074 Field_reference_expression::do_get_backend(Translate_context* context)
14075 {
14076   Bexpression* bstruct = this->expr_->get_backend(context);
14077   return context->gogo()->backend()->struct_field_expression(bstruct,
14078 							     this->field_index_,
14079 							     this->location());
14080 }
14081 
14082 // Dump ast representation for a field reference expression.
14083 
14084 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14085 Field_reference_expression::do_dump_expression(
14086     Ast_dump_context* ast_dump_context) const
14087 {
14088   this->expr_->dump_expression(ast_dump_context);
14089   ast_dump_context->ostream() << "." <<  this->field_index_;
14090 }
14091 
14092 // Make a reference to a qualified identifier in an expression.
14093 
14094 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)14095 Expression::make_field_reference(Expression* expr, unsigned int field_index,
14096 				 Location location)
14097 {
14098   return new Field_reference_expression(expr, field_index, location);
14099 }
14100 
14101 // Class Interface_field_reference_expression.
14102 
14103 // Return an expression for the pointer to the function to call.
14104 
14105 Expression*
get_function()14106 Interface_field_reference_expression::get_function()
14107 {
14108   Expression* ref = this->expr_;
14109   Location loc = this->location();
14110   if (ref->type()->points_to() != NULL)
14111     ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
14112 
14113   Expression* mtable =
14114       Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
14115   Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
14116 
14117   std::string name = Gogo::unpack_hidden_name(this->name_);
14118   unsigned int index;
14119   const Struct_field* field = mtable_type->find_local_field(name, &index);
14120   go_assert(field != NULL);
14121 
14122   mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
14123   return Expression::make_field_reference(mtable, index, loc);
14124 }
14125 
14126 // Return an expression for the first argument to pass to the interface
14127 // function.
14128 
14129 Expression*
get_underlying_object()14130 Interface_field_reference_expression::get_underlying_object()
14131 {
14132   Expression* expr = this->expr_;
14133   if (expr->type()->points_to() != NULL)
14134     expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
14135                                         this->location());
14136   return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
14137                                          this->location());
14138 }
14139 
14140 // Traversal.
14141 
14142 int
do_traverse(Traverse * traverse)14143 Interface_field_reference_expression::do_traverse(Traverse* traverse)
14144 {
14145   return Expression::traverse(&this->expr_, traverse);
14146 }
14147 
14148 // Lower the expression.  If this expression is not called, we need to
14149 // evaluate the expression twice when converting to the backend
14150 // interface.  So introduce a temporary variable if necessary.
14151 
14152 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14153 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
14154 						 Statement_inserter* inserter)
14155 {
14156   if (this->expr_->is_error_expression()
14157       || this->expr_->type()->is_error_type())
14158     {
14159       go_assert(saw_errors());
14160       return Expression::make_error(this->location());
14161     }
14162 
14163   if (!this->expr_->is_variable())
14164     {
14165       Temporary_statement* temp =
14166 	Statement::make_temporary(NULL, this->expr_, this->location());
14167       inserter->insert(temp);
14168       this->expr_ = Expression::make_temporary_reference(temp, this->location());
14169     }
14170   return this;
14171 }
14172 
14173 // Return the type of an interface field reference.
14174 
14175 Type*
do_type()14176 Interface_field_reference_expression::do_type()
14177 {
14178   Type* expr_type = this->expr_->type();
14179 
14180   Type* points_to = expr_type->points_to();
14181   if (points_to != NULL)
14182     expr_type = points_to;
14183 
14184   Interface_type* interface_type = expr_type->interface_type();
14185   if (interface_type == NULL)
14186     return Type::make_error_type();
14187 
14188   const Typed_identifier* method = interface_type->find_method(this->name_);
14189   if (method == NULL)
14190     return Type::make_error_type();
14191 
14192   return method->type();
14193 }
14194 
14195 // Determine types.
14196 
14197 void
do_determine_type(const Type_context *)14198 Interface_field_reference_expression::do_determine_type(const Type_context*)
14199 {
14200   this->expr_->determine_type_no_context();
14201 }
14202 
14203 // Check the types for an interface field reference.
14204 
14205 void
do_check_types(Gogo *)14206 Interface_field_reference_expression::do_check_types(Gogo*)
14207 {
14208   Type* type = this->expr_->type();
14209 
14210   Type* points_to = type->points_to();
14211   if (points_to != NULL)
14212     type = points_to;
14213 
14214   Interface_type* interface_type = type->interface_type();
14215   if (interface_type == NULL)
14216     {
14217       if (!type->is_error_type())
14218 	this->report_error(_("expected interface or pointer to interface"));
14219     }
14220   else
14221     {
14222       const Typed_identifier* method =
14223 	interface_type->find_method(this->name_);
14224       if (method == NULL)
14225 	{
14226 	  go_error_at(this->location(), "method %qs not in interface",
14227                       Gogo::message_name(this->name_).c_str());
14228 	  this->set_is_error();
14229 	}
14230     }
14231 }
14232 
14233 // If an interface field reference is not simply called, then it is
14234 // represented as a closure.  The closure will hold a single variable,
14235 // the value of the interface on which the method should be called.
14236 // The function will be a simple thunk that pulls the value from the
14237 // closure and calls the method with the remaining arguments.
14238 
14239 // Because method values are not common, we don't build all thunks for
14240 // all possible interface methods, but instead only build them as we
14241 // need them.  In particular, we even build them on demand for
14242 // interface methods defined in other packages.
14243 
14244 Interface_field_reference_expression::Interface_method_thunks
14245   Interface_field_reference_expression::interface_method_thunks;
14246 
14247 // Find or create the thunk to call method NAME on TYPE.
14248 
14249 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)14250 Interface_field_reference_expression::create_thunk(Gogo* gogo,
14251 						   Interface_type* type,
14252 						   const std::string& name)
14253 {
14254   std::pair<Interface_type*, Method_thunks*> val(type, NULL);
14255   std::pair<Interface_method_thunks::iterator, bool> ins =
14256     Interface_field_reference_expression::interface_method_thunks.insert(val);
14257   if (ins.second)
14258     {
14259       // This is the first time we have seen this interface.
14260       ins.first->second = new Method_thunks();
14261     }
14262 
14263   for (Method_thunks::const_iterator p = ins.first->second->begin();
14264        p != ins.first->second->end();
14265        p++)
14266     if (p->first == name)
14267       return p->second;
14268 
14269   Location loc = type->location();
14270 
14271   const Typed_identifier* method_id = type->find_method(name);
14272   if (method_id == NULL)
14273     return Named_object::make_erroneous_name(gogo->thunk_name());
14274 
14275   Function_type* orig_fntype = method_id->type()->function_type();
14276   if (orig_fntype == NULL)
14277     return Named_object::make_erroneous_name(gogo->thunk_name());
14278 
14279   Struct_field_list* sfl = new Struct_field_list();
14280   // The type here is wrong--it should be the C function type.  But it
14281   // doesn't really matter.
14282   Type* vt = Type::make_pointer_type(Type::make_void_type());
14283   sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
14284   sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
14285   Struct_type* st = Type::make_struct_type(sfl, loc);
14286   st->set_is_struct_incomparable();
14287   Type* closure_type = Type::make_pointer_type(st);
14288 
14289   Function_type* new_fntype = orig_fntype->copy_with_names();
14290 
14291   std::string thunk_name = gogo->thunk_name();
14292   Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
14293 					      false, loc);
14294 
14295   Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
14296   cvar->set_is_used();
14297   cvar->set_is_closure();
14298   Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
14299 						 NULL, cvar);
14300   new_no->func_value()->set_closure_var(cp);
14301 
14302   gogo->start_block(loc);
14303 
14304   // Field 0 of the closure is the function code pointer, field 1 is
14305   // the value on which to invoke the method.
14306   Expression* arg = Expression::make_var_reference(cp, loc);
14307   arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
14308   arg = Expression::make_field_reference(arg, 1, loc);
14309 
14310   Expression *ifre = Expression::make_interface_field_reference(arg, name,
14311 								loc);
14312 
14313   const Typed_identifier_list* orig_params = orig_fntype->parameters();
14314   Expression_list* args;
14315   if (orig_params == NULL || orig_params->empty())
14316     args = NULL;
14317   else
14318     {
14319       const Typed_identifier_list* new_params = new_fntype->parameters();
14320       args = new Expression_list();
14321       for (Typed_identifier_list::const_iterator p = new_params->begin();
14322 	   p != new_params->end();
14323 	   ++p)
14324 	{
14325 	  Named_object* p_no = gogo->lookup(p->name(), NULL);
14326 	  go_assert(p_no != NULL
14327 		    && p_no->is_variable()
14328 		    && p_no->var_value()->is_parameter());
14329 	  args->push_back(Expression::make_var_reference(p_no, loc));
14330 	}
14331     }
14332 
14333   Call_expression* call = Expression::make_call(ifre, args,
14334 						orig_fntype->is_varargs(),
14335 						loc);
14336   call->set_varargs_are_lowered();
14337 
14338   Statement* s = Statement::make_return_from_call(call, loc);
14339   gogo->add_statement(s);
14340   Block* b = gogo->finish_block(loc);
14341   gogo->add_block(b, loc);
14342   gogo->lower_block(new_no, b);
14343   gogo->flatten_block(new_no, b);
14344   gogo->finish_function(loc);
14345 
14346   ins.first->second->push_back(std::make_pair(name, new_no));
14347   return new_no;
14348 }
14349 
14350 // Get the backend representation for a method value.
14351 
14352 Bexpression*
do_get_backend(Translate_context * context)14353 Interface_field_reference_expression::do_get_backend(Translate_context* context)
14354 {
14355   Interface_type* type = this->expr_->type()->interface_type();
14356   if (type == NULL)
14357     {
14358       go_assert(saw_errors());
14359       return context->backend()->error_expression();
14360     }
14361 
14362   Named_object* thunk =
14363     Interface_field_reference_expression::create_thunk(context->gogo(),
14364 						       type, this->name_);
14365   if (thunk->is_erroneous())
14366     {
14367       go_assert(saw_errors());
14368       return context->backend()->error_expression();
14369     }
14370 
14371   // FIXME: We should lower this earlier, but we can't it lower it in
14372   // the lowering pass because at that point we don't know whether we
14373   // need to create the thunk or not.  If the expression is called, we
14374   // don't need the thunk.
14375 
14376   Location loc = this->location();
14377 
14378   Struct_field_list* fields = new Struct_field_list();
14379   fields->push_back(Struct_field(Typed_identifier("fn",
14380 						  thunk->func_value()->type(),
14381 						  loc)));
14382   fields->push_back(Struct_field(Typed_identifier("val",
14383 						  this->expr_->type(),
14384 						  loc)));
14385   Struct_type* st = Type::make_struct_type(fields, loc);
14386   st->set_is_struct_incomparable();
14387 
14388   Expression_list* vals = new Expression_list();
14389   vals->push_back(Expression::make_func_code_reference(thunk, loc));
14390   vals->push_back(this->expr_);
14391 
14392   Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
14393   Bexpression* bclosure =
14394     Expression::make_heap_expression(expr, loc)->get_backend(context);
14395 
14396   Gogo* gogo = context->gogo();
14397   Btype* btype = this->type()->get_backend(gogo);
14398   bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
14399 
14400   Expression* nil_check =
14401       Expression::make_binary(OPERATOR_EQEQ, this->expr_,
14402                               Expression::make_nil(loc), loc);
14403   Bexpression* bnil_check = nil_check->get_backend(context);
14404 
14405   Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
14406   Bexpression* bcrash = crash->get_backend(context);
14407 
14408   Bfunction* bfn = context->function()->func_value()->get_decl();
14409   Bexpression* bcond =
14410       gogo->backend()->conditional_expression(bfn, NULL,
14411                                               bnil_check, bcrash, NULL, loc);
14412   Bfunction* bfunction = context->function()->func_value()->get_decl();
14413   Bstatement* cond_statement =
14414       gogo->backend()->expression_statement(bfunction, bcond);
14415   return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
14416 }
14417 
14418 // Dump ast representation for an interface field reference.
14419 
14420 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14421 Interface_field_reference_expression::do_dump_expression(
14422     Ast_dump_context* ast_dump_context) const
14423 {
14424   this->expr_->dump_expression(ast_dump_context);
14425   ast_dump_context->ostream() << "." << this->name_;
14426 }
14427 
14428 // Make a reference to a field in an interface.
14429 
14430 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)14431 Expression::make_interface_field_reference(Expression* expr,
14432 					   const std::string& field,
14433 					   Location location)
14434 {
14435   return new Interface_field_reference_expression(expr, field, location);
14436 }
14437 
14438 // A general selector.  This is a Parser_expression for LEFT.NAME.  It
14439 // is lowered after we know the type of the left hand side.
14440 
14441 class Selector_expression : public Parser_expression
14442 {
14443  public:
Selector_expression(Expression * left,const std::string & name,Location location)14444   Selector_expression(Expression* left, const std::string& name,
14445 		      Location location)
14446     : Parser_expression(EXPRESSION_SELECTOR, location),
14447       left_(left), name_(name)
14448   { }
14449 
14450  protected:
14451   int
do_traverse(Traverse * traverse)14452   do_traverse(Traverse* traverse)
14453   { return Expression::traverse(&this->left_, traverse); }
14454 
14455   Expression*
14456   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
14457 
14458   Expression*
do_copy()14459   do_copy()
14460   {
14461     return new Selector_expression(this->left_->copy(), this->name_,
14462 				   this->location());
14463   }
14464 
14465   void
14466   do_dump_expression(Ast_dump_context* ast_dump_context) const;
14467 
14468  private:
14469   Expression*
14470   lower_method_expression(Gogo*);
14471 
14472   // The expression on the left hand side.
14473   Expression* left_;
14474   // The name on the right hand side.
14475   std::string name_;
14476 };
14477 
14478 // Lower a selector expression once we know the real type of the left
14479 // hand side.
14480 
14481 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)14482 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
14483 			      int)
14484 {
14485   Expression* left = this->left_;
14486   if (left->is_type_expression())
14487     return this->lower_method_expression(gogo);
14488   return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
14489 				    this->location());
14490 }
14491 
14492 // Lower a method expression T.M or (*T).M.  We turn this into a
14493 // function literal.
14494 
14495 Expression*
lower_method_expression(Gogo * gogo)14496 Selector_expression::lower_method_expression(Gogo* gogo)
14497 {
14498   Location location = this->location();
14499   Type* left_type = this->left_->type();
14500   Type* type = left_type;
14501   const std::string& name(this->name_);
14502 
14503   bool is_pointer;
14504   if (type->points_to() == NULL)
14505     is_pointer = false;
14506   else
14507     {
14508       is_pointer = true;
14509       type = type->points_to();
14510     }
14511   Named_type* nt = type->named_type();
14512   if (nt == NULL)
14513     {
14514       go_error_at(location,
14515                   ("method expression requires named type or "
14516                    "pointer to named type"));
14517       return Expression::make_error(location);
14518     }
14519 
14520   bool is_ambiguous;
14521   Method* method = nt->method_function(name, &is_ambiguous);
14522   const Typed_identifier* imethod = NULL;
14523   if (method == NULL && !is_pointer)
14524     {
14525       Interface_type* it = nt->interface_type();
14526       if (it != NULL)
14527 	imethod = it->find_method(name);
14528     }
14529 
14530   if ((method == NULL && imethod == NULL)
14531       || (left_type->named_type() != NULL && left_type->points_to() != NULL))
14532     {
14533       if (!is_ambiguous)
14534 	go_error_at(location, "type %<%s%s%> has no method %<%s%>",
14535                     is_pointer ? "*" : "",
14536                     nt->message_name().c_str(),
14537                     Gogo::message_name(name).c_str());
14538       else
14539 	go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
14540                     Gogo::message_name(name).c_str(),
14541                     is_pointer ? "*" : "",
14542                     nt->message_name().c_str());
14543       return Expression::make_error(location);
14544     }
14545 
14546   if (method != NULL && !is_pointer && !method->is_value_method())
14547     {
14548       go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
14549                   nt->message_name().c_str(),
14550                   Gogo::message_name(name).c_str());
14551       return Expression::make_error(location);
14552     }
14553 
14554   // Build a new function type in which the receiver becomes the first
14555   // argument.
14556   Function_type* method_type;
14557   if (method != NULL)
14558     {
14559       method_type = method->type();
14560       go_assert(method_type->is_method());
14561     }
14562   else
14563     {
14564       method_type = imethod->type()->function_type();
14565       go_assert(method_type != NULL && !method_type->is_method());
14566     }
14567 
14568   const char* const receiver_name = "$this";
14569   Typed_identifier_list* parameters = new Typed_identifier_list();
14570   parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
14571 					 location));
14572 
14573   const Typed_identifier_list* method_parameters = method_type->parameters();
14574   if (method_parameters != NULL)
14575     {
14576       int i = 0;
14577       for (Typed_identifier_list::const_iterator p = method_parameters->begin();
14578 	   p != method_parameters->end();
14579 	   ++p, ++i)
14580 	{
14581 	  if (!p->name().empty())
14582 	    parameters->push_back(*p);
14583 	  else
14584 	    {
14585 	      char buf[20];
14586 	      snprintf(buf, sizeof buf, "$param%d", i);
14587 	      parameters->push_back(Typed_identifier(buf, p->type(),
14588 						     p->location()));
14589 	    }
14590 	}
14591     }
14592 
14593   const Typed_identifier_list* method_results = method_type->results();
14594   Typed_identifier_list* results;
14595   if (method_results == NULL)
14596     results = NULL;
14597   else
14598     {
14599       results = new Typed_identifier_list();
14600       for (Typed_identifier_list::const_iterator p = method_results->begin();
14601 	   p != method_results->end();
14602 	   ++p)
14603 	results->push_back(*p);
14604     }
14605 
14606   Function_type* fntype = Type::make_function_type(NULL, parameters, results,
14607 						   location);
14608   if (method_type->is_varargs())
14609     fntype->set_is_varargs();
14610 
14611   // We generate methods which always takes a pointer to the receiver
14612   // as their first argument.  If this is for a pointer type, we can
14613   // simply reuse the existing function.  We use an internal hack to
14614   // get the right type.
14615   // FIXME: This optimization is disabled because it doesn't yet work
14616   // with function descriptors when the method expression is not
14617   // directly called.
14618   if (method != NULL && is_pointer && false)
14619     {
14620       Named_object* mno = (method->needs_stub_method()
14621 			   ? method->stub_object()
14622 			   : method->named_object());
14623       Expression* f = Expression::make_func_reference(mno, NULL, location);
14624       f = Expression::make_cast(fntype, f, location);
14625       Type_conversion_expression* tce =
14626 	static_cast<Type_conversion_expression*>(f);
14627       tce->set_may_convert_function_types();
14628       return f;
14629     }
14630 
14631   Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
14632 					  location);
14633 
14634   Named_object* vno = gogo->lookup(receiver_name, NULL);
14635   go_assert(vno != NULL);
14636   Expression* ve = Expression::make_var_reference(vno, location);
14637   Expression* bm;
14638   if (method != NULL)
14639     bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
14640   else
14641     bm = Expression::make_interface_field_reference(ve, name, location);
14642 
14643   // Even though we found the method above, if it has an error type we
14644   // may see an error here.
14645   if (bm->is_error_expression())
14646     {
14647       gogo->finish_function(location);
14648       return bm;
14649     }
14650 
14651   Expression_list* args;
14652   if (parameters->size() <= 1)
14653     args = NULL;
14654   else
14655     {
14656       args = new Expression_list();
14657       Typed_identifier_list::const_iterator p = parameters->begin();
14658       ++p;
14659       for (; p != parameters->end(); ++p)
14660 	{
14661 	  vno = gogo->lookup(p->name(), NULL);
14662 	  go_assert(vno != NULL);
14663 	  args->push_back(Expression::make_var_reference(vno, location));
14664 	}
14665     }
14666 
14667   gogo->start_block(location);
14668 
14669   Call_expression* call = Expression::make_call(bm, args,
14670 						method_type->is_varargs(),
14671 						location);
14672 
14673   Statement* s = Statement::make_return_from_call(call, location);
14674   gogo->add_statement(s);
14675 
14676   Block* b = gogo->finish_block(location);
14677 
14678   gogo->add_block(b, location);
14679 
14680   // Lower the call in case there are multiple results.
14681   gogo->lower_block(no, b);
14682   gogo->flatten_block(no, b);
14683 
14684   gogo->finish_function(location);
14685 
14686   return Expression::make_func_reference(no, NULL, location);
14687 }
14688 
14689 // Dump the ast for a selector expression.
14690 
14691 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14692 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14693     const
14694 {
14695   ast_dump_context->dump_expression(this->left_);
14696   ast_dump_context->ostream() << ".";
14697   ast_dump_context->ostream() << this->name_;
14698 }
14699 
14700 // Make a selector expression.
14701 
14702 Expression*
make_selector(Expression * left,const std::string & name,Location location)14703 Expression::make_selector(Expression* left, const std::string& name,
14704 			  Location location)
14705 {
14706   return new Selector_expression(left, name, location);
14707 }
14708 
14709 // Class Allocation_expression.
14710 
14711 int
do_traverse(Traverse * traverse)14712 Allocation_expression::do_traverse(Traverse* traverse)
14713 {
14714   return Type::traverse(this->type_, traverse);
14715 }
14716 
14717 Type*
do_type()14718 Allocation_expression::do_type()
14719 {
14720   return Type::make_pointer_type(this->type_);
14721 }
14722 
14723 void
do_check_types(Gogo *)14724 Allocation_expression::do_check_types(Gogo*)
14725 {
14726   if (!this->type_->in_heap())
14727     go_error_at(this->location(), "cannot heap allocate go:notinheap type");
14728 }
14729 
14730 // Make a copy of an allocation expression.
14731 
14732 Expression*
do_copy()14733 Allocation_expression::do_copy()
14734 {
14735   Allocation_expression* alloc =
14736     new Allocation_expression(this->type_->copy_expressions(),
14737 			      this->location());
14738   if (this->allocate_on_stack_)
14739     alloc->set_allocate_on_stack();
14740   if (this->no_zero_)
14741     alloc->set_no_zero();
14742   return alloc;
14743 }
14744 
14745 // Return the backend representation for an allocation expression.
14746 
14747 Bexpression*
do_get_backend(Translate_context * context)14748 Allocation_expression::do_get_backend(Translate_context* context)
14749 {
14750   Gogo* gogo = context->gogo();
14751   Location loc = this->location();
14752   Btype* btype = this->type_->get_backend(gogo);
14753 
14754   if (this->allocate_on_stack_)
14755     {
14756       int64_t size;
14757       bool ok = this->type_->backend_type_size(gogo, &size);
14758       if (!ok)
14759         {
14760           go_assert(saw_errors());
14761           return gogo->backend()->error_expression();
14762         }
14763       Bstatement* decl;
14764       Named_object* fn = context->function();
14765       go_assert(fn != NULL);
14766       Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14767       Bexpression* init = (this->no_zero_
14768                            ? NULL
14769                            : gogo->backend()->zero_expression(btype));
14770       Bvariable* temp =
14771         gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14772                                             init, true, loc, &decl);
14773       Bexpression* ret = gogo->backend()->var_expression(temp, loc);
14774       ret = gogo->backend()->address_expression(ret, loc);
14775       ret = gogo->backend()->compound_expression(decl, ret, loc);
14776       return ret;
14777     }
14778 
14779   Bexpression* space =
14780     gogo->allocate_memory(this->type_, loc)->get_backend(context);
14781   Btype* pbtype = gogo->backend()->pointer_type(btype);
14782   return gogo->backend()->convert_expression(pbtype, space, loc);
14783 }
14784 
14785 // Dump ast representation for an allocation expression.
14786 
14787 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14788 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14789     const
14790 {
14791   ast_dump_context->ostream() << "new(";
14792   ast_dump_context->dump_type(this->type_);
14793   ast_dump_context->ostream() << ")";
14794 }
14795 
14796 // Make an allocation expression.
14797 
14798 Expression*
make_allocation(Type * type,Location location)14799 Expression::make_allocation(Type* type, Location location)
14800 {
14801   return new Allocation_expression(type, location);
14802 }
14803 
14804 // Class Ordered_value_list.
14805 
14806 int
traverse_vals(Traverse * traverse)14807 Ordered_value_list::traverse_vals(Traverse* traverse)
14808 {
14809   if (this->vals_ != NULL)
14810     {
14811       if (this->traverse_order_ == NULL)
14812 	{
14813 	  if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
14814 	    return TRAVERSE_EXIT;
14815 	}
14816       else
14817 	{
14818 	  for (std::vector<unsigned long>::const_iterator p =
14819 		   this->traverse_order_->begin();
14820 	       p != this->traverse_order_->end();
14821 	       ++p)
14822 	    {
14823 	      if (Expression::traverse(&this->vals_->at(*p), traverse)
14824 		  == TRAVERSE_EXIT)
14825 		return TRAVERSE_EXIT;
14826 	    }
14827 	}
14828     }
14829   return TRAVERSE_CONTINUE;
14830 }
14831 
14832 // Class Struct_construction_expression.
14833 
14834 // Traversal.
14835 
14836 int
do_traverse(Traverse * traverse)14837 Struct_construction_expression::do_traverse(Traverse* traverse)
14838 {
14839   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
14840     return TRAVERSE_EXIT;
14841   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14842     return TRAVERSE_EXIT;
14843   return TRAVERSE_CONTINUE;
14844 }
14845 
14846 // Return whether this is a constant initializer.
14847 
14848 bool
is_constant_struct() const14849 Struct_construction_expression::is_constant_struct() const
14850 {
14851   if (this->vals() == NULL)
14852     return true;
14853   for (Expression_list::const_iterator pv = this->vals()->begin();
14854        pv != this->vals()->end();
14855        ++pv)
14856     {
14857       if (*pv != NULL
14858 	  && !(*pv)->is_constant()
14859 	  && (!(*pv)->is_composite_literal()
14860 	      || (*pv)->is_nonconstant_composite_literal()))
14861 	return false;
14862     }
14863 
14864   const Struct_field_list* fields = this->type_->struct_type()->fields();
14865   for (Struct_field_list::const_iterator pf = fields->begin();
14866        pf != fields->end();
14867        ++pf)
14868     {
14869       // There are no constant constructors for interfaces.
14870       if (pf->type()->interface_type() != NULL)
14871 	return false;
14872     }
14873 
14874   return true;
14875 }
14876 
14877 // Return whether this is a zero value.
14878 
14879 bool
do_is_zero_value() const14880 Struct_construction_expression::do_is_zero_value() const
14881 {
14882   if (this->vals() == NULL)
14883     return true;
14884   for (Expression_list::const_iterator pv = this->vals()->begin();
14885        pv != this->vals()->end();
14886        ++pv)
14887     if (*pv != NULL && !(*pv)->is_zero_value())
14888       return false;
14889 
14890   const Struct_field_list* fields = this->type_->struct_type()->fields();
14891   for (Struct_field_list::const_iterator pf = fields->begin();
14892        pf != fields->end();
14893        ++pf)
14894     {
14895       // Interface conversion may cause a zero value being converted
14896       // to a non-zero value, like interface{}(0).  Be conservative.
14897       if (pf->type()->interface_type() != NULL)
14898         return false;
14899     }
14900 
14901   return true;
14902 }
14903 
14904 // Return whether this struct can be used as a constant initializer.
14905 
14906 bool
do_is_static_initializer() const14907 Struct_construction_expression::do_is_static_initializer() const
14908 {
14909   if (this->vals() == NULL)
14910     return true;
14911   for (Expression_list::const_iterator pv = this->vals()->begin();
14912        pv != this->vals()->end();
14913        ++pv)
14914     {
14915       if (*pv != NULL && !(*pv)->is_static_initializer())
14916 	return false;
14917     }
14918 
14919   const Struct_field_list* fields = this->type_->struct_type()->fields();
14920   for (Struct_field_list::const_iterator pf = fields->begin();
14921        pf != fields->end();
14922        ++pf)
14923     {
14924       // There are no constant constructors for interfaces.
14925       if (pf->type()->interface_type() != NULL)
14926 	return false;
14927     }
14928 
14929   return true;
14930 }
14931 
14932 // Final type determination.
14933 
14934 void
do_determine_type(const Type_context *)14935 Struct_construction_expression::do_determine_type(const Type_context*)
14936 {
14937   if (this->vals() == NULL)
14938     return;
14939   const Struct_field_list* fields = this->type_->struct_type()->fields();
14940   Expression_list::const_iterator pv = this->vals()->begin();
14941   for (Struct_field_list::const_iterator pf = fields->begin();
14942        pf != fields->end();
14943        ++pf, ++pv)
14944     {
14945       if (pv == this->vals()->end())
14946 	return;
14947       if (*pv != NULL)
14948 	{
14949 	  Type_context subcontext(pf->type(), false);
14950 	  (*pv)->determine_type(&subcontext);
14951 	}
14952     }
14953   // Extra values are an error we will report elsewhere; we still want
14954   // to determine the type to avoid knockon errors.
14955   for (; pv != this->vals()->end(); ++pv)
14956     (*pv)->determine_type_no_context();
14957 }
14958 
14959 // Check types.
14960 
14961 void
do_check_types(Gogo *)14962 Struct_construction_expression::do_check_types(Gogo*)
14963 {
14964   if (this->vals() == NULL)
14965     return;
14966 
14967   Struct_type* st = this->type_->struct_type();
14968   if (this->vals()->size() > st->field_count())
14969     {
14970       this->report_error(_("too many expressions for struct"));
14971       return;
14972     }
14973 
14974   const Struct_field_list* fields = st->fields();
14975   Expression_list::const_iterator pv = this->vals()->begin();
14976   int i = 0;
14977   for (Struct_field_list::const_iterator pf = fields->begin();
14978        pf != fields->end();
14979        ++pf, ++pv, ++i)
14980     {
14981       if (pv == this->vals()->end())
14982 	{
14983 	  this->report_error(_("too few expressions for struct"));
14984 	  break;
14985 	}
14986 
14987       if (*pv == NULL)
14988 	continue;
14989 
14990       std::string reason;
14991       if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
14992 	{
14993 	  if (reason.empty())
14994 	    go_error_at((*pv)->location(),
14995                         "incompatible type for field %d in struct construction",
14996                         i + 1);
14997 	  else
14998 	    go_error_at((*pv)->location(),
14999                         ("incompatible type for field %d in "
15000                          "struct construction (%s)"),
15001                         i + 1, reason.c_str());
15002 	  this->set_is_error();
15003 	}
15004     }
15005   go_assert(pv == this->vals()->end());
15006 }
15007 
15008 // Copy.
15009 
15010 Expression*
do_copy()15011 Struct_construction_expression::do_copy()
15012 {
15013   Struct_construction_expression* ret =
15014     new Struct_construction_expression(this->type_->copy_expressions(),
15015 				       (this->vals() == NULL
15016 					? NULL
15017 					: this->vals()->copy()),
15018 				       this->location());
15019   if (this->traverse_order() != NULL)
15020     ret->set_traverse_order(this->traverse_order());
15021   return ret;
15022 }
15023 
15024 // Flatten a struct construction expression.  Store the values into
15025 // temporaries in case they need interface conversion.
15026 
15027 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15028 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
15029 					   Statement_inserter* inserter)
15030 {
15031   if (this->vals() == NULL)
15032     return this;
15033 
15034   // If this is a constant struct, we don't need temporaries.
15035   if (this->is_constant_struct() || this->is_static_initializer())
15036     return this;
15037 
15038   Location loc = this->location();
15039   for (Expression_list::iterator pv = this->vals()->begin();
15040        pv != this->vals()->end();
15041        ++pv)
15042     {
15043       if (*pv != NULL)
15044 	{
15045           if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15046             {
15047               go_assert(saw_errors());
15048               return Expression::make_error(loc);
15049             }
15050 	  if (!(*pv)->is_variable())
15051 	    {
15052 	      Temporary_statement* temp =
15053 		Statement::make_temporary(NULL, *pv, loc);
15054 	      inserter->insert(temp);
15055 	      *pv = Expression::make_temporary_reference(temp, loc);
15056 	    }
15057 	}
15058     }
15059   return this;
15060 }
15061 
15062 // Make implicit type conversions explicit.
15063 
15064 void
do_add_conversions()15065 Struct_construction_expression::do_add_conversions()
15066 {
15067   if (this->vals() == NULL)
15068     return;
15069 
15070   Location loc = this->location();
15071   const Struct_field_list* fields = this->type_->struct_type()->fields();
15072   Expression_list::iterator pv = this->vals()->begin();
15073   for (Struct_field_list::const_iterator pf = fields->begin();
15074        pf != fields->end();
15075        ++pf, ++pv)
15076     {
15077       if (pv == this->vals()->end())
15078         break;
15079       if (*pv != NULL)
15080         {
15081           Type* ft = pf->type();
15082           if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
15083               && ft->interface_type() != NULL)
15084            *pv = Expression::make_cast(ft, *pv, loc);
15085         }
15086     }
15087 }
15088 
15089 // Return the backend representation for constructing a struct.
15090 
15091 Bexpression*
do_get_backend(Translate_context * context)15092 Struct_construction_expression::do_get_backend(Translate_context* context)
15093 {
15094   Gogo* gogo = context->gogo();
15095 
15096   Btype* btype = this->type_->get_backend(gogo);
15097   if (this->vals() == NULL)
15098     return gogo->backend()->zero_expression(btype);
15099 
15100   const Struct_field_list* fields = this->type_->struct_type()->fields();
15101   Expression_list::const_iterator pv = this->vals()->begin();
15102   std::vector<Bexpression*> init;
15103   for (Struct_field_list::const_iterator pf = fields->begin();
15104        pf != fields->end();
15105        ++pf)
15106     {
15107       Btype* fbtype = pf->type()->get_backend(gogo);
15108       if (pv == this->vals()->end())
15109         init.push_back(gogo->backend()->zero_expression(fbtype));
15110       else if (*pv == NULL)
15111 	{
15112           init.push_back(gogo->backend()->zero_expression(fbtype));
15113 	  ++pv;
15114 	}
15115       else
15116 	{
15117           Expression* val =
15118               Expression::convert_for_assignment(gogo, pf->type(),
15119                                                  *pv, this->location());
15120           init.push_back(val->get_backend(context));
15121 	  ++pv;
15122 	}
15123     }
15124   if (this->type_->struct_type()->has_padding())
15125     {
15126       // Feed an extra value if there is a padding field.
15127       Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
15128       init.push_back(gogo->backend()->zero_expression(fbtype));
15129     }
15130   return gogo->backend()->constructor_expression(btype, init, this->location());
15131 }
15132 
15133 // Export a struct construction.
15134 
15135 void
do_export(Export_function_body * efb) const15136 Struct_construction_expression::do_export(Export_function_body* efb) const
15137 {
15138   efb->write_c_string("$convert(");
15139   efb->write_type(this->type_);
15140   for (Expression_list::const_iterator pv = this->vals()->begin();
15141        pv != this->vals()->end();
15142        ++pv)
15143     {
15144       efb->write_c_string(", ");
15145       if (*pv != NULL)
15146 	(*pv)->export_expression(efb);
15147     }
15148   efb->write_c_string(")");
15149 }
15150 
15151 // Dump ast representation of a struct construction expression.
15152 
15153 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15154 Struct_construction_expression::do_dump_expression(
15155     Ast_dump_context* ast_dump_context) const
15156 {
15157   ast_dump_context->dump_type(this->type_);
15158   ast_dump_context->ostream() << "{";
15159   ast_dump_context->dump_expression_list(this->vals());
15160   ast_dump_context->ostream() << "}";
15161 }
15162 
15163 // Make a struct composite literal.  This used by the thunk code.
15164 
15165 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)15166 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
15167 					  Location location)
15168 {
15169   go_assert(type->struct_type() != NULL);
15170   return new Struct_construction_expression(type, vals, location);
15171 }
15172 
15173 // Class Array_construction_expression.
15174 
15175 // Traversal.
15176 
15177 int
do_traverse(Traverse * traverse)15178 Array_construction_expression::do_traverse(Traverse* traverse)
15179 {
15180   if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
15181     return TRAVERSE_EXIT;
15182   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15183     return TRAVERSE_EXIT;
15184   return TRAVERSE_CONTINUE;
15185 }
15186 
15187 // Return whether this is a constant initializer.
15188 
15189 bool
is_constant_array() const15190 Array_construction_expression::is_constant_array() const
15191 {
15192   if (this->vals() == NULL)
15193     return true;
15194 
15195   // There are no constant constructors for interfaces.
15196   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15197     return false;
15198 
15199   for (Expression_list::const_iterator pv = this->vals()->begin();
15200        pv != this->vals()->end();
15201        ++pv)
15202     {
15203       if (*pv != NULL
15204 	  && !(*pv)->is_constant()
15205 	  && (!(*pv)->is_composite_literal()
15206 	      || (*pv)->is_nonconstant_composite_literal()))
15207 	return false;
15208     }
15209   return true;
15210 }
15211 
15212 // Return whether this is a zero value.
15213 
15214 bool
do_is_zero_value() const15215 Array_construction_expression::do_is_zero_value() const
15216 {
15217   if (this->vals() == NULL)
15218     return true;
15219 
15220   // Interface conversion may cause a zero value being converted
15221   // to a non-zero value, like interface{}(0).  Be conservative.
15222   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15223     return false;
15224 
15225   for (Expression_list::const_iterator pv = this->vals()->begin();
15226        pv != this->vals()->end();
15227        ++pv)
15228     if (*pv != NULL && !(*pv)->is_zero_value())
15229       return false;
15230 
15231   return true;
15232 }
15233 
15234 // Return whether this can be used a constant initializer.
15235 
15236 bool
do_is_static_initializer() const15237 Array_construction_expression::do_is_static_initializer() const
15238 {
15239   if (this->vals() == NULL)
15240     return true;
15241 
15242   // There are no constant constructors for interfaces.
15243   if (this->type_->array_type()->element_type()->interface_type() != NULL)
15244     return false;
15245 
15246   for (Expression_list::const_iterator pv = this->vals()->begin();
15247        pv != this->vals()->end();
15248        ++pv)
15249     {
15250       if (*pv != NULL && !(*pv)->is_static_initializer())
15251 	return false;
15252     }
15253   return true;
15254 }
15255 
15256 // Final type determination.
15257 
15258 void
do_determine_type(const Type_context *)15259 Array_construction_expression::do_determine_type(const Type_context*)
15260 {
15261   if (this->vals() == NULL)
15262     return;
15263   Type_context subcontext(this->type_->array_type()->element_type(), false);
15264   for (Expression_list::const_iterator pv = this->vals()->begin();
15265        pv != this->vals()->end();
15266        ++pv)
15267     {
15268       if (*pv != NULL)
15269 	(*pv)->determine_type(&subcontext);
15270     }
15271 }
15272 
15273 // Check types.
15274 
15275 void
do_check_types(Gogo *)15276 Array_construction_expression::do_check_types(Gogo*)
15277 {
15278   if (this->vals() == NULL)
15279     return;
15280 
15281   Array_type* at = this->type_->array_type();
15282   int i = 0;
15283   Type* element_type = at->element_type();
15284   for (Expression_list::const_iterator pv = this->vals()->begin();
15285        pv != this->vals()->end();
15286        ++pv, ++i)
15287     {
15288       if (*pv != NULL
15289 	  && !Type::are_assignable(element_type, (*pv)->type(), NULL))
15290 	{
15291 	  go_error_at((*pv)->location(),
15292                       "incompatible type for element %d in composite literal",
15293                       i + 1);
15294 	  this->set_is_error();
15295 	}
15296     }
15297 }
15298 
15299 // Flatten an array construction expression.  Store the values into
15300 // temporaries in case they need interface conversion.
15301 
15302 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15303 Array_construction_expression::do_flatten(Gogo*, Named_object*,
15304 					   Statement_inserter* inserter)
15305 {
15306   if (this->vals() == NULL)
15307     return this;
15308 
15309   // If this is a constant array, we don't need temporaries.
15310   if (this->is_constant_array() || this->is_static_initializer())
15311     return this;
15312 
15313   Location loc = this->location();
15314   for (Expression_list::iterator pv = this->vals()->begin();
15315        pv != this->vals()->end();
15316        ++pv)
15317     {
15318       if (*pv != NULL)
15319 	{
15320           if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15321             {
15322               go_assert(saw_errors());
15323               return Expression::make_error(loc);
15324             }
15325 	  if (!(*pv)->is_variable())
15326 	    {
15327 	      Temporary_statement* temp =
15328 		Statement::make_temporary(NULL, *pv, loc);
15329 	      inserter->insert(temp);
15330 	      *pv = Expression::make_temporary_reference(temp, loc);
15331 	    }
15332 	}
15333     }
15334   return this;
15335 }
15336 
15337 // Make implicit type conversions explicit.
15338 
15339 void
do_add_conversions()15340 Array_construction_expression::do_add_conversions()
15341 {
15342   if (this->vals() == NULL)
15343     return;
15344 
15345   Type* et = this->type_->array_type()->element_type();
15346   if (et->interface_type() == NULL)
15347     return;
15348 
15349   Location loc = this->location();
15350   for (Expression_list::iterator pv = this->vals()->begin();
15351        pv != this->vals()->end();
15352        ++pv)
15353     if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
15354       *pv = Expression::make_cast(et, *pv, loc);
15355 }
15356 
15357 // Get a constructor expression for the array values.
15358 
15359 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)15360 Array_construction_expression::get_constructor(Translate_context* context,
15361                                                Btype* array_btype)
15362 {
15363   Type* element_type = this->type_->array_type()->element_type();
15364 
15365   std::vector<unsigned long> indexes;
15366   std::vector<Bexpression*> vals;
15367   Gogo* gogo = context->gogo();
15368   if (this->vals() != NULL)
15369     {
15370       size_t i = 0;
15371       std::vector<unsigned long>::const_iterator pi;
15372       if (this->indexes_ != NULL)
15373 	pi = this->indexes_->begin();
15374       for (Expression_list::const_iterator pv = this->vals()->begin();
15375 	   pv != this->vals()->end();
15376 	   ++pv, ++i)
15377 	{
15378 	  if (this->indexes_ != NULL)
15379 	    go_assert(pi != this->indexes_->end());
15380 
15381 	  if (this->indexes_ == NULL)
15382 	    indexes.push_back(i);
15383 	  else
15384 	    indexes.push_back(*pi);
15385 	  if (*pv == NULL)
15386 	    {
15387 	      Btype* ebtype = element_type->get_backend(gogo);
15388 	      Bexpression *zv = gogo->backend()->zero_expression(ebtype);
15389 	      vals.push_back(zv);
15390 	    }
15391 	  else
15392 	    {
15393               Expression* val_expr =
15394                   Expression::convert_for_assignment(gogo, element_type, *pv,
15395                                                      this->location());
15396 	      vals.push_back(val_expr->get_backend(context));
15397 	    }
15398 	  if (this->indexes_ != NULL)
15399 	    ++pi;
15400 	}
15401       if (this->indexes_ != NULL)
15402 	go_assert(pi == this->indexes_->end());
15403     }
15404   return gogo->backend()->array_constructor_expression(array_btype, indexes,
15405                                                        vals, this->location());
15406 }
15407 
15408 // Export an array construction.
15409 
15410 void
do_export(Export_function_body * efb) const15411 Array_construction_expression::do_export(Export_function_body* efb) const
15412 {
15413   efb->write_c_string("$convert(");
15414   efb->write_type(this->type_);
15415   if (this->vals() != NULL)
15416     {
15417       std::vector<unsigned long>::const_iterator pi;
15418       if (this->indexes_ != NULL)
15419 	pi = this->indexes_->begin();
15420       for (Expression_list::const_iterator pv = this->vals()->begin();
15421 	   pv != this->vals()->end();
15422 	   ++pv)
15423 	{
15424 	  efb->write_c_string(", ");
15425 
15426 	  if (this->indexes_ != NULL)
15427 	    {
15428 	      char buf[100];
15429 	      snprintf(buf, sizeof buf, "%lu", *pi);
15430 	      efb->write_c_string(buf);
15431 	      efb->write_c_string(":");
15432 	    }
15433 
15434 	  if (*pv != NULL)
15435 	    (*pv)->export_expression(efb);
15436 
15437 	  if (this->indexes_ != NULL)
15438 	    ++pi;
15439 	}
15440     }
15441   efb->write_c_string(")");
15442 }
15443 
15444 // Dump ast representation of an array construction expression.
15445 
15446 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15447 Array_construction_expression::do_dump_expression(
15448     Ast_dump_context* ast_dump_context) const
15449 {
15450   Expression* length = this->type_->array_type()->length();
15451 
15452   ast_dump_context->ostream() << "[" ;
15453   if (length != NULL)
15454     {
15455       ast_dump_context->dump_expression(length);
15456     }
15457   ast_dump_context->ostream() << "]" ;
15458   ast_dump_context->dump_type(this->type_);
15459   this->dump_slice_storage_expression(ast_dump_context);
15460   ast_dump_context->ostream() << "{" ;
15461   if (this->indexes_ == NULL)
15462     ast_dump_context->dump_expression_list(this->vals());
15463   else
15464     {
15465       Expression_list::const_iterator pv = this->vals()->begin();
15466       for (std::vector<unsigned long>::const_iterator pi =
15467 	     this->indexes_->begin();
15468 	   pi != this->indexes_->end();
15469 	   ++pi, ++pv)
15470 	{
15471 	  if (pi != this->indexes_->begin())
15472 	    ast_dump_context->ostream() << ", ";
15473 	  ast_dump_context->ostream() << *pi << ':';
15474 	  ast_dump_context->dump_expression(*pv);
15475 	}
15476     }
15477   ast_dump_context->ostream() << "}" ;
15478 
15479 }
15480 
15481 // Class Fixed_array_construction_expression.
15482 
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15483 Fixed_array_construction_expression::Fixed_array_construction_expression(
15484     Type* type, const std::vector<unsigned long>* indexes,
15485     Expression_list* vals, Location location)
15486   : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
15487 				  type, indexes, vals, location)
15488 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
15489 
15490 
15491 // Copy.
15492 
15493 Expression*
do_copy()15494 Fixed_array_construction_expression::do_copy()
15495 {
15496   Type* t = this->type()->copy_expressions();
15497   return new Fixed_array_construction_expression(t, this->indexes(),
15498 						 (this->vals() == NULL
15499 						  ? NULL
15500 						  : this->vals()->copy()),
15501 						 this->location());
15502 }
15503 
15504 // Return the backend representation for constructing a fixed array.
15505 
15506 Bexpression*
do_get_backend(Translate_context * context)15507 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
15508 {
15509   Type* type = this->type();
15510   Btype* btype = type->get_backend(context->gogo());
15511   return this->get_constructor(context, btype);
15512 }
15513 
15514 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)15515 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
15516                                          Location location)
15517 {
15518   go_assert(type->array_type() != NULL && !type->is_slice_type());
15519   return new Fixed_array_construction_expression(type, NULL, vals, location);
15520 }
15521 
15522 // Class Slice_construction_expression.
15523 
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15524 Slice_construction_expression::Slice_construction_expression(
15525   Type* type, const std::vector<unsigned long>* indexes,
15526   Expression_list* vals, Location location)
15527   : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
15528 				  type, indexes, vals, location),
15529     valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
15530     storage_escapes_(true)
15531 {
15532   go_assert(type->is_slice_type());
15533 
15534   unsigned long lenval;
15535   Expression* length;
15536   if (vals == NULL || vals->empty())
15537     lenval = 0;
15538   else
15539     {
15540       if (this->indexes() == NULL)
15541 	lenval = vals->size();
15542       else
15543 	lenval = indexes->back() + 1;
15544     }
15545   Type* int_type = Type::lookup_integer_type("int");
15546   length = Expression::make_integer_ul(lenval, int_type, location);
15547   Type* element_type = type->array_type()->element_type();
15548   Array_type* array_type = Type::make_array_type(element_type, length);
15549   array_type->set_is_array_incomparable();
15550   this->valtype_ = array_type;
15551 }
15552 
15553 // Traversal.
15554 
15555 int
do_traverse(Traverse * traverse)15556 Slice_construction_expression::do_traverse(Traverse* traverse)
15557 {
15558   if (this->Array_construction_expression::do_traverse(traverse)
15559       == TRAVERSE_EXIT)
15560     return TRAVERSE_EXIT;
15561   if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
15562     return TRAVERSE_EXIT;
15563   if (this->array_val_ != NULL
15564       && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
15565     return TRAVERSE_EXIT;
15566   if (this->slice_storage_ != NULL
15567       && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
15568     return TRAVERSE_EXIT;
15569   return TRAVERSE_CONTINUE;
15570 }
15571 
15572 // Helper routine to create fixed array value underlying the slice literal.
15573 // May be called during flattening, or later during do_get_backend().
15574 
15575 Expression*
create_array_val()15576 Slice_construction_expression::create_array_val()
15577 {
15578   Array_type* array_type = this->type()->array_type();
15579   if (array_type == NULL)
15580     {
15581       go_assert(this->type()->is_error());
15582       return NULL;
15583     }
15584 
15585   Location loc = this->location();
15586   go_assert(this->valtype_ != NULL);
15587 
15588   Expression_list* vals = this->vals();
15589   return new Fixed_array_construction_expression(
15590       this->valtype_, this->indexes(), vals, loc);
15591 }
15592 
15593 // If we're previous established that the slice storage does not
15594 // escape, then create a separate array temp val here for it. We
15595 // need to do this as part of flattening so as to be able to insert
15596 // the new temp statement.
15597 
15598 Expression*
do_flatten(Gogo * gogo,Named_object * no,Statement_inserter * inserter)15599 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
15600                                           Statement_inserter* inserter)
15601 {
15602   if (this->type()->array_type() == NULL)
15603     return NULL;
15604 
15605   // Base class flattening first
15606   this->Array_construction_expression::do_flatten(gogo, no, inserter);
15607 
15608   // Create a stack-allocated storage temp if storage won't escape
15609   if (!this->storage_escapes_
15610       && this->slice_storage_ == NULL
15611       && this->element_count() > 0)
15612     {
15613       Location loc = this->location();
15614       this->array_val_ = this->create_array_val();
15615       go_assert(this->array_val_);
15616       Temporary_statement* temp =
15617           Statement::make_temporary(this->valtype_, this->array_val_, loc);
15618       inserter->insert(temp);
15619       this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
15620     }
15621   return this;
15622 }
15623 
15624 // When dumping a slice construction expression that has an explicit
15625 // storeage temp, emit the temp here (if we don't do this the storage
15626 // temp appears unused in the AST dump).
15627 
15628 void
15629 Slice_construction_expression::
dump_slice_storage_expression(Ast_dump_context * ast_dump_context) const15630 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
15631 {
15632   if (this->slice_storage_ == NULL)
15633     return;
15634   ast_dump_context->ostream() << "storage=" ;
15635   ast_dump_context->dump_expression(this->slice_storage_);
15636 }
15637 
15638 // Copy.
15639 
15640 Expression*
do_copy()15641 Slice_construction_expression::do_copy()
15642 {
15643   return new Slice_construction_expression(this->type()->copy_expressions(),
15644 					   this->indexes(),
15645 					   (this->vals() == NULL
15646 					    ? NULL
15647 					    : this->vals()->copy()),
15648 					   this->location());
15649 }
15650 
15651 // Return the backend representation for constructing a slice.
15652 
15653 Bexpression*
do_get_backend(Translate_context * context)15654 Slice_construction_expression::do_get_backend(Translate_context* context)
15655 {
15656   if (this->array_val_ == NULL)
15657     this->array_val_ = this->create_array_val();
15658   if (this->array_val_ == NULL)
15659     {
15660       go_assert(this->type()->is_error());
15661       return context->backend()->error_expression();
15662     }
15663 
15664   Location loc = this->location();
15665 
15666   bool is_static_initializer = this->array_val_->is_static_initializer();
15667 
15668   // We have to copy the initial values into heap memory if we are in
15669   // a function or if the values are not constants.
15670   bool copy_to_heap = context->function() != NULL || !is_static_initializer;
15671 
15672   Expression* space;
15673 
15674   if (this->slice_storage_ != NULL)
15675     {
15676       go_assert(!this->storage_escapes_);
15677       space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
15678     }
15679   else if (!copy_to_heap)
15680     {
15681       // The initializer will only run once.
15682       space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
15683       space->unary_expression()->set_is_slice_init();
15684     }
15685   else
15686     {
15687       go_assert(this->storage_escapes_ || this->element_count() == 0);
15688       space = Expression::make_heap_expression(this->array_val_, loc);
15689     }
15690   Array_type* at = this->valtype_->array_type();
15691   Type* et = at->element_type();
15692   space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
15693 				       space, loc);
15694 
15695   // Build a constructor for the slice.
15696   Expression* len = at->length();
15697   Expression* slice_val =
15698     Expression::make_slice_value(this->type(), space, len, len, loc);
15699   return slice_val->get_backend(context);
15700 }
15701 
15702 // Make a slice composite literal.  This is used by the type
15703 // descriptor code.
15704 
15705 Slice_construction_expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)15706 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
15707 					 Location location)
15708 {
15709   go_assert(type->is_slice_type());
15710   return new Slice_construction_expression(type, NULL, vals, location);
15711 }
15712 
15713 // Class Map_construction_expression.
15714 
15715 // Traversal.
15716 
15717 int
do_traverse(Traverse * traverse)15718 Map_construction_expression::do_traverse(Traverse* traverse)
15719 {
15720   if (this->vals_ != NULL
15721       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
15722     return TRAVERSE_EXIT;
15723   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15724     return TRAVERSE_EXIT;
15725   return TRAVERSE_CONTINUE;
15726 }
15727 
15728 // Flatten constructor initializer into a temporary variable since
15729 // we need to take its address for __go_construct_map.
15730 
15731 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)15732 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
15733                                         Statement_inserter* inserter)
15734 {
15735   if (!this->is_error_expression()
15736       && this->vals_ != NULL
15737       && !this->vals_->empty()
15738       && this->constructor_temp_ == NULL)
15739     {
15740       Map_type* mt = this->type_->map_type();
15741       Type* key_type = mt->key_type();
15742       Type* val_type = mt->val_type();
15743       this->element_type_ = Type::make_builtin_struct_type(2,
15744                                                            "__key", key_type,
15745                                                            "__val", val_type);
15746 
15747       Expression_list* value_pairs = new Expression_list();
15748       Location loc = this->location();
15749 
15750       size_t i = 0;
15751       for (Expression_list::const_iterator pv = this->vals_->begin();
15752            pv != this->vals_->end();
15753            ++pv, ++i)
15754         {
15755           Expression_list* key_value_pair = new Expression_list();
15756           Expression* key = *pv;
15757           if (key->is_error_expression() || key->type()->is_error_type())
15758             {
15759               go_assert(saw_errors());
15760               return Expression::make_error(loc);
15761             }
15762 	  if (key->type()->interface_type() != NULL && !key->is_variable())
15763 	    {
15764 	      Temporary_statement* temp =
15765 		Statement::make_temporary(NULL, key, loc);
15766 	      inserter->insert(temp);
15767 	      key = Expression::make_temporary_reference(temp, loc);
15768 	    }
15769 	  key = Expression::convert_for_assignment(gogo, key_type, key, loc);
15770 
15771           ++pv;
15772           Expression* val = *pv;
15773           if (val->is_error_expression() || val->type()->is_error_type())
15774             {
15775               go_assert(saw_errors());
15776               return Expression::make_error(loc);
15777             }
15778 	  if (val->type()->interface_type() != NULL && !val->is_variable())
15779 	    {
15780 	      Temporary_statement* temp =
15781 		Statement::make_temporary(NULL, val, loc);
15782 	      inserter->insert(temp);
15783 	      val = Expression::make_temporary_reference(temp, loc);
15784 	    }
15785 	  val = Expression::convert_for_assignment(gogo, val_type, val, loc);
15786 
15787           key_value_pair->push_back(key);
15788           key_value_pair->push_back(val);
15789           value_pairs->push_back(
15790               Expression::make_struct_composite_literal(this->element_type_,
15791                                                         key_value_pair, loc));
15792         }
15793 
15794       Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
15795       Array_type* ctor_type =
15796           Type::make_array_type(this->element_type_, element_count);
15797       ctor_type->set_is_array_incomparable();
15798       Expression* constructor =
15799           new Fixed_array_construction_expression(ctor_type, NULL,
15800                                                   value_pairs, loc);
15801 
15802       this->constructor_temp_ =
15803           Statement::make_temporary(NULL, constructor, loc);
15804       constructor->issue_nil_check();
15805       this->constructor_temp_->set_is_address_taken();
15806       inserter->insert(this->constructor_temp_);
15807     }
15808 
15809   return this;
15810 }
15811 
15812 // Final type determination.
15813 
15814 void
do_determine_type(const Type_context *)15815 Map_construction_expression::do_determine_type(const Type_context*)
15816 {
15817   if (this->vals_ == NULL)
15818     return;
15819 
15820   Map_type* mt = this->type_->map_type();
15821   Type_context key_context(mt->key_type(), false);
15822   Type_context val_context(mt->val_type(), false);
15823   for (Expression_list::const_iterator pv = this->vals_->begin();
15824        pv != this->vals_->end();
15825        ++pv)
15826     {
15827       (*pv)->determine_type(&key_context);
15828       ++pv;
15829       (*pv)->determine_type(&val_context);
15830     }
15831 }
15832 
15833 // Check types.
15834 
15835 void
do_check_types(Gogo *)15836 Map_construction_expression::do_check_types(Gogo*)
15837 {
15838   if (this->vals_ == NULL)
15839     return;
15840 
15841   Map_type* mt = this->type_->map_type();
15842   int i = 0;
15843   Type* key_type = mt->key_type();
15844   Type* val_type = mt->val_type();
15845   for (Expression_list::const_iterator pv = this->vals_->begin();
15846        pv != this->vals_->end();
15847        ++pv, ++i)
15848     {
15849       if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
15850 	{
15851 	  go_error_at((*pv)->location(),
15852                       "incompatible type for element %d key in map construction",
15853                       i + 1);
15854 	  this->set_is_error();
15855 	}
15856       ++pv;
15857       if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
15858 	{
15859 	  go_error_at((*pv)->location(),
15860                       ("incompatible type for element %d value "
15861                        "in map construction"),
15862 		   i + 1);
15863 	  this->set_is_error();
15864 	}
15865     }
15866 }
15867 
15868 // Copy.
15869 
15870 Expression*
do_copy()15871 Map_construction_expression::do_copy()
15872 {
15873   return new Map_construction_expression(this->type_->copy_expressions(),
15874 					 (this->vals_ == NULL
15875 					  ? NULL
15876 					  : this->vals_->copy()),
15877 					 this->location());
15878 }
15879 
15880 // Make implicit type conversions explicit.
15881 
15882 void
do_add_conversions()15883 Map_construction_expression::do_add_conversions()
15884 {
15885   if (this->vals_ == NULL || this->vals_->empty())
15886     return;
15887 
15888   Map_type* mt = this->type_->map_type();
15889   Type* kt = mt->key_type();
15890   Type* vt = mt->val_type();
15891   bool key_is_interface = (kt->interface_type() != NULL);
15892   bool val_is_interface = (vt->interface_type() != NULL);
15893   if (!key_is_interface && !val_is_interface)
15894     return;
15895 
15896   Location loc = this->location();
15897   for (Expression_list::iterator pv = this->vals_->begin();
15898        pv != this->vals_->end();
15899        ++pv)
15900     {
15901       if (key_is_interface &&
15902           !Type::are_identical(kt, (*pv)->type(), 0, NULL))
15903         *pv = Expression::make_cast(kt, *pv, loc);
15904       ++pv;
15905       if (val_is_interface &&
15906           !Type::are_identical(vt, (*pv)->type(), 0, NULL))
15907         *pv = Expression::make_cast(vt, *pv, loc);
15908     }
15909 }
15910 
15911 // Return the backend representation for constructing a map.
15912 
15913 Bexpression*
do_get_backend(Translate_context * context)15914 Map_construction_expression::do_get_backend(Translate_context* context)
15915 {
15916   if (this->is_error_expression())
15917     return context->backend()->error_expression();
15918   Location loc = this->location();
15919 
15920   size_t i = 0;
15921   Expression* ventries;
15922   if (this->vals_ == NULL || this->vals_->empty())
15923     ventries = Expression::make_nil(loc);
15924   else
15925     {
15926       go_assert(this->constructor_temp_ != NULL);
15927       i = this->vals_->size() / 2;
15928 
15929       Expression* ctor_ref =
15930           Expression::make_temporary_reference(this->constructor_temp_, loc);
15931       ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
15932     }
15933 
15934   Map_type* mt = this->type_->map_type();
15935   if (this->element_type_ == NULL)
15936       this->element_type_ =
15937           Type::make_builtin_struct_type(2,
15938                                          "__key", mt->key_type(),
15939                                          "__val", mt->val_type());
15940   Expression* descriptor = Expression::make_type_descriptor(mt, loc);
15941 
15942   Type* uintptr_t = Type::lookup_integer_type("uintptr");
15943   Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
15944 
15945   Expression* entry_size =
15946       Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
15947 
15948   unsigned int field_index;
15949   const Struct_field* valfield =
15950       this->element_type_->find_local_field("__val", &field_index);
15951   Expression* val_offset =
15952       Expression::make_struct_field_offset(this->element_type_, valfield);
15953 
15954   Expression* map_ctor =
15955       Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
15956                          entry_size, val_offset, ventries);
15957   return map_ctor->get_backend(context);
15958 }
15959 
15960 // Export an array construction.
15961 
15962 void
do_export(Export_function_body * efb) const15963 Map_construction_expression::do_export(Export_function_body* efb) const
15964 {
15965   efb->write_c_string("$convert(");
15966   efb->write_type(this->type_);
15967   for (Expression_list::const_iterator pv = this->vals_->begin();
15968        pv != this->vals_->end();
15969        ++pv)
15970     {
15971       efb->write_c_string(", ");
15972       (*pv)->export_expression(efb);
15973     }
15974   efb->write_c_string(")");
15975 }
15976 
15977 // Dump ast representation for a map construction expression.
15978 
15979 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15980 Map_construction_expression::do_dump_expression(
15981     Ast_dump_context* ast_dump_context) const
15982 {
15983   ast_dump_context->ostream() << "{" ;
15984   ast_dump_context->dump_expression_list(this->vals_, true);
15985   ast_dump_context->ostream() << "}";
15986 }
15987 
15988 // A composite literal key.  This is seen during parsing, but is not
15989 // resolved to a named_object in case this is a composite literal of
15990 // struct type.
15991 
15992 class Composite_literal_key_expression : public Parser_expression
15993 {
15994  public:
Composite_literal_key_expression(const std::string & name,Location location)15995   Composite_literal_key_expression(const std::string& name, Location location)
15996     : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
15997       name_(name)
15998   { }
15999 
16000   const std::string&
name() const16001   name() const
16002   { return this->name_; }
16003 
16004  protected:
16005   Expression*
16006   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
16007 
16008   Expression*
do_copy()16009   do_copy()
16010   {
16011     return new Composite_literal_key_expression(this->name_, this->location());
16012   }
16013 
16014   void
16015   do_dump_expression(Ast_dump_context*) const;
16016 
16017  private:
16018   // The name.
16019   std::string name_;
16020 };
16021 
16022 // Lower a composite literal key.  We will never get here for keys in
16023 // composite literals of struct types, because that is prevented by
16024 // Composite_literal_expression::do_traverse.  So if we do get here,
16025 // this must be a regular name reference after all.
16026 
16027 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)16028 Composite_literal_key_expression::do_lower(Gogo* gogo, Named_object*,
16029 					   Statement_inserter*, int)
16030 {
16031   Named_object* no = gogo->lookup(this->name_, NULL);
16032   if (no == NULL)
16033     {
16034       // Gogo::lookup doesn't look in the global namespace, and names
16035       // used in composite literal keys aren't seen by
16036       // Gogo::define_global_names, so we have to look in the global
16037       // namespace ourselves.
16038       no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
16039       if (no == NULL)
16040 	{
16041 	  go_error_at(this->location(), "reference to undefined name %qs",
16042 		      Gogo::message_name(this->name_).c_str());
16043 	  return Expression::make_error(this->location());
16044 	}
16045     }
16046   return Expression::make_unknown_reference(no, this->location());
16047 }
16048 
16049 // Dump a composite literal key.
16050 
16051 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16052 Composite_literal_key_expression::do_dump_expression(
16053     Ast_dump_context* ast_dump_context) const
16054 {
16055   ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
16056 }
16057 
16058 // Make a composite literal key.
16059 
16060 Expression*
make_composite_literal_key(const std::string & name,Location location)16061 Expression::make_composite_literal_key(const std::string& name,
16062 				       Location location)
16063 {
16064   return new Composite_literal_key_expression(name, location);
16065 }
16066 
16067 // Class Composite_literal_expression.
16068 
16069 // Traversal.
16070 
16071 int
do_traverse(Traverse * traverse)16072 Composite_literal_expression::do_traverse(Traverse* traverse)
16073 {
16074   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16075     return TRAVERSE_EXIT;
16076 
16077   // If this is a struct composite literal with keys, then the keys
16078   // are field names, not expressions.  We don't want to traverse them
16079   // in that case.  If we do, we can give an erroneous error "variable
16080   // initializer refers to itself."  See bug482.go in the testsuite.
16081   if (this->has_keys_ && this->vals_ != NULL)
16082     {
16083       // The type may not be resolvable at this point.
16084       Type* type = this->type_;
16085 
16086       for (int depth = 0; depth < this->depth_; ++depth)
16087         {
16088 	  type = type->deref();
16089           if (type->array_type() != NULL)
16090             type = type->array_type()->element_type();
16091           else if (type->map_type() != NULL)
16092             {
16093               if (this->key_path_[depth])
16094                 type = type->map_type()->key_type();
16095               else
16096                 type = type->map_type()->val_type();
16097             }
16098           else
16099             {
16100               // This error will be reported during lowering.
16101               return TRAVERSE_CONTINUE;
16102             }
16103         }
16104       type = type->deref();
16105 
16106       while (true)
16107 	{
16108 	  if (type->classification() == Type::TYPE_NAMED)
16109 	    type = type->named_type()->real_type();
16110 	  else if (type->classification() == Type::TYPE_FORWARD)
16111 	    {
16112 	      Type* t = type->forwarded();
16113 	      if (t == type)
16114 		break;
16115 	      type = t;
16116 	    }
16117 	  else
16118 	    break;
16119 	}
16120 
16121       if (type->classification() == Type::TYPE_STRUCT)
16122 	{
16123 	  Expression_list::iterator p = this->vals_->begin();
16124 	  while (p != this->vals_->end())
16125 	    {
16126 	      // Skip key.
16127 	      ++p;
16128 	      go_assert(p != this->vals_->end());
16129 	      if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16130 		return TRAVERSE_EXIT;
16131 	      ++p;
16132 	    }
16133 	  return TRAVERSE_CONTINUE;
16134 	}
16135     }
16136 
16137   if (this->vals_ != NULL)
16138     return this->vals_->traverse(traverse);
16139 
16140   return TRAVERSE_CONTINUE;
16141 }
16142 
16143 // Lower a generic composite literal into a specific version based on
16144 // the type.
16145 
16146 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)16147 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
16148 				       Statement_inserter* inserter, int)
16149 {
16150   Type* type = this->type_;
16151 
16152   for (int depth = 0; depth < this->depth_; ++depth)
16153     {
16154       type = type->deref();
16155       if (type->array_type() != NULL)
16156 	type = type->array_type()->element_type();
16157       else if (type->map_type() != NULL)
16158         {
16159           if (this->key_path_[depth])
16160             type = type->map_type()->key_type();
16161           else
16162             type = type->map_type()->val_type();
16163         }
16164       else
16165 	{
16166 	  if (!type->is_error())
16167 	    go_error_at(this->location(),
16168                         ("may only omit types within composite literals "
16169                          "of slice, array, or map type"));
16170 	  return Expression::make_error(this->location());
16171 	}
16172     }
16173 
16174   Type *pt = type->points_to();
16175   bool is_pointer = false;
16176   if (pt != NULL)
16177     {
16178       is_pointer = true;
16179       type = pt;
16180     }
16181 
16182   Expression* ret;
16183   if (type->is_error())
16184     return Expression::make_error(this->location());
16185   else if (type->struct_type() != NULL)
16186     ret = this->lower_struct(gogo, type);
16187   else if (type->array_type() != NULL)
16188     ret = this->lower_array(type);
16189   else if (type->map_type() != NULL)
16190     ret = this->lower_map(gogo, function, inserter, type);
16191   else
16192     {
16193       go_error_at(this->location(),
16194                   ("expected struct, slice, array, or map type "
16195                    "for composite literal"));
16196       return Expression::make_error(this->location());
16197     }
16198 
16199   if (is_pointer)
16200     ret = Expression::make_heap_expression(ret, this->location());
16201 
16202   return ret;
16203 }
16204 
16205 // Lower a struct composite literal.
16206 
16207 Expression*
lower_struct(Gogo * gogo,Type * type)16208 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
16209 {
16210   Location location = this->location();
16211   Struct_type* st = type->struct_type();
16212   if (this->vals_ == NULL || !this->has_keys_)
16213     {
16214       if (this->vals_ != NULL
16215 	  && !this->vals_->empty()
16216 	  && type->named_type() != NULL
16217 	  && type->named_type()->named_object()->package() != NULL)
16218 	{
16219 	  for (Struct_field_list::const_iterator pf = st->fields()->begin();
16220 	       pf != st->fields()->end();
16221 	       ++pf)
16222 	    {
16223 	      if (Gogo::is_hidden_name(pf->field_name())
16224 		  || pf->is_embedded_builtin(gogo))
16225 		go_error_at(this->location(),
16226                             "assignment of unexported field %qs in %qs literal",
16227                             Gogo::message_name(pf->field_name()).c_str(),
16228                             type->named_type()->message_name().c_str());
16229 	    }
16230 	}
16231 
16232       return new Struct_construction_expression(type, this->vals_, location);
16233     }
16234 
16235   size_t field_count = st->field_count();
16236   std::vector<Expression*> vals(field_count);
16237   std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
16238   Expression_list::const_iterator p = this->vals_->begin();
16239   Expression* external_expr = NULL;
16240   const Named_object* external_no = NULL;
16241   while (p != this->vals_->end())
16242     {
16243       Expression* name_expr = *p;
16244 
16245       ++p;
16246       go_assert(p != this->vals_->end());
16247       Expression* val = *p;
16248 
16249       ++p;
16250 
16251       if (name_expr == NULL)
16252 	{
16253 	  go_error_at(val->location(),
16254                       "mixture of field and value initializers");
16255 	  return Expression::make_error(location);
16256 	}
16257 
16258       bool bad_key = false;
16259       std::string name;
16260       const Named_object* no = NULL;
16261       switch (name_expr->classification())
16262 	{
16263 	case EXPRESSION_COMPOSITE_LITERAL_KEY:
16264 	  name =
16265 	    static_cast<Composite_literal_key_expression*>(name_expr)->name();
16266 	  break;
16267 
16268 	case EXPRESSION_UNKNOWN_REFERENCE:
16269 	  name = name_expr->unknown_expression()->name();
16270 	  if (type->named_type() != NULL)
16271 	    {
16272 	      // If the named object found for this field name comes from a
16273 	      // different package than the struct it is a part of, do not count
16274 	      // this incorrect lookup as a usage of the object's package.
16275 	      no = name_expr->unknown_expression()->named_object();
16276 	      if (no->package() != NULL
16277 		  && no->package() != type->named_type()->named_object()->package())
16278 		no->package()->forget_usage(name_expr);
16279 	    }
16280 	  break;
16281 
16282 	case EXPRESSION_CONST_REFERENCE:
16283 	  no = static_cast<Const_expression*>(name_expr)->named_object();
16284 	  break;
16285 
16286 	case EXPRESSION_TYPE:
16287 	  {
16288 	    Type* t = name_expr->type();
16289 	    Named_type* nt = t->named_type();
16290 	    if (nt == NULL)
16291 	      bad_key = true;
16292 	    else
16293 	      no = nt->named_object();
16294 	  }
16295 	  break;
16296 
16297 	case EXPRESSION_VAR_REFERENCE:
16298 	  no = name_expr->var_expression()->named_object();
16299 	  break;
16300 
16301 	case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16302 	  no = name_expr->enclosed_var_expression()->variable();
16303 	  break;
16304 
16305 	case EXPRESSION_FUNC_REFERENCE:
16306 	  no = name_expr->func_expression()->named_object();
16307 	  break;
16308 
16309 	default:
16310 	  bad_key = true;
16311 	  break;
16312 	}
16313       if (bad_key)
16314 	{
16315 	  go_error_at(name_expr->location(), "expected struct field name");
16316 	  return Expression::make_error(location);
16317 	}
16318 
16319       if (no != NULL)
16320 	{
16321 	  if (no->package() != NULL && external_expr == NULL)
16322 	    {
16323 	      external_expr = name_expr;
16324 	      external_no = no;
16325 	    }
16326 
16327 	  name = no->name();
16328 
16329 	  // A predefined name won't be packed.  If it starts with a
16330 	  // lower case letter we need to check for that case, because
16331 	  // the field name will be packed.  FIXME.
16332 	  if (!Gogo::is_hidden_name(name)
16333 	      && name[0] >= 'a'
16334 	      && name[0] <= 'z')
16335 	    {
16336 	      Named_object* gno = gogo->lookup_global(name.c_str());
16337 	      if (gno == no)
16338 		name = gogo->pack_hidden_name(name, false);
16339 	    }
16340 	}
16341 
16342       unsigned int index;
16343       const Struct_field* sf = st->find_local_field(name, &index);
16344       if (sf == NULL)
16345 	{
16346 	  go_error_at(name_expr->location(), "unknown field %qs in %qs",
16347                       Gogo::message_name(name).c_str(),
16348                       (type->named_type() != NULL
16349                        ? type->named_type()->message_name().c_str()
16350                        : "unnamed struct"));
16351 	  return Expression::make_error(location);
16352 	}
16353       if (vals[index] != NULL)
16354 	{
16355 	  go_error_at(name_expr->location(),
16356                       "duplicate value for field %qs in %qs",
16357                       Gogo::message_name(name).c_str(),
16358                       (type->named_type() != NULL
16359                        ? type->named_type()->message_name().c_str()
16360                        : "unnamed struct"));
16361 	  return Expression::make_error(location);
16362 	}
16363 
16364       if (type->named_type() != NULL
16365 	  && type->named_type()->named_object()->package() != NULL
16366 	  && (Gogo::is_hidden_name(sf->field_name())
16367 	      || sf->is_embedded_builtin(gogo)))
16368 	go_error_at(name_expr->location(),
16369                     "assignment of unexported field %qs in %qs literal",
16370                     Gogo::message_name(sf->field_name()).c_str(),
16371                     type->named_type()->message_name().c_str());
16372 
16373       vals[index] = val;
16374       traverse_order->push_back(static_cast<unsigned long>(index));
16375     }
16376 
16377   if (!this->all_are_names_)
16378     {
16379       // This is a weird case like bug462 in the testsuite.
16380       if (external_expr == NULL)
16381 	go_error_at(this->location(), "unknown field in %qs literal",
16382                     (type->named_type() != NULL
16383                      ? type->named_type()->message_name().c_str()
16384                      : "unnamed struct"));
16385       else
16386 	go_error_at(external_expr->location(), "unknown field %qs in %qs",
16387                     external_no->message_name().c_str(),
16388                     (type->named_type() != NULL
16389                      ? type->named_type()->message_name().c_str()
16390                      : "unnamed struct"));
16391       return Expression::make_error(location);
16392     }
16393 
16394   Expression_list* list = new Expression_list;
16395   list->reserve(field_count);
16396   for (size_t i = 0; i < field_count; ++i)
16397     list->push_back(vals[i]);
16398 
16399   Struct_construction_expression* ret =
16400     new Struct_construction_expression(type, list, location);
16401   ret->set_traverse_order(traverse_order);
16402   return ret;
16403 }
16404 
16405 // Index/value/traversal-order triple.
16406 
16407 struct IVT_triple {
16408   unsigned long index;
16409   unsigned long traversal_order;
16410   Expression* expr;
IVT_tripleIVT_triple16411   IVT_triple(unsigned long i, unsigned long to, Expression *e)
16412       : index(i), traversal_order(to), expr(e) { }
operator <IVT_triple16413   bool operator<(const IVT_triple& other) const
16414   { return this->index < other.index; }
16415 };
16416 
16417 // Lower an array composite literal.
16418 
16419 Expression*
lower_array(Type * type)16420 Composite_literal_expression::lower_array(Type* type)
16421 {
16422   Location location = this->location();
16423   if (this->vals_ == NULL || !this->has_keys_)
16424     return this->make_array(type, NULL, this->vals_);
16425 
16426   std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
16427   indexes->reserve(this->vals_->size());
16428   bool indexes_out_of_order = false;
16429   Expression_list* vals = new Expression_list();
16430   vals->reserve(this->vals_->size());
16431   unsigned long index = 0;
16432   Expression_list::const_iterator p = this->vals_->begin();
16433   while (p != this->vals_->end())
16434     {
16435       Expression* index_expr = *p;
16436 
16437       ++p;
16438       go_assert(p != this->vals_->end());
16439       Expression* val = *p;
16440 
16441       ++p;
16442 
16443       if (index_expr == NULL)
16444 	{
16445 	  if (std::find(indexes->begin(), indexes->end(), index)
16446 	      != indexes->end())
16447 	    {
16448 	      go_error_at(val->location(),
16449 			  "duplicate value for index %lu", index);
16450 	      return Expression::make_error(location);
16451 	    }
16452 	  if (!indexes->empty())
16453 	    indexes->push_back(index);
16454 	}
16455       else
16456 	{
16457 	  if (indexes->empty() && !vals->empty())
16458 	    {
16459 	      for (size_t i = 0; i < vals->size(); ++i)
16460 		indexes->push_back(i);
16461 	    }
16462 
16463 	  Numeric_constant nc;
16464 	  if (!index_expr->numeric_constant_value(&nc))
16465 	    {
16466 	      go_error_at(index_expr->location(),
16467                           "index expression is not integer constant");
16468 	      return Expression::make_error(location);
16469 	    }
16470 
16471 	  switch (nc.to_unsigned_long(&index))
16472 	    {
16473 	    case Numeric_constant::NC_UL_VALID:
16474 	      break;
16475 	    case Numeric_constant::NC_UL_NOTINT:
16476 	      go_error_at(index_expr->location(),
16477                           "index expression is not integer constant");
16478 	      return Expression::make_error(location);
16479 	    case Numeric_constant::NC_UL_NEGATIVE:
16480 	      go_error_at(index_expr->location(),
16481                           "index expression is negative");
16482 	      return Expression::make_error(location);
16483 	    case Numeric_constant::NC_UL_BIG:
16484 	      go_error_at(index_expr->location(), "index value overflow");
16485 	      return Expression::make_error(location);
16486 	    default:
16487 	      go_unreachable();
16488 	    }
16489 
16490 	  Named_type* ntype = Type::lookup_integer_type("int");
16491 	  Integer_type* inttype = ntype->integer_type();
16492 	  if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
16493 	      && index >> (inttype->bits() - 1) != 0)
16494 	    {
16495 	      go_error_at(index_expr->location(), "index value overflow");
16496 	      return Expression::make_error(location);
16497 	    }
16498 
16499 	  if (std::find(indexes->begin(), indexes->end(), index)
16500 	      != indexes->end())
16501 	    {
16502 	      go_error_at(index_expr->location(),
16503                           "duplicate value for index %lu",
16504                           index);
16505 	      return Expression::make_error(location);
16506 	    }
16507 
16508 	  if (!indexes->empty() && index < indexes->back())
16509 	    indexes_out_of_order = true;
16510 
16511 	  indexes->push_back(index);
16512 	}
16513 
16514       vals->push_back(val);
16515 
16516       ++index;
16517     }
16518 
16519   if (indexes->empty())
16520     {
16521       delete indexes;
16522       indexes = NULL;
16523     }
16524 
16525   std::vector<unsigned long>* traverse_order = NULL;
16526   if (indexes_out_of_order)
16527     {
16528       typedef std::vector<IVT_triple> V;
16529 
16530       V v;
16531       v.reserve(indexes->size());
16532       std::vector<unsigned long>::const_iterator pi = indexes->begin();
16533       unsigned long torder = 0;
16534       for (Expression_list::const_iterator pe = vals->begin();
16535 	   pe != vals->end();
16536 	   ++pe, ++pi, ++torder)
16537 	v.push_back(IVT_triple(*pi, torder, *pe));
16538 
16539       std::sort(v.begin(), v.end());
16540 
16541       delete indexes;
16542       delete vals;
16543 
16544       indexes = new std::vector<unsigned long>();
16545       indexes->reserve(v.size());
16546       vals = new Expression_list();
16547       vals->reserve(v.size());
16548       traverse_order = new std::vector<unsigned long>();
16549       traverse_order->reserve(v.size());
16550 
16551       for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
16552 	{
16553 	  indexes->push_back(pv->index);
16554 	  vals->push_back(pv->expr);
16555 	  traverse_order->push_back(pv->traversal_order);
16556 	}
16557     }
16558 
16559   Expression* ret = this->make_array(type, indexes, vals);
16560   Array_construction_expression* ace = ret->array_literal();
16561   if (ace != NULL && traverse_order != NULL)
16562     ace->set_traverse_order(traverse_order);
16563   return ret;
16564 }
16565 
16566 // Actually build the array composite literal. This handles
16567 // [...]{...}.
16568 
16569 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)16570 Composite_literal_expression::make_array(
16571     Type* type,
16572     const std::vector<unsigned long>* indexes,
16573     Expression_list* vals)
16574 {
16575   Location location = this->location();
16576   Array_type* at = type->array_type();
16577 
16578   if (at->length() != NULL && at->length()->is_nil_expression())
16579     {
16580       size_t size;
16581       if (vals == NULL)
16582 	size = 0;
16583       else if (indexes != NULL)
16584 	size = indexes->back() + 1;
16585       else
16586 	{
16587 	  size = vals->size();
16588 	  Integer_type* it = Type::lookup_integer_type("int")->integer_type();
16589 	  if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
16590 	      && size >> (it->bits() - 1) != 0)
16591 	    {
16592 	      go_error_at(location, "too many elements in composite literal");
16593 	      return Expression::make_error(location);
16594 	    }
16595 	}
16596 
16597       Expression* elen = Expression::make_integer_ul(size, NULL, location);
16598       at = Type::make_array_type(at->element_type(), elen);
16599       type = at;
16600     }
16601   else if (at->length() != NULL
16602 	   && !at->length()->is_error_expression()
16603 	   && this->vals_ != NULL)
16604     {
16605       Numeric_constant nc;
16606       unsigned long val;
16607       if (at->length()->numeric_constant_value(&nc)
16608 	  && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
16609 	{
16610 	  if (indexes == NULL)
16611 	    {
16612 	      if (this->vals_->size() > val)
16613 		{
16614 		  go_error_at(location,
16615                               "too many elements in composite literal");
16616 		  return Expression::make_error(location);
16617 		}
16618 	    }
16619 	  else
16620 	    {
16621 	      unsigned long max = indexes->back();
16622 	      if (max >= val)
16623 		{
16624 		  go_error_at(location,
16625                               ("some element keys in composite literal "
16626                                "are out of range"));
16627 		  return Expression::make_error(location);
16628 		}
16629 	    }
16630 	}
16631     }
16632 
16633   if (at->length() != NULL)
16634     return new Fixed_array_construction_expression(type, indexes, vals,
16635 						   location);
16636   else
16637     return new Slice_construction_expression(type, indexes, vals, location);
16638 }
16639 
16640 // Lower a map composite literal.
16641 
16642 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)16643 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
16644 					Statement_inserter* inserter,
16645 					Type* type)
16646 {
16647   Location location = this->location();
16648   Unordered_map(unsigned int, std::vector<Expression*>) st;
16649   Unordered_map(unsigned int, std::vector<Expression*>) nt;
16650   if (this->vals_ != NULL)
16651     {
16652       if (!this->has_keys_)
16653 	{
16654 	  go_error_at(location, "map composite literal must have keys");
16655 	  return Expression::make_error(location);
16656 	}
16657 
16658       for (Expression_list::iterator p = this->vals_->begin();
16659 	   p != this->vals_->end();
16660 	   p += 2)
16661 	{
16662 	  if (*p == NULL)
16663 	    {
16664 	      ++p;
16665 	      go_error_at((*p)->location(),
16666                           ("map composite literal must "
16667                            "have keys for every value"));
16668 	      return Expression::make_error(location);
16669 	    }
16670 	  // Make sure we have lowered the key; it may not have been
16671 	  // lowered in order to handle keys for struct composite
16672 	  // literals.  Lower it now to get the right error message.
16673 	  if ((*p)->unknown_expression() != NULL)
16674 	    {
16675 	      gogo->lower_expression(function, inserter, &*p);
16676 	      go_assert((*p)->is_error_expression());
16677 	      return Expression::make_error(location);
16678 	    }
16679 	  // Check if there are duplicate constant keys.
16680 	  if (!(*p)->is_constant())
16681 	    continue;
16682 	  std::string sval;
16683 	  Numeric_constant nval;
16684 	  if ((*p)->string_constant_value(&sval)) // Check string keys.
16685 	    {
16686 	      unsigned int h = Gogo::hash_string(sval, 0);
16687 	      // Search the index h in the hash map.
16688 	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16689 	      mit = st.find(h);
16690 	      if (mit == st.end())
16691 		{
16692 		  // No duplicate since h is a new index.
16693 		  // Create a new vector indexed by h and add it to the hash map.
16694 		  std::vector<Expression*> l;
16695 		  l.push_back(*p);
16696 		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16697 		  st.insert(val);
16698 		}
16699 	      else
16700 		{
16701 		  // Do further check since index h already exists.
16702 		  for (std::vector<Expression*>::iterator lit =
16703 			   mit->second.begin();
16704 		       lit != mit->second.end();
16705 		       lit++)
16706 		    {
16707 		      std::string s;
16708 		      bool ok = (*lit)->string_constant_value(&s);
16709 		      go_assert(ok);
16710 		      if (s == sval)
16711 			{
16712 			  go_error_at((*p)->location(), ("duplicate key "
16713 				      "in map literal"));
16714 			  return Expression::make_error(location);
16715 			}
16716 		    }
16717 		  // Add this new string key to the vector indexed by h.
16718 		  mit->second.push_back(*p);
16719 		}
16720 	    }
16721 	  else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
16722 	    {
16723 	      unsigned int h = nval.hash(0);
16724 	      Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16725 	      mit = nt.find(h);
16726 	      if (mit == nt.end())
16727 		{
16728 		  // No duplicate since h is a new code.
16729 		  // Create a new vector indexed by h and add it to the hash map.
16730 		  std::vector<Expression*> l;
16731 		  l.push_back(*p);
16732 		  std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16733 		  nt.insert(val);
16734 		}
16735 	      else
16736 		{
16737 		  // Do further check since h already exists.
16738 		  for (std::vector<Expression*>::iterator lit =
16739 			   mit->second.begin();
16740 		       lit != mit->second.end();
16741 		       lit++)
16742 		    {
16743 		      Numeric_constant rval;
16744 		      bool ok = (*lit)->numeric_constant_value(&rval);
16745 		      go_assert(ok);
16746 		      if (nval.equals(rval))
16747 			{
16748 			  go_error_at((*p)->location(),
16749 				      "duplicate key in map literal");
16750 			  return Expression::make_error(location);
16751 			}
16752 		    }
16753 		  // Add this new numeric key to the vector indexed by h.
16754 		  mit->second.push_back(*p);
16755 		}
16756 	    }
16757 	}
16758     }
16759 
16760   return new Map_construction_expression(type, this->vals_, location);
16761 }
16762 
16763 // Copy.
16764 
16765 Expression*
do_copy()16766 Composite_literal_expression::do_copy()
16767 {
16768   Composite_literal_expression* ret =
16769     new Composite_literal_expression(this->type_->copy_expressions(),
16770 				     this->depth_, this->has_keys_,
16771 				     (this->vals_ == NULL
16772 				      ? NULL
16773 				      : this->vals_->copy()),
16774 				     this->all_are_names_,
16775 				     this->location());
16776   ret->key_path_ = this->key_path_;
16777   return ret;
16778 }
16779 
16780 // Dump ast representation for a composite literal expression.
16781 
16782 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16783 Composite_literal_expression::do_dump_expression(
16784                                Ast_dump_context* ast_dump_context) const
16785 {
16786   ast_dump_context->ostream() << "composite(";
16787   ast_dump_context->dump_type(this->type_);
16788   ast_dump_context->ostream() << ", {";
16789   ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
16790   ast_dump_context->ostream() << "})";
16791 }
16792 
16793 // Make a composite literal expression.
16794 
16795 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)16796 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
16797 				   Expression_list* vals, bool all_are_names,
16798 				   Location location)
16799 {
16800   return new Composite_literal_expression(type, depth, has_keys, vals,
16801 					  all_are_names, location);
16802 }
16803 
16804 // Return whether this expression is a composite literal.
16805 
16806 bool
is_composite_literal() const16807 Expression::is_composite_literal() const
16808 {
16809   switch (this->classification_)
16810     {
16811     case EXPRESSION_COMPOSITE_LITERAL:
16812     case EXPRESSION_STRUCT_CONSTRUCTION:
16813     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16814     case EXPRESSION_SLICE_CONSTRUCTION:
16815     case EXPRESSION_MAP_CONSTRUCTION:
16816       return true;
16817     default:
16818       return false;
16819     }
16820 }
16821 
16822 // Return whether this expression is a composite literal which is not
16823 // constant.
16824 
16825 bool
is_nonconstant_composite_literal() const16826 Expression::is_nonconstant_composite_literal() const
16827 {
16828   switch (this->classification_)
16829     {
16830     case EXPRESSION_STRUCT_CONSTRUCTION:
16831       {
16832 	const Struct_construction_expression *psce =
16833 	  static_cast<const Struct_construction_expression*>(this);
16834 	return !psce->is_constant_struct();
16835       }
16836     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16837       {
16838 	const Fixed_array_construction_expression *pace =
16839 	  static_cast<const Fixed_array_construction_expression*>(this);
16840 	return !pace->is_constant_array();
16841       }
16842     case EXPRESSION_SLICE_CONSTRUCTION:
16843       {
16844 	const Slice_construction_expression *pace =
16845 	  static_cast<const Slice_construction_expression*>(this);
16846 	return !pace->is_constant_array();
16847       }
16848     case EXPRESSION_MAP_CONSTRUCTION:
16849       return true;
16850     default:
16851       return false;
16852     }
16853 }
16854 
16855 // Return true if this is a variable or temporary_variable.
16856 
16857 bool
is_variable() const16858 Expression::is_variable() const
16859 {
16860   switch (this->classification_)
16861     {
16862     case EXPRESSION_VAR_REFERENCE:
16863     case EXPRESSION_TEMPORARY_REFERENCE:
16864     case EXPRESSION_SET_AND_USE_TEMPORARY:
16865     case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16866       return true;
16867     default:
16868       return false;
16869     }
16870 }
16871 
16872 // Return true if this is a reference to a local variable.
16873 
16874 bool
is_local_variable() const16875 Expression::is_local_variable() const
16876 {
16877   const Var_expression* ve = this->var_expression();
16878   if (ve == NULL)
16879     return false;
16880   const Named_object* no = ve->named_object();
16881   return (no->is_result_variable()
16882 	  || (no->is_variable() && !no->var_value()->is_global()));
16883 }
16884 
16885 const Named_object*
named_constant() const16886 Expression::named_constant() const
16887 {
16888   if (this->classification() != EXPRESSION_CONST_REFERENCE)
16889     return NULL;
16890   const Const_expression* ce = static_cast<const Const_expression*>(this);
16891   return ce->named_object();
16892 }
16893 
16894 // Class Type_guard_expression.
16895 
16896 // Traversal.
16897 
16898 int
do_traverse(Traverse * traverse)16899 Type_guard_expression::do_traverse(Traverse* traverse)
16900 {
16901   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
16902       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16903     return TRAVERSE_EXIT;
16904   return TRAVERSE_CONTINUE;
16905 }
16906 
16907 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)16908 Type_guard_expression::do_flatten(Gogo*, Named_object*,
16909                                   Statement_inserter* inserter)
16910 {
16911   if (this->expr_->is_error_expression()
16912       || this->expr_->type()->is_error_type())
16913     {
16914       go_assert(saw_errors());
16915       return Expression::make_error(this->location());
16916     }
16917 
16918   if (!this->expr_->is_variable())
16919     {
16920       Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
16921                                                             this->location());
16922       inserter->insert(temp);
16923       this->expr_ =
16924           Expression::make_temporary_reference(temp, this->location());
16925     }
16926   return this;
16927 }
16928 
16929 // Check types of a type guard expression.  The expression must have
16930 // an interface type, but the actual type conversion is checked at run
16931 // time.
16932 
16933 void
do_check_types(Gogo *)16934 Type_guard_expression::do_check_types(Gogo*)
16935 {
16936   Type* expr_type = this->expr_->type();
16937   if (expr_type->interface_type() == NULL)
16938     {
16939       if (!expr_type->is_error() && !this->type_->is_error())
16940 	this->report_error(_("type assertion only valid for interface types"));
16941       this->set_is_error();
16942     }
16943   else if (this->type_->interface_type() == NULL)
16944     {
16945       std::string reason;
16946       if (!expr_type->interface_type()->implements_interface(this->type_,
16947 							     &reason))
16948 	{
16949 	  if (!this->type_->is_error())
16950 	    {
16951 	      if (reason.empty())
16952 		this->report_error(_("impossible type assertion: "
16953 				     "type does not implement interface"));
16954 	      else
16955 		go_error_at(this->location(),
16956                             ("impossible type assertion: "
16957                              "type does not implement interface (%s)"),
16958                             reason.c_str());
16959 	    }
16960 	  this->set_is_error();
16961 	}
16962     }
16963 }
16964 
16965 // Copy.
16966 
16967 Expression*
do_copy()16968 Type_guard_expression::do_copy()
16969 {
16970   return new Type_guard_expression(this->expr_->copy(),
16971 				   this->type_->copy_expressions(),
16972 				   this->location());
16973 }
16974 
16975 // Return the backend representation for a type guard expression.
16976 
16977 Bexpression*
do_get_backend(Translate_context * context)16978 Type_guard_expression::do_get_backend(Translate_context* context)
16979 {
16980   Expression* conversion;
16981   if (this->type_->interface_type() != NULL)
16982     conversion =
16983         Expression::convert_interface_to_interface(this->type_, this->expr_,
16984                                                    true, this->location());
16985   else
16986     conversion =
16987         Expression::convert_for_assignment(context->gogo(), this->type_,
16988                                            this->expr_, this->location());
16989 
16990   Gogo* gogo = context->gogo();
16991   Btype* bt = this->type_->get_backend(gogo);
16992   Bexpression* bexpr = conversion->get_backend(context);
16993   return gogo->backend()->convert_expression(bt, bexpr, this->location());
16994 }
16995 
16996 // Dump ast representation for a type guard expression.
16997 
16998 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16999 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
17000     const
17001 {
17002   this->expr_->dump_expression(ast_dump_context);
17003   ast_dump_context->ostream() <<  ".";
17004   ast_dump_context->dump_type(this->type_);
17005 }
17006 
17007 // Make a type guard expression.
17008 
17009 Expression*
make_type_guard(Expression * expr,Type * type,Location location)17010 Expression::make_type_guard(Expression* expr, Type* type,
17011 			    Location location)
17012 {
17013   return new Type_guard_expression(expr, type, location);
17014 }
17015 
17016 // Class Heap_expression.
17017 
17018 // Return the type of the expression stored on the heap.
17019 
17020 Type*
do_type()17021 Heap_expression::do_type()
17022 { return Type::make_pointer_type(this->expr_->type()); }
17023 
17024 // Return the backend representation for allocating an expression on the heap.
17025 
17026 Bexpression*
do_get_backend(Translate_context * context)17027 Heap_expression::do_get_backend(Translate_context* context)
17028 {
17029   Type* etype = this->expr_->type();
17030   if (this->expr_->is_error_expression() || etype->is_error())
17031     return context->backend()->error_expression();
17032 
17033   Location loc = this->location();
17034   Gogo* gogo = context->gogo();
17035   Btype* btype = this->type()->get_backend(gogo);
17036 
17037   Expression* alloc = Expression::make_allocation(etype, loc);
17038   if (this->allocate_on_stack_)
17039     alloc->allocation_expression()->set_allocate_on_stack();
17040   Bexpression* space = alloc->get_backend(context);
17041 
17042   Bstatement* decl;
17043   Named_object* fn = context->function();
17044   go_assert(fn != NULL);
17045   Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
17046   Bvariable* space_temp =
17047     gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
17048 					space, true, loc, &decl);
17049   Btype* expr_btype = etype->get_backend(gogo);
17050 
17051   Bexpression* bexpr = this->expr_->get_backend(context);
17052 
17053   // If this assignment needs a write barrier, call typedmemmove.  We
17054   // don't do this in the write barrier pass because in some cases
17055   // backend conversion can introduce new Heap_expression values.
17056   Bstatement* assn;
17057   if (!etype->has_pointer() || this->allocate_on_stack_)
17058     {
17059       space = gogo->backend()->var_expression(space_temp, loc);
17060       Bexpression* ref =
17061 	gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17062       assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
17063     }
17064   else
17065     {
17066       Bstatement* edecl;
17067       Bvariable* btemp =
17068 	gogo->backend()->temporary_variable(fndecl, context->bblock(),
17069 					    expr_btype, bexpr, true, loc,
17070 					    &edecl);
17071       Bexpression* btempref = gogo->backend()->var_expression(btemp,
17072 							      loc);
17073       space = gogo->backend()->var_expression(space_temp, loc);
17074       Type* etype_ptr = Type::make_pointer_type(etype);
17075       Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
17076       Expression* erhs;
17077       Expression* call;
17078       if (etype->is_direct_iface_type())
17079         {
17080           // Single pointer.
17081           Type* uintptr_type = Type::lookup_integer_type("uintptr");
17082           erhs = Expression::make_backend(btempref, etype, loc);
17083           erhs = Expression::unpack_direct_iface(erhs, loc);
17084           erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
17085           call = Runtime::make_call(Runtime::GCWRITEBARRIER, loc, 2,
17086                                     elhs, erhs);
17087         }
17088       else
17089         {
17090           Expression* td = Expression::make_type_descriptor(etype, loc);
17091           Bexpression* addr =
17092             gogo->backend()->address_expression(btempref, loc);
17093           erhs = Expression::make_backend(addr, etype_ptr, loc);
17094           call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
17095                                     td, elhs, erhs);
17096         }
17097       Statement* cs = Statement::make_statement(call, false);
17098 
17099       space = gogo->backend()->var_expression(space_temp, loc);
17100       Bexpression* ref =
17101         gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17102       Expression* eref = Expression::make_backend(ref, etype, loc);
17103       btempref = gogo->backend()->var_expression(btemp, loc);
17104       erhs = Expression::make_backend(btempref, etype, loc);
17105       Statement* as = Statement::make_assignment(eref, erhs, loc);
17106 
17107       as = gogo->check_write_barrier(context->block(), as, cs);
17108       Bstatement* s = as->get_backend(context);
17109 
17110       assn = gogo->backend()->compound_statement(edecl, s);
17111     }
17112   decl = gogo->backend()->compound_statement(decl, assn);
17113   space = gogo->backend()->var_expression(space_temp, loc);
17114   return gogo->backend()->compound_expression(decl, space, loc);
17115 }
17116 
17117 // Dump ast representation for a heap expression.
17118 
17119 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17120 Heap_expression::do_dump_expression(
17121     Ast_dump_context* ast_dump_context) const
17122 {
17123   ast_dump_context->ostream() << "&(";
17124   ast_dump_context->dump_expression(this->expr_);
17125   ast_dump_context->ostream() << ")";
17126 }
17127 
17128 // Allocate an expression on the heap.
17129 
17130 Expression*
make_heap_expression(Expression * expr,Location location)17131 Expression::make_heap_expression(Expression* expr, Location location)
17132 {
17133   return new Heap_expression(expr, location);
17134 }
17135 
17136 // Class Receive_expression.
17137 
17138 // Return the type of a receive expression.
17139 
17140 Type*
do_type()17141 Receive_expression::do_type()
17142 {
17143   if (this->is_error_expression())
17144     return Type::make_error_type();
17145   Channel_type* channel_type = this->channel_->type()->channel_type();
17146   if (channel_type == NULL)
17147     {
17148       this->report_error(_("expected channel"));
17149       return Type::make_error_type();
17150     }
17151   return channel_type->element_type();
17152 }
17153 
17154 // Check types for a receive expression.
17155 
17156 void
do_check_types(Gogo *)17157 Receive_expression::do_check_types(Gogo*)
17158 {
17159   Type* type = this->channel_->type();
17160   if (type->is_error())
17161     {
17162       go_assert(saw_errors());
17163       this->set_is_error();
17164       return;
17165     }
17166   if (type->channel_type() == NULL)
17167     {
17168       this->report_error(_("expected channel"));
17169       return;
17170     }
17171   if (!type->channel_type()->may_receive())
17172     {
17173       this->report_error(_("invalid receive on send-only channel"));
17174       return;
17175     }
17176 }
17177 
17178 // Flattening for receive expressions creates a temporary variable to store
17179 // received data in for receives.
17180 
17181 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)17182 Receive_expression::do_flatten(Gogo*, Named_object*,
17183                                Statement_inserter* inserter)
17184 {
17185   Channel_type* channel_type = this->channel_->type()->channel_type();
17186   if (channel_type == NULL)
17187     {
17188       go_assert(saw_errors());
17189       return this;
17190     }
17191   else if (this->channel_->is_error_expression())
17192    {
17193      go_assert(saw_errors());
17194      return Expression::make_error(this->location());
17195    }
17196 
17197   Type* element_type = channel_type->element_type();
17198   if (this->temp_receiver_ == NULL)
17199     {
17200       this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
17201 						       this->location());
17202       this->temp_receiver_->set_is_address_taken();
17203       inserter->insert(this->temp_receiver_);
17204     }
17205 
17206   return this;
17207 }
17208 
17209 // Get the backend representation for a receive expression.
17210 
17211 Bexpression*
do_get_backend(Translate_context * context)17212 Receive_expression::do_get_backend(Translate_context* context)
17213 {
17214   Location loc = this->location();
17215 
17216   Channel_type* channel_type = this->channel_->type()->channel_type();
17217   if (channel_type == NULL)
17218     {
17219       go_assert(this->channel_->type()->is_error());
17220       return context->backend()->error_expression();
17221     }
17222 
17223   Expression* recv_ref =
17224     Expression::make_temporary_reference(this->temp_receiver_, loc);
17225   Expression* recv_addr =
17226     Expression::make_temporary_reference(this->temp_receiver_, loc);
17227   recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
17228   Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
17229 					this->channel_, recv_addr);
17230   return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
17231 }
17232 
17233 // Export a receive expression.
17234 
17235 void
do_export(Export_function_body * efb) const17236 Receive_expression::do_export(Export_function_body* efb) const
17237 {
17238   efb->write_c_string("<-");
17239   this->channel_->export_expression(efb);
17240 }
17241 
17242 // Dump ast representation for a receive expression.
17243 
17244 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17245 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
17246 {
17247   ast_dump_context->ostream() << " <- " ;
17248   ast_dump_context->dump_expression(channel_);
17249 }
17250 
17251 // Import a receive expression.
17252 
17253 Expression*
do_import(Import_expression * imp,Location loc)17254 Receive_expression::do_import(Import_expression* imp, Location loc)
17255 {
17256   imp->require_c_string("<-");
17257   Expression* expr = Expression::import_expression(imp, loc);
17258   return Expression::make_receive(expr, loc);
17259 }
17260 
17261 // Make a receive expression.
17262 
17263 Receive_expression*
make_receive(Expression * channel,Location location)17264 Expression::make_receive(Expression* channel, Location location)
17265 {
17266   return new Receive_expression(channel, location);
17267 }
17268 
17269 // An expression which evaluates to a pointer to the type descriptor
17270 // of a type.
17271 
17272 class Type_descriptor_expression : public Expression
17273 {
17274  public:
Type_descriptor_expression(Type * type,Location location)17275   Type_descriptor_expression(Type* type, Location location)
17276     : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
17277       type_(type)
17278   { }
17279 
17280  protected:
17281   int
17282   do_traverse(Traverse*);
17283 
17284   Type*
do_type()17285   do_type()
17286   { return Type::make_type_descriptor_ptr_type(); }
17287 
17288   bool
do_is_static_initializer() const17289   do_is_static_initializer() const
17290   { return true; }
17291 
17292   void
do_determine_type(const Type_context *)17293   do_determine_type(const Type_context*)
17294   { }
17295 
17296   Expression*
do_copy()17297   do_copy()
17298   { return this; }
17299 
17300   Bexpression*
do_get_backend(Translate_context * context)17301   do_get_backend(Translate_context* context)
17302   {
17303     return this->type_->type_descriptor_pointer(context->gogo(),
17304 						this->location());
17305   }
17306 
17307   void
17308   do_dump_expression(Ast_dump_context*) const;
17309 
17310  private:
17311   // The type for which this is the descriptor.
17312   Type* type_;
17313 };
17314 
17315 int
do_traverse(Traverse * traverse)17316 Type_descriptor_expression::do_traverse(Traverse* traverse)
17317 {
17318   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17319     return TRAVERSE_EXIT;
17320   return TRAVERSE_CONTINUE;
17321 }
17322 
17323 // Dump ast representation for a type descriptor expression.
17324 
17325 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17326 Type_descriptor_expression::do_dump_expression(
17327     Ast_dump_context* ast_dump_context) const
17328 {
17329   ast_dump_context->dump_type(this->type_);
17330 }
17331 
17332 // Make a type descriptor expression.
17333 
17334 Expression*
make_type_descriptor(Type * type,Location location)17335 Expression::make_type_descriptor(Type* type, Location location)
17336 {
17337   return new Type_descriptor_expression(type, location);
17338 }
17339 
17340 // An expression which evaluates to a pointer to the Garbage Collection symbol
17341 // of a type.
17342 
17343 class GC_symbol_expression : public Expression
17344 {
17345  public:
GC_symbol_expression(Type * type)17346   GC_symbol_expression(Type* type)
17347     : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
17348       type_(type)
17349   {}
17350 
17351  protected:
17352   Type*
do_type()17353   do_type()
17354   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17355 
17356   bool
do_is_static_initializer() const17357   do_is_static_initializer() const
17358   { return true; }
17359 
17360   void
do_determine_type(const Type_context *)17361   do_determine_type(const Type_context*)
17362   { }
17363 
17364   Expression*
do_copy()17365   do_copy()
17366   { return this; }
17367 
17368   Bexpression*
do_get_backend(Translate_context * context)17369   do_get_backend(Translate_context* context)
17370   { return this->type_->gc_symbol_pointer(context->gogo()); }
17371 
17372   void
17373   do_dump_expression(Ast_dump_context*) const;
17374 
17375  private:
17376   // The type which this gc symbol describes.
17377   Type* type_;
17378 };
17379 
17380 // Dump ast representation for a gc symbol expression.
17381 
17382 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17383 GC_symbol_expression::do_dump_expression(
17384     Ast_dump_context* ast_dump_context) const
17385 {
17386   ast_dump_context->ostream() << "gcdata(";
17387   ast_dump_context->dump_type(this->type_);
17388   ast_dump_context->ostream() << ")";
17389 }
17390 
17391 // Make a gc symbol expression.
17392 
17393 Expression*
make_gc_symbol(Type * type)17394 Expression::make_gc_symbol(Type* type)
17395 {
17396   return new GC_symbol_expression(type);
17397 }
17398 
17399 // An expression that evaluates to a pointer to a symbol holding the
17400 // ptrmask data of a type.
17401 
17402 class Ptrmask_symbol_expression : public Expression
17403 {
17404  public:
Ptrmask_symbol_expression(Type * type)17405   Ptrmask_symbol_expression(Type* type)
17406     : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
17407       type_(type)
17408   {}
17409 
17410  protected:
17411   Type*
do_type()17412   do_type()
17413   { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17414 
17415   bool
do_is_static_initializer() const17416   do_is_static_initializer() const
17417   { return true; }
17418 
17419   void
do_determine_type(const Type_context *)17420   do_determine_type(const Type_context*)
17421   { }
17422 
17423   Expression*
do_copy()17424   do_copy()
17425   { return this; }
17426 
17427   Bexpression*
17428   do_get_backend(Translate_context*);
17429 
17430   void
17431   do_dump_expression(Ast_dump_context*) const;
17432 
17433  private:
17434   // The type that this ptrmask symbol describes.
17435   Type* type_;
17436 };
17437 
17438 // Return the ptrmask variable.
17439 
17440 Bexpression*
do_get_backend(Translate_context * context)17441 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
17442 {
17443   Gogo* gogo = context->gogo();
17444 
17445   // If this type does not need a gcprog, then we can use the standard
17446   // GC symbol.
17447   int64_t ptrsize, ptrdata;
17448   if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
17449     return this->type_->gc_symbol_pointer(gogo);
17450 
17451   // Otherwise we have to build a ptrmask variable, and return a
17452   // pointer to it.
17453 
17454   Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
17455   Location bloc = Linemap::predeclared_location();
17456   Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
17457   Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
17458 
17459   Type* uint8_type = Type::lookup_integer_type("uint8");
17460   Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
17461   Btype* ubtype = pointer_uint8_type->get_backend(gogo);
17462   return gogo->backend()->convert_expression(ubtype, baddr, bloc);
17463 }
17464 
17465 // Dump AST for a ptrmask symbol expression.
17466 
17467 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17468 Ptrmask_symbol_expression::do_dump_expression(
17469     Ast_dump_context* ast_dump_context) const
17470 {
17471   ast_dump_context->ostream() << "ptrmask(";
17472   ast_dump_context->dump_type(this->type_);
17473   ast_dump_context->ostream() << ")";
17474 }
17475 
17476 // Make a ptrmask symbol expression.
17477 
17478 Expression*
make_ptrmask_symbol(Type * type)17479 Expression::make_ptrmask_symbol(Type* type)
17480 {
17481   return new Ptrmask_symbol_expression(type);
17482 }
17483 
17484 // An expression which evaluates to some characteristic of a type.
17485 // This is only used to initialize fields of a type descriptor.  Using
17486 // a new expression class is slightly inefficient but gives us a good
17487 // separation between the frontend and the middle-end with regard to
17488 // how types are laid out.
17489 
17490 class Type_info_expression : public Expression
17491 {
17492  public:
Type_info_expression(Type * type,Type_info type_info)17493   Type_info_expression(Type* type, Type_info type_info)
17494     : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
17495       type_(type), type_info_(type_info)
17496   { }
17497 
17498  protected:
17499   bool
do_is_static_initializer() const17500   do_is_static_initializer() const
17501   { return true; }
17502 
17503   Type*
17504   do_type();
17505 
17506   void
do_determine_type(const Type_context *)17507   do_determine_type(const Type_context*)
17508   { }
17509 
17510   Expression*
do_copy()17511   do_copy()
17512   { return this; }
17513 
17514   Bexpression*
17515   do_get_backend(Translate_context* context);
17516 
17517   void
17518   do_dump_expression(Ast_dump_context*) const;
17519 
17520  private:
17521   // The type for which we are getting information.
17522   Type* type_;
17523   // What information we want.
17524   Type_info type_info_;
17525 };
17526 
17527 // The type is chosen to match what the type descriptor struct
17528 // expects.
17529 
17530 Type*
do_type()17531 Type_info_expression::do_type()
17532 {
17533   switch (this->type_info_)
17534     {
17535     case TYPE_INFO_SIZE:
17536     case TYPE_INFO_BACKEND_PTRDATA:
17537     case TYPE_INFO_DESCRIPTOR_PTRDATA:
17538       return Type::lookup_integer_type("uintptr");
17539     case TYPE_INFO_ALIGNMENT:
17540     case TYPE_INFO_FIELD_ALIGNMENT:
17541       return Type::lookup_integer_type("uint8");
17542     default:
17543       go_unreachable();
17544     }
17545 }
17546 
17547 // Return the backend representation for type information.
17548 
17549 Bexpression*
do_get_backend(Translate_context * context)17550 Type_info_expression::do_get_backend(Translate_context* context)
17551 {
17552   Gogo* gogo = context->gogo();
17553   bool ok = true;
17554   int64_t val;
17555   switch (this->type_info_)
17556     {
17557     case TYPE_INFO_SIZE:
17558       ok = this->type_->backend_type_size(gogo, &val);
17559       break;
17560     case TYPE_INFO_ALIGNMENT:
17561       ok = this->type_->backend_type_align(gogo, &val);
17562       break;
17563     case TYPE_INFO_FIELD_ALIGNMENT:
17564       ok = this->type_->backend_type_field_align(gogo, &val);
17565       break;
17566     case TYPE_INFO_BACKEND_PTRDATA:
17567       ok = this->type_->backend_type_ptrdata(gogo, &val);
17568       break;
17569     case TYPE_INFO_DESCRIPTOR_PTRDATA:
17570       ok = this->type_->descriptor_ptrdata(gogo, &val);
17571       break;
17572     default:
17573       go_unreachable();
17574     }
17575   if (!ok)
17576     {
17577       go_assert(saw_errors());
17578       return gogo->backend()->error_expression();
17579     }
17580   Expression* e = Expression::make_integer_int64(val, this->type(),
17581 						 this->location());
17582   return e->get_backend(context);
17583 }
17584 
17585 // Dump ast representation for a type info expression.
17586 
17587 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17588 Type_info_expression::do_dump_expression(
17589     Ast_dump_context* ast_dump_context) const
17590 {
17591   ast_dump_context->ostream() << "typeinfo(";
17592   ast_dump_context->dump_type(this->type_);
17593   ast_dump_context->ostream() << ",";
17594   ast_dump_context->ostream() <<
17595     (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
17596     : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
17597     : this->type_info_ == TYPE_INFO_SIZE ? "size"
17598     : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
17599     : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
17600     : "unknown");
17601   ast_dump_context->ostream() << ")";
17602 }
17603 
17604 // Make a type info expression.
17605 
17606 Expression*
make_type_info(Type * type,Type_info type_info)17607 Expression::make_type_info(Type* type, Type_info type_info)
17608 {
17609   return new Type_info_expression(type, type_info);
17610 }
17611 
17612 // An expression that evaluates to some characteristic of a slice.
17613 // This is used when indexing, bound-checking, or nil checking a slice.
17614 
17615 class Slice_info_expression : public Expression
17616 {
17617  public:
Slice_info_expression(Expression * slice,Slice_info slice_info,Location location)17618   Slice_info_expression(Expression* slice, Slice_info slice_info,
17619                         Location location)
17620     : Expression(EXPRESSION_SLICE_INFO, location),
17621       slice_(slice), slice_info_(slice_info)
17622   { }
17623 
17624  protected:
17625   Type*
17626   do_type();
17627 
17628   void
do_determine_type(const Type_context *)17629   do_determine_type(const Type_context*)
17630   { }
17631 
17632   Expression*
do_copy()17633   do_copy()
17634   {
17635     return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
17636                                      this->location());
17637   }
17638 
17639   Bexpression*
17640   do_get_backend(Translate_context* context);
17641 
17642   void
17643   do_dump_expression(Ast_dump_context*) const;
17644 
17645   void
do_issue_nil_check()17646   do_issue_nil_check()
17647   { this->slice_->issue_nil_check(); }
17648 
17649  private:
17650   // The slice for which we are getting information.
17651   Expression* slice_;
17652   // What information we want.
17653   Slice_info slice_info_;
17654 };
17655 
17656 // Return the type of the slice info.
17657 
17658 Type*
do_type()17659 Slice_info_expression::do_type()
17660 {
17661   switch (this->slice_info_)
17662     {
17663     case SLICE_INFO_VALUE_POINTER:
17664       return Type::make_pointer_type(
17665           this->slice_->type()->array_type()->element_type());
17666     case SLICE_INFO_LENGTH:
17667     case SLICE_INFO_CAPACITY:
17668         return Type::lookup_integer_type("int");
17669     default:
17670       go_unreachable();
17671     }
17672 }
17673 
17674 // Return the backend information for slice information.
17675 
17676 Bexpression*
do_get_backend(Translate_context * context)17677 Slice_info_expression::do_get_backend(Translate_context* context)
17678 {
17679   Gogo* gogo = context->gogo();
17680   Bexpression* bslice = this->slice_->get_backend(context);
17681   switch (this->slice_info_)
17682     {
17683     case SLICE_INFO_VALUE_POINTER:
17684     case SLICE_INFO_LENGTH:
17685     case SLICE_INFO_CAPACITY:
17686       return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
17687 						      this->location());
17688       break;
17689     default:
17690       go_unreachable();
17691     }
17692 }
17693 
17694 // Dump ast representation for a type info expression.
17695 
17696 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17697 Slice_info_expression::do_dump_expression(
17698     Ast_dump_context* ast_dump_context) const
17699 {
17700   ast_dump_context->ostream() << "sliceinfo(";
17701   this->slice_->dump_expression(ast_dump_context);
17702   ast_dump_context->ostream() << ",";
17703   ast_dump_context->ostream() <<
17704       (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
17705     : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
17706     : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
17707     : "unknown");
17708   ast_dump_context->ostream() << ")";
17709 }
17710 
17711 // Make a slice info expression.
17712 
17713 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)17714 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
17715                             Location location)
17716 {
17717   return new Slice_info_expression(slice, slice_info, location);
17718 }
17719 
17720 // Class Slice_value_expression.
17721 
17722 int
do_traverse(Traverse * traverse)17723 Slice_value_expression::do_traverse(Traverse* traverse)
17724 {
17725   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
17726       || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
17727       || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
17728       || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
17729     return TRAVERSE_EXIT;
17730   return TRAVERSE_CONTINUE;
17731 }
17732 
17733 Expression*
do_copy()17734 Slice_value_expression::do_copy()
17735 {
17736   return new Slice_value_expression(this->type_->copy_expressions(),
17737 				    this->valmem_->copy(),
17738 				    this->len_->copy(), this->cap_->copy(),
17739 				    this->location());
17740 }
17741 
17742 Bexpression*
do_get_backend(Translate_context * context)17743 Slice_value_expression::do_get_backend(Translate_context* context)
17744 {
17745   std::vector<Bexpression*> vals(3);
17746   vals[0] = this->valmem_->get_backend(context);
17747   vals[1] = this->len_->get_backend(context);
17748   vals[2] = this->cap_->get_backend(context);
17749 
17750   Gogo* gogo = context->gogo();
17751   Btype* btype = this->type_->get_backend(gogo);
17752   return gogo->backend()->constructor_expression(btype, vals, this->location());
17753 }
17754 
17755 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17756 Slice_value_expression::do_dump_expression(
17757     Ast_dump_context* ast_dump_context) const
17758 {
17759   ast_dump_context->ostream() << "slicevalue(";
17760   ast_dump_context->ostream() << "values: ";
17761   this->valmem_->dump_expression(ast_dump_context);
17762   ast_dump_context->ostream() << ", length: ";
17763   this->len_->dump_expression(ast_dump_context);
17764   ast_dump_context->ostream() << ", capacity: ";
17765   this->cap_->dump_expression(ast_dump_context);
17766   ast_dump_context->ostream() << ")";
17767 }
17768 
17769 Expression*
make_slice_value(Type * at,Expression * valmem,Expression * len,Expression * cap,Location location)17770 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
17771                              Expression* cap, Location location)
17772 {
17773   go_assert(at->is_slice_type());
17774   go_assert(valmem->is_nil_expression()
17775 	    || (at->array_type()->element_type()
17776 		== valmem->type()->points_to()));
17777   return new Slice_value_expression(at, valmem, len, cap, location);
17778 }
17779 
17780 // Look through the expression of a Slice_value_expression's valmem to
17781 // find an call to makeslice.  If found, return the call expression and
17782 // the containing temporary statement (if any).
17783 
17784 std::pair<Call_expression*, Temporary_statement*>
find_makeslice_call(Expression * expr)17785 Expression::find_makeslice_call(Expression* expr)
17786 {
17787   Unsafe_type_conversion_expression* utce =
17788     expr->unsafe_conversion_expression();
17789   if (utce != NULL)
17790     expr = utce->expr();
17791 
17792   Slice_value_expression* sve = expr->slice_value_expression();
17793   if (sve == NULL)
17794     return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17795   expr = sve->valmem();
17796 
17797   utce = expr->unsafe_conversion_expression();
17798   if (utce != NULL)
17799     expr = utce->expr();
17800 
17801   Temporary_reference_expression* tre = expr->temporary_reference_expression();
17802   Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
17803   if (ts != NULL && ts->init() != NULL && !ts->assigned()
17804       && !ts->is_address_taken())
17805     expr = ts->init();
17806 
17807   Call_expression* call = expr->call_expression();
17808   if (call == NULL)
17809     return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17810 
17811   Func_expression* fe = call->fn()->func_expression();
17812   if (fe != NULL
17813       && fe->runtime_code() == Runtime::MAKESLICE)
17814     return std::make_pair(call, ts);
17815 
17816   return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17817 }
17818 
17819 // An expression that evaluates to some characteristic of a non-empty interface.
17820 // This is used to access the method table or underlying object of an interface.
17821 
17822 class Interface_info_expression : public Expression
17823 {
17824  public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)17825   Interface_info_expression(Expression* iface, Interface_info iface_info,
17826                             Location location)
17827     : Expression(EXPRESSION_INTERFACE_INFO, location),
17828       iface_(iface), iface_info_(iface_info)
17829   { }
17830 
17831  protected:
17832   Type*
17833   do_type();
17834 
17835   void
do_determine_type(const Type_context *)17836   do_determine_type(const Type_context*)
17837   { }
17838 
17839   Expression*
do_copy()17840   do_copy()
17841   {
17842     return new Interface_info_expression(this->iface_->copy(),
17843                                          this->iface_info_, this->location());
17844   }
17845 
17846   Bexpression*
17847   do_get_backend(Translate_context* context);
17848 
17849   void
17850   do_dump_expression(Ast_dump_context*) const;
17851 
17852   void
do_issue_nil_check()17853   do_issue_nil_check()
17854   { this->iface_->issue_nil_check(); }
17855 
17856  private:
17857   // The interface for which we are getting information.
17858   Expression* iface_;
17859   // What information we want.
17860   Interface_info iface_info_;
17861 };
17862 
17863 // Return the type of the interface info.
17864 
17865 Type*
do_type()17866 Interface_info_expression::do_type()
17867 {
17868   switch (this->iface_info_)
17869     {
17870     case INTERFACE_INFO_METHODS:
17871       {
17872         typedef Unordered_map(Interface_type*, Type*) Hashtable;
17873         static Hashtable result_types;
17874 
17875         Interface_type* itype = this->iface_->type()->interface_type();
17876 
17877         Hashtable::const_iterator pr = result_types.find(itype);
17878         if (pr != result_types.end())
17879           return pr->second;
17880 
17881         Type* pdt = Type::make_type_descriptor_ptr_type();
17882         if (itype->is_empty())
17883           {
17884             result_types[itype] = pdt;
17885             return pdt;
17886           }
17887 
17888         Location loc = this->location();
17889         Struct_field_list* sfl = new Struct_field_list();
17890         sfl->push_back(
17891             Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
17892 
17893         for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
17894              p != itype->methods()->end();
17895              ++p)
17896           {
17897             Function_type* ft = p->type()->function_type();
17898             go_assert(ft->receiver() == NULL);
17899 
17900             const Typed_identifier_list* params = ft->parameters();
17901             Typed_identifier_list* mparams = new Typed_identifier_list();
17902             if (params != NULL)
17903               mparams->reserve(params->size() + 1);
17904             Type* vt = Type::make_pointer_type(Type::make_void_type());
17905             mparams->push_back(Typed_identifier("", vt, ft->location()));
17906             if (params != NULL)
17907               {
17908                 for (Typed_identifier_list::const_iterator pp = params->begin();
17909                      pp != params->end();
17910                      ++pp)
17911                   mparams->push_back(*pp);
17912               }
17913 
17914             Typed_identifier_list* mresults = (ft->results() == NULL
17915                                                ? NULL
17916                                                : ft->results()->copy());
17917             Backend_function_type* mft =
17918                 Type::make_backend_function_type(NULL, mparams, mresults,
17919                                                  ft->location());
17920 
17921             std::string fname = Gogo::unpack_hidden_name(p->name());
17922             sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
17923           }
17924 
17925 	Struct_type* st = Type::make_struct_type(sfl, loc);
17926 	st->set_is_struct_incomparable();
17927 	Pointer_type *pt = Type::make_pointer_type(st);
17928         result_types[itype] = pt;
17929         return pt;
17930       }
17931     case INTERFACE_INFO_OBJECT:
17932       return Type::make_pointer_type(Type::make_void_type());
17933     default:
17934       go_unreachable();
17935     }
17936 }
17937 
17938 // Return the backend representation for interface information.
17939 
17940 Bexpression*
do_get_backend(Translate_context * context)17941 Interface_info_expression::do_get_backend(Translate_context* context)
17942 {
17943   Gogo* gogo = context->gogo();
17944   Bexpression* biface = this->iface_->get_backend(context);
17945   switch (this->iface_info_)
17946     {
17947     case INTERFACE_INFO_METHODS:
17948     case INTERFACE_INFO_OBJECT:
17949       return gogo->backend()->struct_field_expression(biface, this->iface_info_,
17950 						      this->location());
17951       break;
17952     default:
17953       go_unreachable();
17954     }
17955 }
17956 
17957 // Dump ast representation for an interface info expression.
17958 
17959 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17960 Interface_info_expression::do_dump_expression(
17961     Ast_dump_context* ast_dump_context) const
17962 {
17963   bool is_empty = this->iface_->type()->interface_type()->is_empty();
17964   ast_dump_context->ostream() << "interfaceinfo(";
17965   this->iface_->dump_expression(ast_dump_context);
17966   ast_dump_context->ostream() << ",";
17967   ast_dump_context->ostream() <<
17968       (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
17969     : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
17970     : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
17971     : "unknown");
17972   ast_dump_context->ostream() << ")";
17973 }
17974 
17975 // Make an interface info expression.
17976 
17977 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)17978 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
17979                                 Location location)
17980 {
17981   return new Interface_info_expression(iface, iface_info, location);
17982 }
17983 
17984 // An expression that represents an interface value.  The first field is either
17985 // a type descriptor for an empty interface or a pointer to the interface method
17986 // table for a non-empty interface.  The second field is always the object.
17987 
17988 class Interface_value_expression : public Expression
17989 {
17990  public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)17991   Interface_value_expression(Type* type, Expression* first_field,
17992                              Expression* obj, Location location)
17993       : Expression(EXPRESSION_INTERFACE_VALUE, location),
17994         type_(type), first_field_(first_field), obj_(obj)
17995   { }
17996 
17997  protected:
17998   int
17999   do_traverse(Traverse*);
18000 
18001   Type*
do_type()18002   do_type()
18003   { return this->type_; }
18004 
18005   void
do_determine_type(const Type_context *)18006   do_determine_type(const Type_context*)
18007   { go_unreachable(); }
18008 
18009   Expression*
do_copy()18010   do_copy()
18011   {
18012     return new Interface_value_expression(this->type_->copy_expressions(),
18013                                           this->first_field_->copy(),
18014                                           this->obj_->copy(), this->location());
18015   }
18016 
18017   Bexpression*
18018   do_get_backend(Translate_context* context);
18019 
18020   void
18021   do_dump_expression(Ast_dump_context*) const;
18022 
18023  private:
18024   // The type of the interface value.
18025   Type* type_;
18026   // The first field of the interface (either a type descriptor or a pointer
18027   // to the method table.
18028   Expression* first_field_;
18029   // The underlying object of the interface.
18030   Expression* obj_;
18031 };
18032 
18033 int
do_traverse(Traverse * traverse)18034 Interface_value_expression::do_traverse(Traverse* traverse)
18035 {
18036   if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
18037       || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
18038     return TRAVERSE_EXIT;
18039   return TRAVERSE_CONTINUE;
18040 }
18041 
18042 Bexpression*
do_get_backend(Translate_context * context)18043 Interface_value_expression::do_get_backend(Translate_context* context)
18044 {
18045   std::vector<Bexpression*> vals(2);
18046   vals[0] = this->first_field_->get_backend(context);
18047   vals[1] = this->obj_->get_backend(context);
18048 
18049   Gogo* gogo = context->gogo();
18050   Btype* btype = this->type_->get_backend(gogo);
18051   return gogo->backend()->constructor_expression(btype, vals, this->location());
18052 }
18053 
18054 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18055 Interface_value_expression::do_dump_expression(
18056     Ast_dump_context* ast_dump_context) const
18057 {
18058   ast_dump_context->ostream() << "interfacevalue(";
18059   ast_dump_context->ostream() <<
18060       (this->type_->interface_type()->is_empty()
18061        ? "type_descriptor: "
18062        : "methods: ");
18063   this->first_field_->dump_expression(ast_dump_context);
18064   ast_dump_context->ostream() << ", object: ";
18065   this->obj_->dump_expression(ast_dump_context);
18066   ast_dump_context->ostream() << ")";
18067 }
18068 
18069 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)18070 Expression::make_interface_value(Type* type, Expression* first_value,
18071                                  Expression* object, Location location)
18072 {
18073   return new Interface_value_expression(type, first_value, object, location);
18074 }
18075 
18076 // An interface method table for a pair of types: an interface type and a type
18077 // that implements that interface.
18078 
18079 class Interface_mtable_expression : public Expression
18080 {
18081  public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)18082   Interface_mtable_expression(Interface_type* itype, Type* type,
18083                               bool is_pointer, Location location)
18084       : Expression(EXPRESSION_INTERFACE_MTABLE, location),
18085         itype_(itype), type_(type), is_pointer_(is_pointer),
18086 	method_table_type_(NULL), bvar_(NULL)
18087   { }
18088 
18089  protected:
18090   int
18091   do_traverse(Traverse*);
18092 
18093   Type*
18094   do_type();
18095 
18096   bool
do_is_static_initializer() const18097   do_is_static_initializer() const
18098   { return true; }
18099 
18100   void
do_determine_type(const Type_context *)18101   do_determine_type(const Type_context*)
18102   { go_unreachable(); }
18103 
18104   Expression*
do_copy()18105   do_copy()
18106   {
18107     Interface_type* itype = this->itype_->copy_expressions()->interface_type();
18108     return new Interface_mtable_expression(itype,
18109 					   this->type_->copy_expressions(),
18110                                            this->is_pointer_, this->location());
18111   }
18112 
18113   bool
do_is_addressable() const18114   do_is_addressable() const
18115   { return true; }
18116 
18117   Bexpression*
18118   do_get_backend(Translate_context* context);
18119 
18120   void
18121   do_dump_expression(Ast_dump_context*) const;
18122 
18123  private:
18124   // The interface type for which the methods are defined.
18125   Interface_type* itype_;
18126   // The type to construct the interface method table for.
18127   Type* type_;
18128   // Whether this table contains the method set for the receiver type or the
18129   // pointer receiver type.
18130   bool is_pointer_;
18131   // The type of the method table.
18132   Type* method_table_type_;
18133   // The backend variable that refers to the interface method table.
18134   Bvariable* bvar_;
18135 };
18136 
18137 int
do_traverse(Traverse * traverse)18138 Interface_mtable_expression::do_traverse(Traverse* traverse)
18139 {
18140   if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
18141       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
18142     return TRAVERSE_EXIT;
18143   return TRAVERSE_CONTINUE;
18144 }
18145 
18146 Type*
do_type()18147 Interface_mtable_expression::do_type()
18148 {
18149   if (this->method_table_type_ != NULL)
18150     return this->method_table_type_;
18151 
18152   const Typed_identifier_list* interface_methods = this->itype_->methods();
18153   go_assert(!interface_methods->empty());
18154 
18155   Struct_field_list* sfl = new Struct_field_list;
18156   Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
18157                        this->location());
18158   sfl->push_back(Struct_field(tid));
18159   Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
18160   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18161        p != interface_methods->end();
18162        ++p)
18163     {
18164       // We want C function pointers here, not func descriptors; model
18165       // using void* pointers.
18166       Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
18167       sfl->push_back(Struct_field(method));
18168     }
18169   Struct_type* st = Type::make_struct_type(sfl, this->location());
18170   st->set_is_struct_incomparable();
18171   this->method_table_type_ = st;
18172   return this->method_table_type_;
18173 }
18174 
18175 Bexpression*
do_get_backend(Translate_context * context)18176 Interface_mtable_expression::do_get_backend(Translate_context* context)
18177 {
18178   Gogo* gogo = context->gogo();
18179   Location loc = Linemap::predeclared_location();
18180   if (this->bvar_ != NULL)
18181     return gogo->backend()->var_expression(this->bvar_, this->location());
18182 
18183   const Typed_identifier_list* interface_methods = this->itype_->methods();
18184   go_assert(!interface_methods->empty());
18185 
18186   std::string mangled_name =
18187     gogo->interface_method_table_name(this->itype_, this->type_,
18188 				      this->is_pointer_);
18189 
18190   // Set is_public if we are converting a named type to an interface
18191   // type that is defined in the same package as the named type, and
18192   // the interface has hidden methods.  In that case the interface
18193   // method table will be defined by the package that defines the
18194   // types.
18195   bool is_public = false;
18196   if (this->type_->named_type() != NULL
18197       && (this->type_->named_type()->named_object()->package()
18198 	  == this->itype_->package()))
18199     {
18200       for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18201 	   p != interface_methods->end();
18202 	   ++p)
18203 	{
18204 	  if (Gogo::is_hidden_name(p->name()))
18205 	    {
18206 	      is_public = true;
18207 	      break;
18208 	    }
18209 	}
18210     }
18211 
18212   if (is_public
18213       && this->type_->named_type()->named_object()->package() != NULL)
18214     {
18215       // The interface conversion table is defined elsewhere.
18216       Btype* btype = this->type()->get_backend(gogo);
18217       std::string asm_name(go_selectively_encode_id(mangled_name));
18218       this->bvar_ =
18219           gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
18220                                                       btype, loc);
18221       return gogo->backend()->var_expression(this->bvar_, this->location());
18222     }
18223 
18224   // The first element is the type descriptor.
18225   Type* td_type;
18226   if (!this->is_pointer_)
18227     td_type = this->type_;
18228   else
18229     td_type = Type::make_pointer_type(this->type_);
18230 
18231   std::vector<Backend::Btyped_identifier> bstructfields;
18232 
18233   // Build an interface method table for a type: a type descriptor followed by a
18234   // list of function pointers, one for each interface method.  This is used for
18235   // interfaces.
18236   Expression_list* svals = new Expression_list();
18237   Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
18238   svals->push_back(tdescriptor);
18239 
18240   Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
18241   Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
18242   bstructfields.push_back(btd);
18243 
18244   Named_type* nt = this->type_->named_type();
18245   Struct_type* st = this->type_->struct_type();
18246   go_assert(nt != NULL || st != NULL);
18247 
18248   for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18249        p != interface_methods->end();
18250        ++p)
18251     {
18252       bool is_ambiguous;
18253       Method* m;
18254       if (nt != NULL)
18255 	m = nt->method_function(p->name(), &is_ambiguous);
18256       else
18257 	m = st->method_function(p->name(), &is_ambiguous);
18258       go_assert(m != NULL);
18259       Named_object* no =
18260         (this->is_pointer_
18261          && this->type_->is_direct_iface_type()
18262          && m->is_value_method()
18263          ? m->iface_stub_object()
18264          : m->named_object());
18265 
18266       go_assert(no->is_function() || no->is_function_declaration());
18267 
18268       Function_type* fcn_type = (no->is_function()
18269                                  ? no->func_value()->type()
18270                                  : no->func_declaration_value()->type());
18271       Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
18272       Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
18273       bstructfields.push_back(bmtype);
18274 
18275       svals->push_back(Expression::make_func_code_reference(no, loc));
18276     }
18277 
18278   Btype *btype = gogo->backend()->struct_type(bstructfields);
18279   std::vector<Bexpression*> ctor_bexprs;
18280   for (Expression_list::const_iterator pe = svals->begin();
18281        pe != svals->end();
18282        ++pe)
18283     {
18284       ctor_bexprs.push_back((*pe)->get_backend(context));
18285     }
18286   Bexpression* ctor =
18287       gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
18288 
18289   std::string asm_name(go_selectively_encode_id(mangled_name));
18290   this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
18291 						  !is_public, btype, loc);
18292   gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
18293                                              !is_public, btype, loc, ctor);
18294   return gogo->backend()->var_expression(this->bvar_, loc);
18295 }
18296 
18297 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18298 Interface_mtable_expression::do_dump_expression(
18299     Ast_dump_context* ast_dump_context) const
18300 {
18301   ast_dump_context->ostream() << "__go_"
18302                               << (this->is_pointer_ ? "pimt__" : "imt_");
18303   ast_dump_context->dump_type(this->itype_);
18304   ast_dump_context->ostream() << "__";
18305   ast_dump_context->dump_type(this->type_);
18306 }
18307 
18308 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)18309 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
18310                                       bool is_pointer, Location location)
18311 {
18312   return new Interface_mtable_expression(itype, type, is_pointer, location);
18313 }
18314 
18315 // An expression which evaluates to the offset of a field within a
18316 // struct.  This, like Type_info_expression, q.v., is only used to
18317 // initialize fields of a type descriptor.
18318 
18319 class Struct_field_offset_expression : public Expression
18320 {
18321  public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)18322   Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
18323     : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
18324 		 Linemap::predeclared_location()),
18325       type_(type), field_(field)
18326   { }
18327 
18328  protected:
18329   bool
do_is_static_initializer() const18330   do_is_static_initializer() const
18331   { return true; }
18332 
18333   Type*
do_type()18334   do_type()
18335   { return Type::lookup_integer_type("uintptr"); }
18336 
18337   void
do_determine_type(const Type_context *)18338   do_determine_type(const Type_context*)
18339   { }
18340 
18341   Expression*
do_copy()18342   do_copy()
18343   { return this; }
18344 
18345   Bexpression*
18346   do_get_backend(Translate_context* context);
18347 
18348   void
18349   do_dump_expression(Ast_dump_context*) const;
18350 
18351  private:
18352   // The type of the struct.
18353   Struct_type* type_;
18354   // The field.
18355   const Struct_field* field_;
18356 };
18357 
18358 // Return the backend representation for a struct field offset.
18359 
18360 Bexpression*
do_get_backend(Translate_context * context)18361 Struct_field_offset_expression::do_get_backend(Translate_context* context)
18362 {
18363   const Struct_field_list* fields = this->type_->fields();
18364   Struct_field_list::const_iterator p;
18365   unsigned i = 0;
18366   for (p = fields->begin();
18367        p != fields->end();
18368        ++p, ++i)
18369     if (&*p == this->field_)
18370       break;
18371   go_assert(&*p == this->field_);
18372 
18373   Gogo* gogo = context->gogo();
18374   Btype* btype = this->type_->get_backend(gogo);
18375 
18376   int64_t offset = gogo->backend()->type_field_offset(btype, i);
18377   Type* uptr_type = Type::lookup_integer_type("uintptr");
18378   Expression* ret =
18379     Expression::make_integer_int64(offset, uptr_type,
18380 				   Linemap::predeclared_location());
18381   return ret->get_backend(context);
18382 }
18383 
18384 // Dump ast representation for a struct field offset expression.
18385 
18386 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18387 Struct_field_offset_expression::do_dump_expression(
18388     Ast_dump_context* ast_dump_context) const
18389 {
18390   ast_dump_context->ostream() <<  "unsafe.Offsetof(";
18391   ast_dump_context->dump_type(this->type_);
18392   ast_dump_context->ostream() << '.';
18393   ast_dump_context->ostream() <<
18394     Gogo::message_name(this->field_->field_name());
18395   ast_dump_context->ostream() << ")";
18396 }
18397 
18398 // Make an expression for a struct field offset.
18399 
18400 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)18401 Expression::make_struct_field_offset(Struct_type* type,
18402 				     const Struct_field* field)
18403 {
18404   return new Struct_field_offset_expression(type, field);
18405 }
18406 
18407 // An expression which evaluates to the address of an unnamed label.
18408 
18409 class Label_addr_expression : public Expression
18410 {
18411  public:
Label_addr_expression(Label * label,Location location)18412   Label_addr_expression(Label* label, Location location)
18413     : Expression(EXPRESSION_LABEL_ADDR, location),
18414       label_(label)
18415   { }
18416 
18417  protected:
18418   Type*
do_type()18419   do_type()
18420   { return Type::make_pointer_type(Type::make_void_type()); }
18421 
18422   void
do_determine_type(const Type_context *)18423   do_determine_type(const Type_context*)
18424   { }
18425 
18426   Expression*
do_copy()18427   do_copy()
18428   { return new Label_addr_expression(this->label_, this->location()); }
18429 
18430   Bexpression*
do_get_backend(Translate_context * context)18431   do_get_backend(Translate_context* context)
18432   { return this->label_->get_addr(context, this->location()); }
18433 
18434   void
do_dump_expression(Ast_dump_context * ast_dump_context) const18435   do_dump_expression(Ast_dump_context* ast_dump_context) const
18436   { ast_dump_context->ostream() << this->label_->name(); }
18437 
18438  private:
18439   // The label whose address we are taking.
18440   Label* label_;
18441 };
18442 
18443 // Make an expression for the address of an unnamed label.
18444 
18445 Expression*
make_label_addr(Label * label,Location location)18446 Expression::make_label_addr(Label* label, Location location)
18447 {
18448   return new Label_addr_expression(label, location);
18449 }
18450 
18451 // Class Conditional_expression.
18452 
18453 // Traversal.
18454 
18455 int
do_traverse(Traverse * traverse)18456 Conditional_expression::do_traverse(Traverse* traverse)
18457 {
18458   if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
18459       || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
18460       || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
18461     return TRAVERSE_EXIT;
18462   return TRAVERSE_CONTINUE;
18463 }
18464 
18465 // Return the type of the conditional expression.
18466 
18467 Type*
do_type()18468 Conditional_expression::do_type()
18469 {
18470   Type* result_type = Type::make_void_type();
18471   if (Type::are_identical(this->then_->type(), this->else_->type(),
18472 			  Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
18473                           NULL))
18474     result_type = this->then_->type();
18475   else if (this->then_->is_nil_expression()
18476            || this->else_->is_nil_expression())
18477     result_type = (!this->then_->is_nil_expression()
18478                    ? this->then_->type()
18479                    : this->else_->type());
18480   return result_type;
18481 }
18482 
18483 // Determine type for a conditional expression.
18484 
18485 void
do_determine_type(const Type_context * context)18486 Conditional_expression::do_determine_type(const Type_context* context)
18487 {
18488   this->cond_->determine_type_no_context();
18489   this->then_->determine_type(context);
18490   this->else_->determine_type(context);
18491 }
18492 
18493 // Get the backend representation of a conditional expression.
18494 
18495 Bexpression*
do_get_backend(Translate_context * context)18496 Conditional_expression::do_get_backend(Translate_context* context)
18497 {
18498   Gogo* gogo = context->gogo();
18499   Btype* result_btype = this->type()->get_backend(gogo);
18500   Bexpression* cond = this->cond_->get_backend(context);
18501   Bexpression* then = this->then_->get_backend(context);
18502   Bexpression* belse = this->else_->get_backend(context);
18503   Bfunction* bfn = context->function()->func_value()->get_decl();
18504   return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
18505 						 belse, this->location());
18506 }
18507 
18508 // Dump ast representation of a conditional expression.
18509 
18510 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18511 Conditional_expression::do_dump_expression(
18512     Ast_dump_context* ast_dump_context) const
18513 {
18514   ast_dump_context->ostream() << "(";
18515   ast_dump_context->dump_expression(this->cond_);
18516   ast_dump_context->ostream() << " ? ";
18517   ast_dump_context->dump_expression(this->then_);
18518   ast_dump_context->ostream() << " : ";
18519   ast_dump_context->dump_expression(this->else_);
18520   ast_dump_context->ostream() << ") ";
18521 }
18522 
18523 // Make a conditional expression.
18524 
18525 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)18526 Expression::make_conditional(Expression* cond, Expression* then,
18527                              Expression* else_expr, Location location)
18528 {
18529   return new Conditional_expression(cond, then, else_expr, location);
18530 }
18531 
18532 // Class Compound_expression.
18533 
18534 // Traversal.
18535 
18536 int
do_traverse(Traverse * traverse)18537 Compound_expression::do_traverse(Traverse* traverse)
18538 {
18539   if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
18540       || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
18541     return TRAVERSE_EXIT;
18542   return TRAVERSE_CONTINUE;
18543 }
18544 
18545 // Return the type of the compound expression.
18546 
18547 Type*
do_type()18548 Compound_expression::do_type()
18549 {
18550   return this->expr_->type();
18551 }
18552 
18553 // Determine type for a compound expression.
18554 
18555 void
do_determine_type(const Type_context * context)18556 Compound_expression::do_determine_type(const Type_context* context)
18557 {
18558   this->init_->determine_type_no_context();
18559   this->expr_->determine_type(context);
18560 }
18561 
18562 // Get the backend representation of a compound expression.
18563 
18564 Bexpression*
do_get_backend(Translate_context * context)18565 Compound_expression::do_get_backend(Translate_context* context)
18566 {
18567   Gogo* gogo = context->gogo();
18568   Bexpression* binit = this->init_->get_backend(context);
18569   Bfunction* bfunction = context->function()->func_value()->get_decl();
18570   Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
18571                                                                 binit);
18572   Bexpression* bexpr = this->expr_->get_backend(context);
18573   return gogo->backend()->compound_expression(init_stmt, bexpr,
18574 					      this->location());
18575 }
18576 
18577 // Dump ast representation of a conditional expression.
18578 
18579 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18580 Compound_expression::do_dump_expression(
18581     Ast_dump_context* ast_dump_context) const
18582 {
18583   ast_dump_context->ostream() << "(";
18584   ast_dump_context->dump_expression(this->init_);
18585   ast_dump_context->ostream() << ",";
18586   ast_dump_context->dump_expression(this->expr_);
18587   ast_dump_context->ostream() << ") ";
18588 }
18589 
18590 // Make a compound expression.
18591 
18592 Expression*
make_compound(Expression * init,Expression * expr,Location location)18593 Expression::make_compound(Expression* init, Expression* expr, Location location)
18594 {
18595   return new Compound_expression(init, expr, location);
18596 }
18597 
18598 // Class Backend_expression.
18599 
18600 int
do_traverse(Traverse *)18601 Backend_expression::do_traverse(Traverse*)
18602 {
18603   return TRAVERSE_CONTINUE;
18604 }
18605 
18606 Expression*
do_copy()18607 Backend_expression::do_copy()
18608 {
18609   return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
18610 				this->location());
18611 }
18612 
18613 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18614 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
18615 {
18616   ast_dump_context->ostream() << "backend_expression<";
18617   ast_dump_context->dump_type(this->type_);
18618   ast_dump_context->ostream() << ">";
18619 }
18620 
18621 Expression*
make_backend(Bexpression * bexpr,Type * type,Location location)18622 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
18623 {
18624   return new Backend_expression(bexpr, type, location);
18625 }
18626 
18627 // Import an expression.  This comes at the end in order to see the
18628 // various class definitions.
18629 
18630 Expression*
import_expression(Import_expression * imp,Location loc)18631 Expression::import_expression(Import_expression* imp, Location loc)
18632 {
18633   Expression* expr = Expression::import_expression_without_suffix(imp, loc);
18634   while (true)
18635     {
18636       if (imp->match_c_string("("))
18637 	{
18638 	  imp->advance(1);
18639 	  Expression_list* args = new Expression_list();
18640 	  bool is_varargs = false;
18641 	  while (!imp->match_c_string(")"))
18642 	    {
18643 	      Expression* arg = Expression::import_expression(imp, loc);
18644 	      if (arg->is_error_expression())
18645 		return arg;
18646 	      args->push_back(arg);
18647 	      if (imp->match_c_string(")"))
18648 		break;
18649 	      else if (imp->match_c_string("...)"))
18650 		{
18651 		  imp->advance(3);
18652 		  is_varargs = true;
18653 		  break;
18654 		}
18655 	      imp->require_c_string(", ");
18656 	    }
18657 	  imp->require_c_string(")");
18658 	  expr = Expression::make_call(expr, args, is_varargs, loc);
18659           expr->call_expression()->set_varargs_are_lowered();
18660 	}
18661       else if (imp->match_c_string("["))
18662 	{
18663 	  imp->advance(1);
18664 	  Expression* start = Expression::import_expression(imp, loc);
18665 	  Expression* end = NULL;
18666 	  Expression* cap = NULL;
18667 	  if (imp->match_c_string(":"))
18668 	    {
18669 	      imp->advance(1);
18670 	      int c = imp->peek_char();
18671 	      if (c == ':' || c == ']')
18672 		end = Expression::make_nil(loc);
18673 	      else
18674 		end = Expression::import_expression(imp, loc);
18675 	      if (imp->match_c_string(":"))
18676 		{
18677 		  imp->advance(1);
18678 		  cap = Expression::import_expression(imp, loc);
18679 		}
18680 	    }
18681 	  imp->require_c_string("]");
18682 	  expr = Expression::make_index(expr, start, end, cap, loc);
18683 	}
18684       else
18685 	break;
18686     }
18687 
18688   return expr;
18689 }
18690 
18691 // Import an expression without considering a suffix (function
18692 // arguments, index operations, etc.).
18693 
18694 Expression*
import_expression_without_suffix(Import_expression * imp,Location loc)18695 Expression::import_expression_without_suffix(Import_expression* imp,
18696 					     Location loc)
18697 {
18698   int c = imp->peek_char();
18699   if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
18700     return Unary_expression::do_import(imp, loc);
18701   else if (c == '(')
18702     return Binary_expression::do_import(imp, loc);
18703   else if (imp->match_c_string("$true")
18704 	   || imp->match_c_string("$false")
18705 	   || (imp->version() < EXPORT_FORMAT_V3
18706 	       && (imp->match_c_string("true")
18707 		   || imp->match_c_string("false"))))
18708     return Boolean_expression::do_import(imp, loc);
18709   else if (c == '"')
18710     return String_expression::do_import(imp, loc);
18711   else if (c == '-' || (c >= '0' && c <= '9'))
18712     {
18713       // This handles integers, floats and complex constants.
18714       return Integer_expression::do_import(imp, loc);
18715     }
18716   else if (imp->match_c_string("<-"))
18717     return Receive_expression::do_import(imp, loc);
18718   else if (imp->match_c_string("$nil")
18719 	   || (imp->version() < EXPORT_FORMAT_V3
18720 	       && imp->match_c_string("nil")))
18721     return Nil_expression::do_import(imp, loc);
18722   else if (imp->match_c_string("$convert")
18723 	   || (imp->version() < EXPORT_FORMAT_V3
18724 	       && imp->match_c_string("convert")))
18725     return Type_conversion_expression::do_import(imp, loc);
18726 
18727   Import_function_body* ifb = imp->ifb();
18728   if (ifb == NULL)
18729     {
18730       go_error_at(imp->location(), "import error: expected expression");
18731       return Expression::make_error(loc);
18732     }
18733   if (ifb->saw_error())
18734     return Expression::make_error(loc);
18735 
18736   if (ifb->match_c_string("$t"))
18737     return Temporary_reference_expression::do_import(ifb, loc);
18738 
18739   return Expression::import_identifier(ifb, loc);
18740 }
18741 
18742 // Import an identifier in an expression.  This is a reference to a
18743 // variable or function.
18744 
18745 Expression*
import_identifier(Import_function_body * ifb,Location loc)18746 Expression::import_identifier(Import_function_body* ifb, Location loc)
18747 {
18748   std::string id;
18749   Package* pkg;
18750   bool is_exported;
18751   if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
18752     {
18753       if (!ifb->saw_error())
18754 	go_error_at(ifb->location(),
18755 		    "import error for %qs: bad qualified identifier at %lu",
18756 		    ifb->name().c_str(),
18757 		    static_cast<unsigned long>(ifb->off()));
18758       ifb->set_saw_error();
18759       return Expression::make_error(loc);
18760     }
18761 
18762   Named_object* no = NULL;
18763   if (pkg == NULL && is_exported)
18764     no = ifb->block()->bindings()->lookup(id);
18765   if (no == NULL)
18766     {
18767       const Package* ipkg = pkg;
18768       if (ipkg == NULL)
18769 	ipkg = ifb->function()->package();
18770       if (!is_exported)
18771 	id = '.' + ipkg->pkgpath() + '.' + id;
18772       no = ipkg->bindings()->lookup(id);
18773     }
18774   if (no == NULL)
18775     no = ifb->gogo()->lookup_global(id.c_str());
18776 
18777   if (no == NULL)
18778     {
18779       if (!ifb->saw_error())
18780 	go_error_at(ifb->location(),
18781 		    "import error for %qs: lookup of %qs failed",
18782 		    ifb->name().c_str(), id.c_str());
18783       ifb->set_saw_error();
18784       return Expression::make_error(loc);
18785     }
18786 
18787   if (no->is_variable() || no->is_result_variable())
18788     return Expression::make_var_reference(no, loc);
18789   else if (no->is_function() || no->is_function_declaration())
18790     return Expression::make_func_reference(no, NULL, loc);
18791   else
18792     {
18793       if (!ifb->saw_error())
18794 	go_error_at(ifb->location(),
18795 		    ("import error for %qs: "
18796 		     "unexpected type of identifier %qs (%d)"),
18797 		    ifb->name().c_str(),
18798 		    id.c_str(), no->classification());
18799       ifb->set_saw_error();
18800       return Expression::make_error(loc);
18801     }
18802 }
18803 
18804 // Class Expression_list.
18805 
18806 // Traverse the list.
18807 
18808 int
traverse(Traverse * traverse)18809 Expression_list::traverse(Traverse* traverse)
18810 {
18811   for (Expression_list::iterator p = this->begin();
18812        p != this->end();
18813        ++p)
18814     {
18815       if (*p != NULL)
18816 	{
18817 	  if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
18818 	    return TRAVERSE_EXIT;
18819 	}
18820     }
18821   return TRAVERSE_CONTINUE;
18822 }
18823 
18824 // Copy the list.
18825 
18826 Expression_list*
copy()18827 Expression_list::copy()
18828 {
18829   Expression_list* ret = new Expression_list();
18830   for (Expression_list::iterator p = this->begin();
18831        p != this->end();
18832        ++p)
18833     {
18834       if (*p == NULL)
18835 	ret->push_back(NULL);
18836       else
18837 	ret->push_back((*p)->copy());
18838     }
18839   return ret;
18840 }
18841 
18842 // Return whether an expression list has an error expression.
18843 
18844 bool
contains_error() const18845 Expression_list::contains_error() const
18846 {
18847   for (Expression_list::const_iterator p = this->begin();
18848        p != this->end();
18849        ++p)
18850     if (*p != NULL && (*p)->is_error_expression())
18851       return true;
18852   return false;
18853 }
18854 
18855 // Class Numeric_constant.
18856 
18857 // Destructor.
18858 
~Numeric_constant()18859 Numeric_constant::~Numeric_constant()
18860 {
18861   this->clear();
18862 }
18863 
18864 // Copy constructor.
18865 
Numeric_constant(const Numeric_constant & a)18866 Numeric_constant::Numeric_constant(const Numeric_constant& a)
18867   : classification_(a.classification_), type_(a.type_)
18868 {
18869   switch (a.classification_)
18870     {
18871     case NC_INVALID:
18872       break;
18873     case NC_INT:
18874     case NC_RUNE:
18875       mpz_init_set(this->u_.int_val, a.u_.int_val);
18876       break;
18877     case NC_FLOAT:
18878       mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
18879       break;
18880     case NC_COMPLEX:
18881       mpc_init2(this->u_.complex_val, mpc_precision);
18882       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
18883       break;
18884     default:
18885       go_unreachable();
18886     }
18887 }
18888 
18889 // Assignment operator.
18890 
18891 Numeric_constant&
operator =(const Numeric_constant & a)18892 Numeric_constant::operator=(const Numeric_constant& a)
18893 {
18894   this->clear();
18895   this->classification_ = a.classification_;
18896   this->type_ = a.type_;
18897   switch (a.classification_)
18898     {
18899     case NC_INVALID:
18900       break;
18901     case NC_INT:
18902     case NC_RUNE:
18903       mpz_init_set(this->u_.int_val, a.u_.int_val);
18904       break;
18905     case NC_FLOAT:
18906       mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
18907       break;
18908     case NC_COMPLEX:
18909       mpc_init2(this->u_.complex_val, mpc_precision);
18910       mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
18911       break;
18912     default:
18913       go_unreachable();
18914     }
18915   return *this;
18916 }
18917 
18918 // Check equality with another numeric constant.
18919 
18920 bool
equals(const Numeric_constant & a) const18921 Numeric_constant::equals(const Numeric_constant& a) const
18922 {
18923   if (this->classification_ != a.classification_)
18924     return false;
18925 
18926   if (this->type_ != NULL && a.type_ != NULL
18927       && !Type::are_identical(this->type_, a.type_,
18928 			      Type::COMPARE_ALIASES, NULL))
18929     return false;
18930 
18931   switch (a.classification_)
18932     {
18933     case NC_INVALID:
18934       break;
18935     case NC_INT:
18936     case NC_RUNE:
18937       return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
18938     case NC_FLOAT:
18939       return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
18940     case NC_COMPLEX:
18941       return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
18942     default:
18943       go_unreachable();
18944     }
18945   return false;
18946 }
18947 
18948 // Clear the contents.
18949 
18950 void
clear()18951 Numeric_constant::clear()
18952 {
18953   switch (this->classification_)
18954     {
18955     case NC_INVALID:
18956       break;
18957     case NC_INT:
18958     case NC_RUNE:
18959       mpz_clear(this->u_.int_val);
18960       break;
18961     case NC_FLOAT:
18962       mpfr_clear(this->u_.float_val);
18963       break;
18964     case NC_COMPLEX:
18965       mpc_clear(this->u_.complex_val);
18966       break;
18967     default:
18968       go_unreachable();
18969     }
18970   this->classification_ = NC_INVALID;
18971 }
18972 
18973 // Set to an unsigned long value.
18974 
18975 void
set_unsigned_long(Type * type,unsigned long val)18976 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
18977 {
18978   this->clear();
18979   this->classification_ = NC_INT;
18980   this->type_ = type;
18981   mpz_init_set_ui(this->u_.int_val, val);
18982 }
18983 
18984 // Set to an integer value.
18985 
18986 void
set_int(Type * type,const mpz_t val)18987 Numeric_constant::set_int(Type* type, const mpz_t val)
18988 {
18989   this->clear();
18990   this->classification_ = NC_INT;
18991   this->type_ = type;
18992   mpz_init_set(this->u_.int_val, val);
18993 }
18994 
18995 // Set to a rune value.
18996 
18997 void
set_rune(Type * type,const mpz_t val)18998 Numeric_constant::set_rune(Type* type, const mpz_t val)
18999 {
19000   this->clear();
19001   this->classification_ = NC_RUNE;
19002   this->type_ = type;
19003   mpz_init_set(this->u_.int_val, val);
19004 }
19005 
19006 // Set to a floating point value.
19007 
19008 void
set_float(Type * type,const mpfr_t val)19009 Numeric_constant::set_float(Type* type, const mpfr_t val)
19010 {
19011   this->clear();
19012   this->classification_ = NC_FLOAT;
19013   this->type_ = type;
19014 
19015   // Numeric constants do not have negative zero values, so remove
19016   // them here.  They also don't have infinity or NaN values, but we
19017   // should never see them here.
19018   int bits = 0;
19019   if (type != NULL
19020       && type->float_type() != NULL
19021       && !type->float_type()->is_abstract())
19022     bits = type->float_type()->bits();
19023   if (Numeric_constant::is_float_neg_zero(val, bits))
19024     mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
19025   else
19026     mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
19027 }
19028 
19029 // Set to a complex value.
19030 
19031 void
set_complex(Type * type,const mpc_t val)19032 Numeric_constant::set_complex(Type* type, const mpc_t val)
19033 {
19034   this->clear();
19035   this->classification_ = NC_COMPLEX;
19036   this->type_ = type;
19037 
19038   // Avoid negative zero as in set_float.
19039   int bits = 0;
19040   if (type != NULL
19041       && type->complex_type() != NULL
19042       && !type->complex_type()->is_abstract())
19043     bits = type->complex_type()->bits() / 2;
19044 
19045   mpfr_t real;
19046   mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
19047   if (Numeric_constant::is_float_neg_zero(real, bits))
19048     mpfr_set_ui(real, 0, MPFR_RNDN);
19049 
19050   mpfr_t imag;
19051   mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
19052   if (Numeric_constant::is_float_neg_zero(imag, bits))
19053     mpfr_set_ui(imag, 0, MPFR_RNDN);
19054 
19055   mpc_init2(this->u_.complex_val, mpc_precision);
19056   mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
19057 
19058   mpfr_clear(real);
19059   mpfr_clear(imag);
19060 }
19061 
19062 // Return whether VAL, at a precision of BITS, is a negative zero.
19063 // BITS may be zero in which case it is ignored.
19064 
19065 bool
is_float_neg_zero(const mpfr_t val,int bits)19066 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
19067 {
19068   if (!mpfr_signbit(val))
19069     return false;
19070   if (mpfr_zero_p(val))
19071     return true;
19072   mpfr_exp_t min_exp;
19073   switch (bits)
19074     {
19075     case 0:
19076       return false;
19077     case 32:
19078       // In a denormalized float32 the exponent is -126, and there are
19079       // 24 bits of which at least the last must be 1, so the smallest
19080       // representable non-zero exponent is -126 - (24 - 1) == -149.
19081       min_exp = -149;
19082       break;
19083     case 64:
19084       // Minimum exponent is -1022, there are 53 bits.
19085       min_exp = -1074;
19086       break;
19087     default:
19088       go_unreachable();
19089     }
19090   return mpfr_get_exp(val) < min_exp;
19091 }
19092 
19093 // Get an int value.
19094 
19095 void
get_int(mpz_t * val) const19096 Numeric_constant::get_int(mpz_t* val) const
19097 {
19098   go_assert(this->is_int());
19099   mpz_init_set(*val, this->u_.int_val);
19100 }
19101 
19102 // Get a rune value.
19103 
19104 void
get_rune(mpz_t * val) const19105 Numeric_constant::get_rune(mpz_t* val) const
19106 {
19107   go_assert(this->is_rune());
19108   mpz_init_set(*val, this->u_.int_val);
19109 }
19110 
19111 // Get a floating point value.
19112 
19113 void
get_float(mpfr_t * val) const19114 Numeric_constant::get_float(mpfr_t* val) const
19115 {
19116   go_assert(this->is_float());
19117   mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19118 }
19119 
19120 // Get a complex value.
19121 
19122 void
get_complex(mpc_t * val) const19123 Numeric_constant::get_complex(mpc_t* val) const
19124 {
19125   go_assert(this->is_complex());
19126   mpc_init2(*val, mpc_precision);
19127   mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19128 }
19129 
19130 // Express value as unsigned long if possible.
19131 
19132 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const19133 Numeric_constant::to_unsigned_long(unsigned long* val) const
19134 {
19135   switch (this->classification_)
19136     {
19137     case NC_INT:
19138     case NC_RUNE:
19139       return this->mpz_to_unsigned_long(this->u_.int_val, val);
19140     case NC_FLOAT:
19141       return this->mpfr_to_unsigned_long(this->u_.float_val, val);
19142     case NC_COMPLEX:
19143       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19144 	return NC_UL_NOTINT;
19145       return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
19146 					 val);
19147     default:
19148       go_unreachable();
19149     }
19150 }
19151 
19152 // Express integer value as unsigned long if possible.
19153 
19154 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const19155 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
19156 				       unsigned long *val) const
19157 {
19158   if (mpz_sgn(ival) < 0)
19159     return NC_UL_NEGATIVE;
19160   unsigned long ui = mpz_get_ui(ival);
19161   if (mpz_cmp_ui(ival, ui) != 0)
19162     return NC_UL_BIG;
19163   *val = ui;
19164   return NC_UL_VALID;
19165 }
19166 
19167 // Express floating point value as unsigned long if possible.
19168 
19169 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const19170 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
19171 					unsigned long *val) const
19172 {
19173   if (!mpfr_integer_p(fval))
19174     return NC_UL_NOTINT;
19175   mpz_t ival;
19176   mpz_init(ival);
19177   mpfr_get_z(ival, fval, MPFR_RNDN);
19178   To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
19179   mpz_clear(ival);
19180   return ret;
19181 }
19182 
19183 // Express value as memory size if possible.
19184 
19185 bool
to_memory_size(int64_t * val) const19186 Numeric_constant::to_memory_size(int64_t* val) const
19187 {
19188   switch (this->classification_)
19189     {
19190     case NC_INT:
19191     case NC_RUNE:
19192       return this->mpz_to_memory_size(this->u_.int_val, val);
19193     case NC_FLOAT:
19194       return this->mpfr_to_memory_size(this->u_.float_val, val);
19195     case NC_COMPLEX:
19196       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19197 	return false;
19198       return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
19199     default:
19200       go_unreachable();
19201     }
19202 }
19203 
19204 // Express integer as memory size if possible.
19205 
19206 bool
mpz_to_memory_size(const mpz_t ival,int64_t * val) const19207 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
19208 {
19209   if (mpz_sgn(ival) < 0)
19210     return false;
19211   if (mpz_fits_slong_p(ival))
19212     {
19213       *val = static_cast<int64_t>(mpz_get_si(ival));
19214       return true;
19215     }
19216 
19217   // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
19218   // positive value.
19219   if (mpz_sizeinbase(ival, 2) >= 64)
19220     return false;
19221 
19222   mpz_t q, r;
19223   mpz_init(q);
19224   mpz_init(r);
19225   mpz_tdiv_q_2exp(q, ival, 32);
19226   mpz_tdiv_r_2exp(r, ival, 32);
19227   go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
19228   *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
19229 	  + static_cast<int64_t>(mpz_get_ui(r)));
19230   mpz_clear(r);
19231   mpz_clear(q);
19232   return true;
19233 }
19234 
19235 // Express floating point value as memory size if possible.
19236 
19237 bool
mpfr_to_memory_size(const mpfr_t fval,int64_t * val) const19238 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
19239 {
19240   if (!mpfr_integer_p(fval))
19241     return false;
19242   mpz_t ival;
19243   mpz_init(ival);
19244   mpfr_get_z(ival, fval, MPFR_RNDN);
19245   bool ret = this->mpz_to_memory_size(ival, val);
19246   mpz_clear(ival);
19247   return ret;
19248 }
19249 
19250 // Convert value to integer if possible.
19251 
19252 bool
to_int(mpz_t * val) const19253 Numeric_constant::to_int(mpz_t* val) const
19254 {
19255   switch (this->classification_)
19256     {
19257     case NC_INT:
19258     case NC_RUNE:
19259       mpz_init_set(*val, this->u_.int_val);
19260       return true;
19261     case NC_FLOAT:
19262       if (!mpfr_integer_p(this->u_.float_val))
19263 	return false;
19264       mpz_init(*val);
19265       mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
19266       return true;
19267     case NC_COMPLEX:
19268       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
19269 	  || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
19270 	return false;
19271       mpz_init(*val);
19272       mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19273       return true;
19274     default:
19275       go_unreachable();
19276     }
19277 }
19278 
19279 // Convert value to floating point if possible.
19280 
19281 bool
to_float(mpfr_t * val) const19282 Numeric_constant::to_float(mpfr_t* val) const
19283 {
19284   switch (this->classification_)
19285     {
19286     case NC_INT:
19287     case NC_RUNE:
19288       mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
19289       return true;
19290     case NC_FLOAT:
19291       mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19292       return true;
19293     case NC_COMPLEX:
19294       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19295 	return false;
19296       mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19297       return true;
19298     default:
19299       go_unreachable();
19300     }
19301 }
19302 
19303 // Convert value to complex.
19304 
19305 bool
to_complex(mpc_t * val) const19306 Numeric_constant::to_complex(mpc_t* val) const
19307 {
19308   mpc_init2(*val, mpc_precision);
19309   switch (this->classification_)
19310     {
19311     case NC_INT:
19312     case NC_RUNE:
19313       mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
19314       return true;
19315     case NC_FLOAT:
19316       mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
19317       return true;
19318     case NC_COMPLEX:
19319       mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19320       return true;
19321     default:
19322       go_unreachable();
19323     }
19324 }
19325 
19326 // Get the type.
19327 
19328 Type*
type() const19329 Numeric_constant::type() const
19330 {
19331   if (this->type_ != NULL)
19332     return this->type_;
19333   switch (this->classification_)
19334     {
19335     case NC_INT:
19336       return Type::make_abstract_integer_type();
19337     case NC_RUNE:
19338       return Type::make_abstract_character_type();
19339     case NC_FLOAT:
19340       return Type::make_abstract_float_type();
19341     case NC_COMPLEX:
19342       return Type::make_abstract_complex_type();
19343     default:
19344       go_unreachable();
19345     }
19346 }
19347 
19348 // If the constant can be expressed in TYPE, then set the type of the
19349 // constant to TYPE and return true.  Otherwise return false, and, if
19350 // ISSUE_ERROR is true, report an appropriate error message.
19351 
19352 bool
set_type(Type * type,bool issue_error,Location loc)19353 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
19354 {
19355   bool ret;
19356   if (type == NULL || type->is_error())
19357     ret = true;
19358   else if (type->integer_type() != NULL)
19359     ret = this->check_int_type(type->integer_type(), issue_error, loc);
19360   else if (type->float_type() != NULL)
19361     ret = this->check_float_type(type->float_type(), issue_error, loc);
19362   else if (type->complex_type() != NULL)
19363     ret = this->check_complex_type(type->complex_type(), issue_error, loc);
19364   else
19365     {
19366       ret = false;
19367       if (issue_error)
19368         go_assert(saw_errors());
19369     }
19370   if (ret)
19371     this->type_ = type;
19372   return ret;
19373 }
19374 
19375 // Check whether the constant can be expressed in an integer type.
19376 
19377 bool
check_int_type(Integer_type * type,bool issue_error,Location location)19378 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
19379 				 Location location)
19380 {
19381   mpz_t val;
19382   switch (this->classification_)
19383     {
19384     case NC_INT:
19385     case NC_RUNE:
19386       mpz_init_set(val, this->u_.int_val);
19387       break;
19388 
19389     case NC_FLOAT:
19390       if (!mpfr_integer_p(this->u_.float_val))
19391 	{
19392 	  if (issue_error)
19393             {
19394               go_error_at(location,
19395                           "floating-point constant truncated to integer");
19396               this->set_invalid();
19397             }
19398 	  return false;
19399 	}
19400       mpz_init(val);
19401       mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
19402       break;
19403 
19404     case NC_COMPLEX:
19405       if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
19406 	  || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19407 	{
19408 	  if (issue_error)
19409             {
19410               go_error_at(location, "complex constant truncated to integer");
19411               this->set_invalid();
19412             }
19413 	  return false;
19414 	}
19415       mpz_init(val);
19416       mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19417       break;
19418 
19419     default:
19420       go_unreachable();
19421     }
19422 
19423   bool ret;
19424   if (type->is_abstract())
19425     ret = true;
19426   else
19427     {
19428       int bits = mpz_sizeinbase(val, 2);
19429       if (type->is_unsigned())
19430 	{
19431 	  // For an unsigned type we can only accept a nonnegative
19432 	  // number, and we must be able to represents at least BITS.
19433 	  ret = mpz_sgn(val) >= 0 && bits <= type->bits();
19434 	}
19435       else
19436 	{
19437 	  // For a signed type we need an extra bit to indicate the
19438 	  // sign.  We have to handle the most negative integer
19439 	  // specially.
19440 	  ret = (bits + 1 <= type->bits()
19441 		 || (bits <= type->bits()
19442 		     && mpz_sgn(val) < 0
19443 		     && (mpz_scan1(val, 0)
19444 			 == static_cast<unsigned long>(type->bits() - 1))
19445 		     && mpz_scan0(val, type->bits()) == ULONG_MAX));
19446 	}
19447     }
19448 
19449   if (!ret && issue_error)
19450     {
19451       go_error_at(location, "integer constant overflow");
19452       this->set_invalid();
19453     }
19454 
19455   return ret;
19456 }
19457 
19458 // Check whether the constant can be expressed in a floating point
19459 // type.
19460 
19461 bool
check_float_type(Float_type * type,bool issue_error,Location location)19462 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
19463 				   Location location)
19464 {
19465   mpfr_t val;
19466   switch (this->classification_)
19467     {
19468     case NC_INT:
19469     case NC_RUNE:
19470       mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
19471       break;
19472 
19473     case NC_FLOAT:
19474       mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
19475       break;
19476 
19477     case NC_COMPLEX:
19478       if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19479 	{
19480 	  if (issue_error)
19481             {
19482               this->set_invalid();
19483               go_error_at(location,
19484 			  "complex constant truncated to floating-point");
19485             }
19486 	  return false;
19487 	}
19488       mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19489       break;
19490 
19491     default:
19492       go_unreachable();
19493     }
19494 
19495   bool ret;
19496   if (type->is_abstract())
19497     ret = true;
19498   else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
19499     {
19500       // A NaN or Infinity always fits in the range of the type.
19501       ret = true;
19502     }
19503   else
19504     {
19505       mpfr_exp_t exp = mpfr_get_exp(val);
19506       mpfr_exp_t max_exp;
19507       switch (type->bits())
19508 	{
19509 	case 32:
19510 	  max_exp = 128;
19511 	  break;
19512 	case 64:
19513 	  max_exp = 1024;
19514 	  break;
19515 	default:
19516 	  go_unreachable();
19517 	}
19518 
19519       ret = exp <= max_exp;
19520 
19521       if (ret)
19522 	{
19523 	  // Round the constant to the desired type.
19524 	  mpfr_t t;
19525 	  mpfr_init(t);
19526 	  switch (type->bits())
19527 	    {
19528 	    case 32:
19529 	      mpfr_set_prec(t, 24);
19530 	      break;
19531 	    case 64:
19532 	      mpfr_set_prec(t, 53);
19533 	      break;
19534 	    default:
19535 	      go_unreachable();
19536 	    }
19537 	  mpfr_set(t, val, MPFR_RNDN);
19538 	  mpfr_set(val, t, MPFR_RNDN);
19539 	  mpfr_clear(t);
19540 
19541 	  this->set_float(type, val);
19542 	}
19543     }
19544 
19545   mpfr_clear(val);
19546 
19547   if (!ret && issue_error)
19548     {
19549       go_error_at(location, "floating-point constant overflow");
19550       this->set_invalid();
19551     }
19552 
19553   return ret;
19554 }
19555 
19556 // Check whether the constant can be expressed in a complex type.
19557 
19558 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)19559 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
19560 				     Location location)
19561 {
19562   if (type->is_abstract())
19563     return true;
19564 
19565   mpfr_exp_t max_exp;
19566   switch (type->bits())
19567     {
19568     case 64:
19569       max_exp = 128;
19570       break;
19571     case 128:
19572       max_exp = 1024;
19573       break;
19574     default:
19575       go_unreachable();
19576     }
19577 
19578   mpc_t val;
19579   mpc_init2(val, mpc_precision);
19580   switch (this->classification_)
19581     {
19582     case NC_INT:
19583     case NC_RUNE:
19584       mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
19585       break;
19586 
19587     case NC_FLOAT:
19588       mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
19589       break;
19590 
19591     case NC_COMPLEX:
19592       mpc_set(val, this->u_.complex_val, MPC_RNDNN);
19593       break;
19594 
19595     default:
19596       go_unreachable();
19597     }
19598 
19599   bool ret = true;
19600   if (!mpfr_nan_p(mpc_realref(val))
19601       && !mpfr_inf_p(mpc_realref(val))
19602       && !mpfr_zero_p(mpc_realref(val))
19603       && mpfr_get_exp(mpc_realref(val)) > max_exp)
19604     {
19605       if (issue_error)
19606         {
19607           go_error_at(location, "complex real part overflow");
19608           this->set_invalid();
19609         }
19610       ret = false;
19611     }
19612 
19613   if (!mpfr_nan_p(mpc_imagref(val))
19614       && !mpfr_inf_p(mpc_imagref(val))
19615       && !mpfr_zero_p(mpc_imagref(val))
19616       && mpfr_get_exp(mpc_imagref(val)) > max_exp)
19617     {
19618       if (issue_error)
19619         {
19620           go_error_at(location, "complex imaginary part overflow");
19621           this->set_invalid();
19622         }
19623       ret = false;
19624     }
19625 
19626   if (ret)
19627     {
19628       // Round the constant to the desired type.
19629       mpc_t t;
19630       switch (type->bits())
19631 	{
19632 	case 64:
19633 	  mpc_init2(t, 24);
19634 	  break;
19635 	case 128:
19636 	  mpc_init2(t, 53);
19637 	  break;
19638 	default:
19639 	  go_unreachable();
19640 	}
19641       mpc_set(t, val, MPC_RNDNN);
19642       mpc_set(val, t, MPC_RNDNN);
19643       mpc_clear(t);
19644 
19645       this->set_complex(type, val);
19646     }
19647 
19648   mpc_clear(val);
19649 
19650   return ret;
19651 }
19652 
19653 // Return an Expression for this value.
19654 
19655 Expression*
expression(Location loc) const19656 Numeric_constant::expression(Location loc) const
19657 {
19658   switch (this->classification_)
19659     {
19660     case NC_INT:
19661       return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
19662     case NC_RUNE:
19663       return Expression::make_character(&this->u_.int_val, this->type_, loc);
19664     case NC_FLOAT:
19665       return Expression::make_float(&this->u_.float_val, this->type_, loc);
19666     case NC_COMPLEX:
19667       return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
19668     case NC_INVALID:
19669       go_assert(saw_errors());
19670       return Expression::make_error(loc);
19671     default:
19672       go_unreachable();
19673     }
19674 }
19675 
19676 // Calculate a hash code with a given seed.
19677 
19678 unsigned int
hash(unsigned int seed) const19679 Numeric_constant::hash(unsigned int seed) const
19680 {
19681   unsigned long val;
19682   const unsigned int PRIME = 97;
19683   long e = 0;
19684   double f = 1.0;
19685   mpfr_t m;
19686 
19687   switch (this->classification_)
19688     {
19689     case NC_INVALID:
19690       return PRIME;
19691     case NC_INT:
19692     case NC_RUNE:
19693       val = mpz_get_ui(this->u_.int_val);
19694       break;
19695     case NC_COMPLEX:
19696       mpfr_init(m);
19697       mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
19698       val = mpfr_get_ui(m, MPFR_RNDN);
19699       mpfr_clear(m);
19700       break;
19701     case NC_FLOAT:
19702       f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
19703       val = static_cast<unsigned long>(e + static_cast<long>(f));
19704       break;
19705     default:
19706       go_unreachable();
19707     }
19708 
19709   return (static_cast<unsigned int>(val) + seed) * PRIME;
19710 }
19711