OSDN Git Service

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