OSDN Git Service

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