OSDN Git Service

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