OSDN Git Service

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