OSDN Git Service

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