OSDN Git Service

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