OSDN Git Service

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