OSDN Git Service

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