OSDN Git Service

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