OSDN Git Service

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