OSDN Git Service

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