OSDN Git Service

compiler: Fix handling of indirection of circular types.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / expressions.cc
1 // expressions.cc -- Go frontend expression handling.
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 #include "go-system.h"
8
9 #include <gmp.h>
10
11 #ifndef ENABLE_BUILD_WITH_CXX
12 extern "C"
13 {
14 #endif
15
16 #include "toplev.h"
17 #include "intl.h"
18 #include "tree.h"
19 #include "gimple.h"
20 #include "tree-iterator.h"
21 #include "convert.h"
22 #include "real.h"
23 #include "realmpfr.h"
24
25 #ifndef ENABLE_BUILD_WITH_CXX
26 }
27 #endif
28
29 #include "go-c.h"
30 #include "gogo.h"
31 #include "types.h"
32 #include "export.h"
33 #include "import.h"
34 #include "statements.h"
35 #include "lex.h"
36 #include "runtime.h"
37 #include "backend.h"
38 #include "expressions.h"
39 #include "ast-dump.h"
40
41 // Class Expression.
42
43 Expression::Expression(Expression_classification classification,
44                        Location location)
45   : classification_(classification), location_(location)
46 {
47 }
48
49 Expression::~Expression()
50 {
51 }
52
53 // If this expression has a constant integer value, return it.
54
55 bool
56 Expression::integer_constant_value(bool iota_is_constant, mpz_t val,
57                                    Type** ptype) const
58 {
59   *ptype = NULL;
60   return this->do_integer_constant_value(iota_is_constant, val, ptype);
61 }
62
63 // If this expression has a constant floating point value, return it.
64
65 bool
66 Expression::float_constant_value(mpfr_t val, Type** ptype) const
67 {
68   *ptype = NULL;
69   if (this->do_float_constant_value(val, ptype))
70     return true;
71   mpz_t ival;
72   mpz_init(ival);
73   Type* t;
74   bool ret;
75   if (!this->do_integer_constant_value(false, ival, &t))
76     ret = false;
77   else
78     {
79       mpfr_set_z(val, ival, GMP_RNDN);
80       ret = true;
81     }
82   mpz_clear(ival);
83   return ret;
84 }
85
86 // If this expression has a constant complex value, return it.
87
88 bool
89 Expression::complex_constant_value(mpfr_t real, mpfr_t imag,
90                                    Type** ptype) const
91 {
92   *ptype = NULL;
93   if (this->do_complex_constant_value(real, imag, ptype))
94     return true;
95   Type *t;
96   if (this->float_constant_value(real, &t))
97     {
98       mpfr_set_ui(imag, 0, GMP_RNDN);
99       return true;
100     }
101   return false;
102 }
103
104 // Traverse the expressions.
105
106 int
107 Expression::traverse(Expression** pexpr, Traverse* traverse)
108 {
109   Expression* expr = *pexpr;
110   if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
111     {
112       int t = traverse->expression(pexpr);
113       if (t == TRAVERSE_EXIT)
114         return TRAVERSE_EXIT;
115       else if (t == TRAVERSE_SKIP_COMPONENTS)
116         return TRAVERSE_CONTINUE;
117     }
118   return expr->do_traverse(traverse);
119 }
120
121 // Traverse subexpressions of this expression.
122
123 int
124 Expression::traverse_subexpressions(Traverse* traverse)
125 {
126   return this->do_traverse(traverse);
127 }
128
129 // Default implementation for do_traverse for child classes.
130
131 int
132 Expression::do_traverse(Traverse*)
133 {
134   return TRAVERSE_CONTINUE;
135 }
136
137 // This virtual function is called by the parser if the value of this
138 // expression is being discarded.  By default, we give an error.
139 // Expressions with side effects override.
140
141 void
142 Expression::do_discarding_value()
143 {
144   this->unused_value_error();
145 }
146
147 // This virtual function is called to export expressions.  This will
148 // only be used by expressions which may be constant.
149
150 void
151 Expression::do_export(Export*) const
152 {
153   go_unreachable();
154 }
155
156 // Give an error saying that the value of the expression is not used.
157
158 void
159 Expression::unused_value_error()
160 {
161   error_at(this->location(), "value computed is not used");
162 }
163
164 // Note that this expression is an error.  This is called by children
165 // when they discover an error.
166
167 void
168 Expression::set_is_error()
169 {
170   this->classification_ = EXPRESSION_ERROR;
171 }
172
173 // For children to call to report an error conveniently.
174
175 void
176 Expression::report_error(const char* msg)
177 {
178   error_at(this->location_, "%s", msg);
179   this->set_is_error();
180 }
181
182 // Set types of variables and constants.  This is implemented by the
183 // child class.
184
185 void
186 Expression::determine_type(const Type_context* context)
187 {
188   this->do_determine_type(context);
189 }
190
191 // Set types when there is no context.
192
193 void
194 Expression::determine_type_no_context()
195 {
196   Type_context context;
197   this->do_determine_type(&context);
198 }
199
200 // Return a tree handling any conversions which must be done during
201 // assignment.
202
203 tree
204 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
205                                    Type* rhs_type, tree rhs_tree,
206                                    Location location)
207 {
208   if (lhs_type == rhs_type)
209     return rhs_tree;
210
211   if (lhs_type->is_error() || rhs_type->is_error())
212     return error_mark_node;
213
214   if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
215     return error_mark_node;
216
217   Gogo* gogo = context->gogo();
218
219   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
220   if (lhs_type_tree == error_mark_node)
221     return error_mark_node;
222
223   if (lhs_type->interface_type() != NULL)
224     {
225       if (rhs_type->interface_type() == NULL)
226         return Expression::convert_type_to_interface(context, lhs_type,
227                                                      rhs_type, rhs_tree,
228                                                      location);
229       else
230         return Expression::convert_interface_to_interface(context, lhs_type,
231                                                           rhs_type, rhs_tree,
232                                                           false, location);
233     }
234   else if (rhs_type->interface_type() != NULL)
235     return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
236                                                  rhs_tree, location);
237   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
238     {
239       // Assigning nil to an open array.
240       go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
241
242       VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
243
244       constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
245       tree field = TYPE_FIELDS(lhs_type_tree);
246       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
247                         "__values") == 0);
248       elt->index = field;
249       elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
250
251       elt = VEC_quick_push(constructor_elt, init, NULL);
252       field = DECL_CHAIN(field);
253       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
254                         "__count") == 0);
255       elt->index = field;
256       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
257
258       elt = VEC_quick_push(constructor_elt, init, NULL);
259       field = DECL_CHAIN(field);
260       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
261                         "__capacity") == 0);
262       elt->index = field;
263       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
264
265       tree val = build_constructor(lhs_type_tree, init);
266       TREE_CONSTANT(val) = 1;
267
268       return val;
269     }
270   else if (rhs_type->is_nil_type())
271     {
272       // The left hand side should be a pointer type at the tree
273       // level.
274       go_assert(POINTER_TYPE_P(lhs_type_tree));
275       return fold_convert(lhs_type_tree, null_pointer_node);
276     }
277   else if (lhs_type_tree == TREE_TYPE(rhs_tree))
278     {
279       // No conversion is needed.
280       return rhs_tree;
281     }
282   else if (POINTER_TYPE_P(lhs_type_tree)
283            || INTEGRAL_TYPE_P(lhs_type_tree)
284            || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
285            || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
286     return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
287   else if (TREE_CODE(lhs_type_tree) == RECORD_TYPE
288            && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
289     {
290       // This conversion must be permitted by Go, or we wouldn't have
291       // gotten here.
292       go_assert(int_size_in_bytes(lhs_type_tree)
293                  == int_size_in_bytes(TREE_TYPE(rhs_tree)));
294       return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
295                              lhs_type_tree, rhs_tree);
296     }
297   else
298     {
299       go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
300       return rhs_tree;
301     }
302 }
303
304 // Return a tree for a conversion from a non-interface type to an
305 // interface type.
306
307 tree
308 Expression::convert_type_to_interface(Translate_context* context,
309                                       Type* lhs_type, Type* rhs_type,
310                                       tree rhs_tree, Location location)
311 {
312   Gogo* gogo = context->gogo();
313   Interface_type* lhs_interface_type = lhs_type->interface_type();
314   bool lhs_is_empty = lhs_interface_type->is_empty();
315
316   // Since RHS_TYPE is a static type, we can create the interface
317   // method table at compile time.
318
319   // When setting an interface to nil, we just set both fields to
320   // NULL.
321   if (rhs_type->is_nil_type())
322     {
323       Btype* lhs_btype = lhs_type->get_backend(gogo);
324       return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
325     }
326
327   // This should have been checked already.
328   go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
329
330   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
331   if (lhs_type_tree == error_mark_node)
332     return error_mark_node;
333
334   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
335   // then the first field is the type descriptor for RHS_TYPE.
336   // Otherwise it is the interface method table for RHS_TYPE.
337   tree first_field_value;
338   if (lhs_is_empty)
339     first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
340   else
341     {
342       // Build the interface method table for this interface and this
343       // object type: a list of function pointers for each interface
344       // method.
345       Named_type* rhs_named_type = rhs_type->named_type();
346       bool is_pointer = false;
347       if (rhs_named_type == NULL)
348         {
349           rhs_named_type = rhs_type->deref()->named_type();
350           is_pointer = true;
351         }
352       tree method_table;
353       if (rhs_named_type == NULL)
354         method_table = null_pointer_node;
355       else
356         method_table =
357           rhs_named_type->interface_method_table(gogo, lhs_interface_type,
358                                                  is_pointer);
359       first_field_value = fold_convert_loc(location.gcc_location(),
360                                            const_ptr_type_node, method_table);
361     }
362   if (first_field_value == error_mark_node)
363     return error_mark_node;
364
365   // Start building a constructor for the value we will return.
366
367   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
368
369   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
370   tree field = TYPE_FIELDS(lhs_type_tree);
371   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
372                     (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
373   elt->index = field;
374   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
375                                 first_field_value);
376
377   elt = VEC_quick_push(constructor_elt, init, NULL);
378   field = DECL_CHAIN(field);
379   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
380   elt->index = field;
381
382   if (rhs_type->points_to() != NULL)
383     {
384       //  We are assigning a pointer to the interface; the interface
385       // holds the pointer itself.
386       elt->value = rhs_tree;
387       return build_constructor(lhs_type_tree, init);
388     }
389
390   // We are assigning a non-pointer value to the interface; the
391   // interface gets a copy of the value in the heap.
392
393   tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
394
395   tree space = gogo->allocate_memory(rhs_type, object_size, location);
396   space = fold_convert_loc(location.gcc_location(),
397                            build_pointer_type(TREE_TYPE(rhs_tree)), space);
398   space = save_expr(space);
399
400   tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
401   TREE_THIS_NOTRAP(ref) = 1;
402   tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
403                              void_type_node, ref, rhs_tree);
404
405   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
406                                 space);
407
408   return build2(COMPOUND_EXPR, lhs_type_tree, set,
409                 build_constructor(lhs_type_tree, init));
410 }
411
412 // Return a tree for the type descriptor of RHS_TREE, which has
413 // interface type RHS_TYPE.  If RHS_TREE is nil the result will be
414 // NULL.
415
416 tree
417 Expression::get_interface_type_descriptor(Translate_context*,
418                                           Type* rhs_type, tree rhs_tree,
419                                           Location location)
420 {
421   tree rhs_type_tree = TREE_TYPE(rhs_tree);
422   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
423   tree rhs_field = TYPE_FIELDS(rhs_type_tree);
424   tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
425                   NULL_TREE);
426   if (rhs_type->interface_type()->is_empty())
427     {
428       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
429                         "__type_descriptor") == 0);
430       return v;
431     }
432
433   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
434              == 0);
435   go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
436   v = save_expr(v);
437   tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
438   go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
439   tree f = TYPE_FIELDS(TREE_TYPE(v1));
440   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
441              == 0);
442   v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
443
444   tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
445                             v, fold_convert_loc(location.gcc_location(),
446                                                 TREE_TYPE(v),
447                                                 null_pointer_node));
448   tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
449                             null_pointer_node);
450   return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
451                          eq, n, v1);
452 }
453
454 // Return a tree for the conversion of an interface type to an
455 // interface type.
456
457 tree
458 Expression::convert_interface_to_interface(Translate_context* context,
459                                            Type *lhs_type, Type *rhs_type,
460                                            tree rhs_tree, bool for_type_guard,
461                                            Location location)
462 {
463   Gogo* gogo = context->gogo();
464   Interface_type* lhs_interface_type = lhs_type->interface_type();
465   bool lhs_is_empty = lhs_interface_type->is_empty();
466
467   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
468   if (lhs_type_tree == error_mark_node)
469     return error_mark_node;
470
471   // In the general case this requires runtime examination of the type
472   // method table to match it up with the interface methods.
473
474   // FIXME: If all of the methods in the right hand side interface
475   // also appear in the left hand side interface, then we don't need
476   // to do a runtime check, although we still need to build a new
477   // method table.
478
479   // Get the type descriptor for the right hand side.  This will be
480   // NULL for a nil interface.
481
482   if (!DECL_P(rhs_tree))
483     rhs_tree = save_expr(rhs_tree);
484
485   tree rhs_type_descriptor =
486     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
487                                               location);
488
489   // The result is going to be a two element constructor.
490
491   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
492
493   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
494   tree field = TYPE_FIELDS(lhs_type_tree);
495   elt->index = field;
496
497   if (for_type_guard)
498     {
499       // A type assertion fails when converting a nil interface.
500       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
501                                                                    location);
502       static tree assert_interface_decl;
503       tree call = Gogo::call_builtin(&assert_interface_decl,
504                                      location,
505                                      "__go_assert_interface",
506                                      2,
507                                      ptr_type_node,
508                                      TREE_TYPE(lhs_type_descriptor),
509                                      lhs_type_descriptor,
510                                      TREE_TYPE(rhs_type_descriptor),
511                                      rhs_type_descriptor);
512       if (call == error_mark_node)
513         return error_mark_node;
514       // This will panic if the interface conversion fails.
515       TREE_NOTHROW(assert_interface_decl) = 0;
516       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
517                                     call);
518     }
519   else if (lhs_is_empty)
520     {
521       // A convertion to an empty interface always succeeds, and the
522       // first field is just the type descriptor of the object.
523       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
524                         "__type_descriptor") == 0);
525       elt->value = fold_convert_loc(location.gcc_location(),
526                                     TREE_TYPE(field), rhs_type_descriptor);
527     }
528   else
529     {
530       // A conversion to a non-empty interface may fail, but unlike a
531       // type assertion converting nil will always succeed.
532       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
533                  == 0);
534       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
535                                                                    location);
536       static tree convert_interface_decl;
537       tree call = Gogo::call_builtin(&convert_interface_decl,
538                                      location,
539                                      "__go_convert_interface",
540                                      2,
541                                      ptr_type_node,
542                                      TREE_TYPE(lhs_type_descriptor),
543                                      lhs_type_descriptor,
544                                      TREE_TYPE(rhs_type_descriptor),
545                                      rhs_type_descriptor);
546       if (call == error_mark_node)
547         return error_mark_node;
548       // This will panic if the interface conversion fails.
549       TREE_NOTHROW(convert_interface_decl) = 0;
550       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
551                                     call);
552     }
553
554   // The second field is simply the object pointer.
555
556   elt = VEC_quick_push(constructor_elt, init, NULL);
557   field = DECL_CHAIN(field);
558   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
559   elt->index = field;
560
561   tree rhs_type_tree = TREE_TYPE(rhs_tree);
562   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
563   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
564   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
565   elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
566                       NULL_TREE);
567
568   return build_constructor(lhs_type_tree, init);
569 }
570
571 // Return a tree for the conversion of an interface type to a
572 // non-interface type.
573
574 tree
575 Expression::convert_interface_to_type(Translate_context* context,
576                                       Type *lhs_type, Type* rhs_type,
577                                       tree rhs_tree, Location location)
578 {
579   Gogo* gogo = context->gogo();
580   tree rhs_type_tree = TREE_TYPE(rhs_tree);
581
582   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
583   if (lhs_type_tree == error_mark_node)
584     return error_mark_node;
585
586   // Call a function to check that the type is valid.  The function
587   // will panic with an appropriate runtime type error if the type is
588   // not valid.
589
590   tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
591
592   if (!DECL_P(rhs_tree))
593     rhs_tree = save_expr(rhs_tree);
594
595   tree rhs_type_descriptor =
596     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
597                                               location);
598
599   tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
600                                                                 location);
601
602   static tree check_interface_type_decl;
603   tree call = Gogo::call_builtin(&check_interface_type_decl,
604                                  location,
605                                  "__go_check_interface_type",
606                                  3,
607                                  void_type_node,
608                                  TREE_TYPE(lhs_type_descriptor),
609                                  lhs_type_descriptor,
610                                  TREE_TYPE(rhs_type_descriptor),
611                                  rhs_type_descriptor,
612                                  TREE_TYPE(rhs_inter_descriptor),
613                                  rhs_inter_descriptor);
614   if (call == error_mark_node)
615     return error_mark_node;
616   // This call will panic if the conversion is invalid.
617   TREE_NOTHROW(check_interface_type_decl) = 0;
618
619   // If the call succeeds, pull out the value.
620   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
621   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
622   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
623   tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
624                     NULL_TREE);
625
626   // If the value is a pointer, then it is the value we want.
627   // Otherwise it points to the value.
628   if (lhs_type->points_to() == NULL)
629     {
630       val = fold_convert_loc(location.gcc_location(),
631                              build_pointer_type(lhs_type_tree), val);
632       val = build_fold_indirect_ref_loc(location.gcc_location(), val);
633     }
634
635   return build2(COMPOUND_EXPR, lhs_type_tree, call,
636                 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
637 }
638
639 // Convert an expression to a tree.  This is implemented by the child
640 // class.  Not that it is not in general safe to call this multiple
641 // times for a single expression, but that we don't catch such errors.
642
643 tree
644 Expression::get_tree(Translate_context* context)
645 {
646   // The child may have marked this expression as having an error.
647   if (this->classification_ == EXPRESSION_ERROR)
648     return error_mark_node;
649
650   return this->do_get_tree(context);
651 }
652
653 // Return a tree for VAL in TYPE.
654
655 tree
656 Expression::integer_constant_tree(mpz_t val, tree type)
657 {
658   if (type == error_mark_node)
659     return error_mark_node;
660   else if (TREE_CODE(type) == INTEGER_TYPE)
661     return double_int_to_tree(type,
662                               mpz_get_double_int(type, val, true));
663   else if (TREE_CODE(type) == REAL_TYPE)
664     {
665       mpfr_t fval;
666       mpfr_init_set_z(fval, val, GMP_RNDN);
667       tree ret = Expression::float_constant_tree(fval, type);
668       mpfr_clear(fval);
669       return ret;
670     }
671   else if (TREE_CODE(type) == COMPLEX_TYPE)
672     {
673       mpfr_t fval;
674       mpfr_init_set_z(fval, val, GMP_RNDN);
675       tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
676       mpfr_clear(fval);
677       tree imag = build_real_from_int_cst(TREE_TYPE(type),
678                                           integer_zero_node);
679       return build_complex(type, real, imag);
680     }
681   else
682     go_unreachable();
683 }
684
685 // Return a tree for VAL in TYPE.
686
687 tree
688 Expression::float_constant_tree(mpfr_t val, tree type)
689 {
690   if (type == error_mark_node)
691     return error_mark_node;
692   else if (TREE_CODE(type) == INTEGER_TYPE)
693     {
694       mpz_t ival;
695       mpz_init(ival);
696       mpfr_get_z(ival, val, GMP_RNDN);
697       tree ret = Expression::integer_constant_tree(ival, type);
698       mpz_clear(ival);
699       return ret;
700     }
701   else if (TREE_CODE(type) == REAL_TYPE)
702     {
703       REAL_VALUE_TYPE r1;
704       real_from_mpfr(&r1, val, type, GMP_RNDN);
705       REAL_VALUE_TYPE r2;
706       real_convert(&r2, TYPE_MODE(type), &r1);
707       return build_real(type, r2);
708     }
709   else if (TREE_CODE(type) == COMPLEX_TYPE)
710     {
711       REAL_VALUE_TYPE r1;
712       real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
713       REAL_VALUE_TYPE r2;
714       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
715       tree imag = build_real_from_int_cst(TREE_TYPE(type),
716                                           integer_zero_node);
717       return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
718     }
719   else
720     go_unreachable();
721 }
722
723 // Return a tree for REAL/IMAG in TYPE.
724
725 tree
726 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
727 {
728   if (type == error_mark_node)
729     return error_mark_node;
730   else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
731     return Expression::float_constant_tree(real, type);
732   else if (TREE_CODE(type) == COMPLEX_TYPE)
733     {
734       REAL_VALUE_TYPE r1;
735       real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
736       REAL_VALUE_TYPE r2;
737       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
738
739       REAL_VALUE_TYPE r3;
740       real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
741       REAL_VALUE_TYPE r4;
742       real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
743
744       return build_complex(type, build_real(TREE_TYPE(type), r2),
745                            build_real(TREE_TYPE(type), r4));
746     }
747   else
748     go_unreachable();
749 }
750
751 // Return a tree which evaluates to true if VAL, of arbitrary integer
752 // type, is negative or is more than the maximum value of BOUND_TYPE.
753 // If SOFAR is not NULL, it is or'red into the result.  The return
754 // value may be NULL if SOFAR is NULL.
755
756 tree
757 Expression::check_bounds(tree val, tree bound_type, tree sofar,
758                          Location loc)
759 {
760   tree val_type = TREE_TYPE(val);
761   tree ret = NULL_TREE;
762
763   if (!TYPE_UNSIGNED(val_type))
764     {
765       ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
766                             build_int_cst(val_type, 0));
767       if (ret == boolean_false_node)
768         ret = NULL_TREE;
769     }
770
771   HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
772   HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
773   go_assert(val_type_size != -1 && bound_type_size != -1);
774   if (val_type_size > bound_type_size
775       || (val_type_size == bound_type_size
776           && TYPE_UNSIGNED(val_type)
777           && !TYPE_UNSIGNED(bound_type)))
778     {
779       tree max = TYPE_MAX_VALUE(bound_type);
780       tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
781                                  val, fold_convert_loc(loc.gcc_location(),
782                                                        val_type, max));
783       if (big == boolean_false_node)
784         ;
785       else if (ret == NULL_TREE)
786         ret = big;
787       else
788         ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
789                               boolean_type_node, ret, big);
790     }
791
792   if (ret == NULL_TREE)
793     return sofar;
794   else if (sofar == NULL_TREE)
795     return ret;
796   else
797     return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
798                            sofar, ret);
799 }
800
801 void
802 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
803 {
804   this->do_dump_expression(ast_dump_context);
805 }
806
807 // Error expressions.  This are used to avoid cascading errors.
808
809 class Error_expression : public Expression
810 {
811  public:
812   Error_expression(Location location)
813     : Expression(EXPRESSION_ERROR, location)
814   { }
815
816  protected:
817   bool
818   do_is_constant() const
819   { return true; }
820
821   bool
822   do_integer_constant_value(bool, mpz_t val, Type**) const
823   {
824     mpz_set_ui(val, 0);
825     return true;
826   }
827
828   bool
829   do_float_constant_value(mpfr_t val, Type**) const
830   {
831     mpfr_set_ui(val, 0, GMP_RNDN);
832     return true;
833   }
834
835   bool
836   do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const
837   {
838     mpfr_set_ui(real, 0, GMP_RNDN);
839     mpfr_set_ui(imag, 0, GMP_RNDN);
840     return true;
841   }
842
843   void
844   do_discarding_value()
845   { }
846
847   Type*
848   do_type()
849   { return Type::make_error_type(); }
850
851   void
852   do_determine_type(const Type_context*)
853   { }
854
855   Expression*
856   do_copy()
857   { return this; }
858
859   bool
860   do_is_addressable() const
861   { return true; }
862
863   tree
864   do_get_tree(Translate_context*)
865   { return error_mark_node; }
866
867   void
868   do_dump_expression(Ast_dump_context*) const;
869 };
870
871 // Dump the ast representation for an error expression to a dump context.
872
873 void
874 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
875 {
876   ast_dump_context->ostream() << "_Error_" ;
877 }
878
879 Expression*
880 Expression::make_error(Location location)
881 {
882   return new Error_expression(location);
883 }
884
885 // An expression which is really a type.  This is used during parsing.
886 // It is an error if these survive after lowering.
887
888 class
889 Type_expression : public Expression
890 {
891  public:
892   Type_expression(Type* type, Location location)
893     : Expression(EXPRESSION_TYPE, location),
894       type_(type)
895   { }
896
897  protected:
898   int
899   do_traverse(Traverse* traverse)
900   { return Type::traverse(this->type_, traverse); }
901
902   Type*
903   do_type()
904   { return this->type_; }
905
906   void
907   do_determine_type(const Type_context*)
908   { }
909
910   void
911   do_check_types(Gogo*)
912   { this->report_error(_("invalid use of type")); }
913
914   Expression*
915   do_copy()
916   { return this; }
917
918   tree
919   do_get_tree(Translate_context*)
920   { go_unreachable(); }
921
922   void do_dump_expression(Ast_dump_context*) const;
923  
924  private:
925   // The type which we are representing as an expression.
926   Type* type_;
927 };
928
929 void
930 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
931 {
932   ast_dump_context->dump_type(this->type_);
933 }
934
935 Expression*
936 Expression::make_type(Type* type, Location location)
937 {
938   return new Type_expression(type, location);
939 }
940
941 // Class Parser_expression.
942
943 Type*
944 Parser_expression::do_type()
945 {
946   // We should never really ask for the type of a Parser_expression.
947   // However, it can happen, at least when we have an invalid const
948   // whose initializer refers to the const itself.  In that case we
949   // may ask for the type when lowering the const itself.
950   go_assert(saw_errors());
951   return Type::make_error_type();
952 }
953
954 // Class Var_expression.
955
956 // Lower a variable expression.  Here we just make sure that the
957 // initialization expression of the variable has been lowered.  This
958 // ensures that we will be able to determine the type of the variable
959 // if necessary.
960
961 Expression*
962 Var_expression::do_lower(Gogo* gogo, Named_object* function,
963                          Statement_inserter* inserter, int)
964 {
965   if (this->variable_->is_variable())
966     {
967       Variable* var = this->variable_->var_value();
968       // This is either a local variable or a global variable.  A
969       // reference to a variable which is local to an enclosing
970       // function will be a reference to a field in a closure.
971       if (var->is_global())
972         {
973           function = NULL;
974           inserter = NULL;
975         }
976       var->lower_init_expression(gogo, function, inserter);
977     }
978   return this;
979 }
980
981 // Return the type of a reference to a variable.
982
983 Type*
984 Var_expression::do_type()
985 {
986   if (this->variable_->is_variable())
987     return this->variable_->var_value()->type();
988   else if (this->variable_->is_result_variable())
989     return this->variable_->result_var_value()->type();
990   else
991     go_unreachable();
992 }
993
994 // Determine the type of a reference to a variable.
995
996 void
997 Var_expression::do_determine_type(const Type_context*)
998 {
999   if (this->variable_->is_variable())
1000     this->variable_->var_value()->determine_type();
1001 }
1002
1003 // Something takes the address of this variable.  This means that we
1004 // may want to move the variable onto the heap.
1005
1006 void
1007 Var_expression::do_address_taken(bool escapes)
1008 {
1009   if (!escapes)
1010     {
1011       if (this->variable_->is_variable())
1012         this->variable_->var_value()->set_non_escaping_address_taken();
1013       else if (this->variable_->is_result_variable())
1014         this->variable_->result_var_value()->set_non_escaping_address_taken();
1015       else
1016         go_unreachable();
1017     }
1018   else
1019     {
1020       if (this->variable_->is_variable())
1021         this->variable_->var_value()->set_address_taken();
1022       else if (this->variable_->is_result_variable())
1023         this->variable_->result_var_value()->set_address_taken();
1024       else
1025         go_unreachable();
1026     }
1027 }
1028
1029 // Get the tree for a reference to a variable.
1030
1031 tree
1032 Var_expression::do_get_tree(Translate_context* context)
1033 {
1034   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
1035                                                           context->function());
1036   tree ret = var_to_tree(bvar);
1037   if (ret == error_mark_node)
1038     return error_mark_node;
1039   bool is_in_heap;
1040   if (this->variable_->is_variable())
1041     is_in_heap = this->variable_->var_value()->is_in_heap();
1042   else if (this->variable_->is_result_variable())
1043     is_in_heap = this->variable_->result_var_value()->is_in_heap();
1044   else
1045     go_unreachable();
1046   if (is_in_heap)
1047     {
1048       ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
1049       TREE_THIS_NOTRAP(ret) = 1;
1050     }
1051   return ret;
1052 }
1053
1054 // Ast dump for variable expression.
1055
1056 void
1057 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1058 {
1059   ast_dump_context->ostream() << this->variable_->name() ;
1060 }
1061
1062 // Make a reference to a variable in an expression.
1063
1064 Expression*
1065 Expression::make_var_reference(Named_object* var, Location location)
1066 {
1067   if (var->is_sink())
1068     return Expression::make_sink(location);
1069
1070   // FIXME: Creating a new object for each reference to a variable is
1071   // wasteful.
1072   return new Var_expression(var, location);
1073 }
1074
1075 // Class Temporary_reference_expression.
1076
1077 // The type.
1078
1079 Type*
1080 Temporary_reference_expression::do_type()
1081 {
1082   return this->statement_->type();
1083 }
1084
1085 // Called if something takes the address of this temporary variable.
1086 // We never have to move temporary variables to the heap, but we do
1087 // need to know that they must live in the stack rather than in a
1088 // register.
1089
1090 void
1091 Temporary_reference_expression::do_address_taken(bool)
1092 {
1093   this->statement_->set_is_address_taken();
1094 }
1095
1096 // Get a tree referring to the variable.
1097
1098 tree
1099 Temporary_reference_expression::do_get_tree(Translate_context* context)
1100 {
1101   Bvariable* bvar = this->statement_->get_backend_variable(context);
1102
1103   // The gcc backend can't represent the same set of recursive types
1104   // that the Go frontend can.  In some cases this means that a
1105   // temporary variable won't have the right backend type.  Correct
1106   // that here by adding a type cast.  We need to use base() to push
1107   // the circularity down one level.
1108   tree ret = var_to_tree(bvar);
1109   if (!this->is_lvalue_
1110       && POINTER_TYPE_P(TREE_TYPE(ret))
1111       && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1112     {
1113       Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1114       tree type_tree = type_to_tree(type_btype);
1115       ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1116     }
1117   return ret;
1118 }
1119
1120 // Ast dump for temporary reference.
1121
1122 void
1123 Temporary_reference_expression::do_dump_expression(
1124                                 Ast_dump_context* ast_dump_context) const
1125 {
1126   ast_dump_context->dump_temp_variable_name(this->statement_);
1127 }
1128
1129 // Make a reference to a temporary variable.
1130
1131 Temporary_reference_expression*
1132 Expression::make_temporary_reference(Temporary_statement* statement,
1133                                      Location location)
1134 {
1135   return new Temporary_reference_expression(statement, location);
1136 }
1137
1138 // Class Set_and_use_temporary_expression.
1139
1140 // Return the type.
1141
1142 Type*
1143 Set_and_use_temporary_expression::do_type()
1144 {
1145   return this->statement_->type();
1146 }
1147
1148 // Take the address.
1149
1150 void
1151 Set_and_use_temporary_expression::do_address_taken(bool)
1152 {
1153   this->statement_->set_is_address_taken();
1154 }
1155
1156 // Return the backend representation.
1157
1158 tree
1159 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1160 {
1161   Bvariable* bvar = this->statement_->get_backend_variable(context);
1162   tree var_tree = var_to_tree(bvar);
1163   tree expr_tree = this->expr_->get_tree(context);
1164   if (var_tree == error_mark_node || expr_tree == error_mark_node)
1165     return error_mark_node;
1166   Location loc = this->location();
1167   return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1168                     build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1169                                var_tree, expr_tree),
1170                     var_tree);
1171 }
1172
1173 // Dump.
1174
1175 void
1176 Set_and_use_temporary_expression::do_dump_expression(
1177     Ast_dump_context* ast_dump_context) const
1178 {
1179   ast_dump_context->ostream() << '(';
1180   ast_dump_context->dump_temp_variable_name(this->statement_);
1181   ast_dump_context->ostream() << " = ";
1182   this->expr_->dump_expression(ast_dump_context);
1183   ast_dump_context->ostream() << ')';
1184 }
1185
1186 // Make a set-and-use temporary.
1187
1188 Set_and_use_temporary_expression*
1189 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1190                                        Expression* expr, Location location)
1191 {
1192   return new Set_and_use_temporary_expression(statement, expr, location);
1193 }
1194
1195 // A sink expression--a use of the blank identifier _.
1196
1197 class Sink_expression : public Expression
1198 {
1199  public:
1200   Sink_expression(Location location)
1201     : Expression(EXPRESSION_SINK, location),
1202       type_(NULL), var_(NULL_TREE)
1203   { }
1204
1205  protected:
1206   void
1207   do_discarding_value()
1208   { }
1209
1210   Type*
1211   do_type();
1212
1213   void
1214   do_determine_type(const Type_context*);
1215
1216   Expression*
1217   do_copy()
1218   { return new Sink_expression(this->location()); }
1219
1220   tree
1221   do_get_tree(Translate_context*);
1222
1223   void
1224   do_dump_expression(Ast_dump_context*) const;
1225
1226  private:
1227   // The type of this sink variable.
1228   Type* type_;
1229   // The temporary variable we generate.
1230   tree var_;
1231 };
1232
1233 // Return the type of a sink expression.
1234
1235 Type*
1236 Sink_expression::do_type()
1237 {
1238   if (this->type_ == NULL)
1239     return Type::make_sink_type();
1240   return this->type_;
1241 }
1242
1243 // Determine the type of a sink expression.
1244
1245 void
1246 Sink_expression::do_determine_type(const Type_context* context)
1247 {
1248   if (context->type != NULL)
1249     this->type_ = context->type;
1250 }
1251
1252 // Return a temporary variable for a sink expression.  This will
1253 // presumably be a write-only variable which the middle-end will drop.
1254
1255 tree
1256 Sink_expression::do_get_tree(Translate_context* context)
1257 {
1258   if (this->var_ == NULL_TREE)
1259     {
1260       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1261       Btype* bt = this->type_->get_backend(context->gogo());
1262       this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1263     }
1264   return this->var_;
1265 }
1266
1267 // Ast dump for sink expression.
1268
1269 void
1270 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1271 {
1272   ast_dump_context->ostream() << "_" ;
1273 }
1274
1275 // Make a sink expression.
1276
1277 Expression*
1278 Expression::make_sink(Location location)
1279 {
1280   return new Sink_expression(location);
1281 }
1282
1283 // Class Func_expression.
1284
1285 // FIXME: Can a function expression appear in a constant expression?
1286 // The value is unchanging.  Initializing a constant to the address of
1287 // a function seems like it could work, though there might be little
1288 // point to it.
1289
1290 // Traversal.
1291
1292 int
1293 Func_expression::do_traverse(Traverse* traverse)
1294 {
1295   return (this->closure_ == NULL
1296           ? TRAVERSE_CONTINUE
1297           : Expression::traverse(&this->closure_, traverse));
1298 }
1299
1300 // Return the type of a function expression.
1301
1302 Type*
1303 Func_expression::do_type()
1304 {
1305   if (this->function_->is_function())
1306     return this->function_->func_value()->type();
1307   else if (this->function_->is_function_declaration())
1308     return this->function_->func_declaration_value()->type();
1309   else
1310     go_unreachable();
1311 }
1312
1313 // Get the tree for a function expression without evaluating the
1314 // closure.
1315
1316 tree
1317 Func_expression::get_tree_without_closure(Gogo* gogo)
1318 {
1319   Function_type* fntype;
1320   if (this->function_->is_function())
1321     fntype = this->function_->func_value()->type();
1322   else if (this->function_->is_function_declaration())
1323     fntype = this->function_->func_declaration_value()->type();
1324   else
1325     go_unreachable();
1326
1327   // Builtin functions are handled specially by Call_expression.  We
1328   // can't take their address.
1329   if (fntype->is_builtin())
1330     {
1331       error_at(this->location(),
1332                "invalid use of special builtin function %qs; must be called",
1333                this->function_->name().c_str());
1334       return error_mark_node;
1335     }
1336
1337   Named_object* no = this->function_;
1338
1339   tree id = no->get_id(gogo);
1340   if (id == error_mark_node)
1341     return error_mark_node;
1342
1343   tree fndecl;
1344   if (no->is_function())
1345     fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1346   else if (no->is_function_declaration())
1347     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1348   else
1349     go_unreachable();
1350
1351   if (fndecl == error_mark_node)
1352     return error_mark_node;
1353
1354   return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1355 }
1356
1357 // Get the tree for a function expression.  This is used when we take
1358 // the address of a function rather than simply calling it.  If the
1359 // function has a closure, we must use a trampoline.
1360
1361 tree
1362 Func_expression::do_get_tree(Translate_context* context)
1363 {
1364   Gogo* gogo = context->gogo();
1365
1366   tree fnaddr = this->get_tree_without_closure(gogo);
1367   if (fnaddr == error_mark_node)
1368     return error_mark_node;
1369
1370   go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1371              && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1372   TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1373
1374   // For a normal non-nested function call, that is all we have to do.
1375   if (!this->function_->is_function()
1376       || this->function_->func_value()->enclosing() == NULL)
1377     {
1378       go_assert(this->closure_ == NULL);
1379       return fnaddr;
1380     }
1381
1382   // For a nested function call, we have to always allocate a
1383   // trampoline.  If we don't always allocate, then closures will not
1384   // be reliably distinct.
1385   Expression* closure = this->closure_;
1386   tree closure_tree;
1387   if (closure == NULL)
1388     closure_tree = null_pointer_node;
1389   else
1390     {
1391       // Get the value of the closure.  This will be a pointer to
1392       // space allocated on the heap.
1393       closure_tree = closure->get_tree(context);
1394       if (closure_tree == error_mark_node)
1395         return error_mark_node;
1396       go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1397     }
1398
1399   // Now we need to build some code on the heap.  This code will load
1400   // the static chain pointer with the closure and then jump to the
1401   // body of the function.  The normal gcc approach is to build the
1402   // code on the stack.  Unfortunately we can not do that, as Go
1403   // permits us to return the function pointer.
1404
1405   return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1406 }
1407
1408 // Ast dump for function.
1409
1410 void
1411 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1412 {
1413   ast_dump_context->ostream() << this->function_->name();
1414   if (this->closure_ != NULL)
1415     {
1416       ast_dump_context->ostream() << " {closure =  ";
1417       this->closure_->dump_expression(ast_dump_context);
1418       ast_dump_context->ostream() << "}";
1419     }
1420 }
1421
1422 // Make a reference to a function in an expression.
1423
1424 Expression*
1425 Expression::make_func_reference(Named_object* function, Expression* closure,
1426                                 Location location)
1427 {
1428   return new Func_expression(function, closure, location);
1429 }
1430
1431 // Class Unknown_expression.
1432
1433 // Return the name of an unknown expression.
1434
1435 const std::string&
1436 Unknown_expression::name() const
1437 {
1438   return this->named_object_->name();
1439 }
1440
1441 // Lower a reference to an unknown name.
1442
1443 Expression*
1444 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1445 {
1446   Location location = this->location();
1447   Named_object* no = this->named_object_;
1448   Named_object* real;
1449   if (!no->is_unknown())
1450     real = no;
1451   else
1452     {
1453       real = no->unknown_value()->real_named_object();
1454       if (real == NULL)
1455         {
1456           if (this->is_composite_literal_key_)
1457             return this;
1458           if (!this->no_error_message_)
1459             error_at(location, "reference to undefined name %qs",
1460                      this->named_object_->message_name().c_str());
1461           return Expression::make_error(location);
1462         }
1463     }
1464   switch (real->classification())
1465     {
1466     case Named_object::NAMED_OBJECT_CONST:
1467       return Expression::make_const_reference(real, location);
1468     case Named_object::NAMED_OBJECT_TYPE:
1469       return Expression::make_type(real->type_value(), location);
1470     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1471       if (this->is_composite_literal_key_)
1472         return this;
1473       if (!this->no_error_message_)
1474         error_at(location, "reference to undefined type %qs",
1475                  real->message_name().c_str());
1476       return Expression::make_error(location);
1477     case Named_object::NAMED_OBJECT_VAR:
1478       real->var_value()->set_is_used();
1479       return Expression::make_var_reference(real, location);
1480     case Named_object::NAMED_OBJECT_FUNC:
1481     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1482       return Expression::make_func_reference(real, NULL, location);
1483     case Named_object::NAMED_OBJECT_PACKAGE:
1484       if (this->is_composite_literal_key_)
1485         return this;
1486       if (!this->no_error_message_)
1487         error_at(location, "unexpected reference to package");
1488       return Expression::make_error(location);
1489     default:
1490       go_unreachable();
1491     }
1492 }
1493
1494 // Dump the ast representation for an unknown expression to a dump context.
1495
1496 void
1497 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1498 {
1499   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1500                               << ")";
1501 }
1502
1503 // Make a reference to an unknown name.
1504
1505 Unknown_expression*
1506 Expression::make_unknown_reference(Named_object* no, Location location)
1507 {
1508   return new Unknown_expression(no, location);
1509 }
1510
1511 // A boolean expression.
1512
1513 class Boolean_expression : public Expression
1514 {
1515  public:
1516   Boolean_expression(bool val, Location location)
1517     : Expression(EXPRESSION_BOOLEAN, location),
1518       val_(val), type_(NULL)
1519   { }
1520
1521   static Expression*
1522   do_import(Import*);
1523
1524  protected:
1525   bool
1526   do_is_constant() const
1527   { return true; }
1528
1529   Type*
1530   do_type();
1531
1532   void
1533   do_determine_type(const Type_context*);
1534
1535   Expression*
1536   do_copy()
1537   { return this; }
1538
1539   tree
1540   do_get_tree(Translate_context*)
1541   { return this->val_ ? boolean_true_node : boolean_false_node; }
1542
1543   void
1544   do_export(Export* exp) const
1545   { exp->write_c_string(this->val_ ? "true" : "false"); }
1546
1547   void
1548   do_dump_expression(Ast_dump_context* ast_dump_context) const
1549   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1550   
1551  private:
1552   // The constant.
1553   bool val_;
1554   // The type as determined by context.
1555   Type* type_;
1556 };
1557
1558 // Get the type.
1559
1560 Type*
1561 Boolean_expression::do_type()
1562 {
1563   if (this->type_ == NULL)
1564     this->type_ = Type::make_boolean_type();
1565   return this->type_;
1566 }
1567
1568 // Set the type from the context.
1569
1570 void
1571 Boolean_expression::do_determine_type(const Type_context* context)
1572 {
1573   if (this->type_ != NULL && !this->type_->is_abstract())
1574     ;
1575   else if (context->type != NULL && context->type->is_boolean_type())
1576     this->type_ = context->type;
1577   else if (!context->may_be_abstract)
1578     this->type_ = Type::lookup_bool_type();
1579 }
1580
1581 // Import a boolean constant.
1582
1583 Expression*
1584 Boolean_expression::do_import(Import* imp)
1585 {
1586   if (imp->peek_char() == 't')
1587     {
1588       imp->require_c_string("true");
1589       return Expression::make_boolean(true, imp->location());
1590     }
1591   else
1592     {
1593       imp->require_c_string("false");
1594       return Expression::make_boolean(false, imp->location());
1595     }
1596 }
1597
1598 // Make a boolean expression.
1599
1600 Expression*
1601 Expression::make_boolean(bool val, Location location)
1602 {
1603   return new Boolean_expression(val, location);
1604 }
1605
1606 // Class String_expression.
1607
1608 // Get the type.
1609
1610 Type*
1611 String_expression::do_type()
1612 {
1613   if (this->type_ == NULL)
1614     this->type_ = Type::make_string_type();
1615   return this->type_;
1616 }
1617
1618 // Set the type from the context.
1619
1620 void
1621 String_expression::do_determine_type(const Type_context* context)
1622 {
1623   if (this->type_ != NULL && !this->type_->is_abstract())
1624     ;
1625   else if (context->type != NULL && context->type->is_string_type())
1626     this->type_ = context->type;
1627   else if (!context->may_be_abstract)
1628     this->type_ = Type::lookup_string_type();
1629 }
1630
1631 // Build a string constant.
1632
1633 tree
1634 String_expression::do_get_tree(Translate_context* context)
1635 {
1636   return context->gogo()->go_string_constant_tree(this->val_);
1637 }
1638
1639  // Write string literal to string dump.
1640
1641 void
1642 String_expression::export_string(String_dump* exp,
1643                                  const String_expression* str)
1644 {
1645   std::string s;
1646   s.reserve(str->val_.length() * 4 + 2);
1647   s += '"';
1648   for (std::string::const_iterator p = str->val_.begin();
1649        p != str->val_.end();
1650        ++p)
1651     {
1652       if (*p == '\\' || *p == '"')
1653         {
1654           s += '\\';
1655           s += *p;
1656         }
1657       else if (*p >= 0x20 && *p < 0x7f)
1658         s += *p;
1659       else if (*p == '\n')
1660         s += "\\n";
1661       else if (*p == '\t')
1662         s += "\\t";
1663       else
1664         {
1665           s += "\\x";
1666           unsigned char c = *p;
1667           unsigned int dig = c >> 4;
1668           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1669           dig = c & 0xf;
1670           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1671         }
1672     }
1673   s += '"';
1674   exp->write_string(s);
1675 }
1676
1677 // Export a string expression.
1678
1679 void
1680 String_expression::do_export(Export* exp) const
1681 {
1682   String_expression::export_string(exp, this);
1683 }
1684
1685 // Import a string expression.
1686
1687 Expression*
1688 String_expression::do_import(Import* imp)
1689 {
1690   imp->require_c_string("\"");
1691   std::string val;
1692   while (true)
1693     {
1694       int c = imp->get_char();
1695       if (c == '"' || c == -1)
1696         break;
1697       if (c != '\\')
1698         val += static_cast<char>(c);
1699       else
1700         {
1701           c = imp->get_char();
1702           if (c == '\\' || c == '"')
1703             val += static_cast<char>(c);
1704           else if (c == 'n')
1705             val += '\n';
1706           else if (c == 't')
1707             val += '\t';
1708           else if (c == 'x')
1709             {
1710               c = imp->get_char();
1711               unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1712               c = imp->get_char();
1713               unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1714               char v = (vh << 4) | vl;
1715               val += v;
1716             }
1717           else
1718             {
1719               error_at(imp->location(), "bad string constant");
1720               return Expression::make_error(imp->location());
1721             }
1722         }
1723     }
1724   return Expression::make_string(val, imp->location());
1725 }
1726
1727 // Ast dump for string expression.
1728
1729 void
1730 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1731 {
1732   String_expression::export_string(ast_dump_context, this);
1733 }
1734
1735 // Make a string expression.
1736
1737 Expression*
1738 Expression::make_string(const std::string& val, Location location)
1739 {
1740   return new String_expression(val, location);
1741 }
1742
1743 // Make an integer expression.
1744
1745 class Integer_expression : public Expression
1746 {
1747  public:
1748   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1749                      Location location)
1750     : Expression(EXPRESSION_INTEGER, location),
1751       type_(type), is_character_constant_(is_character_constant)
1752   { mpz_init_set(this->val_, *val); }
1753
1754   static Expression*
1755   do_import(Import*);
1756
1757   // Return whether VAL fits in the type.
1758   static bool
1759   check_constant(mpz_t val, Type*, Location);
1760
1761   // Write VAL to string dump.
1762   static void
1763   export_integer(String_dump* exp, const mpz_t val);
1764
1765   // Write VAL to dump context.
1766   static void
1767   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1768
1769  protected:
1770   bool
1771   do_is_constant() const
1772   { return true; }
1773
1774   bool
1775   do_integer_constant_value(bool, mpz_t val, Type** ptype) const;
1776
1777   Type*
1778   do_type();
1779
1780   void
1781   do_determine_type(const Type_context* context);
1782
1783   void
1784   do_check_types(Gogo*);
1785
1786   tree
1787   do_get_tree(Translate_context*);
1788
1789   Expression*
1790   do_copy()
1791   {
1792     if (this->is_character_constant_)
1793       return Expression::make_character(&this->val_, this->type_,
1794                                         this->location());
1795     else
1796       return Expression::make_integer(&this->val_, this->type_,
1797                                       this->location());
1798   }
1799
1800   void
1801   do_export(Export*) const;
1802
1803   void
1804   do_dump_expression(Ast_dump_context*) const;
1805
1806  private:
1807   // The integer value.
1808   mpz_t val_;
1809   // The type so far.
1810   Type* type_;
1811   // Whether this is a character constant.
1812   bool is_character_constant_;
1813 };
1814
1815 // Return an integer constant value.
1816
1817 bool
1818 Integer_expression::do_integer_constant_value(bool, mpz_t val,
1819                                               Type** ptype) const
1820 {
1821   if (this->type_ != NULL)
1822     *ptype = this->type_;
1823   mpz_set(val, this->val_);
1824   return true;
1825 }
1826
1827 // Return the current type.  If we haven't set the type yet, we return
1828 // an abstract integer type.
1829
1830 Type*
1831 Integer_expression::do_type()
1832 {
1833   if (this->type_ == NULL)
1834     {
1835       if (this->is_character_constant_)
1836         this->type_ = Type::make_abstract_character_type();
1837       else
1838         this->type_ = Type::make_abstract_integer_type();
1839     }
1840   return this->type_;
1841 }
1842
1843 // Set the type of the integer value.  Here we may switch from an
1844 // abstract type to a real type.
1845
1846 void
1847 Integer_expression::do_determine_type(const Type_context* context)
1848 {
1849   if (this->type_ != NULL && !this->type_->is_abstract())
1850     ;
1851   else if (context->type != NULL
1852            && (context->type->integer_type() != NULL
1853                || context->type->float_type() != NULL
1854                || context->type->complex_type() != NULL))
1855     this->type_ = context->type;
1856   else if (!context->may_be_abstract)
1857     {
1858       if (this->is_character_constant_)
1859         this->type_ = Type::lookup_integer_type("int32");
1860       else
1861         this->type_ = Type::lookup_integer_type("int");
1862     }
1863 }
1864
1865 // Return true if the integer VAL fits in the range of the type TYPE.
1866 // Otherwise give an error and return false.  TYPE may be NULL.
1867
1868 bool
1869 Integer_expression::check_constant(mpz_t val, Type* type,
1870                                    Location location)
1871 {
1872   if (type == NULL)
1873     return true;
1874   Integer_type* itype = type->integer_type();
1875   if (itype == NULL || itype->is_abstract())
1876     return true;
1877
1878   int bits = mpz_sizeinbase(val, 2);
1879
1880   if (itype->is_unsigned())
1881     {
1882       // For an unsigned type we can only accept a nonnegative number,
1883       // and we must be able to represent at least BITS.
1884       if (mpz_sgn(val) >= 0
1885           && bits <= itype->bits())
1886         return true;
1887     }
1888   else
1889     {
1890       // For a signed type we need an extra bit to indicate the sign.
1891       // We have to handle the most negative integer specially.
1892       if (bits + 1 <= itype->bits()
1893           || (bits <= itype->bits()
1894               && mpz_sgn(val) < 0
1895               && (mpz_scan1(val, 0)
1896                   == static_cast<unsigned long>(itype->bits() - 1))
1897               && mpz_scan0(val, itype->bits()) == ULONG_MAX))
1898         return true;
1899     }
1900
1901   error_at(location, "integer constant overflow");
1902   return false;
1903 }
1904
1905 // Check the type of an integer constant.
1906
1907 void
1908 Integer_expression::do_check_types(Gogo*)
1909 {
1910   if (this->type_ == NULL)
1911     return;
1912   if (!Integer_expression::check_constant(this->val_, this->type_,
1913                                           this->location()))
1914     this->set_is_error();
1915 }
1916
1917 // Get a tree for an integer constant.
1918
1919 tree
1920 Integer_expression::do_get_tree(Translate_context* context)
1921 {
1922   Gogo* gogo = context->gogo();
1923   tree type;
1924   if (this->type_ != NULL && !this->type_->is_abstract())
1925     type = type_to_tree(this->type_->get_backend(gogo));
1926   else if (this->type_ != NULL && this->type_->float_type() != NULL)
1927     {
1928       // We are converting to an abstract floating point type.
1929       Type* ftype = Type::lookup_float_type("float64");
1930       type = type_to_tree(ftype->get_backend(gogo));
1931     }
1932   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1933     {
1934       // We are converting to an abstract complex type.
1935       Type* ctype = Type::lookup_complex_type("complex128");
1936       type = type_to_tree(ctype->get_backend(gogo));
1937     }
1938   else
1939     {
1940       // If we still have an abstract type here, then this is being
1941       // used in a constant expression which didn't get reduced for
1942       // some reason.  Use a type which will fit the value.  We use <,
1943       // not <=, because we need an extra bit for the sign bit.
1944       int bits = mpz_sizeinbase(this->val_, 2);
1945       if (bits < INT_TYPE_SIZE)
1946         {
1947           Type* t = Type::lookup_integer_type("int");
1948           type = type_to_tree(t->get_backend(gogo));
1949         }
1950       else if (bits < 64)
1951         {
1952           Type* t = Type::lookup_integer_type("int64");
1953           type = type_to_tree(t->get_backend(gogo));
1954         }
1955       else
1956         type = long_long_integer_type_node;
1957     }
1958   return Expression::integer_constant_tree(this->val_, type);
1959 }
1960
1961 // Write VAL to export data.
1962
1963 void
1964 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1965 {
1966   char* s = mpz_get_str(NULL, 10, val);
1967   exp->write_c_string(s);
1968   free(s);
1969 }
1970
1971 // Export an integer in a constant expression.
1972
1973 void
1974 Integer_expression::do_export(Export* exp) const
1975 {
1976   Integer_expression::export_integer(exp, this->val_);
1977   if (this->is_character_constant_)
1978     exp->write_c_string("'");
1979   // A trailing space lets us reliably identify the end of the number.
1980   exp->write_c_string(" ");
1981 }
1982
1983 // Import an integer, floating point, or complex value.  This handles
1984 // all these types because they all start with digits.
1985
1986 Expression*
1987 Integer_expression::do_import(Import* imp)
1988 {
1989   std::string num = imp->read_identifier();
1990   imp->require_c_string(" ");
1991   if (!num.empty() && num[num.length() - 1] == 'i')
1992     {
1993       mpfr_t real;
1994       size_t plus_pos = num.find('+', 1);
1995       size_t minus_pos = num.find('-', 1);
1996       size_t pos;
1997       if (plus_pos == std::string::npos)
1998         pos = minus_pos;
1999       else if (minus_pos == std::string::npos)
2000         pos = plus_pos;
2001       else
2002         {
2003           error_at(imp->location(), "bad number in import data: %qs",
2004                    num.c_str());
2005           return Expression::make_error(imp->location());
2006         }
2007       if (pos == std::string::npos)
2008         mpfr_set_ui(real, 0, GMP_RNDN);
2009       else
2010         {
2011           std::string real_str = num.substr(0, pos);
2012           if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2013             {
2014               error_at(imp->location(), "bad number in import data: %qs",
2015                        real_str.c_str());
2016               return Expression::make_error(imp->location());
2017             }
2018         }
2019
2020       std::string imag_str;
2021       if (pos == std::string::npos)
2022         imag_str = num;
2023       else
2024         imag_str = num.substr(pos);
2025       imag_str = imag_str.substr(0, imag_str.size() - 1);
2026       mpfr_t imag;
2027       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2028         {
2029           error_at(imp->location(), "bad number in import data: %qs",
2030                    imag_str.c_str());
2031           return Expression::make_error(imp->location());
2032         }
2033       Expression* ret = Expression::make_complex(&real, &imag, NULL,
2034                                                  imp->location());
2035       mpfr_clear(real);
2036       mpfr_clear(imag);
2037       return ret;
2038     }
2039   else if (num.find('.') == std::string::npos
2040            && num.find('E') == std::string::npos)
2041     {
2042       bool is_character_constant = (!num.empty()
2043                                     && num[num.length() - 1] == '\'');
2044       if (is_character_constant)
2045         num = num.substr(0, num.length() - 1);
2046       mpz_t val;
2047       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2048         {
2049           error_at(imp->location(), "bad number in import data: %qs",
2050                    num.c_str());
2051           return Expression::make_error(imp->location());
2052         }
2053       Expression* ret;
2054       if (is_character_constant)
2055         ret = Expression::make_character(&val, NULL, imp->location());
2056       else
2057         ret = Expression::make_integer(&val, NULL, imp->location());
2058       mpz_clear(val);
2059       return ret;
2060     }
2061   else
2062     {
2063       mpfr_t val;
2064       if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2065         {
2066           error_at(imp->location(), "bad number in import data: %qs",
2067                    num.c_str());
2068           return Expression::make_error(imp->location());
2069         }
2070       Expression* ret = Expression::make_float(&val, NULL, imp->location());
2071       mpfr_clear(val);
2072       return ret;
2073     }
2074 }
2075 // Ast dump for integer expression.
2076
2077 void
2078 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2079 {
2080   if (this->is_character_constant_)
2081     ast_dump_context->ostream() << '\'';
2082   Integer_expression::export_integer(ast_dump_context, this->val_);
2083   if (this->is_character_constant_)
2084     ast_dump_context->ostream() << '\'';
2085 }
2086
2087 // Build a new integer value.
2088
2089 Expression*
2090 Expression::make_integer(const mpz_t* val, Type* type, Location location)
2091 {
2092   return new Integer_expression(val, type, false, location);
2093 }
2094
2095 // Build a new character constant value.
2096
2097 Expression*
2098 Expression::make_character(const mpz_t* val, Type* type, Location location)
2099 {
2100   return new Integer_expression(val, type, true, location);
2101 }
2102
2103 // Floats.
2104
2105 class Float_expression : public Expression
2106 {
2107  public:
2108   Float_expression(const mpfr_t* val, Type* type, Location location)
2109     : Expression(EXPRESSION_FLOAT, location),
2110       type_(type)
2111   {
2112     mpfr_init_set(this->val_, *val, GMP_RNDN);
2113   }
2114
2115   // Constrain VAL to fit into TYPE.
2116   static void
2117   constrain_float(mpfr_t val, Type* type);
2118
2119   // Return whether VAL fits in the type.
2120   static bool
2121   check_constant(mpfr_t val, Type*, Location);
2122
2123   // Write VAL to export data.
2124   static void
2125   export_float(String_dump* exp, const mpfr_t val);
2126
2127   // Write VAL to dump file.
2128   static void
2129   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2130
2131  protected:
2132   bool
2133   do_is_constant() const
2134   { return true; }
2135
2136   bool
2137   do_float_constant_value(mpfr_t val, Type**) const;
2138
2139   Type*
2140   do_type();
2141
2142   void
2143   do_determine_type(const Type_context*);
2144
2145   void
2146   do_check_types(Gogo*);
2147
2148   Expression*
2149   do_copy()
2150   { return Expression::make_float(&this->val_, this->type_,
2151                                   this->location()); }
2152
2153   tree
2154   do_get_tree(Translate_context*);
2155
2156   void
2157   do_export(Export*) const;
2158
2159   void
2160   do_dump_expression(Ast_dump_context*) const;
2161
2162  private:
2163   // The floating point value.
2164   mpfr_t val_;
2165   // The type so far.
2166   Type* type_;
2167 };
2168
2169 // Constrain VAL to fit into TYPE.
2170
2171 void
2172 Float_expression::constrain_float(mpfr_t val, Type* type)
2173 {
2174   Float_type* ftype = type->float_type();
2175   if (ftype != NULL && !ftype->is_abstract())
2176     mpfr_prec_round(val, ftype->bits(), GMP_RNDN);
2177 }
2178
2179 // Return a floating point constant value.
2180
2181 bool
2182 Float_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
2183 {
2184   if (this->type_ != NULL)
2185     *ptype = this->type_;
2186   mpfr_set(val, this->val_, GMP_RNDN);
2187   return true;
2188 }
2189
2190 // Return the current type.  If we haven't set the type yet, we return
2191 // an abstract float type.
2192
2193 Type*
2194 Float_expression::do_type()
2195 {
2196   if (this->type_ == NULL)
2197     this->type_ = Type::make_abstract_float_type();
2198   return this->type_;
2199 }
2200
2201 // Set the type of the float value.  Here we may switch from an
2202 // abstract type to a real type.
2203
2204 void
2205 Float_expression::do_determine_type(const Type_context* context)
2206 {
2207   if (this->type_ != NULL && !this->type_->is_abstract())
2208     ;
2209   else if (context->type != NULL
2210            && (context->type->integer_type() != NULL
2211                || context->type->float_type() != NULL
2212                || context->type->complex_type() != NULL))
2213     this->type_ = context->type;
2214   else if (!context->may_be_abstract)
2215     this->type_ = Type::lookup_float_type("float64");
2216 }
2217
2218 // Return true if the floating point value VAL fits in the range of
2219 // the type TYPE.  Otherwise give an error and return false.  TYPE may
2220 // be NULL.
2221
2222 bool
2223 Float_expression::check_constant(mpfr_t val, Type* type,
2224                                  Location location)
2225 {
2226   if (type == NULL)
2227     return true;
2228   Float_type* ftype = type->float_type();
2229   if (ftype == NULL || ftype->is_abstract())
2230     return true;
2231
2232   // A NaN or Infinity always fits in the range of the type.
2233   if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
2234     return true;
2235
2236   mp_exp_t exp = mpfr_get_exp(val);
2237   mp_exp_t max_exp;
2238   switch (ftype->bits())
2239     {
2240     case 32:
2241       max_exp = 128;
2242       break;
2243     case 64:
2244       max_exp = 1024;
2245       break;
2246     default:
2247       go_unreachable();
2248     }
2249   if (exp > max_exp)
2250     {
2251       error_at(location, "floating point constant overflow");
2252       return false;
2253     }
2254   return true;
2255 }
2256
2257 // Check the type of a float value.
2258
2259 void
2260 Float_expression::do_check_types(Gogo*)
2261 {
2262   if (this->type_ == NULL)
2263     return;
2264
2265   if (!Float_expression::check_constant(this->val_, this->type_,
2266                                         this->location()))
2267     this->set_is_error();
2268
2269   Integer_type* integer_type = this->type_->integer_type();
2270   if (integer_type != NULL)
2271     {
2272       if (!mpfr_integer_p(this->val_))
2273         this->report_error(_("floating point constant truncated to integer"));
2274       else
2275         {
2276           go_assert(!integer_type->is_abstract());
2277           mpz_t ival;
2278           mpz_init(ival);
2279           mpfr_get_z(ival, this->val_, GMP_RNDN);
2280           Integer_expression::check_constant(ival, integer_type,
2281                                              this->location());
2282           mpz_clear(ival);
2283         }
2284     }
2285 }
2286
2287 // Get a tree for a float constant.
2288
2289 tree
2290 Float_expression::do_get_tree(Translate_context* context)
2291 {
2292   Gogo* gogo = context->gogo();
2293   tree type;
2294   if (this->type_ != NULL && !this->type_->is_abstract())
2295     type = type_to_tree(this->type_->get_backend(gogo));
2296   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2297     {
2298       // We have an abstract integer type.  We just hope for the best.
2299       type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2300     }
2301   else
2302     {
2303       // If we still have an abstract type here, then this is being
2304       // used in a constant expression which didn't get reduced.  We
2305       // just use float64 and hope for the best.
2306       Type* ft = Type::lookup_float_type("float64");
2307       type = type_to_tree(ft->get_backend(gogo));
2308     }
2309   return Expression::float_constant_tree(this->val_, type);
2310 }
2311
2312 // Write a floating point number to a string dump.
2313
2314 void
2315 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2316 {
2317   mp_exp_t exponent;
2318   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2319   if (*s == '-')
2320     exp->write_c_string("-");
2321   exp->write_c_string("0.");
2322   exp->write_c_string(*s == '-' ? s + 1 : s);
2323   mpfr_free_str(s);
2324   char buf[30];
2325   snprintf(buf, sizeof buf, "E%ld", exponent);
2326   exp->write_c_string(buf);
2327 }
2328
2329 // Export a floating point number in a constant expression.
2330
2331 void
2332 Float_expression::do_export(Export* exp) const
2333 {
2334   Float_expression::export_float(exp, this->val_);
2335   // A trailing space lets us reliably identify the end of the number.
2336   exp->write_c_string(" ");
2337 }
2338
2339 // Dump a floating point number to the dump file.
2340
2341 void
2342 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2343 {
2344   Float_expression::export_float(ast_dump_context, this->val_);
2345 }
2346
2347 // Make a float expression.
2348
2349 Expression*
2350 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2351 {
2352   return new Float_expression(val, type, location);
2353 }
2354
2355 // Complex numbers.
2356
2357 class Complex_expression : public Expression
2358 {
2359  public:
2360   Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2361                      Location location)
2362     : Expression(EXPRESSION_COMPLEX, location),
2363       type_(type)
2364   {
2365     mpfr_init_set(this->real_, *real, GMP_RNDN);
2366     mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2367   }
2368
2369   // Constrain REAL/IMAG to fit into TYPE.
2370   static void
2371   constrain_complex(mpfr_t real, mpfr_t imag, Type* type);
2372
2373   // Return whether REAL/IMAG fits in the type.
2374   static bool
2375   check_constant(mpfr_t real, mpfr_t imag, Type*, Location);
2376
2377   // Write REAL/IMAG to string dump.
2378   static void
2379   export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2380
2381   // Write REAL/IMAG to dump context.
2382   static void
2383   dump_complex(Ast_dump_context* ast_dump_context, 
2384                const mpfr_t real, const mpfr_t val);
2385   
2386  protected:
2387   bool
2388   do_is_constant() const
2389   { return true; }
2390
2391   bool
2392   do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const;
2393
2394   Type*
2395   do_type();
2396
2397   void
2398   do_determine_type(const Type_context*);
2399
2400   void
2401   do_check_types(Gogo*);
2402
2403   Expression*
2404   do_copy()
2405   {
2406     return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2407                                     this->location());
2408   }
2409
2410   tree
2411   do_get_tree(Translate_context*);
2412
2413   void
2414   do_export(Export*) const;
2415
2416   void
2417   do_dump_expression(Ast_dump_context*) const;
2418   
2419  private:
2420   // The real part.
2421   mpfr_t real_;
2422   // The imaginary part;
2423   mpfr_t imag_;
2424   // The type if known.
2425   Type* type_;
2426 };
2427
2428 // Constrain REAL/IMAG to fit into TYPE.
2429
2430 void
2431 Complex_expression::constrain_complex(mpfr_t real, mpfr_t imag, Type* type)
2432 {
2433   Complex_type* ctype = type->complex_type();
2434   if (ctype != NULL && !ctype->is_abstract())
2435     {
2436       mpfr_prec_round(real, ctype->bits() / 2, GMP_RNDN);
2437       mpfr_prec_round(imag, ctype->bits() / 2, GMP_RNDN);
2438     }
2439 }
2440
2441 // Return a complex constant value.
2442
2443 bool
2444 Complex_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
2445                                               Type** ptype) const
2446 {
2447   if (this->type_ != NULL)
2448     *ptype = this->type_;
2449   mpfr_set(real, this->real_, GMP_RNDN);
2450   mpfr_set(imag, this->imag_, GMP_RNDN);
2451   return true;
2452 }
2453
2454 // Return the current type.  If we haven't set the type yet, we return
2455 // an abstract complex type.
2456
2457 Type*
2458 Complex_expression::do_type()
2459 {
2460   if (this->type_ == NULL)
2461     this->type_ = Type::make_abstract_complex_type();
2462   return this->type_;
2463 }
2464
2465 // Set the type of the complex value.  Here we may switch from an
2466 // abstract type to a real type.
2467
2468 void
2469 Complex_expression::do_determine_type(const Type_context* context)
2470 {
2471   if (this->type_ != NULL && !this->type_->is_abstract())
2472     ;
2473   else if (context->type != NULL
2474            && context->type->complex_type() != NULL)
2475     this->type_ = context->type;
2476   else if (!context->may_be_abstract)
2477     this->type_ = Type::lookup_complex_type("complex128");
2478 }
2479
2480 // Return true if the complex value REAL/IMAG fits in the range of the
2481 // type TYPE.  Otherwise give an error and return false.  TYPE may be
2482 // NULL.
2483
2484 bool
2485 Complex_expression::check_constant(mpfr_t real, mpfr_t imag, Type* type,
2486                                    Location location)
2487 {
2488   if (type == NULL)
2489     return true;
2490   Complex_type* ctype = type->complex_type();
2491   if (ctype == NULL || ctype->is_abstract())
2492     return true;
2493
2494   mp_exp_t max_exp;
2495   switch (ctype->bits())
2496     {
2497     case 64:
2498       max_exp = 128;
2499       break;
2500     case 128:
2501       max_exp = 1024;
2502       break;
2503     default:
2504       go_unreachable();
2505     }
2506
2507   // A NaN or Infinity always fits in the range of the type.
2508   if (!mpfr_nan_p(real) && !mpfr_inf_p(real) && !mpfr_zero_p(real))
2509     {
2510       if (mpfr_get_exp(real) > max_exp)
2511         {
2512           error_at(location, "complex real part constant overflow");
2513           return false;
2514         }
2515     }
2516
2517   if (!mpfr_nan_p(imag) && !mpfr_inf_p(imag) && !mpfr_zero_p(imag))
2518     {
2519       if (mpfr_get_exp(imag) > max_exp)
2520         {
2521           error_at(location, "complex imaginary part constant overflow");
2522           return false;
2523         }
2524     }
2525
2526   return true;
2527 }
2528
2529 // Check the type of a complex value.
2530
2531 void
2532 Complex_expression::do_check_types(Gogo*)
2533 {
2534   if (this->type_ == NULL)
2535     return;
2536
2537   if (!Complex_expression::check_constant(this->real_, this->imag_,
2538                                           this->type_, this->location()))
2539     this->set_is_error();
2540 }
2541
2542 // Get a tree for a complex constant.
2543
2544 tree
2545 Complex_expression::do_get_tree(Translate_context* context)
2546 {
2547   Gogo* gogo = context->gogo();
2548   tree type;
2549   if (this->type_ != NULL && !this->type_->is_abstract())
2550     type = type_to_tree(this->type_->get_backend(gogo));
2551   else
2552     {
2553       // If we still have an abstract type here, this this is being
2554       // used in a constant expression which didn't get reduced.  We
2555       // just use complex128 and hope for the best.
2556       Type* ct = Type::lookup_complex_type("complex128");
2557       type = type_to_tree(ct->get_backend(gogo));
2558     }
2559   return Expression::complex_constant_tree(this->real_, this->imag_, type);
2560 }
2561
2562 // Write REAL/IMAG to export data.
2563
2564 void
2565 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2566                                    const mpfr_t imag)
2567 {
2568   if (!mpfr_zero_p(real))
2569     {
2570       Float_expression::export_float(exp, real);
2571       if (mpfr_sgn(imag) > 0)
2572         exp->write_c_string("+");
2573     }
2574   Float_expression::export_float(exp, imag);
2575   exp->write_c_string("i");
2576 }
2577
2578 // Export a complex number in a constant expression.
2579
2580 void
2581 Complex_expression::do_export(Export* exp) const
2582 {
2583   Complex_expression::export_complex(exp, this->real_, this->imag_);
2584   // A trailing space lets us reliably identify the end of the number.
2585   exp->write_c_string(" ");
2586 }
2587
2588 // Dump a complex expression to the dump file.
2589
2590 void
2591 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2592 {
2593   Complex_expression::export_complex(ast_dump_context,
2594                                       this->real_,
2595                                       this->imag_);
2596 }
2597
2598 // Make a complex expression.
2599
2600 Expression*
2601 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2602                          Location location)
2603 {
2604   return new Complex_expression(real, imag, type, location);
2605 }
2606
2607 // Find a named object in an expression.
2608
2609 class Find_named_object : public Traverse
2610 {
2611  public:
2612   Find_named_object(Named_object* no)
2613     : Traverse(traverse_expressions),
2614       no_(no), found_(false)
2615   { }
2616
2617   // Whether we found the object.
2618   bool
2619   found() const
2620   { return this->found_; }
2621
2622  protected:
2623   int
2624   expression(Expression**);
2625
2626  private:
2627   // The object we are looking for.
2628   Named_object* no_;
2629   // Whether we found it.
2630   bool found_;
2631 };
2632
2633 // A reference to a const in an expression.
2634
2635 class Const_expression : public Expression
2636 {
2637  public:
2638   Const_expression(Named_object* constant, Location location)
2639     : Expression(EXPRESSION_CONST_REFERENCE, location),
2640       constant_(constant), type_(NULL), seen_(false)
2641   { }
2642
2643   Named_object*
2644   named_object()
2645   { return this->constant_; }
2646
2647   // Check that the initializer does not refer to the constant itself.
2648   void
2649   check_for_init_loop();
2650
2651  protected:
2652   int
2653   do_traverse(Traverse*);
2654
2655   Expression*
2656   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2657
2658   bool
2659   do_is_constant() const
2660   { return true; }
2661
2662   bool
2663   do_integer_constant_value(bool, mpz_t val, Type**) const;
2664
2665   bool
2666   do_float_constant_value(mpfr_t val, Type**) const;
2667
2668   bool
2669   do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const;
2670
2671   bool
2672   do_string_constant_value(std::string* val) const
2673   { return this->constant_->const_value()->expr()->string_constant_value(val); }
2674
2675   Type*
2676   do_type();
2677
2678   // The type of a const is set by the declaration, not the use.
2679   void
2680   do_determine_type(const Type_context*);
2681
2682   void
2683   do_check_types(Gogo*);
2684
2685   Expression*
2686   do_copy()
2687   { return this; }
2688
2689   tree
2690   do_get_tree(Translate_context* context);
2691
2692   // When exporting a reference to a const as part of a const
2693   // expression, we export the value.  We ignore the fact that it has
2694   // a name.
2695   void
2696   do_export(Export* exp) const
2697   { this->constant_->const_value()->expr()->export_expression(exp); }
2698
2699   void
2700   do_dump_expression(Ast_dump_context*) const;
2701
2702  private:
2703   // The constant.
2704   Named_object* constant_;
2705   // The type of this reference.  This is used if the constant has an
2706   // abstract type.
2707   Type* type_;
2708   // Used to prevent infinite recursion when a constant incorrectly
2709   // refers to itself.
2710   mutable bool seen_;
2711 };
2712
2713 // Traversal.
2714
2715 int
2716 Const_expression::do_traverse(Traverse* traverse)
2717 {
2718   if (this->type_ != NULL)
2719     return Type::traverse(this->type_, traverse);
2720   return TRAVERSE_CONTINUE;
2721 }
2722
2723 // Lower a constant expression.  This is where we convert the
2724 // predeclared constant iota into an integer value.
2725
2726 Expression*
2727 Const_expression::do_lower(Gogo* gogo, Named_object*,
2728                            Statement_inserter*, int iota_value)
2729 {
2730   if (this->constant_->const_value()->expr()->classification()
2731       == EXPRESSION_IOTA)
2732     {
2733       if (iota_value == -1)
2734         {
2735           error_at(this->location(),
2736                    "iota is only defined in const declarations");
2737           iota_value = 0;
2738         }
2739       mpz_t val;
2740       mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2741       Expression* ret = Expression::make_integer(&val, NULL,
2742                                                  this->location());
2743       mpz_clear(val);
2744       return ret;
2745     }
2746
2747   // Make sure that the constant itself has been lowered.
2748   gogo->lower_constant(this->constant_);
2749
2750   return this;
2751 }
2752
2753 // Return an integer constant value.
2754
2755 bool
2756 Const_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val,
2757                                             Type** ptype) const
2758 {
2759   if (this->seen_)
2760     return false;
2761
2762   Type* ctype;
2763   if (this->type_ != NULL)
2764     ctype = this->type_;
2765   else
2766     ctype = this->constant_->const_value()->type();
2767   if (ctype != NULL && ctype->integer_type() == NULL)
2768     return false;
2769
2770   Expression* e = this->constant_->const_value()->expr();
2771
2772   this->seen_ = true;
2773
2774   Type* t;
2775   bool r = e->integer_constant_value(iota_is_constant, val, &t);
2776
2777   this->seen_ = false;
2778
2779   if (r
2780       && ctype != NULL
2781       && !Integer_expression::check_constant(val, ctype, this->location()))
2782     return false;
2783
2784   *ptype = ctype != NULL ? ctype : t;
2785   return r;
2786 }
2787
2788 // Return a floating point constant value.
2789
2790 bool
2791 Const_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
2792 {
2793   if (this->seen_)
2794     return false;
2795
2796   Type* ctype;
2797   if (this->type_ != NULL)
2798     ctype = this->type_;
2799   else
2800     ctype = this->constant_->const_value()->type();
2801   if (ctype != NULL && ctype->float_type() == NULL)
2802     return false;
2803
2804   this->seen_ = true;
2805
2806   Type* t;
2807   bool r = this->constant_->const_value()->expr()->float_constant_value(val,
2808                                                                         &t);
2809
2810   this->seen_ = false;
2811
2812   if (r && ctype != NULL)
2813     {
2814       if (!Float_expression::check_constant(val, ctype, this->location()))
2815         return false;
2816       Float_expression::constrain_float(val, ctype);
2817     }
2818   *ptype = ctype != NULL ? ctype : t;
2819   return r;
2820 }
2821
2822 // Return a complex constant value.
2823
2824 bool
2825 Const_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
2826                                             Type **ptype) const
2827 {
2828   if (this->seen_)
2829     return false;
2830
2831   Type* ctype;
2832   if (this->type_ != NULL)
2833     ctype = this->type_;
2834   else
2835     ctype = this->constant_->const_value()->type();
2836   if (ctype != NULL && ctype->complex_type() == NULL)
2837     return false;
2838
2839   this->seen_ = true;
2840
2841   Type *t;
2842   bool r = this->constant_->const_value()->expr()->complex_constant_value(real,
2843                                                                           imag,
2844                                                                           &t);
2845
2846   this->seen_ = false;
2847
2848   if (r && ctype != NULL)
2849     {
2850       if (!Complex_expression::check_constant(real, imag, ctype,
2851                                               this->location()))
2852         return false;
2853       Complex_expression::constrain_complex(real, imag, ctype);
2854     }
2855   *ptype = ctype != NULL ? ctype : t;
2856   return r;
2857 }
2858
2859 // Return the type of the const reference.
2860
2861 Type*
2862 Const_expression::do_type()
2863 {
2864   if (this->type_ != NULL)
2865     return this->type_;
2866
2867   Named_constant* nc = this->constant_->const_value();
2868
2869   if (this->seen_ || nc->lowering())
2870     {
2871       this->report_error(_("constant refers to itself"));
2872       this->type_ = Type::make_error_type();
2873       return this->type_;
2874     }
2875
2876   this->seen_ = true;
2877
2878   Type* ret = nc->type();
2879
2880   if (ret != NULL)
2881     {
2882       this->seen_ = false;
2883       return ret;
2884     }
2885
2886   // During parsing, a named constant may have a NULL type, but we
2887   // must not return a NULL type here.
2888   ret = nc->expr()->type();
2889
2890   this->seen_ = false;
2891
2892   return ret;
2893 }
2894
2895 // Set the type of the const reference.
2896
2897 void
2898 Const_expression::do_determine_type(const Type_context* context)
2899 {
2900   Type* ctype = this->constant_->const_value()->type();
2901   Type* cetype = (ctype != NULL
2902                   ? ctype
2903                   : this->constant_->const_value()->expr()->type());
2904   if (ctype != NULL && !ctype->is_abstract())
2905     ;
2906   else if (context->type != NULL
2907            && (context->type->integer_type() != NULL
2908                || context->type->float_type() != NULL
2909                || context->type->complex_type() != NULL)
2910            && (cetype->integer_type() != NULL
2911                || cetype->float_type() != NULL
2912                || cetype->complex_type() != NULL))
2913     this->type_ = context->type;
2914   else if (context->type != NULL
2915            && context->type->is_string_type()
2916            && cetype->is_string_type())
2917     this->type_ = context->type;
2918   else if (context->type != NULL
2919            && context->type->is_boolean_type()
2920            && cetype->is_boolean_type())
2921     this->type_ = context->type;
2922   else if (!context->may_be_abstract)
2923     {
2924       if (cetype->is_abstract())
2925         cetype = cetype->make_non_abstract_type();
2926       this->type_ = cetype;
2927     }
2928 }
2929
2930 // Check for a loop in which the initializer of a constant refers to
2931 // the constant itself.
2932
2933 void
2934 Const_expression::check_for_init_loop()
2935 {
2936   if (this->type_ != NULL && this->type_->is_error())
2937     return;
2938
2939   if (this->seen_)
2940     {
2941       this->report_error(_("constant refers to itself"));
2942       this->type_ = Type::make_error_type();
2943       return;
2944     }
2945
2946   Expression* init = this->constant_->const_value()->expr();
2947   Find_named_object find_named_object(this->constant_);
2948
2949   this->seen_ = true;
2950   Expression::traverse(&init, &find_named_object);
2951   this->seen_ = false;
2952
2953   if (find_named_object.found())
2954     {
2955       if (this->type_ == NULL || !this->type_->is_error())
2956         {
2957           this->report_error(_("constant refers to itself"));
2958           this->type_ = Type::make_error_type();
2959         }
2960       return;
2961     }
2962 }
2963
2964 // Check types of a const reference.
2965
2966 void
2967 Const_expression::do_check_types(Gogo*)
2968 {
2969   if (this->type_ != NULL && this->type_->is_error())
2970     return;
2971
2972   this->check_for_init_loop();
2973
2974   if (this->type_ == NULL || this->type_->is_abstract())
2975     return;
2976
2977   // Check for integer overflow.
2978   if (this->type_->integer_type() != NULL)
2979     {
2980       mpz_t ival;
2981       mpz_init(ival);
2982       Type* dummy;
2983       if (!this->integer_constant_value(true, ival, &dummy))
2984         {
2985           mpfr_t fval;
2986           mpfr_init(fval);
2987           Expression* cexpr = this->constant_->const_value()->expr();
2988           if (cexpr->float_constant_value(fval, &dummy))
2989             {
2990               if (!mpfr_integer_p(fval))
2991                 this->report_error(_("floating point constant "
2992                                      "truncated to integer"));
2993               else
2994                 {
2995                   mpfr_get_z(ival, fval, GMP_RNDN);
2996                   Integer_expression::check_constant(ival, this->type_,
2997                                                      this->location());
2998                 }
2999             }
3000           mpfr_clear(fval);
3001         }
3002       mpz_clear(ival);
3003     }
3004 }
3005
3006 // Return a tree for the const reference.
3007
3008 tree
3009 Const_expression::do_get_tree(Translate_context* context)
3010 {
3011   Gogo* gogo = context->gogo();
3012   tree type_tree;
3013   if (this->type_ == NULL)
3014     type_tree = NULL_TREE;
3015   else
3016     {
3017       type_tree = type_to_tree(this->type_->get_backend(gogo));
3018       if (type_tree == error_mark_node)
3019         return error_mark_node;
3020     }
3021
3022   // If the type has been set for this expression, but the underlying
3023   // object is an abstract int or float, we try to get the abstract
3024   // value.  Otherwise we may lose something in the conversion.
3025   if (this->type_ != NULL
3026       && (this->constant_->const_value()->type() == NULL
3027           || this->constant_->const_value()->type()->is_abstract()))
3028     {
3029       Expression* expr = this->constant_->const_value()->expr();
3030       mpz_t ival;
3031       mpz_init(ival);
3032       Type* t;
3033       if (expr->integer_constant_value(true, ival, &t))
3034         {
3035           tree ret = Expression::integer_constant_tree(ival, type_tree);
3036           mpz_clear(ival);
3037           return ret;
3038         }
3039       mpz_clear(ival);
3040
3041       mpfr_t fval;
3042       mpfr_init(fval);
3043       if (expr->float_constant_value(fval, &t))
3044         {
3045           tree ret = Expression::float_constant_tree(fval, type_tree);
3046           mpfr_clear(fval);
3047           return ret;
3048         }
3049
3050       mpfr_t imag;
3051       mpfr_init(imag);
3052       if (expr->complex_constant_value(fval, imag, &t))
3053         {
3054           tree ret = Expression::complex_constant_tree(fval, imag, type_tree);
3055           mpfr_clear(fval);
3056           mpfr_clear(imag);
3057           return ret;
3058         }
3059       mpfr_clear(imag);
3060       mpfr_clear(fval);
3061     }
3062
3063   tree const_tree = this->constant_->get_tree(gogo, context->function());
3064   if (this->type_ == NULL
3065       || const_tree == error_mark_node
3066       || TREE_TYPE(const_tree) == error_mark_node)
3067     return const_tree;
3068
3069   tree ret;
3070   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
3071     ret = fold_convert(type_tree, const_tree);
3072   else if (TREE_CODE(type_tree) == INTEGER_TYPE)
3073     ret = fold(convert_to_integer(type_tree, const_tree));
3074   else if (TREE_CODE(type_tree) == REAL_TYPE)
3075     ret = fold(convert_to_real(type_tree, const_tree));
3076   else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
3077     ret = fold(convert_to_complex(type_tree, const_tree));
3078   else
3079     go_unreachable();
3080   return ret;
3081 }
3082
3083 // Dump ast representation for constant expression.
3084
3085 void
3086 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3087 {
3088   ast_dump_context->ostream() << this->constant_->name();
3089 }
3090
3091 // Make a reference to a constant in an expression.
3092
3093 Expression*
3094 Expression::make_const_reference(Named_object* constant,
3095                                  Location location)
3096 {
3097   return new Const_expression(constant, location);
3098 }
3099
3100 // Find a named object in an expression.
3101
3102 int
3103 Find_named_object::expression(Expression** pexpr)
3104 {
3105   switch ((*pexpr)->classification())
3106     {
3107     case Expression::EXPRESSION_CONST_REFERENCE:
3108       {
3109         Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3110         if (ce->named_object() == this->no_)
3111           break;
3112
3113         // We need to check a constant initializer explicitly, as
3114         // loops here will not be caught by the loop checking for
3115         // variable initializers.
3116         ce->check_for_init_loop();
3117
3118         return TRAVERSE_CONTINUE;
3119       }
3120
3121     case Expression::EXPRESSION_VAR_REFERENCE:
3122       if ((*pexpr)->var_expression()->named_object() == this->no_)
3123         break;
3124       return TRAVERSE_CONTINUE;
3125     case Expression::EXPRESSION_FUNC_REFERENCE:
3126       if ((*pexpr)->func_expression()->named_object() == this->no_)
3127         break;
3128       return TRAVERSE_CONTINUE;
3129     default:
3130       return TRAVERSE_CONTINUE;
3131     }
3132   this->found_ = true;
3133   return TRAVERSE_EXIT;
3134 }
3135
3136 // The nil value.
3137
3138 class Nil_expression : public Expression
3139 {
3140  public:
3141   Nil_expression(Location location)
3142     : Expression(EXPRESSION_NIL, location)
3143   { }
3144
3145   static Expression*
3146   do_import(Import*);
3147
3148  protected:
3149   bool
3150   do_is_constant() const
3151   { return true; }
3152
3153   Type*
3154   do_type()
3155   { return Type::make_nil_type(); }
3156
3157   void
3158   do_determine_type(const Type_context*)
3159   { }
3160
3161   Expression*
3162   do_copy()
3163   { return this; }
3164
3165   tree
3166   do_get_tree(Translate_context*)
3167   { return null_pointer_node; }
3168
3169   void
3170   do_export(Export* exp) const
3171   { exp->write_c_string("nil"); }
3172
3173   void
3174   do_dump_expression(Ast_dump_context* ast_dump_context) const
3175   { ast_dump_context->ostream() << "nil"; }
3176 };
3177
3178 // Import a nil expression.
3179
3180 Expression*
3181 Nil_expression::do_import(Import* imp)
3182 {
3183   imp->require_c_string("nil");
3184   return Expression::make_nil(imp->location());
3185 }
3186
3187 // Make a nil expression.
3188
3189 Expression*
3190 Expression::make_nil(Location location)
3191 {
3192   return new Nil_expression(location);
3193 }
3194
3195 // The value of the predeclared constant iota.  This is little more
3196 // than a marker.  This will be lowered to an integer in
3197 // Const_expression::do_lower, which is where we know the value that
3198 // it should have.
3199
3200 class Iota_expression : public Parser_expression
3201 {
3202  public:
3203   Iota_expression(Location location)
3204     : Parser_expression(EXPRESSION_IOTA, location)
3205   { }
3206
3207  protected:
3208   Expression*
3209   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3210   { go_unreachable(); }
3211
3212   // There should only ever be one of these.
3213   Expression*
3214   do_copy()
3215   { go_unreachable(); }
3216   
3217   void
3218   do_dump_expression(Ast_dump_context* ast_dump_context) const
3219   { ast_dump_context->ostream() << "iota"; } 
3220 };
3221
3222 // Make an iota expression.  This is only called for one case: the
3223 // value of the predeclared constant iota.
3224
3225 Expression*
3226 Expression::make_iota()
3227 {
3228   static Iota_expression iota_expression(Linemap::unknown_location());
3229   return &iota_expression;
3230 }
3231
3232 // A type conversion expression.
3233
3234 class Type_conversion_expression : public Expression
3235 {
3236  public:
3237   Type_conversion_expression(Type* type, Expression* expr,
3238                              Location location)
3239     : Expression(EXPRESSION_CONVERSION, location),
3240       type_(type), expr_(expr), may_convert_function_types_(false)
3241   { }
3242
3243   // Return the type to which we are converting.
3244   Type*
3245   type() const
3246   { return this->type_; }
3247
3248   // Return the expression which we are converting.
3249   Expression*
3250   expr() const
3251   { return this->expr_; }
3252
3253   // Permit converting from one function type to another.  This is
3254   // used internally for method expressions.
3255   void
3256   set_may_convert_function_types()
3257   {
3258     this->may_convert_function_types_ = true;
3259   }
3260
3261   // Import a type conversion expression.
3262   static Expression*
3263   do_import(Import*);
3264
3265  protected:
3266   int
3267   do_traverse(Traverse* traverse);
3268
3269   Expression*
3270   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3271
3272   bool
3273   do_is_constant() const
3274   { return this->expr_->is_constant(); }
3275
3276   bool
3277   do_integer_constant_value(bool, mpz_t, Type**) const;
3278
3279   bool
3280   do_float_constant_value(mpfr_t, Type**) const;
3281
3282   bool
3283   do_complex_constant_value(mpfr_t, mpfr_t, Type**) const;
3284
3285   bool
3286   do_string_constant_value(std::string*) const;
3287
3288   Type*
3289   do_type()
3290   { return this->type_; }
3291
3292   void
3293   do_determine_type(const Type_context*)
3294   {
3295     Type_context subcontext(this->type_, false);
3296     this->expr_->determine_type(&subcontext);
3297   }
3298
3299   void
3300   do_check_types(Gogo*);
3301
3302   Expression*
3303   do_copy()
3304   {
3305     return new Type_conversion_expression(this->type_, this->expr_->copy(),
3306                                           this->location());
3307   }
3308
3309   tree
3310   do_get_tree(Translate_context* context);
3311
3312   void
3313   do_export(Export*) const;
3314
3315   void
3316   do_dump_expression(Ast_dump_context*) const;
3317
3318  private:
3319   // The type to convert to.
3320   Type* type_;
3321   // The expression to convert.
3322   Expression* expr_;
3323   // True if this is permitted to convert function types.  This is
3324   // used internally for method expressions.
3325   bool may_convert_function_types_;
3326 };
3327
3328 // Traversal.
3329
3330 int
3331 Type_conversion_expression::do_traverse(Traverse* traverse)
3332 {
3333   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3334       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3335     return TRAVERSE_EXIT;
3336   return TRAVERSE_CONTINUE;
3337 }
3338
3339 // Convert to a constant at lowering time.
3340
3341 Expression*
3342 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3343                                      Statement_inserter*, int)
3344 {
3345   Type* type = this->type_;
3346   Expression* val = this->expr_;
3347   Location location = this->location();
3348
3349   if (type->integer_type() != NULL)
3350     {
3351       mpz_t ival;
3352       mpz_init(ival);
3353       Type* dummy;
3354       if (val->integer_constant_value(false, ival, &dummy))
3355         {
3356           if (!Integer_expression::check_constant(ival, type, location))
3357             mpz_set_ui(ival, 0);
3358           Expression* ret = Expression::make_integer(&ival, type, location);
3359           mpz_clear(ival);
3360           return ret;
3361         }
3362
3363       mpfr_t fval;
3364       mpfr_init(fval);
3365       if (val->float_constant_value(fval, &dummy))
3366         {
3367           if (!mpfr_integer_p(fval))
3368             {
3369               error_at(location,
3370                        "floating point constant truncated to integer");
3371               return Expression::make_error(location);
3372             }
3373           mpfr_get_z(ival, fval, GMP_RNDN);
3374           if (!Integer_expression::check_constant(ival, type, location))
3375             mpz_set_ui(ival, 0);
3376           Expression* ret = Expression::make_integer(&ival, type, location);
3377           mpfr_clear(fval);
3378           mpz_clear(ival);
3379           return ret;
3380         }
3381       mpfr_clear(fval);
3382       mpz_clear(ival);
3383     }
3384
3385   if (type->float_type() != NULL)
3386     {
3387       mpfr_t fval;
3388       mpfr_init(fval);
3389       Type* dummy;
3390       if (val->float_constant_value(fval, &dummy))
3391         {
3392           if (!Float_expression::check_constant(fval, type, location))
3393             mpfr_set_ui(fval, 0, GMP_RNDN);
3394           Float_expression::constrain_float(fval, type);
3395           Expression *ret = Expression::make_float(&fval, type, location);
3396           mpfr_clear(fval);
3397           return ret;
3398         }
3399       mpfr_clear(fval);
3400     }
3401
3402   if (type->complex_type() != NULL)
3403     {
3404       mpfr_t real;
3405       mpfr_t imag;
3406       mpfr_init(real);
3407       mpfr_init(imag);
3408       Type* dummy;
3409       if (val->complex_constant_value(real, imag, &dummy))
3410         {
3411           if (!Complex_expression::check_constant(real, imag, type, location))
3412             {
3413               mpfr_set_ui(real, 0, GMP_RNDN);
3414               mpfr_set_ui(imag, 0, GMP_RNDN);
3415             }
3416           Complex_expression::constrain_complex(real, imag, type);
3417           Expression* ret = Expression::make_complex(&real, &imag, type,
3418                                                      location);
3419           mpfr_clear(real);
3420           mpfr_clear(imag);
3421           return ret;
3422         }
3423       mpfr_clear(real);
3424       mpfr_clear(imag);
3425     }
3426
3427   if (type->is_slice_type())
3428     {
3429       Type* element_type = type->array_type()->element_type()->forwarded();
3430       bool is_byte = (element_type->integer_type() != NULL
3431                       && element_type->integer_type()->is_byte());
3432       bool is_rune = (element_type->integer_type() != NULL
3433                       && element_type->integer_type()->is_rune());
3434       if (is_byte || is_rune)
3435         {
3436           std::string s;
3437           if (val->string_constant_value(&s))
3438             {
3439               Expression_list* vals = new Expression_list();
3440               if (is_byte)
3441                 {
3442                   for (std::string::const_iterator p = s.begin();
3443                        p != s.end();
3444                        p++)
3445                     {
3446                       mpz_t val;
3447                       mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3448                       Expression* v = Expression::make_integer(&val,
3449                                                                element_type,
3450                                                                location);
3451                       vals->push_back(v);
3452                       mpz_clear(val);
3453                     }
3454                 }
3455               else
3456                 {
3457                   const char *p = s.data();
3458                   const char *pend = s.data() + s.length();
3459                   while (p < pend)
3460                     {
3461                       unsigned int c;
3462                       int adv = Lex::fetch_char(p, &c);
3463                       if (adv == 0)
3464                         {
3465                           warning_at(this->location(), 0,
3466                                      "invalid UTF-8 encoding");
3467                           adv = 1;
3468                         }
3469                       p += adv;
3470                       mpz_t val;
3471                       mpz_init_set_ui(val, c);
3472                       Expression* v = Expression::make_integer(&val,
3473                                                                element_type,
3474                                                                location);
3475                       vals->push_back(v);
3476                       mpz_clear(val);
3477                     }
3478                 }
3479
3480               return Expression::make_slice_composite_literal(type, vals,
3481                                                               location);
3482             }
3483         }
3484     }
3485
3486   return this;
3487 }
3488
3489 // Return the constant integer value if there is one.
3490
3491 bool
3492 Type_conversion_expression::do_integer_constant_value(bool iota_is_constant,
3493                                                       mpz_t val,
3494                                                       Type** ptype) const
3495 {
3496   if (this->type_->integer_type() == NULL)
3497     return false;
3498
3499   mpz_t ival;
3500   mpz_init(ival);
3501   Type* dummy;
3502   if (this->expr_->integer_constant_value(iota_is_constant, ival, &dummy))
3503     {
3504       if (!Integer_expression::check_constant(ival, this->type_,
3505                                               this->location()))
3506         {
3507           mpz_clear(ival);
3508           return false;
3509         }
3510       mpz_set(val, ival);
3511       mpz_clear(ival);
3512       *ptype = this->type_;
3513       return true;
3514     }
3515   mpz_clear(ival);
3516
3517   mpfr_t fval;
3518   mpfr_init(fval);
3519   if (this->expr_->float_constant_value(fval, &dummy))
3520     {
3521       mpfr_get_z(val, fval, GMP_RNDN);
3522       mpfr_clear(fval);
3523       if (!Integer_expression::check_constant(val, this->type_,
3524                                               this->location()))
3525         return false;
3526       *ptype = this->type_;
3527       return true;
3528     }
3529   mpfr_clear(fval);
3530
3531   return false;
3532 }
3533
3534 // Return the constant floating point value if there is one.
3535
3536 bool
3537 Type_conversion_expression::do_float_constant_value(mpfr_t val,
3538                                                     Type** ptype) const
3539 {
3540   if (this->type_->float_type() == NULL)
3541     return false;
3542
3543   mpfr_t fval;
3544   mpfr_init(fval);
3545   Type* dummy;
3546   if (this->expr_->float_constant_value(fval, &dummy))
3547     {
3548       if (!Float_expression::check_constant(fval, this->type_,
3549                                             this->location()))
3550         {
3551           mpfr_clear(fval);
3552           return false;
3553         }
3554       mpfr_set(val, fval, GMP_RNDN);
3555       mpfr_clear(fval);
3556       Float_expression::constrain_float(val, this->type_);
3557       *ptype = this->type_;
3558       return true;
3559     }
3560   mpfr_clear(fval);
3561
3562   return false;
3563 }
3564
3565 // Return the constant complex value if there is one.
3566
3567 bool
3568 Type_conversion_expression::do_complex_constant_value(mpfr_t real,
3569                                                       mpfr_t imag,
3570                                                       Type **ptype) const
3571 {
3572   if (this->type_->complex_type() == NULL)
3573     return false;
3574
3575   mpfr_t rval;
3576   mpfr_t ival;
3577   mpfr_init(rval);
3578   mpfr_init(ival);
3579   Type* dummy;
3580   if (this->expr_->complex_constant_value(rval, ival, &dummy))
3581     {
3582       if (!Complex_expression::check_constant(rval, ival, this->type_,
3583                                               this->location()))
3584         {
3585           mpfr_clear(rval);
3586           mpfr_clear(ival);
3587           return false;
3588         }
3589       mpfr_set(real, rval, GMP_RNDN);
3590       mpfr_set(imag, ival, GMP_RNDN);
3591       mpfr_clear(rval);
3592       mpfr_clear(ival);
3593       Complex_expression::constrain_complex(real, imag, this->type_);
3594       *ptype = this->type_;
3595       return true;
3596     }
3597   mpfr_clear(rval);
3598   mpfr_clear(ival);
3599
3600   return false;  
3601 }
3602
3603 // Return the constant string value if there is one.
3604
3605 bool
3606 Type_conversion_expression::do_string_constant_value(std::string* val) const
3607 {
3608   if (this->type_->is_string_type()
3609       && this->expr_->type()->integer_type() != NULL)
3610     {
3611       mpz_t ival;
3612       mpz_init(ival);
3613       Type* dummy;
3614       if (this->expr_->integer_constant_value(false, ival, &dummy))
3615         {
3616           unsigned long ulval = mpz_get_ui(ival);
3617           if (mpz_cmp_ui(ival, ulval) == 0)
3618             {
3619               Lex::append_char(ulval, true, val, this->location());
3620               mpz_clear(ival);
3621               return true;
3622             }
3623         }
3624       mpz_clear(ival);
3625     }
3626
3627   // FIXME: Could handle conversion from const []int here.
3628
3629   return false;
3630 }
3631
3632 // Check that types are convertible.
3633
3634 void
3635 Type_conversion_expression::do_check_types(Gogo*)
3636 {
3637   Type* type = this->type_;
3638   Type* expr_type = this->expr_->type();
3639   std::string reason;
3640
3641   if (type->is_error() || expr_type->is_error())
3642     {
3643       this->set_is_error();
3644       return;
3645     }
3646
3647   if (this->may_convert_function_types_
3648       && type->function_type() != NULL
3649       && expr_type->function_type() != NULL)
3650     return;
3651
3652   if (Type::are_convertible(type, expr_type, &reason))
3653     return;
3654
3655   error_at(this->location(), "%s", reason.c_str());
3656   this->set_is_error();
3657 }
3658
3659 // Get a tree for a type conversion.
3660
3661 tree
3662 Type_conversion_expression::do_get_tree(Translate_context* context)
3663 {
3664   Gogo* gogo = context->gogo();
3665   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3666   tree expr_tree = this->expr_->get_tree(context);
3667
3668   if (type_tree == error_mark_node
3669       || expr_tree == error_mark_node
3670       || TREE_TYPE(expr_tree) == error_mark_node)
3671     return error_mark_node;
3672
3673   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3674     return fold_convert(type_tree, expr_tree);
3675
3676   Type* type = this->type_;
3677   Type* expr_type = this->expr_->type();
3678   tree ret;
3679   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3680     ret = Expression::convert_for_assignment(context, type, expr_type,
3681                                              expr_tree, this->location());
3682   else if (type->integer_type() != NULL)
3683     {
3684       if (expr_type->integer_type() != NULL
3685           || expr_type->float_type() != NULL
3686           || expr_type->is_unsafe_pointer_type())
3687         ret = fold(convert_to_integer(type_tree, expr_tree));
3688       else
3689         go_unreachable();
3690     }
3691   else if (type->float_type() != NULL)
3692     {
3693       if (expr_type->integer_type() != NULL
3694           || expr_type->float_type() != NULL)
3695         ret = fold(convert_to_real(type_tree, expr_tree));
3696       else
3697         go_unreachable();
3698     }
3699   else if (type->complex_type() != NULL)
3700     {
3701       if (expr_type->complex_type() != NULL)
3702         ret = fold(convert_to_complex(type_tree, expr_tree));
3703       else
3704         go_unreachable();
3705     }
3706   else if (type->is_string_type()
3707            && expr_type->integer_type() != NULL)
3708     {
3709       expr_tree = fold_convert(integer_type_node, expr_tree);
3710       if (host_integerp(expr_tree, 0))
3711         {
3712           HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3713           std::string s;
3714           Lex::append_char(intval, true, &s, this->location());
3715           Expression* se = Expression::make_string(s, this->location());
3716           return se->get_tree(context);
3717         }
3718
3719       static tree int_to_string_fndecl;
3720       ret = Gogo::call_builtin(&int_to_string_fndecl,
3721                                this->location(),
3722                                "__go_int_to_string",
3723                                1,
3724                                type_tree,
3725                                integer_type_node,
3726                                fold_convert(integer_type_node, expr_tree));
3727     }
3728   else if (type->is_string_type() && expr_type->is_slice_type())
3729     {
3730       if (!DECL_P(expr_tree))
3731         expr_tree = save_expr(expr_tree);
3732       Array_type* a = expr_type->array_type();
3733       Type* e = a->element_type()->forwarded();
3734       go_assert(e->integer_type() != NULL);
3735       tree valptr = fold_convert(const_ptr_type_node,
3736                                  a->value_pointer_tree(gogo, expr_tree));
3737       tree len = a->length_tree(gogo, expr_tree);
3738       len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3739                              len);
3740       if (e->integer_type()->is_byte())
3741         {
3742           static tree byte_array_to_string_fndecl;
3743           ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3744                                    this->location(),
3745                                    "__go_byte_array_to_string",
3746                                    2,
3747                                    type_tree,
3748                                    const_ptr_type_node,
3749                                    valptr,
3750                                    integer_type_node,
3751                                    len);
3752         }
3753       else
3754         {
3755           go_assert(e->integer_type()->is_rune());
3756           static tree int_array_to_string_fndecl;
3757           ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3758                                    this->location(),
3759                                    "__go_int_array_to_string",
3760                                    2,
3761                                    type_tree,
3762                                    const_ptr_type_node,
3763                                    valptr,
3764                                    integer_type_node,
3765                                    len);
3766         }
3767     }
3768   else if (type->is_slice_type() && expr_type->is_string_type())
3769     {
3770       Type* e = type->array_type()->element_type()->forwarded();
3771       go_assert(e->integer_type() != NULL);
3772       if (e->integer_type()->is_byte())
3773         {
3774           tree string_to_byte_array_fndecl = NULL_TREE;
3775           ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3776                                    this->location(),
3777                                    "__go_string_to_byte_array",
3778                                    1,
3779                                    type_tree,
3780                                    TREE_TYPE(expr_tree),
3781                                    expr_tree);
3782         }
3783       else
3784         {
3785           go_assert(e->integer_type()->is_rune());
3786           tree string_to_int_array_fndecl = NULL_TREE;
3787           ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3788                                    this->location(),
3789                                    "__go_string_to_int_array",
3790                                    1,
3791                                    type_tree,
3792                                    TREE_TYPE(expr_tree),
3793                                    expr_tree);
3794         }
3795     }
3796   else if ((type->is_unsafe_pointer_type()
3797             && expr_type->points_to() != NULL)
3798            || (expr_type->is_unsafe_pointer_type()
3799                && type->points_to() != NULL))
3800     ret = fold_convert(type_tree, expr_tree);
3801   else if (type->is_unsafe_pointer_type()
3802            && expr_type->integer_type() != NULL)
3803     ret = convert_to_pointer(type_tree, expr_tree);
3804   else if (this->may_convert_function_types_
3805            && type->function_type() != NULL
3806            && expr_type->function_type() != NULL)
3807     ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3808                            expr_tree);
3809   else
3810     ret = Expression::convert_for_assignment(context, type, expr_type,
3811                                              expr_tree, this->location());
3812
3813   return ret;
3814 }
3815
3816 // Output a type conversion in a constant expression.
3817
3818 void
3819 Type_conversion_expression::do_export(Export* exp) const
3820 {
3821   exp->write_c_string("convert(");
3822   exp->write_type(this->type_);
3823   exp->write_c_string(", ");
3824   this->expr_->export_expression(exp);
3825   exp->write_c_string(")");
3826 }
3827
3828 // Import a type conversion or a struct construction.
3829
3830 Expression*
3831 Type_conversion_expression::do_import(Import* imp)
3832 {
3833   imp->require_c_string("convert(");
3834   Type* type = imp->read_type();
3835   imp->require_c_string(", ");
3836   Expression* val = Expression::import_expression(imp);
3837   imp->require_c_string(")");
3838   return Expression::make_cast(type, val, imp->location());
3839 }
3840
3841 // Dump ast representation for a type conversion expression.
3842
3843 void
3844 Type_conversion_expression::do_dump_expression(
3845     Ast_dump_context* ast_dump_context) const
3846 {
3847   ast_dump_context->dump_type(this->type_);
3848   ast_dump_context->ostream() << "(";
3849   ast_dump_context->dump_expression(this->expr_);
3850   ast_dump_context->ostream() << ") ";
3851 }
3852
3853 // Make a type cast expression.
3854
3855 Expression*
3856 Expression::make_cast(Type* type, Expression* val, Location location)
3857 {
3858   if (type->is_error_type() || val->is_error_expression())
3859     return Expression::make_error(location);
3860   return new Type_conversion_expression(type, val, location);
3861 }
3862
3863 // An unsafe type conversion, used to pass values to builtin functions.
3864
3865 class Unsafe_type_conversion_expression : public Expression
3866 {
3867  public:
3868   Unsafe_type_conversion_expression(Type* type, Expression* expr,
3869                                     Location location)
3870     : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3871       type_(type), expr_(expr)
3872   { }
3873
3874  protected:
3875   int
3876   do_traverse(Traverse* traverse);
3877
3878   Type*
3879   do_type()
3880   { return this->type_; }
3881
3882   void
3883   do_determine_type(const Type_context*)
3884   { this->expr_->determine_type_no_context(); }
3885
3886   Expression*
3887   do_copy()
3888   {
3889     return new Unsafe_type_conversion_expression(this->type_,
3890                                                  this->expr_->copy(),
3891                                                  this->location());
3892   }
3893
3894   tree
3895   do_get_tree(Translate_context*);
3896
3897   void
3898   do_dump_expression(Ast_dump_context*) const;
3899
3900  private:
3901   // The type to convert to.
3902   Type* type_;
3903   // The expression to convert.
3904   Expression* expr_;
3905 };
3906
3907 // Traversal.
3908
3909 int
3910 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3911 {
3912   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3913       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3914     return TRAVERSE_EXIT;
3915   return TRAVERSE_CONTINUE;
3916 }
3917
3918 // Convert to backend representation.
3919
3920 tree
3921 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3922 {
3923   // We are only called for a limited number of cases.
3924
3925   Type* t = this->type_;
3926   Type* et = this->expr_->type();
3927
3928   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3929   tree expr_tree = this->expr_->get_tree(context);
3930   if (type_tree == error_mark_node || expr_tree == error_mark_node)
3931     return error_mark_node;
3932
3933   Location loc = this->location();
3934
3935   bool use_view_convert = false;
3936   if (t->is_slice_type())
3937     {
3938       go_assert(et->is_slice_type());
3939       use_view_convert = true;
3940     }
3941   else if (t->map_type() != NULL)
3942     go_assert(et->map_type() != NULL);
3943   else if (t->channel_type() != NULL)
3944     go_assert(et->channel_type() != NULL);
3945   else if (t->points_to() != NULL)
3946     go_assert(et->points_to() != NULL || et->is_nil_type());
3947   else if (et->is_unsafe_pointer_type())
3948     go_assert(t->points_to() != NULL);
3949   else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3950     {
3951       go_assert(et->interface_type() != NULL
3952                  && !et->interface_type()->is_empty());
3953       use_view_convert = true;
3954     }
3955   else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3956     {
3957       go_assert(et->interface_type() != NULL
3958                  && et->interface_type()->is_empty());
3959       use_view_convert = true;
3960     }
3961   else if (t->integer_type() != NULL)
3962     {
3963       go_assert(et->is_boolean_type()
3964                  || et->integer_type() != NULL
3965                  || et->function_type() != NULL
3966                  || et->points_to() != NULL
3967                  || et->map_type() != NULL
3968                  || et->channel_type() != NULL);
3969       return convert_to_integer(type_tree, expr_tree);
3970     }
3971   else
3972     go_unreachable();
3973
3974   if (use_view_convert)
3975     return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3976                            expr_tree);
3977   else
3978     return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3979 }
3980
3981 // Dump ast representation for an unsafe type conversion expression.
3982
3983 void
3984 Unsafe_type_conversion_expression::do_dump_expression(
3985     Ast_dump_context* ast_dump_context) const
3986 {
3987   ast_dump_context->dump_type(this->type_);
3988   ast_dump_context->ostream() << "(";
3989   ast_dump_context->dump_expression(this->expr_);
3990   ast_dump_context->ostream() << ") ";
3991 }
3992
3993 // Make an unsafe type conversion expression.
3994
3995 Expression*
3996 Expression::make_unsafe_cast(Type* type, Expression* expr,
3997                              Location location)
3998 {
3999   return new Unsafe_type_conversion_expression(type, expr, location);
4000 }
4001
4002 // Unary expressions.
4003
4004 class Unary_expression : public Expression
4005 {
4006  public:
4007   Unary_expression(Operator op, Expression* expr, Location location)
4008     : Expression(EXPRESSION_UNARY, location),
4009       op_(op), escapes_(true), create_temp_(false), expr_(expr)
4010   { }
4011
4012   // Return the operator.
4013   Operator
4014   op() const
4015   { return this->op_; }
4016
4017   // Return the operand.
4018   Expression*
4019   operand() const
4020   { return this->expr_; }
4021
4022   // Record that an address expression does not escape.
4023   void
4024   set_does_not_escape()
4025   {
4026     go_assert(this->op_ == OPERATOR_AND);
4027     this->escapes_ = false;
4028   }
4029
4030   // Record that this is an address expression which should create a
4031   // temporary variable if necessary.  This is used for method calls.
4032   void
4033   set_create_temp()
4034   {
4035     go_assert(this->op_ == OPERATOR_AND);
4036     this->create_temp_ = true;
4037   }
4038
4039   // Apply unary opcode OP to UVAL, setting VAL.  Return true if this
4040   // could be done, false if not.
4041   static bool
4042   eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val,
4043                Location);
4044
4045   // Apply unary opcode OP to UVAL, setting VAL.  Return true if this
4046   // could be done, false if not.
4047   static bool
4048   eval_float(Operator op, mpfr_t uval, mpfr_t val);
4049
4050   // Apply unary opcode OP to UREAL/UIMAG, setting REAL/IMAG.  Return
4051   // true if this could be done, false if not.
4052   static bool
4053   eval_complex(Operator op, mpfr_t ureal, mpfr_t uimag, mpfr_t real,
4054                mpfr_t imag);
4055
4056   static Expression*
4057   do_import(Import*);
4058
4059  protected:
4060   int
4061   do_traverse(Traverse* traverse)
4062   { return Expression::traverse(&this->expr_, traverse); }
4063
4064   Expression*
4065   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
4066
4067   bool
4068   do_is_constant() const;
4069
4070   bool
4071   do_integer_constant_value(bool, mpz_t, Type**) const;
4072
4073   bool
4074   do_float_constant_value(mpfr_t, Type**) const;
4075
4076   bool
4077   do_complex_constant_value(mpfr_t, mpfr_t, Type**) const;
4078
4079   Type*
4080   do_type();
4081
4082   void
4083   do_determine_type(const Type_context*);
4084
4085   void
4086   do_check_types(Gogo*);
4087
4088   Expression*
4089   do_copy()
4090   {
4091     return Expression::make_unary(this->op_, this->expr_->copy(),
4092                                   this->location());
4093   }
4094
4095   bool
4096   do_must_eval_subexpressions_in_order(int*) const
4097   { return this->op_ == OPERATOR_MULT; }
4098
4099   bool
4100   do_is_addressable() const
4101   { return this->op_ == OPERATOR_MULT; }
4102
4103   tree
4104   do_get_tree(Translate_context*);
4105
4106   void
4107   do_export(Export*) const;
4108
4109   void
4110   do_dump_expression(Ast_dump_context*) const;
4111
4112  private:
4113   // The unary operator to apply.
4114   Operator op_;
4115   // Normally true.  False if this is an address expression which does
4116   // not escape the current function.
4117   bool escapes_;
4118   // True if this is an address expression which should create a
4119   // temporary variable if necessary.
4120   bool create_temp_;
4121   // The operand.
4122   Expression* expr_;
4123 };
4124
4125 // If we are taking the address of a composite literal, and the
4126 // contents are not constant, then we want to make a heap composite
4127 // instead.
4128
4129 Expression*
4130 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4131 {
4132   Location loc = this->location();
4133   Operator op = this->op_;
4134   Expression* expr = this->expr_;
4135
4136   if (op == OPERATOR_MULT && expr->is_type_expression())
4137     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4138
4139   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
4140   // moving x to the heap.  FIXME: Is it worth doing a real escape
4141   // analysis here?  This case is found in math/unsafe.go and is
4142   // therefore worth special casing.
4143   if (op == OPERATOR_MULT)
4144     {
4145       Expression* e = expr;
4146       while (e->classification() == EXPRESSION_CONVERSION)
4147         {
4148           Type_conversion_expression* te
4149             = static_cast<Type_conversion_expression*>(e);
4150           e = te->expr();
4151         }
4152
4153       if (e->classification() == EXPRESSION_UNARY)
4154         {
4155           Unary_expression* ue = static_cast<Unary_expression*>(e);
4156           if (ue->op_ == OPERATOR_AND)
4157             {
4158               if (e == expr)
4159                 {
4160                   // *&x == x.
4161                   return ue->expr_;
4162                 }
4163               ue->set_does_not_escape();
4164             }
4165         }
4166     }
4167
4168   // Catching an invalid indirection of unsafe.Pointer here avoid
4169   // having to deal with TYPE_VOID in other places.
4170   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4171     {
4172       error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4173       return Expression::make_error(this->location());
4174     }
4175
4176   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS
4177       || op == OPERATOR_NOT || op == OPERATOR_XOR)
4178     {
4179       Expression* ret = NULL;
4180
4181       mpz_t eval;
4182       mpz_init(eval);
4183       Type* etype;
4184       if (expr->integer_constant_value(false, eval, &etype))
4185         {
4186           mpz_t val;
4187           mpz_init(val);
4188           if (Unary_expression::eval_integer(op, etype, eval, val, loc))
4189             ret = Expression::make_integer(&val, etype, loc);
4190           mpz_clear(val);
4191         }
4192       mpz_clear(eval);
4193       if (ret != NULL)
4194         return ret;
4195
4196       if (op == OPERATOR_PLUS || op == OPERATOR_MINUS)
4197         {
4198           mpfr_t fval;
4199           mpfr_init(fval);
4200           Type* ftype;
4201           if (expr->float_constant_value(fval, &ftype))
4202             {
4203               mpfr_t val;
4204               mpfr_init(val);
4205               if (Unary_expression::eval_float(op, fval, val))
4206                 ret = Expression::make_float(&val, ftype, loc);
4207               mpfr_clear(val);
4208             }
4209           if (ret != NULL)
4210             {
4211               mpfr_clear(fval);
4212               return ret;
4213             }
4214
4215           mpfr_t ival;
4216           mpfr_init(ival);
4217           if (expr->complex_constant_value(fval, ival, &ftype))
4218             {
4219               mpfr_t real;
4220               mpfr_t imag;
4221               mpfr_init(real);
4222               mpfr_init(imag);
4223               if (Unary_expression::eval_complex(op, fval, ival, real, imag))
4224                 ret = Expression::make_complex(&real, &imag, ftype, loc);
4225               mpfr_clear(real);
4226               mpfr_clear(imag);
4227             }
4228           mpfr_clear(ival);
4229           mpfr_clear(fval);
4230           if (ret != NULL)
4231             return ret;
4232         }
4233     }
4234
4235   return this;
4236 }
4237
4238 // Return whether a unary expression is a constant.
4239
4240 bool
4241 Unary_expression::do_is_constant() const
4242 {
4243   if (this->op_ == OPERATOR_MULT)
4244     {
4245       // Indirecting through a pointer is only constant if the object
4246       // to which the expression points is constant, but we currently
4247       // have no way to determine that.
4248       return false;
4249     }
4250   else if (this->op_ == OPERATOR_AND)
4251     {
4252       // Taking the address of a variable is constant if it is a
4253       // global variable, not constant otherwise.  In other cases
4254       // taking the address is probably not a constant.
4255       Var_expression* ve = this->expr_->var_expression();
4256       if (ve != NULL)
4257         {
4258           Named_object* no = ve->named_object();
4259           return no->is_variable() && no->var_value()->is_global();
4260         }
4261       return false;
4262     }
4263   else
4264     return this->expr_->is_constant();
4265 }
4266
4267 // Apply unary opcode OP to UVAL, setting VAL.  UTYPE is the type of
4268 // UVAL, if known; it may be NULL.  Return true if this could be done,
4269 // false if not.
4270
4271 bool
4272 Unary_expression::eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val,
4273                                Location location)
4274 {
4275   switch (op)
4276     {
4277     case OPERATOR_PLUS:
4278       mpz_set(val, uval);
4279       return true;
4280     case OPERATOR_MINUS:
4281       mpz_neg(val, uval);
4282       return Integer_expression::check_constant(val, utype, location);
4283     case OPERATOR_NOT:
4284       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4285       return true;
4286     case OPERATOR_XOR:
4287       if (utype == NULL
4288           || utype->integer_type() == NULL
4289           || utype->integer_type()->is_abstract())
4290         mpz_com(val, uval);
4291       else
4292         {
4293           // The number of HOST_WIDE_INTs that it takes to represent
4294           // UVAL.
4295           size_t count = ((mpz_sizeinbase(uval, 2)
4296                            + HOST_BITS_PER_WIDE_INT
4297                            - 1)
4298                           / HOST_BITS_PER_WIDE_INT);
4299
4300           unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4301           memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4302
4303           size_t obits = utype->integer_type()->bits();
4304
4305           if (!utype->integer_type()->is_unsigned()
4306               && mpz_sgn(uval) < 0)
4307             {
4308               mpz_t adj;
4309               mpz_init_set_ui(adj, 1);
4310               mpz_mul_2exp(adj, adj, obits);
4311               mpz_add(uval, uval, adj);
4312               mpz_clear(adj);
4313             }
4314
4315           size_t ecount;
4316           mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4317           go_assert(ecount <= count);
4318
4319           // Trim down to the number of words required by the type.
4320           size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4321                            / HOST_BITS_PER_WIDE_INT);
4322           go_assert(ocount <= count);
4323
4324           for (size_t i = 0; i < ocount; ++i)
4325             phwi[i] = ~phwi[i];
4326
4327           size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4328           if (clearbits != 0)
4329             phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4330                                  >> clearbits);
4331
4332           mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4333
4334           if (!utype->integer_type()->is_unsigned()
4335               && mpz_tstbit(val, obits - 1))
4336             {
4337               mpz_t adj;
4338               mpz_init_set_ui(adj, 1);
4339               mpz_mul_2exp(adj, adj, obits);
4340               mpz_sub(val, val, adj);
4341               mpz_clear(adj);
4342             }
4343
4344           delete[] phwi;
4345         }
4346       return Integer_expression::check_constant(val, utype, location);
4347     case OPERATOR_AND:
4348     case OPERATOR_MULT:
4349       return false;
4350     default:
4351       go_unreachable();
4352     }
4353 }
4354
4355 // Apply unary opcode OP to UVAL, setting VAL.  Return true if this
4356 // could be done, false if not.
4357
4358 bool
4359 Unary_expression::eval_float(Operator op, mpfr_t uval, mpfr_t val)
4360 {
4361   switch (op)
4362     {
4363     case OPERATOR_PLUS:
4364       mpfr_set(val, uval, GMP_RNDN);
4365       return true;
4366     case OPERATOR_MINUS:
4367       mpfr_neg(val, uval, GMP_RNDN);
4368       return true;
4369     case OPERATOR_NOT:
4370     case OPERATOR_XOR:
4371     case OPERATOR_AND:
4372     case OPERATOR_MULT:
4373       return false;
4374     default:
4375       go_unreachable();
4376     }
4377 }
4378
4379 // Apply unary opcode OP to RVAL/IVAL, setting REAL/IMAG.  Return true
4380 // if this could be done, false if not.
4381
4382 bool
4383 Unary_expression::eval_complex(Operator op, mpfr_t rval, mpfr_t ival,
4384                                mpfr_t real, mpfr_t imag)
4385 {
4386   switch (op)
4387     {
4388     case OPERATOR_PLUS:
4389       mpfr_set(real, rval, GMP_RNDN);
4390       mpfr_set(imag, ival, GMP_RNDN);
4391       return true;
4392     case OPERATOR_MINUS:
4393       mpfr_neg(real, rval, GMP_RNDN);
4394       mpfr_neg(imag, ival, GMP_RNDN);
4395       return true;
4396     case OPERATOR_NOT:
4397     case OPERATOR_XOR:
4398     case OPERATOR_AND:
4399     case OPERATOR_MULT:
4400       return false;
4401     default:
4402       go_unreachable();
4403     }
4404 }
4405
4406 // Return the integral constant value of a unary expression, if it has one.
4407
4408 bool
4409 Unary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val,
4410                                             Type** ptype) const
4411 {
4412   mpz_t uval;
4413   mpz_init(uval);
4414   bool ret;
4415   if (!this->expr_->integer_constant_value(iota_is_constant, uval, ptype))
4416     ret = false;
4417   else
4418     ret = Unary_expression::eval_integer(this->op_, *ptype, uval, val,
4419                                          this->location());
4420   mpz_clear(uval);
4421   return ret;
4422 }
4423
4424 // Return the floating point constant value of a unary expression, if
4425 // it has one.
4426
4427 bool
4428 Unary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
4429 {
4430   mpfr_t uval;
4431   mpfr_init(uval);
4432   bool ret;
4433   if (!this->expr_->float_constant_value(uval, ptype))
4434     ret = false;
4435   else
4436     ret = Unary_expression::eval_float(this->op_, uval, val);
4437   mpfr_clear(uval);
4438   return ret;
4439 }
4440
4441 // Return the complex constant value of a unary expression, if it has
4442 // one.
4443
4444 bool
4445 Unary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
4446                                             Type** ptype) const
4447 {
4448   mpfr_t rval;
4449   mpfr_t ival;
4450   mpfr_init(rval);
4451   mpfr_init(ival);
4452   bool ret;
4453   if (!this->expr_->complex_constant_value(rval, ival, ptype))
4454     ret = false;
4455   else
4456     ret = Unary_expression::eval_complex(this->op_, rval, ival, real, imag);
4457   mpfr_clear(rval);
4458   mpfr_clear(ival);
4459   return ret;
4460 }
4461
4462 // Return the type of a unary expression.
4463
4464 Type*
4465 Unary_expression::do_type()
4466 {
4467   switch (this->op_)
4468     {
4469     case OPERATOR_PLUS:
4470     case OPERATOR_MINUS:
4471     case OPERATOR_NOT:
4472     case OPERATOR_XOR:
4473       return this->expr_->type();
4474
4475     case OPERATOR_AND:
4476       return Type::make_pointer_type(this->expr_->type());
4477
4478     case OPERATOR_MULT:
4479       {
4480         Type* subtype = this->expr_->type();
4481         Type* points_to = subtype->points_to();
4482         if (points_to == NULL)
4483           return Type::make_error_type();
4484         return points_to;
4485       }
4486
4487     default:
4488       go_unreachable();
4489     }
4490 }
4491
4492 // Determine abstract types for a unary expression.
4493
4494 void
4495 Unary_expression::do_determine_type(const Type_context* context)
4496 {
4497   switch (this->op_)
4498     {
4499     case OPERATOR_PLUS:
4500     case OPERATOR_MINUS:
4501     case OPERATOR_NOT:
4502     case OPERATOR_XOR:
4503       this->expr_->determine_type(context);
4504       break;
4505
4506     case OPERATOR_AND:
4507       // Taking the address of something.
4508       {
4509         Type* subtype = (context->type == NULL
4510                          ? NULL
4511                          : context->type->points_to());
4512         Type_context subcontext(subtype, false);
4513         this->expr_->determine_type(&subcontext);
4514       }
4515       break;
4516
4517     case OPERATOR_MULT:
4518       // Indirecting through a pointer.
4519       {
4520         Type* subtype = (context->type == NULL
4521                          ? NULL
4522                          : Type::make_pointer_type(context->type));
4523         Type_context subcontext(subtype, false);
4524         this->expr_->determine_type(&subcontext);
4525       }
4526       break;
4527
4528     default:
4529       go_unreachable();
4530     }
4531 }
4532
4533 // Check types for a unary expression.
4534
4535 void
4536 Unary_expression::do_check_types(Gogo*)
4537 {
4538   Type* type = this->expr_->type();
4539   if (type->is_error())
4540     {
4541       this->set_is_error();
4542       return;
4543     }
4544
4545   switch (this->op_)
4546     {
4547     case OPERATOR_PLUS:
4548     case OPERATOR_MINUS:
4549       if (type->integer_type() == NULL
4550           && type->float_type() == NULL
4551           && type->complex_type() == NULL)
4552         this->report_error(_("expected numeric type"));
4553       break;
4554
4555     case OPERATOR_NOT:
4556     case OPERATOR_XOR:
4557       if (type->integer_type() == NULL
4558           && !type->is_boolean_type())
4559         this->report_error(_("expected integer or boolean type"));
4560       break;
4561
4562     case OPERATOR_AND:
4563       if (!this->expr_->is_addressable())
4564         {
4565           if (!this->create_temp_)
4566             this->report_error(_("invalid operand for unary %<&%>"));
4567         }
4568       else
4569         this->expr_->address_taken(this->escapes_);
4570       break;
4571
4572     case OPERATOR_MULT:
4573       // Indirecting through a pointer.
4574       if (type->points_to() == NULL)
4575         this->report_error(_("expected pointer"));
4576       break;
4577
4578     default:
4579       go_unreachable();
4580     }
4581 }
4582
4583 // Get a tree for a unary expression.
4584
4585 tree
4586 Unary_expression::do_get_tree(Translate_context* context)
4587 {
4588   Location loc = this->location();
4589
4590   // Taking the address of a set-and-use-temporary expression requires
4591   // setting the temporary and then taking the address.
4592   if (this->op_ == OPERATOR_AND)
4593     {
4594       Set_and_use_temporary_expression* sut =
4595         this->expr_->set_and_use_temporary_expression();
4596       if (sut != NULL)
4597         {
4598           Temporary_statement* temp = sut->temporary();
4599           Bvariable* bvar = temp->get_backend_variable(context);
4600           tree var_tree = var_to_tree(bvar);
4601           Expression* val = sut->expression();
4602           tree val_tree = val->get_tree(context);
4603           if (var_tree == error_mark_node || val_tree == error_mark_node)
4604             return error_mark_node;
4605           tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
4606                                                     var_tree);
4607           return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4608                             TREE_TYPE(addr_tree),
4609                             build2_loc(sut->location().gcc_location(),
4610                                        MODIFY_EXPR, void_type_node,
4611                                        var_tree, val_tree),
4612                             addr_tree);
4613         }
4614     }
4615
4616   tree expr = this->expr_->get_tree(context);
4617   if (expr == error_mark_node)
4618     return error_mark_node;
4619
4620   switch (this->op_)
4621     {
4622     case OPERATOR_PLUS:
4623       return expr;
4624
4625     case OPERATOR_MINUS:
4626       {
4627         tree type = TREE_TYPE(expr);
4628         tree compute_type = excess_precision_type(type);
4629         if (compute_type != NULL_TREE)
4630           expr = ::convert(compute_type, expr);
4631         tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
4632                                    (compute_type != NULL_TREE
4633                                     ? compute_type
4634                                     : type),
4635                                    expr);
4636         if (compute_type != NULL_TREE)
4637           ret = ::convert(type, ret);
4638         return ret;
4639       }
4640
4641     case OPERATOR_NOT:
4642       if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
4643         return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4644                                TREE_TYPE(expr), expr);
4645       else
4646         return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4647                                expr, build_int_cst(TREE_TYPE(expr), 0));
4648
4649     case OPERATOR_XOR:
4650       return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4651                              expr);
4652
4653     case OPERATOR_AND:
4654       if (!this->create_temp_)
4655         {
4656           // We should not see a non-constant constructor here; cases
4657           // where we would see one should have been moved onto the
4658           // heap at parse time.  Taking the address of a nonconstant
4659           // constructor will not do what the programmer expects.
4660           go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4661           go_assert(TREE_CODE(expr) != ADDR_EXPR);
4662         }
4663
4664       // Build a decl for a constant constructor.
4665       if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4666         {
4667           tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4668                                  create_tmp_var_name("C"), TREE_TYPE(expr));
4669           DECL_EXTERNAL(decl) = 0;
4670           TREE_PUBLIC(decl) = 0;
4671           TREE_READONLY(decl) = 1;
4672           TREE_CONSTANT(decl) = 1;
4673           TREE_STATIC(decl) = 1;
4674           TREE_ADDRESSABLE(decl) = 1;
4675           DECL_ARTIFICIAL(decl) = 1;
4676           DECL_INITIAL(decl) = expr;
4677           rest_of_decl_compilation(decl, 1, 0);
4678           expr = decl;
4679         }
4680
4681       if (this->create_temp_
4682           && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4683           && !DECL_P(expr)
4684           && TREE_CODE(expr) != INDIRECT_REF
4685           && TREE_CODE(expr) != COMPONENT_REF)
4686         {
4687           tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4688           DECL_IGNORED_P(tmp) = 1;
4689           DECL_INITIAL(tmp) = expr;
4690           TREE_ADDRESSABLE(tmp) = 1;
4691           return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4692                             build_pointer_type(TREE_TYPE(expr)),
4693                             build1_loc(loc.gcc_location(), DECL_EXPR,
4694                                        void_type_node, tmp),
4695                             build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4696         }
4697
4698       return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4699
4700     case OPERATOR_MULT:
4701       {
4702         go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4703
4704         // If we are dereferencing the pointer to a large struct, we
4705         // need to check for nil.  We don't bother to check for small
4706         // structs because we expect the system to crash on a nil
4707         // pointer dereference.
4708         tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4709         if (!VOID_TYPE_P(target_type_tree))
4710           {
4711             HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4712             if (s == -1 || s >= 4096)
4713               {
4714                 if (!DECL_P(expr))
4715                   expr = save_expr(expr);
4716                 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4717                                                boolean_type_node,
4718                                                expr,
4719                                                fold_convert(TREE_TYPE(expr),
4720                                                             null_pointer_node));
4721                 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4722                                                  loc);
4723                 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4724                                        TREE_TYPE(expr), build3(COND_EXPR,
4725                                                                void_type_node,
4726                                                                compare, crash,
4727                                                                NULL_TREE),
4728                                        expr);
4729               }
4730           }
4731
4732         // If the type of EXPR is a recursive pointer type, then we
4733         // need to insert a cast before indirecting.
4734         if (VOID_TYPE_P(target_type_tree))
4735           {
4736             Type* pt = this->expr_->type()->points_to();
4737             tree ind = type_to_tree(pt->get_backend(context->gogo()));
4738             expr = fold_convert_loc(loc.gcc_location(),
4739                                     build_pointer_type(ind), expr);
4740           }
4741
4742         return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4743       }
4744
4745     default:
4746       go_unreachable();
4747     }
4748 }
4749
4750 // Export a unary expression.
4751
4752 void
4753 Unary_expression::do_export(Export* exp) const
4754 {
4755   switch (this->op_)
4756     {
4757     case OPERATOR_PLUS:
4758       exp->write_c_string("+ ");
4759       break;
4760     case OPERATOR_MINUS:
4761       exp->write_c_string("- ");
4762       break;
4763     case OPERATOR_NOT:
4764       exp->write_c_string("! ");
4765       break;
4766     case OPERATOR_XOR:
4767       exp->write_c_string("^ ");
4768       break;
4769     case OPERATOR_AND:
4770     case OPERATOR_MULT:
4771     default:
4772       go_unreachable();
4773     }
4774   this->expr_->export_expression(exp);
4775 }
4776
4777 // Import a unary expression.
4778
4779 Expression*
4780 Unary_expression::do_import(Import* imp)
4781 {
4782   Operator op;
4783   switch (imp->get_char())
4784     {
4785     case '+':
4786       op = OPERATOR_PLUS;
4787       break;
4788     case '-':
4789       op = OPERATOR_MINUS;
4790       break;
4791     case '!':
4792       op = OPERATOR_NOT;
4793       break;
4794     case '^':
4795       op = OPERATOR_XOR;
4796       break;
4797     default:
4798       go_unreachable();
4799     }
4800   imp->require_c_string(" ");
4801   Expression* expr = Expression::import_expression(imp);
4802   return Expression::make_unary(op, expr, imp->location());
4803 }
4804
4805 // Dump ast representation of an unary expression.
4806
4807 void
4808 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4809 {
4810   ast_dump_context->dump_operator(this->op_);
4811   ast_dump_context->ostream() << "(";
4812   ast_dump_context->dump_expression(this->expr_);
4813   ast_dump_context->ostream() << ") ";
4814 }
4815
4816 // Make a unary expression.
4817
4818 Expression*
4819 Expression::make_unary(Operator op, Expression* expr, Location location)
4820 {
4821   return new Unary_expression(op, expr, location);
4822 }
4823
4824 // If this is an indirection through a pointer, return the expression
4825 // being pointed through.  Otherwise return this.
4826
4827 Expression*
4828 Expression::deref()
4829 {
4830   if (this->classification_ == EXPRESSION_UNARY)
4831     {
4832       Unary_expression* ue = static_cast<Unary_expression*>(this);
4833       if (ue->op() == OPERATOR_MULT)
4834         return ue->operand();
4835     }
4836   return this;
4837 }
4838
4839 // Class Binary_expression.
4840
4841 // Traversal.
4842
4843 int
4844 Binary_expression::do_traverse(Traverse* traverse)
4845 {
4846   int t = Expression::traverse(&this->left_, traverse);
4847   if (t == TRAVERSE_EXIT)
4848     return TRAVERSE_EXIT;
4849   return Expression::traverse(&this->right_, traverse);
4850 }
4851
4852 // Compare integer constants according to OP.
4853
4854 bool
4855 Binary_expression::compare_integer(Operator op, mpz_t left_val,
4856                                    mpz_t right_val)
4857 {
4858   int i = mpz_cmp(left_val, right_val);
4859   switch (op)
4860     {
4861     case OPERATOR_EQEQ:
4862       return i == 0;
4863     case OPERATOR_NOTEQ:
4864       return i != 0;
4865     case OPERATOR_LT:
4866       return i < 0;
4867     case OPERATOR_LE:
4868       return i <= 0;
4869     case OPERATOR_GT:
4870       return i > 0;
4871     case OPERATOR_GE:
4872       return i >= 0;
4873     default:
4874       go_unreachable();
4875     }
4876 }
4877
4878 // Compare floating point constants according to OP.
4879
4880 bool
4881 Binary_expression::compare_float(Operator op, Type* type, mpfr_t left_val,
4882                                  mpfr_t right_val)
4883 {
4884   int i;
4885   if (type == NULL)
4886     i = mpfr_cmp(left_val, right_val);
4887   else
4888     {
4889       mpfr_t lv;
4890       mpfr_init_set(lv, left_val, GMP_RNDN);
4891       mpfr_t rv;
4892       mpfr_init_set(rv, right_val, GMP_RNDN);
4893       Float_expression::constrain_float(lv, type);
4894       Float_expression::constrain_float(rv, type);
4895       i = mpfr_cmp(lv, rv);
4896       mpfr_clear(lv);
4897       mpfr_clear(rv);
4898     }
4899   switch (op)
4900     {
4901     case OPERATOR_EQEQ:
4902       return i == 0;
4903     case OPERATOR_NOTEQ:
4904       return i != 0;
4905     case OPERATOR_LT:
4906       return i < 0;
4907     case OPERATOR_LE:
4908       return i <= 0;
4909     case OPERATOR_GT:
4910       return i > 0;
4911     case OPERATOR_GE:
4912       return i >= 0;
4913     default:
4914       go_unreachable();
4915     }
4916 }
4917
4918 // Compare complex constants according to OP.  Complex numbers may
4919 // only be compared for equality.
4920
4921 bool
4922 Binary_expression::compare_complex(Operator op, Type* type,
4923                                    mpfr_t left_real, mpfr_t left_imag,
4924                                    mpfr_t right_real, mpfr_t right_imag)
4925 {
4926   bool is_equal;
4927   if (type == NULL)
4928     is_equal = (mpfr_cmp(left_real, right_real) == 0
4929                 && mpfr_cmp(left_imag, right_imag) == 0);
4930   else
4931     {
4932       mpfr_t lr;
4933       mpfr_t li;
4934       mpfr_init_set(lr, left_real, GMP_RNDN);
4935       mpfr_init_set(li, left_imag, GMP_RNDN);
4936       mpfr_t rr;
4937       mpfr_t ri;
4938       mpfr_init_set(rr, right_real, GMP_RNDN);
4939       mpfr_init_set(ri, right_imag, GMP_RNDN);
4940       Complex_expression::constrain_complex(lr, li, type);
4941       Complex_expression::constrain_complex(rr, ri, type);
4942       is_equal = mpfr_cmp(lr, rr) == 0 && mpfr_cmp(li, ri) == 0;
4943       mpfr_clear(lr);
4944       mpfr_clear(li);
4945       mpfr_clear(rr);
4946       mpfr_clear(ri);
4947     }
4948   switch (op)
4949     {
4950     case OPERATOR_EQEQ:
4951       return is_equal;
4952     case OPERATOR_NOTEQ:
4953       return !is_equal;
4954     default:
4955       go_unreachable();
4956     }
4957 }
4958
4959 // Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL.
4960 // LEFT_TYPE is the type of LEFT_VAL, RIGHT_TYPE is the type of
4961 // RIGHT_VAL; LEFT_TYPE and/or RIGHT_TYPE may be NULL.  Return true if
4962 // this could be done, false if not.
4963
4964 bool
4965 Binary_expression::eval_integer(Operator op, Type* left_type, mpz_t left_val,
4966                                 Type* right_type, mpz_t right_val,
4967                                 Location location, mpz_t val)
4968 {
4969   bool is_shift_op = false;
4970   switch (op)
4971     {
4972     case OPERATOR_OROR:
4973     case OPERATOR_ANDAND:
4974     case OPERATOR_EQEQ:
4975     case OPERATOR_NOTEQ:
4976     case OPERATOR_LT:
4977     case OPERATOR_LE:
4978     case OPERATOR_GT:
4979     case OPERATOR_GE:
4980       // These return boolean values.  We should probably handle them
4981       // anyhow in case a type conversion is used on the result.
4982       return false;
4983     case OPERATOR_PLUS:
4984       mpz_add(val, left_val, right_val);
4985       break;
4986     case OPERATOR_MINUS:
4987       mpz_sub(val, left_val, right_val);
4988       break;
4989     case OPERATOR_OR:
4990       mpz_ior(val, left_val, right_val);
4991       break;
4992     case OPERATOR_XOR:
4993       mpz_xor(val, left_val, right_val);
4994       break;
4995     case OPERATOR_MULT:
4996       mpz_mul(val, left_val, right_val);
4997       break;
4998     case OPERATOR_DIV:
4999       if (mpz_sgn(right_val) != 0)
5000         mpz_tdiv_q(val, left_val, right_val);
5001       else
5002         {
5003           error_at(location, "division by zero");
5004           mpz_set_ui(val, 0);
5005           return true;
5006         }
5007       break;
5008     case OPERATOR_MOD:
5009       if (mpz_sgn(right_val) != 0)
5010         mpz_tdiv_r(val, left_val, right_val);
5011       else
5012         {
5013           error_at(location, "division by zero");
5014           mpz_set_ui(val, 0);
5015           return true;
5016         }
5017       break;
5018     case OPERATOR_LSHIFT:
5019       {
5020         unsigned long shift = mpz_get_ui(right_val);
5021         if (mpz_cmp_ui(right_val, shift) != 0 || shift > 0x100000)
5022           {
5023             error_at(location, "shift count overflow");
5024             mpz_set_ui(val, 0);
5025             return true;
5026           }
5027         mpz_mul_2exp(val, left_val, shift);
5028         is_shift_op = true;
5029         break;
5030       }
5031       break;
5032     case OPERATOR_RSHIFT:
5033       {
5034         unsigned long shift = mpz_get_ui(right_val);
5035         if (mpz_cmp_ui(right_val, shift) != 0)
5036           {
5037             error_at(location, "shift count overflow");
5038             mpz_set_ui(val, 0);
5039             return true;
5040           }
5041         if (mpz_cmp_ui(left_val, 0) >= 0)
5042           mpz_tdiv_q_2exp(val, left_val, shift);
5043         else
5044           mpz_fdiv_q_2exp(val, left_val, shift);
5045         is_shift_op = true;
5046         break;
5047       }
5048       break;
5049     case OPERATOR_AND:
5050       mpz_and(val, left_val, right_val);
5051       break;
5052     case OPERATOR_BITCLEAR:
5053       {
5054         mpz_t tval;
5055         mpz_init(tval);
5056         mpz_com(tval, right_val);
5057         mpz_and(val, left_val, tval);
5058         mpz_clear(tval);
5059       }
5060       break;
5061     default:
5062       go_unreachable();
5063     }
5064
5065   Type* type = left_type;
5066   if (!is_shift_op)
5067     {
5068       if (type == NULL)
5069         type = right_type;
5070       else if (type != right_type && right_type != NULL)
5071         {
5072           if (type->is_abstract())
5073             type = right_type;
5074           else if (!right_type->is_abstract())
5075             {
5076               // This look like a type error which should be diagnosed
5077               // elsewhere.  Don't do anything here, to avoid an
5078               // unhelpful chain of error messages.
5079               return true;
5080             }
5081         }
5082     }
5083
5084   if (type != NULL && !type->is_abstract())
5085     {
5086       // We have to check the operands too, as we have implicitly
5087       // coerced them to TYPE.
5088       if ((type != left_type
5089            && !Integer_expression::check_constant(left_val, type, location))
5090           || (!is_shift_op
5091               && type != right_type
5092               && !Integer_expression::check_constant(right_val, type,
5093                                                      location))
5094           || !Integer_expression::check_constant(val, type, location))
5095         mpz_set_ui(val, 0);
5096     }
5097
5098   return true;
5099 }
5100
5101 // Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL.
5102 // Return true if this could be done, false if not.
5103
5104 bool
5105 Binary_expression::eval_float(Operator op, Type* left_type, mpfr_t left_val,
5106                               Type* right_type, mpfr_t right_val,
5107                               mpfr_t val, Location location)
5108 {
5109   switch (op)
5110     {
5111     case OPERATOR_OROR:
5112     case OPERATOR_ANDAND:
5113     case OPERATOR_EQEQ:
5114     case OPERATOR_NOTEQ:
5115     case OPERATOR_LT:
5116     case OPERATOR_LE:
5117     case OPERATOR_GT:
5118     case OPERATOR_GE:
5119       // These return boolean values.  We should probably handle them
5120       // anyhow in case a type conversion is used on the result.
5121       return false;
5122     case OPERATOR_PLUS:
5123       mpfr_add(val, left_val, right_val, GMP_RNDN);
5124       break;
5125     case OPERATOR_MINUS:
5126       mpfr_sub(val, left_val, right_val, GMP_RNDN);
5127       break;
5128     case OPERATOR_OR:
5129     case OPERATOR_XOR:
5130     case OPERATOR_AND:
5131     case OPERATOR_BITCLEAR:
5132       return false;
5133     case OPERATOR_MULT:
5134       mpfr_mul(val, left_val, right_val, GMP_RNDN);
5135       break;
5136     case OPERATOR_DIV:
5137       if (mpfr_zero_p(right_val))
5138         error_at(location, "division by zero");
5139       mpfr_div(val, left_val, right_val, GMP_RNDN);
5140       break;
5141     case OPERATOR_MOD:
5142       return false;
5143     case OPERATOR_LSHIFT:
5144     case OPERATOR_RSHIFT:
5145       return false;
5146     default:
5147       go_unreachable();
5148     }
5149
5150   Type* type = left_type;
5151   if (type == NULL)
5152     type = right_type;
5153   else if (type != right_type && right_type != NULL)
5154     {
5155       if (type->is_abstract())
5156         type = right_type;
5157       else if (!right_type->is_abstract())
5158         {
5159           // This looks like a type error which should be diagnosed
5160           // elsewhere.  Don't do anything here, to avoid an unhelpful
5161           // chain of error messages.
5162           return true;
5163         }
5164     }
5165
5166   if (type != NULL && !type->is_abstract())
5167     {
5168       if ((type != left_type
5169            && !Float_expression::check_constant(left_val, type, location))
5170           || (type != right_type
5171               && !Float_expression::check_constant(right_val, type,
5172                                                    location))
5173           || !Float_expression::check_constant(val, type, location))
5174         mpfr_set_ui(val, 0, GMP_RNDN);
5175     }
5176
5177   return true;
5178 }
5179
5180 // Apply binary opcode OP to LEFT_REAL/LEFT_IMAG and
5181 // RIGHT_REAL/RIGHT_IMAG, setting REAL/IMAG.  Return true if this
5182 // could be done, false if not.
5183
5184 bool
5185 Binary_expression::eval_complex(Operator op, Type* left_type,
5186                                 mpfr_t left_real, mpfr_t left_imag,
5187                                 Type *right_type,
5188                                 mpfr_t right_real, mpfr_t right_imag,
5189                                 mpfr_t real, mpfr_t imag,
5190                                 Location location)
5191 {
5192   switch (op)
5193     {
5194     case OPERATOR_OROR:
5195     case OPERATOR_ANDAND:
5196     case OPERATOR_EQEQ:
5197     case OPERATOR_NOTEQ:
5198     case OPERATOR_LT:
5199     case OPERATOR_LE:
5200     case OPERATOR_GT:
5201     case OPERATOR_GE:
5202       // These return boolean values and must be handled differently.
5203       return false;
5204     case OPERATOR_PLUS:
5205       mpfr_add(real, left_real, right_real, GMP_RNDN);
5206       mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
5207       break;
5208     case OPERATOR_MINUS:
5209       mpfr_sub(real, left_real, right_real, GMP_RNDN);
5210       mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
5211       break;
5212     case OPERATOR_OR:
5213     case OPERATOR_XOR:
5214     case OPERATOR_AND:
5215     case OPERATOR_BITCLEAR:
5216       return false;
5217     case OPERATOR_MULT:
5218       {
5219         // You might think that multiplying two complex numbers would
5220         // be simple, and you would be right, until you start to think
5221         // about getting the right answer for infinity.  If one
5222         // operand here is infinity and the other is anything other
5223         // than zero or NaN, then we are going to wind up subtracting
5224         // two infinity values.  That will give us a NaN, but the
5225         // correct answer is infinity.
5226
5227         mpfr_t lrrr;
5228         mpfr_init(lrrr);
5229         mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
5230
5231         mpfr_t lrri;
5232         mpfr_init(lrri);
5233         mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
5234
5235         mpfr_t lirr;
5236         mpfr_init(lirr);
5237         mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
5238
5239         mpfr_t liri;
5240         mpfr_init(liri);
5241         mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
5242
5243         mpfr_sub(real, lrrr, liri, GMP_RNDN);
5244         mpfr_add(imag, lrri, lirr, GMP_RNDN);
5245
5246         // If we get NaN on both sides, check whether it should really
5247         // be infinity.  The rule is that if either side of the
5248         // complex number is infinity, then the whole value is
5249         // infinity, even if the other side is NaN.  So the only case
5250         // we have to fix is the one in which both sides are NaN.
5251         if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5252             && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5253             && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5254           {
5255             bool is_infinity = false;
5256
5257             mpfr_t lr;
5258             mpfr_t li;
5259             mpfr_init_set(lr, left_real, GMP_RNDN);
5260             mpfr_init_set(li, left_imag, GMP_RNDN);
5261
5262             mpfr_t rr;
5263             mpfr_t ri;
5264             mpfr_init_set(rr, right_real, GMP_RNDN);
5265             mpfr_init_set(ri, right_imag, GMP_RNDN);
5266
5267             // If the left side is infinity, then the result is
5268             // infinity.
5269             if (mpfr_inf_p(lr) || mpfr_inf_p(li))
5270               {
5271                 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
5272                 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5273                 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
5274                 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5275                 if (mpfr_nan_p(rr))
5276                   {
5277                     mpfr_set_ui(rr, 0, GMP_RNDN);
5278                     mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5279                   }
5280                 if (mpfr_nan_p(ri))
5281                   {
5282                     mpfr_set_ui(ri, 0, GMP_RNDN);
5283                     mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5284                   }
5285                 is_infinity = true;
5286               }
5287
5288             // If the right side is infinity, then the result is
5289             // infinity.
5290             if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
5291               {
5292                 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5293                 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5294                 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5295                 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5296                 if (mpfr_nan_p(lr))
5297                   {
5298                     mpfr_set_ui(lr, 0, GMP_RNDN);
5299                     mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5300                   }
5301                 if (mpfr_nan_p(li))
5302                   {
5303                     mpfr_set_ui(li, 0, GMP_RNDN);
5304                     mpfr_copysign(li, li, left_imag, GMP_RNDN);
5305                   }
5306                 is_infinity = true;
5307               }
5308
5309             // If we got an overflow in the intermediate computations,
5310             // then the result is infinity.
5311             if (!is_infinity
5312                 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
5313                     || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
5314               {
5315                 if (mpfr_nan_p(lr))
5316                   {
5317                     mpfr_set_ui(lr, 0, GMP_RNDN);
5318                     mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5319                   }
5320                 if (mpfr_nan_p(li))
5321                   {
5322                     mpfr_set_ui(li, 0, GMP_RNDN);
5323                     mpfr_copysign(li, li, left_imag, GMP_RNDN);
5324                   }
5325                 if (mpfr_nan_p(rr))
5326                   {
5327                     mpfr_set_ui(rr, 0, GMP_RNDN);
5328                     mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5329                   }
5330                 if (mpfr_nan_p(ri))
5331                   {
5332                     mpfr_set_ui(ri, 0, GMP_RNDN);
5333                     mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5334                   }
5335                 is_infinity = true;
5336               }
5337
5338             if (is_infinity)
5339               {
5340                 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
5341                 mpfr_mul(lrri, lr, ri, GMP_RNDN);
5342                 mpfr_mul(lirr, li, rr, GMP_RNDN);
5343                 mpfr_mul(liri, li, ri, GMP_RNDN);
5344                 mpfr_sub(real, lrrr, liri, GMP_RNDN);
5345                 mpfr_add(imag, lrri, lirr, GMP_RNDN);
5346                 mpfr_set_inf(real, mpfr_sgn(real));
5347                 mpfr_set_inf(imag, mpfr_sgn(imag));
5348               }
5349
5350             mpfr_clear(lr);
5351             mpfr_clear(li);
5352             mpfr_clear(rr);
5353             mpfr_clear(ri);
5354           }
5355
5356         mpfr_clear(lrrr);
5357         mpfr_clear(lrri);
5358         mpfr_clear(lirr);
5359         mpfr_clear(liri);                                 
5360       }
5361       break;
5362     case OPERATOR_DIV:
5363       {
5364         // For complex division we want to avoid having an
5365         // intermediate overflow turn the whole result in a NaN.  We
5366         // scale the values to try to avoid this.
5367
5368         if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
5369           error_at(location, "division by zero");
5370
5371         mpfr_t rra;
5372         mpfr_t ria;
5373         mpfr_init(rra);
5374         mpfr_init(ria);
5375         mpfr_abs(rra, right_real, GMP_RNDN);
5376         mpfr_abs(ria, right_imag, GMP_RNDN);
5377         mpfr_t t;
5378         mpfr_init(t);
5379         mpfr_max(t, rra, ria, GMP_RNDN);
5380
5381         mpfr_t rr;
5382         mpfr_t ri;
5383         mpfr_init_set(rr, right_real, GMP_RNDN);
5384         mpfr_init_set(ri, right_imag, GMP_RNDN);
5385         long ilogbw = 0;
5386         if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5387           {
5388             ilogbw = mpfr_get_exp(t);
5389             mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5390             mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5391           }
5392
5393         mpfr_t denom;
5394         mpfr_init(denom);
5395         mpfr_mul(denom, rr, rr, GMP_RNDN);
5396         mpfr_mul(t, ri, ri, GMP_RNDN);
5397         mpfr_add(denom, denom, t, GMP_RNDN);
5398
5399         mpfr_mul(real, left_real, rr, GMP_RNDN);
5400         mpfr_mul(t, left_imag, ri, GMP_RNDN);
5401         mpfr_add(real, real, t, GMP_RNDN);
5402         mpfr_div(real, real, denom, GMP_RNDN);
5403         mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5404
5405         mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5406         mpfr_mul(t, left_real, ri, GMP_RNDN);
5407         mpfr_sub(imag, imag, t, GMP_RNDN);
5408         mpfr_div(imag, imag, denom, GMP_RNDN);
5409         mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5410
5411         // If we wind up with NaN on both sides, check whether we
5412         // should really have infinity.  The rule is that if either
5413         // side of the complex number is infinity, then the whole
5414         // value is infinity, even if the other side is NaN.  So the
5415         // only case we have to fix is the one in which both sides are
5416         // NaN.
5417         if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5418             && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5419             && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5420           {
5421             if (mpfr_zero_p(denom))
5422               {
5423                 mpfr_set_inf(real, mpfr_sgn(rr));
5424                 mpfr_mul(real, real, left_real, GMP_RNDN);
5425                 mpfr_set_inf(imag, mpfr_sgn(rr));
5426                 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5427               }
5428             else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5429                      && mpfr_number_p(rr) && mpfr_number_p(ri))
5430               {
5431                 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5432                 mpfr_copysign(t, t, left_real, GMP_RNDN);
5433
5434                 mpfr_t t2;
5435                 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5436                 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5437
5438                 mpfr_t t3;
5439                 mpfr_init(t3);
5440                 mpfr_mul(t3, t, rr, GMP_RNDN);
5441
5442                 mpfr_t t4;
5443                 mpfr_init(t4);
5444                 mpfr_mul(t4, t2, ri, GMP_RNDN);
5445
5446                 mpfr_add(t3, t3, t4, GMP_RNDN);
5447                 mpfr_set_inf(real, mpfr_sgn(t3));
5448
5449                 mpfr_mul(t3, t2, rr, GMP_RNDN);
5450                 mpfr_mul(t4, t, ri, GMP_RNDN);
5451                 mpfr_sub(t3, t3, t4, GMP_RNDN);
5452                 mpfr_set_inf(imag, mpfr_sgn(t3));
5453
5454                 mpfr_clear(t2);
5455                 mpfr_clear(t3);
5456                 mpfr_clear(t4);
5457               }
5458             else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5459                      && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5460               {
5461                 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5462                 mpfr_copysign(t, t, rr, GMP_RNDN);
5463
5464                 mpfr_t t2;
5465                 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5466                 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5467
5468                 mpfr_t t3;
5469                 mpfr_init(t3);
5470                 mpfr_mul(t3, left_real, t, GMP_RNDN);
5471
5472                 mpfr_t t4;
5473                 mpfr_init(t4);
5474                 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5475
5476                 mpfr_add(t3, t3, t4, GMP_RNDN);
5477                 mpfr_set_ui(real, 0, GMP_RNDN);
5478                 mpfr_mul(real, real, t3, GMP_RNDN);
5479
5480                 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5481                 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5482                 mpfr_sub(t3, t3, t4, GMP_RNDN);
5483                 mpfr_set_ui(imag, 0, GMP_RNDN);
5484                 mpfr_mul(imag, imag, t3, GMP_RNDN);
5485
5486                 mpfr_clear(t2);
5487                 mpfr_clear(t3);
5488                 mpfr_clear(t4);
5489               }
5490           }
5491
5492         mpfr_clear(denom);
5493         mpfr_clear(rr);
5494         mpfr_clear(ri);
5495         mpfr_clear(t);
5496         mpfr_clear(rra);
5497         mpfr_clear(ria);
5498       }
5499       break;
5500     case OPERATOR_MOD:
5501       return false;
5502     case OPERATOR_LSHIFT:
5503     case OPERATOR_RSHIFT:
5504       return false;
5505     default:
5506       go_unreachable();
5507     }
5508
5509   Type* type = left_type;
5510   if (type == NULL)
5511     type = right_type;
5512   else if (type != right_type && right_type != NULL)
5513     {
5514       if (type->is_abstract())
5515         type = right_type;
5516       else if (!right_type->is_abstract())
5517         {
5518           // This looks like a type error which should be diagnosed
5519           // elsewhere.  Don't do anything here, to avoid an unhelpful
5520           // chain of error messages.
5521           return true;
5522         }
5523     }
5524
5525   if (type != NULL && !type->is_abstract())
5526     {
5527       if ((type != left_type
5528            && !Complex_expression::check_constant(left_real, left_imag,
5529                                                   type, location))
5530           || (type != right_type
5531               && !Complex_expression::check_constant(right_real, right_imag,
5532                                                      type, location))
5533           || !Complex_expression::check_constant(real, imag, type,
5534                                                  location))
5535         {
5536           mpfr_set_ui(real, 0, GMP_RNDN);
5537           mpfr_set_ui(imag, 0, GMP_RNDN);
5538         }
5539     }
5540
5541   return true;
5542 }
5543
5544 // Lower a binary expression.  We have to evaluate constant
5545 // expressions now, in order to implement Go's unlimited precision
5546 // constants.
5547
5548 Expression*
5549 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5550                             Statement_inserter* inserter, int)
5551 {
5552   Location location = this->location();
5553   Operator op = this->op_;
5554   Expression* left = this->left_;
5555   Expression* right = this->right_;
5556
5557   const bool is_comparison = (op == OPERATOR_EQEQ
5558                               || op == OPERATOR_NOTEQ
5559                               || op == OPERATOR_LT
5560                               || op == OPERATOR_LE
5561                               || op == OPERATOR_GT
5562                               || op == OPERATOR_GE);
5563
5564   // Integer constant expressions.
5565   {
5566     mpz_t left_val;
5567     mpz_init(left_val);
5568     Type* left_type;
5569     mpz_t right_val;
5570     mpz_init(right_val);
5571     Type* right_type;
5572     if (left->integer_constant_value(false, left_val, &left_type)
5573         && right->integer_constant_value(false, right_val, &right_type))
5574       {
5575         Expression* ret = NULL;
5576         if (left_type != right_type
5577             && left_type != NULL
5578             && !left_type->is_abstract()
5579             && right_type != NULL
5580             && !right_type->is_abstract()
5581             && left_type->base() != right_type->base()
5582             && op != OPERATOR_LSHIFT
5583             && op != OPERATOR_RSHIFT)
5584           {
5585             // May be a type error--let it be diagnosed later.
5586             return this;
5587           }
5588         else if (is_comparison)
5589           {
5590             bool b = Binary_expression::compare_integer(op, left_val,
5591                                                         right_val);
5592             ret = Expression::make_cast(Type::lookup_bool_type(),
5593                                         Expression::make_boolean(b, location),
5594                                         location);
5595           }
5596         else
5597           {
5598             mpz_t val;
5599             mpz_init(val);
5600
5601             if (Binary_expression::eval_integer(op, left_type, left_val,
5602                                                 right_type, right_val,
5603                                                 location, val))
5604               {
5605                 go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND);
5606                 Type* type;
5607                 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5608                   type = left_type;
5609                 else if (left_type == NULL)
5610                   type = right_type;
5611                 else if (right_type == NULL)
5612                   type = left_type;
5613                 else if (!left_type->is_abstract()
5614                          && left_type->named_type() != NULL)
5615                   type = left_type;
5616                 else if (!right_type->is_abstract()
5617                          && right_type->named_type() != NULL)
5618                   type = right_type;
5619                 else if (!left_type->is_abstract())
5620                   type = left_type;
5621                 else if (!right_type->is_abstract())
5622                   type = right_type;
5623                 else if (left_type->float_type() != NULL)
5624                   type = left_type;
5625                 else if (right_type->float_type() != NULL)
5626                   type = right_type;
5627                 else if (left_type->complex_type() != NULL)
5628                   type = left_type;
5629                 else if (right_type->complex_type() != NULL)
5630                   type = right_type;
5631                 else
5632                   type = left_type;
5633
5634                 bool is_character = false;
5635                 if (type == NULL)
5636                   {
5637                     Type* t = this->left_->type();
5638                     if (t->integer_type() != NULL
5639                         && t->integer_type()->is_rune())
5640                       is_character = true;
5641                     else if (op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT)
5642                       {
5643                         t = this->right_->type();
5644                         if (t->integer_type() != NULL
5645                             && t->integer_type()->is_rune())
5646                           is_character = true;
5647                       }
5648                   }
5649
5650                 if (is_character)
5651                   ret = Expression::make_character(&val, type, location);
5652                 else
5653                   ret = Expression::make_integer(&val, type, location);
5654               }
5655
5656             mpz_clear(val);
5657           }
5658
5659         if (ret != NULL)
5660           {
5661             mpz_clear(right_val);
5662             mpz_clear(left_val);
5663             return ret;
5664           }
5665       }
5666     mpz_clear(right_val);
5667     mpz_clear(left_val);
5668   }
5669
5670   // Floating point constant expressions.
5671   {
5672     mpfr_t left_val;
5673     mpfr_init(left_val);
5674     Type* left_type;
5675     mpfr_t right_val;
5676     mpfr_init(right_val);
5677     Type* right_type;
5678     if (left->float_constant_value(left_val, &left_type)
5679         && right->float_constant_value(right_val, &right_type))
5680       {
5681         Expression* ret = NULL;
5682         if (left_type != right_type
5683             && left_type != NULL
5684             && right_type != NULL
5685             && left_type->base() != right_type->base()
5686             && op != OPERATOR_LSHIFT
5687             && op != OPERATOR_RSHIFT)
5688           {
5689             // May be a type error--let it be diagnosed later.
5690             return this;
5691           }
5692         else if (is_comparison)
5693           {
5694             bool b = Binary_expression::compare_float(op,
5695                                                       (left_type != NULL
5696                                                        ? left_type
5697                                                        : right_type),
5698                                                       left_val, right_val);
5699             ret = Expression::make_boolean(b, location);
5700           }
5701         else
5702           {
5703             mpfr_t val;
5704             mpfr_init(val);
5705
5706             if (Binary_expression::eval_float(op, left_type, left_val,
5707                                               right_type, right_val, val,
5708                                               location))
5709               {
5710                 go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND
5711                            && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT);
5712                 Type* type;
5713                 if (left_type == NULL)
5714                   type = right_type;
5715                 else if (right_type == NULL)
5716                   type = left_type;
5717                 else if (!left_type->is_abstract()
5718                          && left_type->named_type() != NULL)
5719                   type = left_type;
5720                 else if (!right_type->is_abstract()
5721                          && right_type->named_type() != NULL)
5722                   type = right_type;
5723                 else if (!left_type->is_abstract())
5724                   type = left_type;
5725                 else if (!right_type->is_abstract())
5726                   type = right_type;
5727                 else if (left_type->float_type() != NULL)
5728                   type = left_type;
5729                 else if (right_type->float_type() != NULL)
5730                   type = right_type;
5731                 else
5732                   type = left_type;
5733                 ret = Expression::make_float(&val, type, location);
5734               }
5735
5736             mpfr_clear(val);
5737           }
5738
5739         if (ret != NULL)
5740           {
5741             mpfr_clear(right_val);
5742             mpfr_clear(left_val);
5743             return ret;
5744           }
5745       }
5746     mpfr_clear(right_val);
5747     mpfr_clear(left_val);
5748   }
5749
5750   // Complex constant expressions.
5751   {
5752     mpfr_t left_real;
5753     mpfr_t left_imag;
5754     mpfr_init(left_real);
5755     mpfr_init(left_imag);
5756     Type* left_type;
5757
5758     mpfr_t right_real;
5759     mpfr_t right_imag;
5760     mpfr_init(right_real);
5761     mpfr_init(right_imag);
5762     Type* right_type;
5763
5764     if (left->complex_constant_value(left_real, left_imag, &left_type)
5765         && right->complex_constant_value(right_real, right_imag, &right_type))
5766       {
5767         Expression* ret = NULL;
5768         if (left_type != right_type
5769             && left_type != NULL
5770             && right_type != NULL
5771             && left_type->base() != right_type->base())
5772           {
5773             // May be a type error--let it be diagnosed later.
5774             return this;
5775           }
5776         else if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5777           {
5778             bool b = Binary_expression::compare_complex(op,
5779                                                         (left_type != NULL
5780                                                          ? left_type
5781                                                          : right_type),
5782                                                         left_real,
5783                                                         left_imag,
5784                                                         right_real,
5785                                                         right_imag);
5786             ret = Expression::make_boolean(b, location);
5787           }
5788         else
5789           {
5790             mpfr_t real;
5791             mpfr_t imag;
5792             mpfr_init(real);
5793             mpfr_init(imag);
5794
5795             if (Binary_expression::eval_complex(op, left_type,
5796                                                 left_real, left_imag,
5797                                                 right_type,
5798                                                 right_real, right_imag,
5799                                                 real, imag,
5800                                                 location))
5801               {
5802                 go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND
5803                            && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT);
5804                 Type* type;
5805                 if (left_type == NULL)
5806                   type = right_type;
5807                 else if (right_type == NULL)
5808                   type = left_type;
5809                 else if (!left_type->is_abstract()
5810                          && left_type->named_type() != NULL)
5811                   type = left_type;
5812                 else if (!right_type->is_abstract()
5813                          && right_type->named_type() != NULL)
5814                   type = right_type;
5815                 else if (!left_type->is_abstract())
5816                   type = left_type;
5817                 else if (!right_type->is_abstract())
5818                   type = right_type;
5819                 else if (left_type->complex_type() != NULL)
5820                   type = left_type;
5821                 else if (right_type->complex_type() != NULL)
5822                   type = right_type;
5823                 else
5824                   type = left_type;
5825                 ret = Expression::make_complex(&real, &imag, type,
5826                                                location);
5827               }
5828             mpfr_clear(real);
5829             mpfr_clear(imag);
5830           }
5831
5832         if (ret != NULL)
5833           {
5834             mpfr_clear(left_real);
5835             mpfr_clear(left_imag);
5836             mpfr_clear(right_real);
5837             mpfr_clear(right_imag);
5838             return ret;
5839           }
5840       }
5841
5842     mpfr_clear(left_real);
5843     mpfr_clear(left_imag);
5844     mpfr_clear(right_real);
5845     mpfr_clear(right_imag);
5846   }
5847
5848   // String constant expressions.
5849   if (left->type()->is_string_type() && right->type()->is_string_type())
5850     {
5851       std::string left_string;
5852       std::string right_string;
5853       if (left->string_constant_value(&left_string)
5854           && right->string_constant_value(&right_string))
5855         {
5856           if (op == OPERATOR_PLUS)
5857             return Expression::make_string(left_string + right_string,
5858                                            location);
5859           else if (is_comparison)
5860             {
5861               int cmp = left_string.compare(right_string);
5862               bool r;
5863               switch (op)
5864                 {
5865                 case OPERATOR_EQEQ:
5866                   r = cmp == 0;
5867                   break;
5868                 case OPERATOR_NOTEQ:
5869                   r = cmp != 0;
5870                   break;
5871                 case OPERATOR_LT:
5872                   r = cmp < 0;
5873                   break;
5874                 case OPERATOR_LE:
5875                   r = cmp <= 0;
5876                   break;
5877                 case OPERATOR_GT:
5878                   r = cmp > 0;
5879                   break;
5880                 case OPERATOR_GE:
5881                   r = cmp >= 0;
5882                   break;
5883                 default:
5884                   go_unreachable();
5885                 }
5886               return Expression::make_boolean(r, location);
5887             }
5888         }
5889     }
5890
5891   // Special case for shift of a floating point constant.
5892   if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5893     {
5894       mpfr_t left_val;
5895       mpfr_init(left_val);
5896       Type* left_type;
5897       mpz_t right_val;
5898       mpz_init(right_val);
5899       Type* right_type;
5900       if (left->float_constant_value(left_val, &left_type)
5901           && right->integer_constant_value(false, right_val, &right_type)
5902           && mpfr_integer_p(left_val)
5903           && (left_type == NULL
5904               || left_type->is_abstract()
5905               || left_type->integer_type() != NULL))
5906         {
5907           mpz_t left_int;
5908           mpz_init(left_int);
5909           mpfr_get_z(left_int, left_val, GMP_RNDN);
5910
5911           mpz_t val;
5912           mpz_init(val);
5913
5914           Expression* ret = NULL;
5915           if (Binary_expression::eval_integer(op, left_type, left_int,
5916                                               right_type, right_val,
5917                                               location, val))
5918             ret = Expression::make_integer(&val, left_type, location);
5919
5920           mpz_clear(left_int);
5921           mpz_clear(val);
5922
5923           if (ret != NULL)
5924             {
5925               mpfr_clear(left_val);
5926               mpz_clear(right_val);
5927               return ret;
5928             }
5929         }
5930
5931       mpfr_clear(left_val);
5932       mpz_clear(right_val);
5933     }
5934
5935   // Lower struct and array comparisons.
5936   if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5937     {
5938       if (left->type()->struct_type() != NULL)
5939         return this->lower_struct_comparison(gogo, inserter);
5940       else if (left->type()->array_type() != NULL
5941                && !left->type()->is_slice_type())
5942         return this->lower_array_comparison(gogo, inserter);
5943     }
5944
5945   return this;
5946 }
5947
5948 // Lower a struct comparison.
5949
5950 Expression*
5951 Binary_expression::lower_struct_comparison(Gogo* gogo,
5952                                            Statement_inserter* inserter)
5953 {
5954   Struct_type* st = this->left_->type()->struct_type();
5955   Struct_type* st2 = this->right_->type()->struct_type();
5956   if (st2 == NULL)
5957     return this;
5958   if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5959     return this;
5960   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5961                                            this->right_->type(), NULL))
5962     return this;
5963
5964   // See if we can compare using memcmp.  As a heuristic, we use
5965   // memcmp rather than field references and comparisons if there are
5966   // more than two fields.
5967   if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5968     return this->lower_compare_to_memcmp(gogo, inserter);
5969
5970   Location loc = this->location();
5971
5972   Expression* left = this->left_;
5973   Temporary_statement* left_temp = NULL;
5974   if (left->var_expression() == NULL
5975       && left->temporary_reference_expression() == NULL)
5976     {
5977       left_temp = Statement::make_temporary(left->type(), NULL, loc);
5978       inserter->insert(left_temp);
5979       left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5980     }
5981
5982   Expression* right = this->right_;
5983   Temporary_statement* right_temp = NULL;
5984   if (right->var_expression() == NULL
5985       && right->temporary_reference_expression() == NULL)
5986     {
5987       right_temp = Statement::make_temporary(right->type(), NULL, loc);
5988       inserter->insert(right_temp);
5989       right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5990     }
5991
5992   Expression* ret = Expression::make_boolean(true, loc);
5993   const Struct_field_list* fields = st->fields();
5994   unsigned int field_index = 0;
5995   for (Struct_field_list::const_iterator pf = fields->begin();
5996        pf != fields->end();
5997        ++pf, ++field_index)
5998     {
5999       if (field_index > 0)
6000         {
6001           if (left_temp == NULL)
6002             left = left->copy();
6003           else
6004             left = Expression::make_temporary_reference(left_temp, loc);
6005           if (right_temp == NULL)
6006             right = right->copy();
6007           else
6008             right = Expression::make_temporary_reference(right_temp, loc);
6009         }
6010       Expression* f1 = Expression::make_field_reference(left, field_index,
6011                                                         loc);
6012       Expression* f2 = Expression::make_field_reference(right, field_index,
6013                                                         loc);
6014       Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6015       ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6016     }
6017
6018   if (this->op_ == OPERATOR_NOTEQ)
6019     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6020
6021   return ret;
6022 }
6023
6024 // Lower an array comparison.
6025
6026 Expression*
6027 Binary_expression::lower_array_comparison(Gogo* gogo,
6028                                           Statement_inserter* inserter)
6029 {
6030   Array_type* at = this->left_->type()->array_type();
6031   Array_type* at2 = this->right_->type()->array_type();
6032   if (at2 == NULL)
6033     return this;
6034   if (at != at2 && !Type::are_identical(at, at2, false, NULL))
6035     return this;
6036   if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6037                                            this->right_->type(), NULL))
6038     return this;
6039
6040   // Call memcmp directly if possible.  This may let the middle-end
6041   // optimize the call.
6042   if (at->compare_is_identity(gogo))
6043     return this->lower_compare_to_memcmp(gogo, inserter);
6044
6045   // Call the array comparison function.
6046   Named_object* hash_fn;
6047   Named_object* equal_fn;
6048   at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
6049                      &hash_fn, &equal_fn);
6050
6051   Location loc = this->location();
6052
6053   Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6054
6055   Expression_list* args = new Expression_list();
6056   args->push_back(this->operand_address(inserter, this->left_));
6057   args->push_back(this->operand_address(inserter, this->right_));
6058   args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
6059
6060   Expression* ret = Expression::make_call(func, args, false, loc);
6061
6062   if (this->op_ == OPERATOR_NOTEQ)
6063     ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6064
6065   return ret;
6066 }
6067
6068 // Lower a struct or array comparison to a call to memcmp.
6069
6070 Expression*
6071 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6072 {
6073   Location loc = this->location();
6074
6075   Expression* a1 = this->operand_address(inserter, this->left_);
6076   Expression* a2 = this->operand_address(inserter, this->right_);
6077   Expression* len = Expression::make_type_info(this->left_->type(),
6078                                                TYPE_INFO_SIZE);
6079
6080   Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6081
6082   mpz_t zval;
6083   mpz_init_set_ui(zval, 0);
6084   Expression* zero = Expression::make_integer(&zval, NULL, loc);
6085   mpz_clear(zval);
6086
6087   return Expression::make_binary(this->op_, call, zero, loc);
6088 }
6089
6090 // Return the address of EXPR, cast to unsafe.Pointer.
6091
6092 Expression*
6093 Binary_expression::operand_address(Statement_inserter* inserter,
6094                                    Expression* expr)
6095 {
6096   Location loc = this->location();
6097
6098   if (!expr->is_addressable())
6099     {
6100       Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6101                                                             loc);
6102       inserter->insert(temp);
6103       expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6104     }
6105   expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6106   static_cast<Unary_expression*>(expr)->set_does_not_escape();
6107   Type* void_type = Type::make_void_type();
6108   Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6109   return Expression::make_cast(unsafe_pointer_type, expr, loc);
6110 }
6111
6112 // Return the integer constant value, if it has one.
6113
6114 bool
6115 Binary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val,
6116                                              Type** ptype) const
6117 {
6118   mpz_t left_val;
6119   mpz_init(left_val);
6120   Type* left_type;
6121   if (!this->left_->integer_constant_value(iota_is_constant, left_val,
6122                                            &left_type))
6123     {
6124       mpz_clear(left_val);
6125       return false;
6126     }
6127
6128   mpz_t right_val;
6129   mpz_init(right_val);
6130   Type* right_type;
6131   if (!this->right_->integer_constant_value(iota_is_constant, right_val,
6132                                             &right_type))
6133     {
6134       mpz_clear(right_val);
6135       mpz_clear(left_val);
6136       return false;
6137     }
6138
6139   bool ret;
6140   if (left_type != right_type
6141       && left_type != NULL
6142       && right_type != NULL
6143       && left_type->base() != right_type->base()
6144       && this->op_ != OPERATOR_RSHIFT
6145       && this->op_ != OPERATOR_LSHIFT)
6146     ret = false;
6147   else
6148     ret = Binary_expression::eval_integer(this->op_, left_type, left_val,
6149                                           right_type, right_val,
6150                                           this->location(), val);
6151
6152   mpz_clear(right_val);
6153   mpz_clear(left_val);
6154
6155   if (ret)
6156     *ptype = left_type;
6157
6158   return ret;
6159 }
6160
6161 // Return the floating point constant value, if it has one.
6162
6163 bool
6164 Binary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
6165 {
6166   mpfr_t left_val;
6167   mpfr_init(left_val);
6168   Type* left_type;
6169   if (!this->left_->float_constant_value(left_val, &left_type))
6170     {
6171       mpfr_clear(left_val);
6172       return false;
6173     }
6174
6175   mpfr_t right_val;
6176   mpfr_init(right_val);
6177   Type* right_type;
6178   if (!this->right_->float_constant_value(right_val, &right_type))
6179     {
6180       mpfr_clear(right_val);
6181       mpfr_clear(left_val);
6182       return false;
6183     }
6184
6185   bool ret;
6186   if (left_type != right_type
6187       && left_type != NULL
6188       && right_type != NULL
6189       && left_type->base() != right_type->base())
6190     ret = false;
6191   else
6192     ret = Binary_expression::eval_float(this->op_, left_type, left_val,
6193                                         right_type, right_val,
6194                                         val, this->location());
6195
6196   mpfr_clear(left_val);
6197   mpfr_clear(right_val);
6198
6199   if (ret)
6200     *ptype = left_type;
6201
6202   return ret;
6203 }
6204
6205 // Return the complex constant value, if it has one.
6206
6207 bool
6208 Binary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
6209                                              Type** ptype) const
6210 {
6211   mpfr_t left_real;
6212   mpfr_t left_imag;
6213   mpfr_init(left_real);
6214   mpfr_init(left_imag);
6215   Type* left_type;
6216   if (!this->left_->complex_constant_value(left_real, left_imag, &left_type))
6217     {
6218       mpfr_clear(left_real);
6219       mpfr_clear(left_imag);
6220       return false;
6221     }
6222
6223   mpfr_t right_real;
6224   mpfr_t right_imag;
6225   mpfr_init(right_real);
6226   mpfr_init(right_imag);
6227   Type* right_type;
6228   if (!this->right_->complex_constant_value(right_real, right_imag,
6229                                             &right_type))
6230     {
6231       mpfr_clear(left_real);
6232       mpfr_clear(left_imag);
6233       mpfr_clear(right_real);
6234       mpfr_clear(right_imag);
6235       return false;
6236     }
6237
6238   bool ret;
6239   if (left_type != right_type
6240       && left_type != NULL
6241       && right_type != NULL
6242       && left_type->base() != right_type->base())
6243     ret = false;
6244   else
6245     ret = Binary_expression::eval_complex(this->op_, left_type,
6246                                           left_real, left_imag,
6247                                           right_type,
6248                                           right_real, right_imag,
6249                                           real, imag,
6250                                           this->location());
6251   mpfr_clear(left_real);
6252   mpfr_clear(left_imag);
6253   mpfr_clear(right_real);
6254   mpfr_clear(right_imag);
6255
6256   if (ret)
6257     *ptype = left_type;
6258
6259   return ret;
6260 }
6261
6262 // Note that the value is being discarded.
6263
6264 void
6265 Binary_expression::do_discarding_value()
6266 {
6267   if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6268     this->right_->discarding_value();
6269   else
6270     this->unused_value_error();
6271 }
6272
6273 // Get type.
6274
6275 Type*
6276 Binary_expression::do_type()
6277 {
6278   if (this->classification() == EXPRESSION_ERROR)
6279     return Type::make_error_type();
6280
6281   switch (this->op_)
6282     {
6283     case OPERATOR_OROR:
6284     case OPERATOR_ANDAND:
6285     case OPERATOR_EQEQ:
6286     case OPERATOR_NOTEQ:
6287     case OPERATOR_LT:
6288     case OPERATOR_LE:
6289     case OPERATOR_GT:
6290     case OPERATOR_GE:
6291       return Type::lookup_bool_type();
6292
6293     case OPERATOR_PLUS:
6294     case OPERATOR_MINUS:
6295     case OPERATOR_OR:
6296     case OPERATOR_XOR:
6297     case OPERATOR_MULT:
6298     case OPERATOR_DIV:
6299     case OPERATOR_MOD:
6300     case OPERATOR_AND:
6301     case OPERATOR_BITCLEAR:
6302       {
6303         Type* left_type = this->left_->type();
6304         Type* right_type = this->right_->type();
6305         if (left_type->is_error())
6306           return left_type;
6307         else if (right_type->is_error())
6308           return right_type;
6309         else if (!Type::are_compatible_for_binop(left_type, right_type))
6310           {
6311             this->report_error(_("incompatible types in binary expression"));
6312             return Type::make_error_type();
6313           }
6314         else if (!left_type->is_abstract() && left_type->named_type() != NULL)
6315           return left_type;
6316         else if (!right_type->is_abstract() && right_type->named_type() != NULL)
6317           return right_type;
6318         else if (!left_type->is_abstract())
6319           return left_type;
6320         else if (!right_type->is_abstract())
6321           return right_type;
6322         else if (left_type->complex_type() != NULL)
6323           return left_type;
6324         else if (right_type->complex_type() != NULL)
6325           return right_type;
6326         else if (left_type->float_type() != NULL)
6327           return left_type;
6328         else if (right_type->float_type() != NULL)
6329           return right_type;
6330         else if (left_type->integer_type() != NULL
6331                  && left_type->integer_type()->is_rune())
6332           return left_type;
6333         else if (right_type->integer_type() != NULL
6334                  && right_type->integer_type()->is_rune())
6335           return right_type;
6336         else
6337           return left_type;
6338       }
6339
6340     case OPERATOR_LSHIFT:
6341     case OPERATOR_RSHIFT:
6342       return this->left_->type();
6343
6344     default:
6345       go_unreachable();
6346     }
6347 }
6348
6349 // Set type for a binary expression.
6350
6351 void
6352 Binary_expression::do_determine_type(const Type_context* context)
6353 {
6354   Type* tleft = this->left_->type();
6355   Type* tright = this->right_->type();
6356
6357   // Both sides should have the same type, except for the shift
6358   // operations.  For a comparison, we should ignore the incoming
6359   // type.
6360
6361   bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6362                       || this->op_ == OPERATOR_RSHIFT);
6363
6364   bool is_comparison = (this->op_ == OPERATOR_EQEQ
6365                         || this->op_ == OPERATOR_NOTEQ
6366                         || this->op_ == OPERATOR_LT
6367                         || this->op_ == OPERATOR_LE
6368                         || this->op_ == OPERATOR_GT
6369                         || this->op_ == OPERATOR_GE);
6370
6371   Type_context subcontext(*context);
6372
6373   if (is_comparison)
6374     {
6375       // In a comparison, the context does not determine the types of
6376       // the operands.
6377       subcontext.type = NULL;
6378     }
6379
6380   // Set the context for the left hand operand.
6381   if (is_shift_op)
6382     {
6383       // The right hand operand of a shift plays no role in
6384       // determining the type of the left hand operand.
6385     }
6386   else if (!tleft->is_abstract())
6387     subcontext.type = tleft;
6388   else if (!tright->is_abstract())
6389     subcontext.type = tright;
6390   else if (subcontext.type == NULL)
6391     {
6392       if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6393           || (tleft->float_type() != NULL && tright->float_type() != NULL)
6394           || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6395         {
6396           // Both sides have an abstract integer, abstract float, or
6397           // abstract complex type.  Just let CONTEXT determine
6398           // whether they may remain abstract or not.
6399         }
6400       else if (tleft->complex_type() != NULL)
6401         subcontext.type = tleft;
6402       else if (tright->complex_type() != NULL)
6403         subcontext.type = tright;
6404       else if (tleft->float_type() != NULL)
6405         subcontext.type = tleft;
6406       else if (tright->float_type() != NULL)
6407         subcontext.type = tright;
6408       else
6409         subcontext.type = tleft;
6410
6411       if (subcontext.type != NULL && !context->may_be_abstract)
6412         subcontext.type = subcontext.type->make_non_abstract_type();
6413     }
6414
6415   this->left_->determine_type(&subcontext);
6416
6417   if (is_shift_op)
6418     {
6419       // We may have inherited an unusable type for the shift operand.
6420       // Give a useful error if that happened.
6421       if (tleft->is_abstract()
6422           && subcontext.type != NULL
6423           && (this->left_->type()->integer_type() == NULL
6424               || (subcontext.type->integer_type() == NULL
6425                   && subcontext.type->float_type() == NULL
6426                   && subcontext.type->complex_type() == NULL)))
6427         this->report_error(("invalid context-determined non-integer type "
6428                             "for shift operand"));
6429
6430       // The context for the right hand operand is the same as for the
6431       // left hand operand, except for a shift operator.
6432       subcontext.type = Type::lookup_integer_type("uint");
6433       subcontext.may_be_abstract = false;
6434     }
6435
6436   this->right_->determine_type(&subcontext);
6437 }
6438
6439 // Report an error if the binary operator OP does not support TYPE.
6440 // OTYPE is the type of the other operand.  Return whether the
6441 // operation is OK.  This should not be used for shift.
6442
6443 bool
6444 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6445                                        Location location)
6446 {
6447   switch (op)
6448     {
6449     case OPERATOR_OROR:
6450     case OPERATOR_ANDAND:
6451       if (!type->is_boolean_type())
6452         {
6453           error_at(location, "expected boolean type");
6454           return false;
6455         }
6456       break;
6457
6458     case OPERATOR_EQEQ:
6459     case OPERATOR_NOTEQ:
6460       {
6461         std::string reason;
6462         if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6463           {
6464             error_at(location, "%s", reason.c_str());
6465             return false;
6466           }
6467       }
6468       break;
6469
6470     case OPERATOR_LT:
6471     case OPERATOR_LE:
6472     case OPERATOR_GT:
6473     case OPERATOR_GE:
6474       {
6475         std::string reason;
6476         if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6477           {
6478             error_at(location, "%s", reason.c_str());
6479             return false;
6480           }
6481       }
6482       break;
6483
6484     case OPERATOR_PLUS:
6485     case OPERATOR_PLUSEQ:
6486       if (type->integer_type() == NULL
6487           && type->float_type() == NULL
6488           && type->complex_type() == NULL
6489           && !type->is_string_type())
6490         {
6491           error_at(location,
6492                    "expected integer, floating, complex, or string type");
6493           return false;
6494         }
6495       break;
6496
6497     case OPERATOR_MINUS:
6498     case OPERATOR_MINUSEQ:
6499     case OPERATOR_MULT:
6500     case OPERATOR_MULTEQ:
6501     case OPERATOR_DIV:
6502     case OPERATOR_DIVEQ:
6503       if (type->integer_type() == NULL
6504           && type->float_type() == NULL
6505           && type->complex_type() == NULL)
6506         {
6507           error_at(location, "expected integer, floating, or complex type");
6508           return false;
6509         }
6510       break;
6511
6512     case OPERATOR_MOD:
6513     case OPERATOR_MODEQ:
6514     case OPERATOR_OR:
6515     case OPERATOR_OREQ:
6516     case OPERATOR_AND:
6517     case OPERATOR_ANDEQ:
6518     case OPERATOR_XOR:
6519     case OPERATOR_XOREQ:
6520     case OPERATOR_BITCLEAR:
6521     case OPERATOR_BITCLEAREQ:
6522       if (type->integer_type() == NULL)
6523         {
6524           error_at(location, "expected integer type");
6525           return false;
6526         }
6527       break;
6528
6529     default:
6530       go_unreachable();
6531     }
6532
6533   return true;
6534 }
6535
6536 // Check types.
6537
6538 void
6539 Binary_expression::do_check_types(Gogo*)
6540 {
6541   if (this->classification() == EXPRESSION_ERROR)
6542     return;
6543
6544   Type* left_type = this->left_->type();
6545   Type* right_type = this->right_->type();
6546   if (left_type->is_error() || right_type->is_error())
6547     {
6548       this->set_is_error();
6549       return;
6550     }
6551
6552   if (this->op_ == OPERATOR_EQEQ
6553       || this->op_ == OPERATOR_NOTEQ
6554       || this->op_ == OPERATOR_LT
6555       || this->op_ == OPERATOR_LE
6556       || this->op_ == OPERATOR_GT
6557       || this->op_ == OPERATOR_GE)
6558     {
6559       if (!Type::are_assignable(left_type, right_type, NULL)
6560           && !Type::are_assignable(right_type, left_type, NULL))
6561         {
6562           this->report_error(_("incompatible types in binary expression"));
6563           return;
6564         }
6565       if (!Binary_expression::check_operator_type(this->op_, left_type,
6566                                                   right_type,
6567                                                   this->location())
6568           || !Binary_expression::check_operator_type(this->op_, right_type,
6569                                                      left_type,
6570                                                      this->location()))
6571         {
6572           this->set_is_error();
6573           return;
6574         }
6575     }
6576   else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6577     {
6578       if (!Type::are_compatible_for_binop(left_type, right_type))
6579         {
6580           this->report_error(_("incompatible types in binary expression"));
6581           return;
6582         }
6583       if (!Binary_expression::check_operator_type(this->op_, left_type,
6584                                                   right_type,
6585                                                   this->location()))
6586         {
6587           this->set_is_error();
6588           return;
6589         }
6590     }
6591   else
6592     {
6593       if (left_type->integer_type() == NULL)
6594         this->report_error(_("shift of non-integer operand"));
6595
6596       if (!right_type->is_abstract()
6597           && (right_type->integer_type() == NULL
6598               || !right_type->integer_type()->is_unsigned()))
6599         this->report_error(_("shift count not unsigned integer"));
6600       else
6601         {
6602           mpz_t val;
6603           mpz_init(val);
6604           Type* type;
6605           if (this->right_->integer_constant_value(true, val, &type))
6606             {
6607               if (mpz_sgn(val) < 0)
6608                 {
6609                   this->report_error(_("negative shift count"));
6610                   mpz_set_ui(val, 0);
6611                   Location rloc = this->right_->location();
6612                   this->right_ = Expression::make_integer(&val, right_type,
6613                                                           rloc);
6614                 }
6615             }
6616           mpz_clear(val);
6617         }
6618     }
6619 }
6620
6621 // Get a tree for a binary expression.
6622
6623 tree
6624 Binary_expression::do_get_tree(Translate_context* context)
6625 {
6626   tree left = this->left_->get_tree(context);
6627   tree right = this->right_->get_tree(context);
6628
6629   if (left == error_mark_node || right == error_mark_node)
6630     return error_mark_node;
6631
6632   enum tree_code code;
6633   bool use_left_type = true;
6634   bool is_shift_op = false;
6635   switch (this->op_)
6636     {
6637     case OPERATOR_EQEQ:
6638     case OPERATOR_NOTEQ:
6639     case OPERATOR_LT:
6640     case OPERATOR_LE:
6641     case OPERATOR_GT:
6642     case OPERATOR_GE:
6643       return Expression::comparison_tree(context, this->op_,
6644                                          this->left_->type(), left,
6645                                          this->right_->type(), right,
6646                                          this->location());
6647
6648     case OPERATOR_OROR:
6649       code = TRUTH_ORIF_EXPR;
6650       use_left_type = false;
6651       break;
6652     case OPERATOR_ANDAND:
6653       code = TRUTH_ANDIF_EXPR;
6654       use_left_type = false;
6655       break;
6656     case OPERATOR_PLUS:
6657       code = PLUS_EXPR;
6658       break;
6659     case OPERATOR_MINUS:
6660       code = MINUS_EXPR;
6661       break;
6662     case OPERATOR_OR:
6663       code = BIT_IOR_EXPR;
6664       break;
6665     case OPERATOR_XOR:
6666       code = BIT_XOR_EXPR;
6667       break;
6668     case OPERATOR_MULT:
6669       code = MULT_EXPR;
6670       break;
6671     case OPERATOR_DIV:
6672       {
6673         Type *t = this->left_->type();
6674         if (t->float_type() != NULL || t->complex_type() != NULL)
6675           code = RDIV_EXPR;
6676         else
6677           code = TRUNC_DIV_EXPR;
6678       }
6679       break;
6680     case OPERATOR_MOD:
6681       code = TRUNC_MOD_EXPR;
6682       break;
6683     case OPERATOR_LSHIFT:
6684       code = LSHIFT_EXPR;
6685       is_shift_op = true;
6686       break;
6687     case OPERATOR_RSHIFT:
6688       code = RSHIFT_EXPR;
6689       is_shift_op = true;
6690       break;
6691     case OPERATOR_AND:
6692       code = BIT_AND_EXPR;
6693       break;
6694     case OPERATOR_BITCLEAR:
6695       right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
6696       code = BIT_AND_EXPR;
6697       break;
6698     default:
6699       go_unreachable();
6700     }
6701
6702   tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
6703
6704   if (this->left_->type()->is_string_type())
6705     {
6706       go_assert(this->op_ == OPERATOR_PLUS);
6707       Type* st = Type::make_string_type();
6708       tree string_type = type_to_tree(st->get_backend(context->gogo()));
6709       static tree string_plus_decl;
6710       return Gogo::call_builtin(&string_plus_decl,
6711                                 this->location(),
6712                                 "__go_string_plus",
6713                                 2,
6714                                 string_type,
6715                                 string_type,
6716                                 left,
6717                                 string_type,
6718                                 right);
6719     }
6720
6721   tree compute_type = excess_precision_type(type);
6722   if (compute_type != NULL_TREE)
6723     {
6724       left = ::convert(compute_type, left);
6725       right = ::convert(compute_type, right);
6726     }
6727
6728   tree eval_saved = NULL_TREE;
6729   if (is_shift_op)
6730     {
6731       // Make sure the values are evaluated.
6732       if (!DECL_P(left) && TREE_SIDE_EFFECTS(left))
6733         {
6734           left = save_expr(left);
6735           eval_saved = left;
6736         }
6737       if (!DECL_P(right) && TREE_SIDE_EFFECTS(right))
6738         {
6739           right = save_expr(right);
6740           if (eval_saved == NULL_TREE)
6741             eval_saved = right;
6742           else
6743             eval_saved = fold_build2_loc(this->location().gcc_location(),
6744                                          COMPOUND_EXPR,
6745                                          void_type_node, eval_saved, right);
6746         }
6747     }
6748
6749   tree ret = fold_build2_loc(this->location().gcc_location(),
6750                              code,
6751                              compute_type != NULL_TREE ? compute_type : type,
6752                              left, right);
6753
6754   if (compute_type != NULL_TREE)
6755     ret = ::convert(type, ret);
6756
6757   // In Go, a shift larger than the size of the type is well-defined.
6758   // This is not true in GENERIC, so we need to insert a conditional.
6759   if (is_shift_op)
6760     {
6761       go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
6762       go_assert(this->left_->type()->integer_type() != NULL);
6763       int bits = TYPE_PRECISION(TREE_TYPE(left));
6764
6765       tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
6766                                  build_int_cst_type(TREE_TYPE(right), bits));
6767
6768       tree overflow_result = fold_convert_loc(this->location().gcc_location(),
6769                                               TREE_TYPE(left),
6770                                               integer_zero_node);
6771       if (this->op_ == OPERATOR_RSHIFT
6772           && !this->left_->type()->integer_type()->is_unsigned())
6773         {
6774           tree neg =
6775             fold_build2_loc(this->location().gcc_location(), LT_EXPR,
6776                             boolean_type_node, left,
6777                             fold_convert_loc(this->location().gcc_location(),
6778                                              TREE_TYPE(left),
6779                                              integer_zero_node));
6780           tree neg_one =
6781             fold_build2_loc(this->location().gcc_location(),
6782                             MINUS_EXPR, TREE_TYPE(left),
6783                             fold_convert_loc(this->location().gcc_location(),
6784                                              TREE_TYPE(left),
6785                                              integer_zero_node),
6786                             fold_convert_loc(this->location().gcc_location(),
6787                                              TREE_TYPE(left),
6788                                              integer_one_node));
6789           overflow_result =
6790             fold_build3_loc(this->location().gcc_location(), COND_EXPR,
6791                             TREE_TYPE(left), neg, neg_one,
6792                             overflow_result);
6793         }
6794
6795       ret = fold_build3_loc(this->location().gcc_location(), COND_EXPR,
6796                             TREE_TYPE(left), compare, ret, overflow_result);
6797
6798       if (eval_saved != NULL_TREE)
6799         ret = fold_build2_loc(this->location().gcc_location(), COMPOUND_EXPR,
6800                               TREE_TYPE(ret), eval_saved, ret);
6801     }
6802
6803   return ret;
6804 }
6805
6806 // Export a binary expression.
6807
6808 void
6809 Binary_expression::do_export(Export* exp) const
6810 {
6811   exp->write_c_string("(");
6812   this->left_->export_expression(exp);
6813   switch (this->op_)
6814     {
6815     case OPERATOR_OROR:
6816       exp->write_c_string(" || ");
6817       break;
6818     case OPERATOR_ANDAND:
6819       exp->write_c_string(" && ");
6820       break;
6821     case OPERATOR_EQEQ:
6822       exp->write_c_string(" == ");
6823       break;
6824     case OPERATOR_NOTEQ:
6825       exp->write_c_string(" != ");
6826       break;
6827     case OPERATOR_LT:
6828       exp->write_c_string(" < ");
6829       break;
6830     case OPERATOR_LE:
6831       exp->write_c_string(" <= ");
6832       break;
6833     case OPERATOR_GT:
6834       exp->write_c_string(" > ");
6835       break;
6836     case OPERATOR_GE:
6837       exp->write_c_string(" >= ");
6838       break;
6839     case OPERATOR_PLUS:
6840       exp->write_c_string(" + ");
6841       break;
6842     case OPERATOR_MINUS:
6843       exp->write_c_string(" - ");
6844       break;
6845     case OPERATOR_OR:
6846       exp->write_c_string(" | ");
6847       break;
6848     case OPERATOR_XOR:
6849       exp->write_c_string(" ^ ");
6850       break;
6851     case OPERATOR_MULT:
6852       exp->write_c_string(" * ");
6853       break;
6854     case OPERATOR_DIV:
6855       exp->write_c_string(" / ");
6856       break;
6857     case OPERATOR_MOD:
6858       exp->write_c_string(" % ");
6859       break;
6860     case OPERATOR_LSHIFT:
6861       exp->write_c_string(" << ");
6862       break;
6863     case OPERATOR_RSHIFT:
6864       exp->write_c_string(" >> ");
6865       break;
6866     case OPERATOR_AND:
6867       exp->write_c_string(" & ");
6868       break;
6869     case OPERATOR_BITCLEAR:
6870       exp->write_c_string(" &^ ");
6871       break;
6872     default:
6873       go_unreachable();
6874     }
6875   this->right_->export_expression(exp);
6876   exp->write_c_string(")");
6877 }
6878
6879 // Import a binary expression.
6880
6881 Expression*
6882 Binary_expression::do_import(Import* imp)
6883 {
6884   imp->require_c_string("(");
6885
6886   Expression* left = Expression::import_expression(imp);
6887
6888   Operator op;
6889   if (imp->match_c_string(" || "))
6890     {
6891       op = OPERATOR_OROR;
6892       imp->advance(4);
6893     }
6894   else if (imp->match_c_string(" && "))
6895     {
6896       op = OPERATOR_ANDAND;
6897       imp->advance(4);
6898     }
6899   else if (imp->match_c_string(" == "))
6900     {
6901       op = OPERATOR_EQEQ;
6902       imp->advance(4);
6903     }
6904   else if (imp->match_c_string(" != "))
6905     {
6906       op = OPERATOR_NOTEQ;
6907       imp->advance(4);
6908     }
6909   else if (imp->match_c_string(" < "))
6910     {
6911       op = OPERATOR_LT;
6912       imp->advance(3);
6913     }
6914   else if (imp->match_c_string(" <= "))
6915     {
6916       op = OPERATOR_LE;
6917       imp->advance(4);
6918     }
6919   else if (imp->match_c_string(" > "))
6920     {
6921       op = OPERATOR_GT;
6922       imp->advance(3);
6923     }
6924   else if (imp->match_c_string(" >= "))
6925     {
6926       op = OPERATOR_GE;
6927       imp->advance(4);
6928     }
6929   else if (imp->match_c_string(" + "))
6930     {
6931       op = OPERATOR_PLUS;
6932       imp->advance(3);
6933     }
6934   else if (imp->match_c_string(" - "))
6935     {
6936       op = OPERATOR_MINUS;
6937       imp->advance(3);
6938     }
6939   else if (imp->match_c_string(" | "))
6940     {
6941       op = OPERATOR_OR;
6942       imp->advance(3);
6943     }
6944   else if (imp->match_c_string(" ^ "))
6945     {
6946       op = OPERATOR_XOR;
6947       imp->advance(3);
6948     }
6949   else if (imp->match_c_string(" * "))
6950     {
6951       op = OPERATOR_MULT;
6952       imp->advance(3);
6953     }
6954   else if (imp->match_c_string(" / "))
6955     {
6956       op = OPERATOR_DIV;
6957       imp->advance(3);
6958     }
6959   else if (imp->match_c_string(" % "))
6960     {
6961       op = OPERATOR_MOD;
6962       imp->advance(3);
6963     }
6964   else if (imp->match_c_string(" << "))
6965     {
6966       op = OPERATOR_LSHIFT;
6967       imp->advance(4);
6968     }
6969   else if (imp->match_c_string(" >> "))
6970     {
6971       op = OPERATOR_RSHIFT;
6972       imp->advance(4);
6973     }
6974   else if (imp->match_c_string(" & "))
6975     {
6976       op = OPERATOR_AND;
6977       imp->advance(3);
6978     }
6979   else if (imp->match_c_string(" &^ "))
6980     {
6981       op = OPERATOR_BITCLEAR;
6982       imp->advance(4);
6983     }
6984   else
6985     {
6986       error_at(imp->location(), "unrecognized binary operator");
6987       return Expression::make_error(imp->location());
6988     }
6989
6990   Expression* right = Expression::import_expression(imp);
6991
6992   imp->require_c_string(")");
6993
6994   return Expression::make_binary(op, left, right, imp->location());
6995 }
6996
6997 // Dump ast representation of a binary expression.
6998
6999 void
7000 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
7001 {
7002   ast_dump_context->ostream() << "(";
7003   ast_dump_context->dump_expression(this->left_);
7004   ast_dump_context->ostream() << " ";
7005   ast_dump_context->dump_operator(this->op_);
7006   ast_dump_context->ostream() << " ";
7007   ast_dump_context->dump_expression(this->right_);
7008   ast_dump_context->ostream() << ") ";
7009 }
7010
7011 // Make a binary expression.
7012
7013 Expression*
7014 Expression::make_binary(Operator op, Expression* left, Expression* right,
7015                         Location location)
7016 {
7017   return new Binary_expression(op, left, right, location);
7018 }
7019
7020 // Implement a comparison.
7021
7022 tree
7023 Expression::comparison_tree(Translate_context* context, Operator op,
7024                             Type* left_type, tree left_tree,
7025                             Type* right_type, tree right_tree,
7026                             Location location)
7027 {
7028   enum tree_code code;
7029   switch (op)
7030     {
7031     case OPERATOR_EQEQ:
7032       code = EQ_EXPR;
7033       break;
7034     case OPERATOR_NOTEQ:
7035       code = NE_EXPR;
7036       break;
7037     case OPERATOR_LT:
7038       code = LT_EXPR;
7039       break;
7040     case OPERATOR_LE:
7041       code = LE_EXPR;
7042       break;
7043     case OPERATOR_GT:
7044       code = GT_EXPR;
7045       break;
7046     case OPERATOR_GE:
7047       code = GE_EXPR;
7048       break;
7049     default:
7050       go_unreachable();
7051     }
7052
7053   if (left_type->is_string_type() && right_type->is_string_type())
7054     {
7055       Type* st = Type::make_string_type();
7056       tree string_type = type_to_tree(st->get_backend(context->gogo()));
7057       static tree string_compare_decl;
7058       left_tree = Gogo::call_builtin(&string_compare_decl,
7059                                      location,
7060                                      "__go_strcmp",
7061                                      2,
7062                                      integer_type_node,
7063                                      string_type,
7064                                      left_tree,
7065                                      string_type,
7066                                      right_tree);
7067       right_tree = build_int_cst_type(integer_type_node, 0);
7068     }
7069   else if ((left_type->interface_type() != NULL
7070             && right_type->interface_type() == NULL
7071             && !right_type->is_nil_type())
7072            || (left_type->interface_type() == NULL
7073                && !left_type->is_nil_type()
7074                && right_type->interface_type() != NULL))
7075     {
7076       // Comparing an interface value to a non-interface value.
7077       if (left_type->interface_type() == NULL)
7078         {
7079           std::swap(left_type, right_type);
7080           std::swap(left_tree, right_tree);
7081         }
7082
7083       // The right operand is not an interface.  We need to take its
7084       // address if it is not a pointer.
7085       tree make_tmp;
7086       tree arg;
7087       if (right_type->points_to() != NULL)
7088         {
7089           make_tmp = NULL_TREE;
7090           arg = right_tree;
7091         }
7092       else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree))
7093         {
7094           make_tmp = NULL_TREE;
7095           arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
7096           if (DECL_P(right_tree))
7097             TREE_ADDRESSABLE(right_tree) = 1;
7098         }
7099       else
7100         {
7101           tree tmp = create_tmp_var(TREE_TYPE(right_tree),
7102                                     get_name(right_tree));
7103           DECL_IGNORED_P(tmp) = 0;
7104           DECL_INITIAL(tmp) = right_tree;
7105           TREE_ADDRESSABLE(tmp) = 1;
7106           make_tmp = build1(DECL_EXPR, void_type_node, tmp);
7107           SET_EXPR_LOCATION(make_tmp, location.gcc_location());
7108           arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
7109         }
7110       arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
7111
7112       tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
7113                                                             location);
7114
7115       if (left_type->interface_type()->is_empty())
7116         {
7117           static tree empty_interface_value_compare_decl;
7118           left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
7119                                          location,
7120                                          "__go_empty_interface_value_compare",
7121                                          3,
7122                                          integer_type_node,
7123                                          TREE_TYPE(left_tree),
7124                                          left_tree,
7125                                          TREE_TYPE(descriptor),
7126                                          descriptor,
7127                                          ptr_type_node,
7128                                          arg);
7129           if (left_tree == error_mark_node)
7130             return error_mark_node;
7131           // This can panic if the type is not comparable.
7132           TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
7133         }
7134       else
7135         {
7136           static tree interface_value_compare_decl;
7137           left_tree = Gogo::call_builtin(&interface_value_compare_decl,
7138                                          location,
7139                                          "__go_interface_value_compare",
7140                                          3,
7141                                          integer_type_node,
7142                                          TREE_TYPE(left_tree),
7143                                          left_tree,
7144                                          TREE_TYPE(descriptor),
7145                                          descriptor,
7146                                          ptr_type_node,
7147                                          arg);
7148           if (left_tree == error_mark_node)
7149             return error_mark_node;
7150           // This can panic if the type is not comparable.
7151           TREE_NOTHROW(interface_value_compare_decl) = 0;
7152         }
7153       right_tree = build_int_cst_type(integer_type_node, 0);
7154
7155       if (make_tmp != NULL_TREE)
7156         left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
7157                            left_tree);
7158     }
7159   else if (left_type->interface_type() != NULL
7160            && right_type->interface_type() != NULL)
7161     {
7162       if (left_type->interface_type()->is_empty()
7163           && right_type->interface_type()->is_empty())
7164         {
7165           static tree empty_interface_compare_decl;
7166           left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
7167                                          location,
7168                                          "__go_empty_interface_compare",
7169                                          2,
7170                                          integer_type_node,
7171                                          TREE_TYPE(left_tree),
7172                                          left_tree,
7173                                          TREE_TYPE(right_tree),
7174                                          right_tree);
7175           if (left_tree == error_mark_node)
7176             return error_mark_node;
7177           // This can panic if the type is uncomparable.
7178           TREE_NOTHROW(empty_interface_compare_decl) = 0;
7179         }
7180       else if (!left_type->interface_type()->is_empty()
7181                && !right_type->interface_type()->is_empty())
7182         {
7183           static tree interface_compare_decl;
7184           left_tree = Gogo::call_builtin(&interface_compare_decl,
7185                                          location,
7186                                          "__go_interface_compare",
7187                                          2,
7188                                          integer_type_node,
7189                                          TREE_TYPE(left_tree),
7190                                          left_tree,
7191                                          TREE_TYPE(right_tree),
7192                                          right_tree);
7193           if (left_tree == error_mark_node)
7194             return error_mark_node;
7195           // This can panic if the type is uncomparable.
7196           TREE_NOTHROW(interface_compare_decl) = 0;
7197         }
7198       else
7199         {
7200           if (left_type->interface_type()->is_empty())
7201             {
7202               go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7203               std::swap(left_type, right_type);
7204               std::swap(left_tree, right_tree);
7205             }
7206           go_assert(!left_type->interface_type()->is_empty());
7207           go_assert(right_type->interface_type()->is_empty());
7208           static tree interface_empty_compare_decl;
7209           left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
7210                                          location,
7211                                          "__go_interface_empty_compare",
7212                                          2,
7213                                          integer_type_node,
7214                                          TREE_TYPE(left_tree),
7215                                          left_tree,
7216                                          TREE_TYPE(right_tree),
7217                                          right_tree);
7218           if (left_tree == error_mark_node)
7219             return error_mark_node;
7220           // This can panic if the type is uncomparable.
7221           TREE_NOTHROW(interface_empty_compare_decl) = 0;
7222         }
7223
7224       right_tree = build_int_cst_type(integer_type_node, 0);
7225     }
7226
7227   if (left_type->is_nil_type()
7228       && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7229     {
7230       std::swap(left_type, right_type);
7231       std::swap(left_tree, right_tree);
7232     }
7233
7234   if (right_type->is_nil_type())
7235     {
7236       if (left_type->array_type() != NULL
7237           && left_type->array_type()->length() == NULL)
7238         {
7239           Array_type* at = left_type->array_type();
7240           left_tree = at->value_pointer_tree(context->gogo(), left_tree);
7241           right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
7242         }
7243       else if (left_type->interface_type() != NULL)
7244         {
7245           // An interface is nil if the first field is nil.
7246           tree left_type_tree = TREE_TYPE(left_tree);
7247           go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
7248           tree field = TYPE_FIELDS(left_type_tree);
7249           left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
7250                              field, NULL_TREE);
7251           right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
7252         }
7253       else
7254         {
7255           go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
7256           right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
7257         }
7258     }
7259
7260   if (left_tree == error_mark_node || right_tree == error_mark_node)
7261     return error_mark_node;
7262
7263   tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
7264   if (CAN_HAVE_LOCATION_P(ret))
7265     SET_EXPR_LOCATION(ret, location.gcc_location());
7266   return ret;
7267 }
7268
7269 // Class Bound_method_expression.
7270
7271 // Traversal.
7272
7273 int
7274 Bound_method_expression::do_traverse(Traverse* traverse)
7275 {
7276   return Expression::traverse(&this->expr_, traverse);
7277 }
7278
7279 // Return the type of a bound method expression.  The type of this
7280 // object is really the type of the method with no receiver.  We
7281 // should be able to get away with just returning the type of the
7282 // method.
7283
7284 Type*
7285 Bound_method_expression::do_type()
7286 {
7287   if (this->method_->is_function())
7288     return this->method_->func_value()->type();
7289   else if (this->method_->is_function_declaration())
7290     return this->method_->func_declaration_value()->type();
7291   else
7292     return Type::make_error_type();
7293 }
7294
7295 // Determine the types of a method expression.
7296
7297 void
7298 Bound_method_expression::do_determine_type(const Type_context*)
7299 {
7300   Function_type* fntype = this->type()->function_type();
7301   if (fntype == NULL || !fntype->is_method())
7302     this->expr_->determine_type_no_context();
7303   else
7304     {
7305       Type_context subcontext(fntype->receiver()->type(), false);
7306       this->expr_->determine_type(&subcontext);
7307     }
7308 }
7309
7310 // Check the types of a method expression.
7311
7312 void
7313 Bound_method_expression::do_check_types(Gogo*)
7314 {
7315   if (!this->method_->is_function()
7316       && !this->method_->is_function_declaration())
7317     this->report_error(_("object is not a method"));
7318   else
7319     {
7320       Type* rtype = this->type()->function_type()->receiver()->type()->deref();
7321       Type* etype = (this->expr_type_ != NULL
7322                      ? this->expr_type_
7323                      : this->expr_->type());
7324       etype = etype->deref();
7325       if (!Type::are_identical(rtype, etype, true, NULL))
7326         this->report_error(_("method type does not match object type"));
7327     }
7328 }
7329
7330 // Get the tree for a method expression.  There is no standard tree
7331 // representation for this.  The only places it may currently be used
7332 // are in a Call_expression or a Go_statement, which will take it
7333 // apart directly.  So this has nothing to do at present.
7334
7335 tree
7336 Bound_method_expression::do_get_tree(Translate_context*)
7337 {
7338   error_at(this->location(), "reference to method other than calling it");
7339   return error_mark_node;
7340 }
7341
7342 // Dump ast representation of a bound method expression.
7343
7344 void
7345 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7346     const
7347 {
7348   if (this->expr_type_ != NULL)
7349     ast_dump_context->ostream() << "(";
7350   ast_dump_context->dump_expression(this->expr_); 
7351   if (this->expr_type_ != NULL) 
7352     {
7353       ast_dump_context->ostream() << ":";
7354       ast_dump_context->dump_type(this->expr_type_);
7355       ast_dump_context->ostream() << ")";
7356     }
7357     
7358   ast_dump_context->ostream() << "." << this->method_->name();
7359 }
7360
7361 // Make a method expression.
7362
7363 Bound_method_expression*
7364 Expression::make_bound_method(Expression* expr, Named_object* method,
7365                               Location location)
7366 {
7367   return new Bound_method_expression(expr, method, location);
7368 }
7369
7370 // Class Builtin_call_expression.  This is used for a call to a
7371 // builtin function.
7372
7373 class Builtin_call_expression : public Call_expression
7374 {
7375  public:
7376   Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
7377                           bool is_varargs, Location location);
7378
7379  protected:
7380   // This overrides Call_expression::do_lower.
7381   Expression*
7382   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7383
7384   bool
7385   do_is_constant() const;
7386
7387   bool
7388   do_integer_constant_value(bool, mpz_t, Type**) const;
7389
7390   bool
7391   do_float_constant_value(mpfr_t, Type**) const;
7392
7393   bool
7394   do_complex_constant_value(mpfr_t, mpfr_t, Type**) const;
7395
7396   void
7397   do_discarding_value();
7398
7399   Type*
7400   do_type();
7401
7402   void
7403   do_determine_type(const Type_context*);
7404
7405   void
7406   do_check_types(Gogo*);
7407
7408   Expression*
7409   do_copy()
7410   {
7411     return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
7412                                        this->args()->copy(),
7413                                        this->is_varargs(),
7414                                        this->location());
7415   }
7416
7417   tree
7418   do_get_tree(Translate_context*);
7419
7420   void
7421   do_export(Export*) const;
7422
7423   virtual bool
7424   do_is_recover_call() const;
7425
7426   virtual void
7427   do_set_recover_arg(Expression*);
7428
7429  private:
7430   // The builtin functions.
7431   enum Builtin_function_code
7432     {
7433       BUILTIN_INVALID,
7434
7435       // Predeclared builtin functions.
7436       BUILTIN_APPEND,
7437       BUILTIN_CAP,
7438       BUILTIN_CLOSE,
7439       BUILTIN_COMPLEX,
7440       BUILTIN_COPY,
7441       BUILTIN_DELETE,
7442       BUILTIN_IMAG,
7443       BUILTIN_LEN,
7444       BUILTIN_MAKE,
7445       BUILTIN_NEW,
7446       BUILTIN_PANIC,
7447       BUILTIN_PRINT,
7448       BUILTIN_PRINTLN,
7449       BUILTIN_REAL,
7450       BUILTIN_RECOVER,
7451
7452       // Builtin functions from the unsafe package.
7453       BUILTIN_ALIGNOF,
7454       BUILTIN_OFFSETOF,
7455       BUILTIN_SIZEOF
7456     };
7457
7458   Expression*
7459   one_arg() const;
7460
7461   bool
7462   check_one_arg();
7463
7464   static Type*
7465   real_imag_type(Type*);
7466
7467   static Type*
7468   complex_type(Type*);
7469
7470   Expression*
7471   lower_make();
7472
7473   bool
7474   check_int_value(Expression*);
7475
7476   // A pointer back to the general IR structure.  This avoids a global
7477   // variable, or passing it around everywhere.
7478   Gogo* gogo_;
7479   // The builtin function being called.
7480   Builtin_function_code code_;
7481   // Used to stop endless loops when the length of an array uses len
7482   // or cap of the array itself.
7483   mutable bool seen_;
7484 };
7485
7486 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7487                                                  Expression* fn,
7488                                                  Expression_list* args,
7489                                                  bool is_varargs,
7490                                                  Location location)
7491   : Call_expression(fn, args, is_varargs, location),
7492     gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
7493 {
7494   Func_expression* fnexp = this->fn()->func_expression();
7495   go_assert(fnexp != NULL);
7496   const std::string& name(fnexp->named_object()->name());
7497   if (name == "append")
7498     this->code_ = BUILTIN_APPEND;
7499   else if (name == "cap")
7500     this->code_ = BUILTIN_CAP;
7501   else if (name == "close")
7502     this->code_ = BUILTIN_CLOSE;
7503   else if (name == "complex")
7504     this->code_ = BUILTIN_COMPLEX;
7505   else if (name == "copy")
7506     this->code_ = BUILTIN_COPY;
7507   else if (name == "delete")
7508     this->code_ = BUILTIN_DELETE;
7509   else if (name == "imag")
7510     this->code_ = BUILTIN_IMAG;
7511   else if (name == "len")
7512     this->code_ = BUILTIN_LEN;
7513   else if (name == "make")
7514     this->code_ = BUILTIN_MAKE;
7515   else if (name == "new")
7516     this->code_ = BUILTIN_NEW;
7517   else if (name == "panic")
7518     this->code_ = BUILTIN_PANIC;
7519   else if (name == "print")
7520     this->code_ = BUILTIN_PRINT;
7521   else if (name == "println")
7522     this->code_ = BUILTIN_PRINTLN;
7523   else if (name == "real")
7524     this->code_ = BUILTIN_REAL;
7525   else if (name == "recover")
7526     this->code_ = BUILTIN_RECOVER;
7527   else if (name == "Alignof")
7528     this->code_ = BUILTIN_ALIGNOF;
7529   else if (name == "Offsetof")
7530     this->code_ = BUILTIN_OFFSETOF;
7531   else if (name == "Sizeof")
7532     this->code_ = BUILTIN_SIZEOF;
7533   else
7534     go_unreachable();
7535 }
7536
7537 // Return whether this is a call to recover.  This is a virtual
7538 // function called from the parent class.
7539
7540 bool
7541 Builtin_call_expression::do_is_recover_call() const
7542 {
7543   if (this->classification() == EXPRESSION_ERROR)
7544     return false;
7545   return this->code_ == BUILTIN_RECOVER;
7546 }
7547
7548 // Set the argument for a call to recover.
7549
7550 void
7551 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7552 {
7553   const Expression_list* args = this->args();
7554   go_assert(args == NULL || args->empty());
7555   Expression_list* new_args = new Expression_list();
7556   new_args->push_back(arg);
7557   this->set_args(new_args);
7558 }
7559
7560 // A traversal class which looks for a call expression.
7561
7562 class Find_call_expression : public Traverse
7563 {
7564  public:
7565   Find_call_expression()
7566     : Traverse(traverse_expressions),
7567       found_(false)
7568   { }
7569
7570   int
7571   expression(Expression**);
7572
7573   bool
7574   found()
7575   { return this->found_; }
7576
7577  private:
7578   bool found_;
7579 };
7580
7581 int
7582 Find_call_expression::expression(Expression** pexpr)
7583 {
7584   if ((*pexpr)->call_expression() != NULL)
7585     {
7586       this->found_ = true;
7587       return TRAVERSE_EXIT;
7588     }
7589   return TRAVERSE_CONTINUE;
7590 }
7591
7592 // Lower a builtin call expression.  This turns new and make into
7593 // specific expressions.  We also convert to a constant if we can.
7594
7595 Expression*
7596 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7597                                   Statement_inserter* inserter, int)
7598 {
7599   if (this->classification() == EXPRESSION_ERROR)
7600     return this;
7601
7602   Location loc = this->location();
7603
7604   if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7605     {
7606       this->report_error(_("invalid use of %<...%> with builtin function"));
7607       return Expression::make_error(loc);
7608     }
7609
7610   if (this->is_constant())
7611     {
7612       // We can only lower len and cap if there are no function calls
7613       // in the arguments.  Otherwise we have to make the call.
7614       if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
7615         {
7616           Expression* arg = this->one_arg();
7617           if (!arg->is_constant())
7618             {
7619               Find_call_expression find_call;
7620               Expression::traverse(&arg, &find_call);
7621               if (find_call.found())
7622                 return this;
7623             }
7624         }
7625
7626       mpz_t ival;
7627       mpz_init(ival);
7628       Type* type;
7629       if (this->integer_constant_value(true, ival, &type))
7630         {
7631           Expression* ret = Expression::make_integer(&ival, type, loc);
7632           mpz_clear(ival);
7633           return ret;
7634         }
7635       mpz_clear(ival);
7636
7637       mpfr_t rval;
7638       mpfr_init(rval);
7639       if (this->float_constant_value(rval, &type))
7640         {
7641           Expression* ret = Expression::make_float(&rval, type, loc);
7642           mpfr_clear(rval);
7643           return ret;
7644         }
7645
7646       mpfr_t imag;
7647       mpfr_init(imag);
7648       if (this->complex_constant_value(rval, imag, &type))
7649         {
7650           Expression* ret = Expression::make_complex(&rval, &imag, type, loc);
7651           mpfr_clear(rval);
7652           mpfr_clear(imag);
7653           return ret;
7654         }
7655       mpfr_clear(rval);
7656       mpfr_clear(imag);
7657     }
7658
7659   switch (this->code_)
7660     {
7661     default:
7662       break;
7663
7664     case BUILTIN_NEW:
7665       {
7666         const Expression_list* args = this->args();
7667         if (args == NULL || args->size() < 1)
7668           this->report_error(_("not enough arguments"));
7669         else if (args->size() > 1)
7670           this->report_error(_("too many arguments"));
7671         else
7672           {
7673             Expression* arg = args->front();
7674             if (!arg->is_type_expression())
7675               {
7676                 error_at(arg->location(), "expected type");
7677                 this->set_is_error();
7678               }
7679             else
7680               return Expression::make_allocation(arg->type(), loc);
7681           }
7682       }
7683       break;
7684
7685     case BUILTIN_MAKE:
7686       return this->lower_make();
7687
7688     case BUILTIN_RECOVER:
7689       if (function != NULL)
7690         function->func_value()->set_calls_recover();
7691       else
7692         {
7693           // Calling recover outside of a function always returns the
7694           // nil empty interface.
7695           Type* eface = Type::make_empty_interface_type(loc);
7696           return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7697         }
7698       break;
7699
7700     case BUILTIN_APPEND:
7701       {
7702         // Lower the varargs.
7703         const Expression_list* args = this->args();
7704         if (args == NULL || args->empty())
7705           return this;
7706         Type* slice_type = args->front()->type();
7707         if (!slice_type->is_slice_type())
7708           {
7709             error_at(args->front()->location(), "argument 1 must be a slice");
7710             this->set_is_error();
7711             return this;
7712           }
7713         Type* element_type = slice_type->array_type()->element_type();
7714         this->lower_varargs(gogo, function, inserter,
7715                             Type::make_array_type(element_type, NULL),
7716                             2);
7717       }
7718       break;
7719
7720     case BUILTIN_DELETE:
7721       {
7722         // Lower to a runtime function call.
7723         const Expression_list* args = this->args();
7724         if (args == NULL || args->size() < 2)
7725           this->report_error(_("not enough arguments"));
7726         else if (args->size() > 2)
7727           this->report_error(_("too many arguments"));
7728         else if (args->front()->type()->map_type() == NULL)
7729           this->report_error(_("argument 1 must be a map"));
7730         else
7731           {
7732             // Since this function returns no value it must appear in
7733             // a statement by itself, so we don't have to worry about
7734             // order of evaluation of values around it.  Evaluate the
7735             // map first to get order of evaluation right.
7736             Map_type* mt = args->front()->type()->map_type();
7737             Temporary_statement* map_temp =
7738               Statement::make_temporary(mt, args->front(), loc);
7739             inserter->insert(map_temp);
7740
7741             Temporary_statement* key_temp =
7742               Statement::make_temporary(mt->key_type(), args->back(), loc);
7743             inserter->insert(key_temp);
7744
7745             Expression* e1 = Expression::make_temporary_reference(map_temp,
7746                                                                   loc);
7747             Expression* e2 = Expression::make_temporary_reference(key_temp,
7748                                                                   loc);
7749             e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7750             return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7751                                       2, e1, e2);
7752           }
7753       }
7754       break;
7755     }
7756
7757   return this;
7758 }
7759
7760 // Lower a make expression.
7761
7762 Expression*
7763 Builtin_call_expression::lower_make()
7764 {
7765   Location loc = this->location();
7766
7767   const Expression_list* args = this->args();
7768   if (args == NULL || args->size() < 1)
7769     {
7770       this->report_error(_("not enough arguments"));
7771       return Expression::make_error(this->location());
7772     }
7773
7774   Expression_list::const_iterator parg = args->begin();
7775
7776   Expression* first_arg = *parg;
7777   if (!first_arg->is_type_expression())
7778     {
7779       error_at(first_arg->location(), "expected type");
7780       this->set_is_error();
7781       return Expression::make_error(this->location());
7782     }
7783   Type* type = first_arg->type();
7784
7785   bool is_slice = false;
7786   bool is_map = false;
7787   bool is_chan = false;
7788   if (type->is_slice_type())
7789     is_slice = true;
7790   else if (type->map_type() != NULL)
7791     is_map = true;
7792   else if (type->channel_type() != NULL)
7793     is_chan = true;
7794   else
7795     {
7796       this->report_error(_("invalid type for make function"));
7797       return Expression::make_error(this->location());
7798     }
7799
7800   bool have_big_args = false;
7801   Type* uintptr_type = Type::lookup_integer_type("uintptr");
7802   int uintptr_bits = uintptr_type->integer_type()->bits();
7803
7804   ++parg;
7805   Expression* len_arg;
7806   if (parg == args->end())
7807     {
7808       if (is_slice)
7809         {
7810           this->report_error(_("length required when allocating a slice"));
7811           return Expression::make_error(this->location());
7812         }
7813
7814       mpz_t zval;
7815       mpz_init_set_ui(zval, 0);
7816       len_arg = Expression::make_integer(&zval, NULL, loc);
7817       mpz_clear(zval);
7818     }
7819   else
7820     {
7821       len_arg = *parg;
7822       if (!this->check_int_value(len_arg))
7823         {
7824           this->report_error(_("bad size for make"));
7825           return Expression::make_error(this->location());
7826         }
7827       if (len_arg->type()->integer_type() != NULL
7828           && len_arg->type()->integer_type()->bits() > uintptr_bits)
7829         have_big_args = true;
7830       ++parg;
7831     }
7832
7833   Expression* cap_arg = NULL;
7834   if (is_slice && parg != args->end())
7835     {
7836       cap_arg = *parg;
7837       if (!this->check_int_value(cap_arg))
7838         {
7839           this->report_error(_("bad capacity when making slice"));
7840           return Expression::make_error(this->location());
7841         }
7842       if (cap_arg->type()->integer_type() != NULL
7843           && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7844         have_big_args = true;
7845       ++parg;
7846     }
7847
7848   if (parg != args->end())
7849     {
7850       this->report_error(_("too many arguments to make"));
7851       return Expression::make_error(this->location());
7852     }
7853
7854   Location type_loc = first_arg->location();
7855   Expression* type_arg;
7856   if (is_slice || is_chan)
7857     type_arg = Expression::make_type_descriptor(type, type_loc);
7858   else if (is_map)
7859     type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7860   else
7861     go_unreachable();
7862
7863   Expression* call;
7864   if (is_slice)
7865     {
7866       if (cap_arg == NULL)
7867         call = Runtime::make_call((have_big_args
7868                                    ? Runtime::MAKESLICE1BIG
7869                                    : Runtime::MAKESLICE1),
7870                                   loc, 2, type_arg, len_arg);
7871       else
7872         call = Runtime::make_call((have_big_args
7873                                    ? Runtime::MAKESLICE2BIG
7874                                    : Runtime::MAKESLICE2),
7875                                   loc, 3, type_arg, len_arg, cap_arg);
7876     }
7877   else if (is_map)
7878     call = Runtime::make_call((have_big_args
7879                                ? Runtime::MAKEMAPBIG
7880                                : Runtime::MAKEMAP),
7881                               loc, 2, type_arg, len_arg);
7882   else if (is_chan)
7883     call = Runtime::make_call((have_big_args
7884                                ? Runtime::MAKECHANBIG
7885                                : Runtime::MAKECHAN),
7886                               loc, 2, type_arg, len_arg);
7887   else
7888     go_unreachable();
7889
7890   return Expression::make_unsafe_cast(type, call, loc);
7891 }
7892
7893 // Return whether an expression has an integer value.  Report an error
7894 // if not.  This is used when handling calls to the predeclared make
7895 // function.
7896
7897 bool
7898 Builtin_call_expression::check_int_value(Expression* e)
7899 {
7900   if (e->type()->integer_type() != NULL)
7901     return true;
7902
7903   // Check for a floating point constant with integer value.
7904   mpfr_t fval;
7905   mpfr_init(fval);
7906
7907   Type* dummy;
7908   if (e->float_constant_value(fval, &dummy) && mpfr_integer_p(fval))
7909     {
7910       mpz_t ival;
7911       mpz_init(ival);
7912
7913       bool ok = false;
7914
7915       mpfr_clear_overflow();
7916       mpfr_clear_erangeflag();
7917       mpfr_get_z(ival, fval, GMP_RNDN);
7918       if (!mpfr_overflow_p()
7919           && !mpfr_erangeflag_p()
7920           && mpz_sgn(ival) >= 0)
7921         {
7922           Named_type* ntype = Type::lookup_integer_type("int");
7923           Integer_type* inttype = ntype->integer_type();
7924           mpz_t max;
7925           mpz_init_set_ui(max, 1);
7926           mpz_mul_2exp(max, max, inttype->bits() - 1);
7927           ok = mpz_cmp(ival, max) < 0;
7928           mpz_clear(max);
7929         }
7930       mpz_clear(ival);
7931
7932       if (ok)
7933         {
7934           mpfr_clear(fval);
7935           return true;
7936         }
7937     }
7938
7939   mpfr_clear(fval);
7940
7941   return false;
7942 }
7943
7944 // Return the type of the real or imag functions, given the type of
7945 // the argument.  We need to map complex to float, complex64 to
7946 // float32, and complex128 to float64, so it has to be done by name.
7947 // This returns NULL if it can't figure out the type.
7948
7949 Type*
7950 Builtin_call_expression::real_imag_type(Type* arg_type)
7951 {
7952   if (arg_type == NULL || arg_type->is_abstract())
7953     return NULL;
7954   Named_type* nt = arg_type->named_type();
7955   if (nt == NULL)
7956     return NULL;
7957   while (nt->real_type()->named_type() != NULL)
7958     nt = nt->real_type()->named_type();
7959   if (nt->name() == "complex64")
7960     return Type::lookup_float_type("float32");
7961   else if (nt->name() == "complex128")
7962     return Type::lookup_float_type("float64");
7963   else
7964     return NULL;
7965 }
7966
7967 // Return the type of the complex function, given the type of one of the
7968 // argments.  Like real_imag_type, we have to map by name.
7969
7970 Type*
7971 Builtin_call_expression::complex_type(Type* arg_type)
7972 {
7973   if (arg_type == NULL || arg_type->is_abstract())
7974     return NULL;
7975   Named_type* nt = arg_type->named_type();
7976   if (nt == NULL)
7977     return NULL;
7978   while (nt->real_type()->named_type() != NULL)
7979     nt = nt->real_type()->named_type();
7980   if (nt->name() == "float32")
7981     return Type::lookup_complex_type("complex64");
7982   else if (nt->name() == "float64")
7983     return Type::lookup_complex_type("complex128");
7984   else
7985     return NULL;
7986 }
7987
7988 // Return a single argument, or NULL if there isn't one.
7989
7990 Expression*
7991 Builtin_call_expression::one_arg() const
7992 {
7993   const Expression_list* args = this->args();
7994   if (args->size() != 1)
7995     return NULL;
7996   return args->front();
7997 }
7998
7999 // Return whether this is constant: len of a string, or len or cap of
8000 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
8001
8002 bool
8003 Builtin_call_expression::do_is_constant() const
8004 {
8005   switch (this->code_)
8006     {
8007     case BUILTIN_LEN:
8008     case BUILTIN_CAP:
8009       {
8010         if (this->seen_)
8011           return false;
8012
8013         Expression* arg = this->one_arg();
8014         if (arg == NULL)
8015           return false;
8016         Type* arg_type = arg->type();
8017
8018         if (arg_type->points_to() != NULL
8019             && arg_type->points_to()->array_type() != NULL
8020             && !arg_type->points_to()->is_slice_type())
8021           arg_type = arg_type->points_to();
8022
8023         if (arg_type->array_type() != NULL
8024             && arg_type->array_type()->length() != NULL)
8025           return true;
8026
8027         if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8028           {
8029             this->seen_ = true;
8030             bool ret = arg->is_constant();
8031             this->seen_ = false;
8032             return ret;
8033           }
8034       }
8035       break;
8036
8037     case BUILTIN_SIZEOF:
8038     case BUILTIN_ALIGNOF:
8039       return this->one_arg() != NULL;
8040
8041     case BUILTIN_OFFSETOF:
8042       {
8043         Expression* arg = this->one_arg();
8044         if (arg == NULL)
8045           return false;
8046         return arg->field_reference_expression() != NULL;
8047       }
8048
8049     case BUILTIN_COMPLEX:
8050       {
8051         const Expression_list* args = this->args();
8052         if (args != NULL && args->size() == 2)
8053           return args->front()->is_constant() && args->back()->is_constant();
8054       }
8055       break;
8056
8057     case BUILTIN_REAL:
8058     case BUILTIN_IMAG:
8059       {
8060         Expression* arg = this->one_arg();
8061         return arg != NULL && arg->is_constant();
8062       }
8063
8064     default:
8065       break;
8066     }
8067
8068   return false;
8069 }
8070
8071 // Return an integer constant value if possible.
8072
8073 bool
8074 Builtin_call_expression::do_integer_constant_value(bool iota_is_constant,
8075                                                    mpz_t val,
8076                                                    Type** ptype) const
8077 {
8078   if (this->code_ == BUILTIN_LEN
8079       || this->code_ == BUILTIN_CAP)
8080     {
8081       Expression* arg = this->one_arg();
8082       if (arg == NULL)
8083         return false;
8084       Type* arg_type = arg->type();
8085
8086       if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8087         {
8088           std::string sval;
8089           if (arg->string_constant_value(&sval))
8090             {
8091               mpz_set_ui(val, sval.length());
8092               *ptype = Type::lookup_integer_type("int");
8093               return true;
8094             }
8095         }
8096
8097       if (arg_type->points_to() != NULL
8098           && arg_type->points_to()->array_type() != NULL
8099           && !arg_type->points_to()->is_slice_type())
8100         arg_type = arg_type->points_to();
8101
8102       if (arg_type->array_type() != NULL
8103           && arg_type->array_type()->length() != NULL)
8104         {
8105           if (this->seen_)
8106             return false;
8107           Expression* e = arg_type->array_type()->length();
8108           this->seen_ = true;
8109           bool r = e->integer_constant_value(iota_is_constant, val, ptype);
8110           this->seen_ = false;
8111           if (r)
8112             {
8113               *ptype = Type::lookup_integer_type("int");
8114               return true;
8115             }
8116         }
8117     }
8118   else if (this->code_ == BUILTIN_SIZEOF
8119            || this->code_ == BUILTIN_ALIGNOF)
8120     {
8121       Expression* arg = this->one_arg();
8122       if (arg == NULL)
8123         return false;
8124       Type* arg_type = arg->type();
8125       if (arg_type->is_error())
8126         return false;
8127       if (arg_type->is_abstract())
8128         return false;
8129       if (arg_type->named_type() != NULL)
8130         arg_type->named_type()->convert(this->gogo_);
8131
8132       unsigned int ret;
8133       if (this->code_ == BUILTIN_SIZEOF)
8134         {
8135           if (!arg_type->backend_type_size(this->gogo_, &ret))
8136             return false;
8137         }
8138       else if (this->code_ == BUILTIN_ALIGNOF)
8139         {
8140           if (arg->field_reference_expression() == NULL)
8141             {
8142               if (!arg_type->backend_type_align(this->gogo_, &ret))
8143                 return false;
8144             }
8145           else
8146             {
8147               // Calling unsafe.Alignof(s.f) returns the alignment of
8148               // the type of f when it is used as a field in a struct.
8149               if (!arg_type->backend_type_field_align(this->gogo_, &ret))
8150                 return false;
8151             }
8152         }
8153       else
8154         go_unreachable();
8155
8156       mpz_set_ui(val, ret);
8157       *ptype = NULL;
8158       return true;
8159     }
8160   else if (this->code_ == BUILTIN_OFFSETOF)
8161     {
8162       Expression* arg = this->one_arg();
8163       if (arg == NULL)
8164         return false;
8165       Field_reference_expression* farg = arg->field_reference_expression();
8166       if (farg == NULL)
8167         return false;
8168       Expression* struct_expr = farg->expr();
8169       Type* st = struct_expr->type();
8170       if (st->struct_type() == NULL)
8171         return false;
8172       if (st->named_type() != NULL)
8173         st->named_type()->convert(this->gogo_);
8174       unsigned int offset;
8175       if (!st->struct_type()->backend_field_offset(this->gogo_,
8176                                                    farg->field_index(),
8177                                                    &offset))
8178         return false;
8179       mpz_set_ui(val, offset);
8180       return true;
8181     }
8182   return false;
8183 }
8184
8185 // Return a floating point constant value if possible.
8186
8187 bool
8188 Builtin_call_expression::do_float_constant_value(mpfr_t val,
8189                                                  Type** ptype) const
8190 {
8191   if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8192     {
8193       Expression* arg = this->one_arg();
8194       if (arg == NULL)
8195         return false;
8196
8197       mpfr_t real;
8198       mpfr_t imag;
8199       mpfr_init(real);
8200       mpfr_init(imag);
8201
8202       bool ret = false;
8203       Type* type;
8204       if (arg->complex_constant_value(real, imag, &type))
8205         {
8206           if (this->code_ == BUILTIN_REAL)
8207             mpfr_set(val, real, GMP_RNDN);
8208           else
8209             mpfr_set(val, imag, GMP_RNDN);
8210           *ptype = Builtin_call_expression::real_imag_type(type);
8211           ret = true;
8212         }
8213
8214       mpfr_clear(real);
8215       mpfr_clear(imag);
8216       return ret;
8217     }
8218
8219   return false;
8220 }
8221
8222 // Return a complex constant value if possible.
8223
8224 bool
8225 Builtin_call_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
8226                                                    Type** ptype) const
8227 {
8228   if (this->code_ == BUILTIN_COMPLEX)
8229     {
8230       const Expression_list* args = this->args();
8231       if (args == NULL || args->size() != 2)
8232         return false;
8233
8234       mpfr_t r;
8235       mpfr_init(r);
8236       Type* rtype;
8237       if (!args->front()->float_constant_value(r, &rtype))
8238         {
8239           mpfr_clear(r);
8240           return false;
8241         }
8242
8243       mpfr_t i;
8244       mpfr_init(i);
8245
8246       bool ret = false;
8247       Type* itype;
8248       if (args->back()->float_constant_value(i, &itype)
8249           && Type::are_identical(rtype, itype, false, NULL))
8250         {
8251           mpfr_set(real, r, GMP_RNDN);
8252           mpfr_set(imag, i, GMP_RNDN);
8253           *ptype = Builtin_call_expression::complex_type(rtype);
8254           ret = true;
8255         }
8256
8257       mpfr_clear(r);
8258       mpfr_clear(i);
8259
8260       return ret;
8261     }
8262
8263   return false;
8264 }
8265
8266 // Give an error if we are discarding the value of an expression which
8267 // should not normally be discarded.  We don't give an error for
8268 // discarding the value of an ordinary function call, but we do for
8269 // builtin functions, purely for consistency with the gc compiler.
8270
8271 void
8272 Builtin_call_expression::do_discarding_value()
8273 {
8274   switch (this->code_)
8275     {
8276     case BUILTIN_INVALID:
8277     default:
8278       go_unreachable();
8279
8280     case BUILTIN_APPEND:
8281     case BUILTIN_CAP:
8282     case BUILTIN_COMPLEX:
8283     case BUILTIN_IMAG:
8284     case BUILTIN_LEN:
8285     case BUILTIN_MAKE:
8286     case BUILTIN_NEW:
8287     case BUILTIN_REAL:
8288     case BUILTIN_ALIGNOF:
8289     case BUILTIN_OFFSETOF:
8290     case BUILTIN_SIZEOF:
8291       this->unused_value_error();
8292       break;
8293
8294     case BUILTIN_CLOSE:
8295     case BUILTIN_COPY:
8296     case BUILTIN_DELETE:
8297     case BUILTIN_PANIC:
8298     case BUILTIN_PRINT:
8299     case BUILTIN_PRINTLN:
8300     case BUILTIN_RECOVER:
8301       break;
8302     }
8303 }
8304
8305 // Return the type.
8306
8307 Type*
8308 Builtin_call_expression::do_type()
8309 {
8310   switch (this->code_)
8311     {
8312     case BUILTIN_INVALID:
8313     default:
8314       go_unreachable();
8315
8316     case BUILTIN_NEW:
8317     case BUILTIN_MAKE:
8318       {
8319         const Expression_list* args = this->args();
8320         if (args == NULL || args->empty())
8321           return Type::make_error_type();
8322         return Type::make_pointer_type(args->front()->type());
8323       }
8324
8325     case BUILTIN_CAP:
8326     case BUILTIN_COPY:
8327     case BUILTIN_LEN:
8328     case BUILTIN_ALIGNOF:
8329     case BUILTIN_OFFSETOF:
8330     case BUILTIN_SIZEOF:
8331       return Type::lookup_integer_type("int");
8332
8333     case BUILTIN_CLOSE:
8334     case BUILTIN_DELETE:
8335     case BUILTIN_PANIC:
8336     case BUILTIN_PRINT:
8337     case BUILTIN_PRINTLN:
8338       return Type::make_void_type();
8339
8340     case BUILTIN_RECOVER:
8341       return Type::make_empty_interface_type(Linemap::predeclared_location());
8342
8343     case BUILTIN_APPEND:
8344       {
8345         const Expression_list* args = this->args();
8346         if (args == NULL || args->empty())
8347           return Type::make_error_type();
8348         return args->front()->type();
8349       }
8350
8351     case BUILTIN_REAL:
8352     case BUILTIN_IMAG:
8353       {
8354         Expression* arg = this->one_arg();
8355         if (arg == NULL)
8356           return Type::make_error_type();
8357         Type* t = arg->type();
8358         if (t->is_abstract())
8359           t = t->make_non_abstract_type();
8360         t = Builtin_call_expression::real_imag_type(t);
8361         if (t == NULL)
8362           t = Type::make_error_type();
8363         return t;
8364       }
8365
8366     case BUILTIN_COMPLEX:
8367       {
8368         const Expression_list* args = this->args();
8369         if (args == NULL || args->size() != 2)
8370           return Type::make_error_type();
8371         Type* t = args->front()->type();
8372         if (t->is_abstract())
8373           {
8374             t = args->back()->type();
8375             if (t->is_abstract())
8376               t = t->make_non_abstract_type();
8377           }
8378         t = Builtin_call_expression::complex_type(t);
8379         if (t == NULL)
8380           t = Type::make_error_type();
8381         return t;
8382       }
8383     }
8384 }
8385
8386 // Determine the type.
8387
8388 void
8389 Builtin_call_expression::do_determine_type(const Type_context* context)
8390 {
8391   if (!this->determining_types())
8392     return;
8393
8394   this->fn()->determine_type_no_context();
8395
8396   const Expression_list* args = this->args();
8397
8398   bool is_print;
8399   Type* arg_type = NULL;
8400   switch (this->code_)
8401     {
8402     case BUILTIN_PRINT:
8403     case BUILTIN_PRINTLN:
8404       // Do not force a large integer constant to "int".
8405       is_print = true;
8406       break;
8407
8408     case BUILTIN_REAL:
8409     case BUILTIN_IMAG:
8410       arg_type = Builtin_call_expression::complex_type(context->type);
8411       is_print = false;
8412       break;
8413
8414     case BUILTIN_COMPLEX:
8415       {
8416         // For the complex function the type of one operand can
8417         // determine the type of the other, as in a binary expression.
8418         arg_type = Builtin_call_expression::real_imag_type(context->type);
8419         if (args != NULL && args->size() == 2)
8420           {
8421             Type* t1 = args->front()->type();
8422             Type* t2 = args->front()->type();
8423             if (!t1->is_abstract())
8424               arg_type = t1;
8425             else if (!t2->is_abstract())
8426               arg_type = t2;
8427           }
8428         is_print = false;
8429       }
8430       break;
8431
8432     default:
8433       is_print = false;
8434       break;
8435     }
8436
8437   if (args != NULL)
8438     {
8439       for (Expression_list::const_iterator pa = args->begin();
8440            pa != args->end();
8441            ++pa)
8442         {
8443           Type_context subcontext;
8444           subcontext.type = arg_type;
8445
8446           if (is_print)
8447             {
8448               // We want to print large constants, we so can't just
8449               // use the appropriate nonabstract type.  Use uint64 for
8450               // an integer if we know it is nonnegative, otherwise
8451               // use int64 for a integer, otherwise use float64 for a
8452               // float or complex128 for a complex.
8453               Type* want_type = NULL;
8454               Type* atype = (*pa)->type();
8455               if (atype->is_abstract())
8456                 {
8457                   if (atype->integer_type() != NULL)
8458                     {
8459                       mpz_t val;
8460                       mpz_init(val);
8461                       Type* dummy;
8462                       if (this->integer_constant_value(true, val, &dummy)
8463                           && mpz_sgn(val) >= 0)
8464                         want_type = Type::lookup_integer_type("uint64");
8465                       else
8466                         want_type = Type::lookup_integer_type("int64");
8467                       mpz_clear(val);
8468                     }
8469                   else if (atype->float_type() != NULL)
8470                     want_type = Type::lookup_float_type("float64");
8471                   else if (atype->complex_type() != NULL)
8472                     want_type = Type::lookup_complex_type("complex128");
8473                   else if (atype->is_abstract_string_type())
8474                     want_type = Type::lookup_string_type();
8475                   else if (atype->is_abstract_boolean_type())
8476                     want_type = Type::lookup_bool_type();
8477                   else
8478                     go_unreachable();
8479                   subcontext.type = want_type;
8480                 }
8481             }
8482
8483           (*pa)->determine_type(&subcontext);
8484         }
8485     }
8486 }
8487
8488 // If there is exactly one argument, return true.  Otherwise give an
8489 // error message and return false.
8490
8491 bool
8492 Builtin_call_expression::check_one_arg()
8493 {
8494   const Expression_list* args = this->args();
8495   if (args == NULL || args->size() < 1)
8496     {
8497       this->report_error(_("not enough arguments"));
8498       return false;
8499     }
8500   else if (args->size() > 1)
8501     {
8502       this->report_error(_("too many arguments"));
8503       return false;
8504     }
8505   if (args->front()->is_error_expression()
8506       || args->front()->type()->is_error())
8507     {
8508       this->set_is_error();
8509       return false;
8510     }
8511   return true;
8512 }
8513
8514 // Check argument types for a builtin function.
8515
8516 void
8517 Builtin_call_expression::do_check_types(Gogo*)
8518 {
8519   switch (this->code_)
8520     {
8521     case BUILTIN_INVALID:
8522     case BUILTIN_NEW:
8523     case BUILTIN_MAKE:
8524     case BUILTIN_DELETE:
8525       return;
8526
8527     case BUILTIN_LEN:
8528     case BUILTIN_CAP:
8529       {
8530         // The single argument may be either a string or an array or a
8531         // map or a channel, or a pointer to a closed array.
8532         if (this->check_one_arg())
8533           {
8534             Type* arg_type = this->one_arg()->type();
8535             if (arg_type->points_to() != NULL
8536                 && arg_type->points_to()->array_type() != NULL
8537                 && !arg_type->points_to()->is_slice_type())
8538               arg_type = arg_type->points_to();
8539             if (this->code_ == BUILTIN_CAP)
8540               {
8541                 if (!arg_type->is_error()
8542                     && arg_type->array_type() == NULL
8543                     && arg_type->channel_type() == NULL)
8544                   this->report_error(_("argument must be array or slice "
8545                                        "or channel"));
8546               }
8547             else
8548               {
8549                 if (!arg_type->is_error()
8550                     && !arg_type->is_string_type()
8551                     && arg_type->array_type() == NULL
8552                     && arg_type->map_type() == NULL
8553                     && arg_type->channel_type() == NULL)
8554                   this->report_error(_("argument must be string or "
8555                                        "array or slice or map or channel"));
8556               }
8557           }
8558       }
8559       break;
8560
8561     case BUILTIN_PRINT:
8562     case BUILTIN_PRINTLN:
8563       {
8564         const Expression_list* args = this->args();
8565         if (args == NULL)
8566           {
8567             if (this->code_ == BUILTIN_PRINT)
8568               warning_at(this->location(), 0,
8569                          "no arguments for builtin function %<%s%>",
8570                          (this->code_ == BUILTIN_PRINT
8571                           ? "print"
8572                           : "println"));
8573           }
8574         else
8575           {
8576             for (Expression_list::const_iterator p = args->begin();
8577                  p != args->end();
8578                  ++p)
8579               {
8580                 Type* type = (*p)->type();
8581                 if (type->is_error()
8582                     || type->is_string_type()
8583                     || type->integer_type() != NULL
8584                     || type->float_type() != NULL
8585                     || type->complex_type() != NULL
8586                     || type->is_boolean_type()
8587                     || type->points_to() != NULL
8588                     || type->interface_type() != NULL
8589                     || type->channel_type() != NULL
8590                     || type->map_type() != NULL
8591                     || type->function_type() != NULL
8592                     || type->is_slice_type())
8593                   ;
8594                 else if ((*p)->is_type_expression())
8595                   {
8596                     // If this is a type expression it's going to give
8597                     // an error anyhow, so we don't need one here.
8598                   }
8599                 else
8600                   this->report_error(_("unsupported argument type to "
8601                                        "builtin function"));
8602               }
8603           }
8604       }
8605       break;
8606
8607     case BUILTIN_CLOSE:
8608       if (this->check_one_arg())
8609         {
8610           if (this->one_arg()->type()->channel_type() == NULL)
8611             this->report_error(_("argument must be channel"));
8612           else if (!this->one_arg()->type()->channel_type()->may_send())
8613             this->report_error(_("cannot close receive-only channel"));
8614         }
8615       break;
8616
8617     case BUILTIN_PANIC:
8618     case BUILTIN_SIZEOF:
8619     case BUILTIN_ALIGNOF:
8620       this->check_one_arg();
8621       break;
8622
8623     case BUILTIN_RECOVER:
8624       if (this->args() != NULL && !this->args()->empty())
8625         this->report_error(_("too many arguments"));
8626       break;
8627
8628     case BUILTIN_OFFSETOF:
8629       if (this->check_one_arg())
8630         {
8631           Expression* arg = this->one_arg();
8632           if (arg->field_reference_expression() == NULL)
8633             this->report_error(_("argument must be a field reference"));
8634         }
8635       break;
8636
8637     case BUILTIN_COPY:
8638       {
8639         const Expression_list* args = this->args();
8640         if (args == NULL || args->size() < 2)
8641           {
8642             this->report_error(_("not enough arguments"));
8643             break;
8644           }
8645         else if (args->size() > 2)
8646           {
8647             this->report_error(_("too many arguments"));
8648             break;
8649           }
8650         Type* arg1_type = args->front()->type();
8651         Type* arg2_type = args->back()->type();
8652         if (arg1_type->is_error() || arg2_type->is_error())
8653           break;
8654
8655         Type* e1;
8656         if (arg1_type->is_slice_type())
8657           e1 = arg1_type->array_type()->element_type();
8658         else
8659           {
8660             this->report_error(_("left argument must be a slice"));
8661             break;
8662           }
8663
8664         if (arg2_type->is_slice_type())
8665           {
8666             Type* e2 = arg2_type->array_type()->element_type();
8667             if (!Type::are_identical(e1, e2, true, NULL))
8668               this->report_error(_("element types must be the same"));
8669           }
8670         else if (arg2_type->is_string_type())
8671           {
8672             if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8673               this->report_error(_("first argument must be []byte"));
8674           }
8675         else
8676             this->report_error(_("second argument must be slice or string"));
8677       }
8678       break;
8679
8680     case BUILTIN_APPEND:
8681       {
8682         const Expression_list* args = this->args();
8683         if (args == NULL || args->size() < 2)
8684           {
8685             this->report_error(_("not enough arguments"));
8686             break;
8687           }
8688         if (args->size() > 2)
8689           {
8690             this->report_error(_("too many arguments"));
8691             break;
8692           }
8693         if (args->front()->type()->is_error()
8694             || args->back()->type()->is_error())
8695           break;
8696
8697         Array_type* at = args->front()->type()->array_type();
8698         Type* e = at->element_type();
8699
8700         // The language permits appending a string to a []byte, as a
8701         // special case.
8702         if (args->back()->type()->is_string_type())
8703           {
8704             if (e->integer_type() != NULL && e->integer_type()->is_byte())
8705               break;
8706           }
8707
8708         // The language says that the second argument must be
8709         // assignable to a slice of the element type of the first
8710         // argument.  We already know the first argument is a slice
8711         // type.
8712         Type* arg2_type = Type::make_array_type(e, NULL);
8713         std::string reason;
8714         if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8715           {
8716             if (reason.empty())
8717               this->report_error(_("argument 2 has invalid type"));
8718             else
8719               {
8720                 error_at(this->location(), "argument 2 has invalid type (%s)",
8721                          reason.c_str());
8722                 this->set_is_error();
8723               }
8724           }
8725         break;
8726       }
8727
8728     case BUILTIN_REAL:
8729     case BUILTIN_IMAG:
8730       if (this->check_one_arg())
8731         {
8732           if (this->one_arg()->type()->complex_type() == NULL)
8733             this->report_error(_("argument must have complex type"));
8734         }
8735       break;
8736
8737     case BUILTIN_COMPLEX:
8738       {
8739         const Expression_list* args = this->args();
8740         if (args == NULL || args->size() < 2)
8741           this->report_error(_("not enough arguments"));
8742         else if (args->size() > 2)
8743           this->report_error(_("too many arguments"));
8744         else if (args->front()->is_error_expression()
8745                  || args->front()->type()->is_error()
8746                  || args->back()->is_error_expression()
8747                  || args->back()->type()->is_error())
8748           this->set_is_error();
8749         else if (!Type::are_identical(args->front()->type(),
8750                                       args->back()->type(), true, NULL))
8751           this->report_error(_("complex arguments must have identical types"));
8752         else if (args->front()->type()->float_type() == NULL)
8753           this->report_error(_("complex arguments must have "
8754                                "floating-point type"));
8755       }
8756       break;
8757
8758     default:
8759       go_unreachable();
8760     }
8761 }
8762
8763 // Return the tree for a builtin function.
8764
8765 tree
8766 Builtin_call_expression::do_get_tree(Translate_context* context)
8767 {
8768   Gogo* gogo = context->gogo();
8769   Location location = this->location();
8770   switch (this->code_)
8771     {
8772     case BUILTIN_INVALID:
8773     case BUILTIN_NEW:
8774     case BUILTIN_MAKE:
8775       go_unreachable();
8776
8777     case BUILTIN_LEN:
8778     case BUILTIN_CAP:
8779       {
8780         const Expression_list* args = this->args();
8781         go_assert(args != NULL && args->size() == 1);
8782         Expression* arg = *args->begin();
8783         Type* arg_type = arg->type();
8784
8785         if (this->seen_)
8786           {
8787             go_assert(saw_errors());
8788             return error_mark_node;
8789           }
8790         this->seen_ = true;
8791
8792         tree arg_tree = arg->get_tree(context);
8793
8794         this->seen_ = false;
8795
8796         if (arg_tree == error_mark_node)
8797           return error_mark_node;
8798
8799         if (arg_type->points_to() != NULL)
8800           {
8801             arg_type = arg_type->points_to();
8802             go_assert(arg_type->array_type() != NULL
8803                        && !arg_type->is_slice_type());
8804             go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
8805             arg_tree = build_fold_indirect_ref(arg_tree);
8806           }
8807
8808         tree val_tree;
8809         if (this->code_ == BUILTIN_LEN)
8810           {
8811             if (arg_type->is_string_type())
8812               val_tree = String_type::length_tree(gogo, arg_tree);
8813             else if (arg_type->array_type() != NULL)
8814               {
8815                 if (this->seen_)
8816                   {
8817                     go_assert(saw_errors());
8818                     return error_mark_node;
8819                   }
8820                 this->seen_ = true;
8821                 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
8822                 this->seen_ = false;
8823               }
8824             else if (arg_type->map_type() != NULL)
8825               {
8826                 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8827                 static tree map_len_fndecl;
8828                 val_tree = Gogo::call_builtin(&map_len_fndecl,
8829                                               location,
8830                                               "__go_map_len",
8831                                               1,
8832                                               integer_type_node,
8833                                               arg_type_tree,
8834                                               arg_tree);
8835               }
8836             else if (arg_type->channel_type() != NULL)
8837               {
8838                 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8839                 static tree chan_len_fndecl;
8840                 val_tree = Gogo::call_builtin(&chan_len_fndecl,
8841                                               location,
8842                                               "__go_chan_len",
8843                                               1,
8844                                               integer_type_node,
8845                                               arg_type_tree,
8846                                               arg_tree);
8847               }
8848             else
8849               go_unreachable();
8850           }
8851         else
8852           {
8853             if (arg_type->array_type() != NULL)
8854               {
8855                 if (this->seen_)
8856                   {
8857                     go_assert(saw_errors());
8858                     return error_mark_node;
8859                   }
8860                 this->seen_ = true;
8861                 val_tree = arg_type->array_type()->capacity_tree(gogo,
8862                                                                  arg_tree);
8863                 this->seen_ = false;
8864               }
8865             else if (arg_type->channel_type() != NULL)
8866               {
8867                 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8868                 static tree chan_cap_fndecl;
8869                 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
8870                                               location,
8871                                               "__go_chan_cap",
8872                                               1,
8873                                               integer_type_node,
8874                                               arg_type_tree,
8875                                               arg_tree);
8876               }
8877             else
8878               go_unreachable();
8879           }
8880
8881         if (val_tree == error_mark_node)
8882           return error_mark_node;
8883
8884         Type* int_type = Type::lookup_integer_type("int");
8885         tree type_tree = type_to_tree(int_type->get_backend(gogo));
8886         if (type_tree == TREE_TYPE(val_tree))
8887           return val_tree;
8888         else
8889           return fold(convert_to_integer(type_tree, val_tree));
8890       }
8891
8892     case BUILTIN_PRINT:
8893     case BUILTIN_PRINTLN:
8894       {
8895         const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8896         tree stmt_list = NULL_TREE;
8897
8898         const Expression_list* call_args = this->args();
8899         if (call_args != NULL)
8900           {
8901             for (Expression_list::const_iterator p = call_args->begin();
8902                  p != call_args->end();
8903                  ++p)
8904               {
8905                 if (is_ln && p != call_args->begin())
8906                   {
8907                     static tree print_space_fndecl;
8908                     tree call = Gogo::call_builtin(&print_space_fndecl,
8909                                                    location,
8910                                                    "__go_print_space",
8911                                                    0,
8912                                                    void_type_node);
8913                     if (call == error_mark_node)
8914                       return error_mark_node;
8915                     append_to_statement_list(call, &stmt_list);
8916                   }
8917
8918                 Type* type = (*p)->type();
8919
8920                 tree arg = (*p)->get_tree(context);
8921                 if (arg == error_mark_node)
8922                   return error_mark_node;
8923
8924                 tree* pfndecl;
8925                 const char* fnname;
8926                 if (type->is_string_type())
8927                   {
8928                     static tree print_string_fndecl;
8929                     pfndecl = &print_string_fndecl;
8930                     fnname = "__go_print_string";
8931                   }
8932                 else if (type->integer_type() != NULL
8933                          && type->integer_type()->is_unsigned())
8934                   {
8935                     static tree print_uint64_fndecl;
8936                     pfndecl = &print_uint64_fndecl;
8937                     fnname = "__go_print_uint64";
8938                     Type* itype = Type::lookup_integer_type("uint64");
8939                     Btype* bitype = itype->get_backend(gogo);
8940                     arg = fold_convert_loc(location.gcc_location(),
8941                                            type_to_tree(bitype), arg);
8942                   }
8943                 else if (type->integer_type() != NULL)
8944                   {
8945                     static tree print_int64_fndecl;
8946                     pfndecl = &print_int64_fndecl;
8947                     fnname = "__go_print_int64";
8948                     Type* itype = Type::lookup_integer_type("int64");
8949                     Btype* bitype = itype->get_backend(gogo);
8950                     arg = fold_convert_loc(location.gcc_location(),
8951                                            type_to_tree(bitype), arg);
8952                   }
8953                 else if (type->float_type() != NULL)
8954                   {
8955                     static tree print_double_fndecl;
8956                     pfndecl = &print_double_fndecl;
8957                     fnname = "__go_print_double";
8958                     arg = fold_convert_loc(location.gcc_location(),
8959                                            double_type_node, arg);
8960                   }
8961                 else if (type->complex_type() != NULL)
8962                   {
8963                     static tree print_complex_fndecl;
8964                     pfndecl = &print_complex_fndecl;
8965                     fnname = "__go_print_complex";
8966                     arg = fold_convert_loc(location.gcc_location(),
8967                                            complex_double_type_node, arg);
8968                   }
8969                 else if (type->is_boolean_type())
8970                   {
8971                     static tree print_bool_fndecl;
8972                     pfndecl = &print_bool_fndecl;
8973                     fnname = "__go_print_bool";
8974                   }
8975                 else if (type->points_to() != NULL
8976                          || type->channel_type() != NULL
8977                          || type->map_type() != NULL
8978                          || type->function_type() != NULL)
8979                   {
8980                     static tree print_pointer_fndecl;
8981                     pfndecl = &print_pointer_fndecl;
8982                     fnname = "__go_print_pointer";
8983                     arg = fold_convert_loc(location.gcc_location(),
8984                                            ptr_type_node, arg);
8985                   }
8986                 else if (type->interface_type() != NULL)
8987                   {
8988                     if (type->interface_type()->is_empty())
8989                       {
8990                         static tree print_empty_interface_fndecl;
8991                         pfndecl = &print_empty_interface_fndecl;
8992                         fnname = "__go_print_empty_interface";
8993                       }
8994                     else
8995                       {
8996                         static tree print_interface_fndecl;
8997                         pfndecl = &print_interface_fndecl;
8998                         fnname = "__go_print_interface";
8999                       }
9000                   }
9001                 else if (type->is_slice_type())
9002                   {
9003                     static tree print_slice_fndecl;
9004                     pfndecl = &print_slice_fndecl;
9005                     fnname = "__go_print_slice";
9006                   }
9007                 else
9008                   {
9009                     go_assert(saw_errors());
9010                     return error_mark_node;
9011                   }
9012
9013                 tree call = Gogo::call_builtin(pfndecl,
9014                                                location,
9015                                                fnname,
9016                                                1,
9017                                                void_type_node,
9018                                                TREE_TYPE(arg),
9019                                                arg);
9020                 if (call == error_mark_node)
9021                   return error_mark_node;
9022                 append_to_statement_list(call, &stmt_list);
9023               }
9024           }
9025
9026         if (is_ln)
9027           {
9028             static tree print_nl_fndecl;
9029             tree call = Gogo::call_builtin(&print_nl_fndecl,
9030                                            location,
9031                                            "__go_print_nl",
9032                                            0,
9033                                            void_type_node);
9034             if (call == error_mark_node)
9035               return error_mark_node;
9036             append_to_statement_list(call, &stmt_list);
9037           }
9038
9039         return stmt_list;
9040       }
9041
9042     case BUILTIN_PANIC:
9043       {
9044         const Expression_list* args = this->args();
9045         go_assert(args != NULL && args->size() == 1);
9046         Expression* arg = args->front();
9047         tree arg_tree = arg->get_tree(context);
9048         if (arg_tree == error_mark_node)
9049           return error_mark_node;
9050         Type *empty =
9051           Type::make_empty_interface_type(Linemap::predeclared_location());
9052         arg_tree = Expression::convert_for_assignment(context, empty,
9053                                                       arg->type(),
9054                                                       arg_tree, location);
9055         static tree panic_fndecl;
9056         tree call = Gogo::call_builtin(&panic_fndecl,
9057                                        location,
9058                                        "__go_panic",
9059                                        1,
9060                                        void_type_node,
9061                                        TREE_TYPE(arg_tree),
9062                                        arg_tree);
9063         if (call == error_mark_node)
9064           return error_mark_node;
9065         // This function will throw an exception.
9066         TREE_NOTHROW(panic_fndecl) = 0;
9067         // This function will not return.
9068         TREE_THIS_VOLATILE(panic_fndecl) = 1;
9069         return call;
9070       }
9071
9072     case BUILTIN_RECOVER:
9073       {
9074         // The argument is set when building recover thunks.  It's a
9075         // boolean value which is true if we can recover a value now.
9076         const Expression_list* args = this->args();
9077         go_assert(args != NULL && args->size() == 1);
9078         Expression* arg = args->front();
9079         tree arg_tree = arg->get_tree(context);
9080         if (arg_tree == error_mark_node)
9081           return error_mark_node;
9082
9083         Type *empty =
9084           Type::make_empty_interface_type(Linemap::predeclared_location());
9085         tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
9086
9087         Type* nil_type = Type::make_nil_type();
9088         Expression* nil = Expression::make_nil(location);
9089         tree nil_tree = nil->get_tree(context);
9090         tree empty_nil_tree = Expression::convert_for_assignment(context,
9091                                                                  empty,
9092                                                                  nil_type,
9093                                                                  nil_tree,
9094                                                                  location);
9095
9096         // We need to handle a deferred call to recover specially,
9097         // because it changes whether it can recover a panic or not.
9098         // See test7 in test/recover1.go.
9099         tree call;
9100         if (this->is_deferred())
9101           {
9102             static tree deferred_recover_fndecl;
9103             call = Gogo::call_builtin(&deferred_recover_fndecl,
9104                                       location,
9105                                       "__go_deferred_recover",
9106                                       0,
9107                                       empty_tree);
9108           }
9109         else
9110           {
9111             static tree recover_fndecl;
9112             call = Gogo::call_builtin(&recover_fndecl,
9113                                       location,
9114                                       "__go_recover",
9115                                       0,
9116                                       empty_tree);
9117           }
9118         if (call == error_mark_node)
9119           return error_mark_node;
9120         return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
9121                                arg_tree, call, empty_nil_tree);
9122       }
9123
9124     case BUILTIN_CLOSE:
9125       {
9126         const Expression_list* args = this->args();
9127         go_assert(args != NULL && args->size() == 1);
9128         Expression* arg = args->front();
9129         tree arg_tree = arg->get_tree(context);
9130         if (arg_tree == error_mark_node)
9131           return error_mark_node;
9132         static tree close_fndecl;
9133         return Gogo::call_builtin(&close_fndecl,
9134                                   location,
9135                                   "__go_builtin_close",
9136                                   1,
9137                                   void_type_node,
9138                                   TREE_TYPE(arg_tree),
9139                                   arg_tree);
9140       }
9141
9142     case BUILTIN_SIZEOF:
9143     case BUILTIN_OFFSETOF:
9144     case BUILTIN_ALIGNOF:
9145       {
9146         mpz_t val;
9147         mpz_init(val);
9148         Type* dummy;
9149         bool b = this->integer_constant_value(true, val, &dummy);
9150         if (!b)
9151           {
9152             go_assert(saw_errors());
9153             return error_mark_node;
9154           }
9155         Type* int_type = Type::lookup_integer_type("int");
9156         tree type = type_to_tree(int_type->get_backend(gogo));
9157         tree ret = Expression::integer_constant_tree(val, type);
9158         mpz_clear(val);
9159         return ret;
9160       }
9161
9162     case BUILTIN_COPY:
9163       {
9164         const Expression_list* args = this->args();
9165         go_assert(args != NULL && args->size() == 2);
9166         Expression* arg1 = args->front();
9167         Expression* arg2 = args->back();
9168
9169         tree arg1_tree = arg1->get_tree(context);
9170         tree arg2_tree = arg2->get_tree(context);
9171         if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
9172           return error_mark_node;
9173
9174         Type* arg1_type = arg1->type();
9175         Array_type* at = arg1_type->array_type();
9176         arg1_tree = save_expr(arg1_tree);
9177         tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
9178         tree arg1_len = at->length_tree(gogo, arg1_tree);
9179         if (arg1_val == error_mark_node || arg1_len == error_mark_node)
9180           return error_mark_node;
9181
9182         Type* arg2_type = arg2->type();
9183         tree arg2_val;
9184         tree arg2_len;
9185         if (arg2_type->is_slice_type())
9186           {
9187             at = arg2_type->array_type();
9188             arg2_tree = save_expr(arg2_tree);
9189             arg2_val = at->value_pointer_tree(gogo, arg2_tree);
9190             arg2_len = at->length_tree(gogo, arg2_tree);
9191           }
9192         else
9193           {
9194             arg2_tree = save_expr(arg2_tree);
9195             arg2_val = String_type::bytes_tree(gogo, arg2_tree);
9196             arg2_len = String_type::length_tree(gogo, arg2_tree);
9197           }
9198         if (arg2_val == error_mark_node || arg2_len == error_mark_node)
9199           return error_mark_node;
9200
9201         arg1_len = save_expr(arg1_len);
9202         arg2_len = save_expr(arg2_len);
9203         tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
9204                                    TREE_TYPE(arg1_len),
9205                                    fold_build2_loc(location.gcc_location(),
9206                                                    LT_EXPR, boolean_type_node,
9207                                                    arg1_len, arg2_len),
9208                                    arg1_len, arg2_len);
9209         len = save_expr(len);
9210
9211         Type* element_type = at->element_type();
9212         Btype* element_btype = element_type->get_backend(gogo);
9213         tree element_type_tree = type_to_tree(element_btype);
9214         if (element_type_tree == error_mark_node)
9215           return error_mark_node;
9216         tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9217         tree bytecount = fold_convert_loc(location.gcc_location(),
9218                                           TREE_TYPE(element_size), len);
9219         bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
9220                                     TREE_TYPE(element_size),
9221                                     bytecount, element_size);
9222         bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
9223                                      bytecount);
9224
9225         arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
9226                                     arg1_val);
9227         arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
9228                                     arg2_val);
9229
9230         static tree copy_fndecl;
9231         tree call = Gogo::call_builtin(&copy_fndecl,
9232                                        location,
9233                                        "__go_copy",
9234                                        3,
9235                                        void_type_node,
9236                                        ptr_type_node,
9237                                        arg1_val,
9238                                        ptr_type_node,
9239                                        arg2_val,
9240                                        size_type_node,
9241                                        bytecount);
9242         if (call == error_mark_node)
9243           return error_mark_node;
9244
9245         return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
9246                                TREE_TYPE(len), call, len);
9247       }
9248
9249     case BUILTIN_APPEND:
9250       {
9251         const Expression_list* args = this->args();
9252         go_assert(args != NULL && args->size() == 2);
9253         Expression* arg1 = args->front();
9254         Expression* arg2 = args->back();
9255
9256         tree arg1_tree = arg1->get_tree(context);
9257         tree arg2_tree = arg2->get_tree(context);
9258         if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
9259           return error_mark_node;
9260
9261         Array_type* at = arg1->type()->array_type();
9262         Type* element_type = at->element_type()->forwarded();
9263
9264         tree arg2_val;
9265         tree arg2_len;
9266         tree element_size;
9267         if (arg2->type()->is_string_type()
9268             && element_type->integer_type() != NULL
9269             && element_type->integer_type()->is_byte())
9270           {
9271             arg2_tree = save_expr(arg2_tree);
9272             arg2_val = String_type::bytes_tree(gogo, arg2_tree);
9273             arg2_len = String_type::length_tree(gogo, arg2_tree);
9274             element_size = size_int(1);
9275           }
9276         else
9277           {
9278             arg2_tree = Expression::convert_for_assignment(context, at,
9279                                                            arg2->type(),
9280                                                            arg2_tree,
9281                                                            location);
9282             if (arg2_tree == error_mark_node)
9283               return error_mark_node;
9284
9285             arg2_tree = save_expr(arg2_tree);
9286
9287              arg2_val = at->value_pointer_tree(gogo, arg2_tree);
9288              arg2_len = at->length_tree(gogo, arg2_tree);
9289
9290              Btype* element_btype = element_type->get_backend(gogo);
9291              tree element_type_tree = type_to_tree(element_btype);
9292              if (element_type_tree == error_mark_node)
9293                return error_mark_node;
9294              element_size = TYPE_SIZE_UNIT(element_type_tree);
9295           }
9296
9297         arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
9298                                     arg2_val);
9299         arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
9300                                     arg2_len);
9301         element_size = fold_convert_loc(location.gcc_location(), size_type_node,
9302                                         element_size);
9303
9304         if (arg2_val == error_mark_node
9305             || arg2_len == error_mark_node
9306             || element_size == error_mark_node)
9307           return error_mark_node;
9308
9309         // We rebuild the decl each time since the slice types may
9310         // change.
9311         tree append_fndecl = NULL_TREE;
9312         return Gogo::call_builtin(&append_fndecl,
9313                                   location,
9314                                   "__go_append",
9315                                   4,
9316                                   TREE_TYPE(arg1_tree),
9317                                   TREE_TYPE(arg1_tree),
9318                                   arg1_tree,
9319                                   ptr_type_node,
9320                                   arg2_val,
9321                                   size_type_node,
9322                                   arg2_len,
9323                                   size_type_node,
9324                                   element_size);
9325       }
9326
9327     case BUILTIN_REAL:
9328     case BUILTIN_IMAG:
9329       {
9330         const Expression_list* args = this->args();
9331         go_assert(args != NULL && args->size() == 1);
9332         Expression* arg = args->front();
9333         tree arg_tree = arg->get_tree(context);
9334         if (arg_tree == error_mark_node)
9335           return error_mark_node;
9336         go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
9337         if (this->code_ == BUILTIN_REAL)
9338           return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
9339                                  TREE_TYPE(TREE_TYPE(arg_tree)),
9340                                  arg_tree);
9341         else
9342           return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
9343                                  TREE_TYPE(TREE_TYPE(arg_tree)),
9344                                  arg_tree);
9345       }
9346
9347     case BUILTIN_COMPLEX:
9348       {
9349         const Expression_list* args = this->args();
9350         go_assert(args != NULL && args->size() == 2);
9351         tree r = args->front()->get_tree(context);
9352         tree i = args->back()->get_tree(context);
9353         if (r == error_mark_node || i == error_mark_node)
9354           return error_mark_node;
9355         go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
9356                    == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
9357         go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
9358         return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
9359                                build_complex_type(TREE_TYPE(r)),
9360                                r, i);
9361       }
9362
9363     default:
9364       go_unreachable();
9365     }
9366 }
9367
9368 // We have to support exporting a builtin call expression, because
9369 // code can set a constant to the result of a builtin expression.
9370
9371 void
9372 Builtin_call_expression::do_export(Export* exp) const
9373 {
9374   bool ok = false;
9375
9376   mpz_t val;
9377   mpz_init(val);
9378   Type* dummy;
9379   if (this->integer_constant_value(true, val, &dummy))
9380     {
9381       Integer_expression::export_integer(exp, val);
9382       ok = true;
9383     }
9384   mpz_clear(val);
9385
9386   if (!ok)
9387     {
9388       mpfr_t fval;
9389       mpfr_init(fval);
9390       if (this->float_constant_value(fval, &dummy))
9391         {
9392           Float_expression::export_float(exp, fval);
9393           ok = true;
9394         }
9395       mpfr_clear(fval);
9396     }
9397
9398   if (!ok)
9399     {
9400       mpfr_t real;
9401       mpfr_t imag;
9402       mpfr_init(real);
9403       mpfr_init(imag);
9404       if (this->complex_constant_value(real, imag, &dummy))
9405         {
9406           Complex_expression::export_complex(exp, real, imag);
9407           ok = true;
9408         }
9409       mpfr_clear(real);
9410       mpfr_clear(imag);
9411     }
9412
9413   if (!ok)
9414     {
9415       error_at(this->location(), "value is not constant");
9416       return;
9417     }
9418
9419   // A trailing space lets us reliably identify the end of the number.
9420   exp->write_c_string(" ");
9421 }
9422
9423 // Class Call_expression.
9424
9425 // Traversal.
9426
9427 int
9428 Call_expression::do_traverse(Traverse* traverse)
9429 {
9430   if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9431     return TRAVERSE_EXIT;
9432   if (this->args_ != NULL)
9433     {
9434       if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9435         return TRAVERSE_EXIT;
9436     }
9437   return TRAVERSE_CONTINUE;
9438 }
9439
9440 // Lower a call statement.
9441
9442 Expression*
9443 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9444                           Statement_inserter* inserter, int)
9445 {
9446   Location loc = this->location();
9447
9448   // A type cast can look like a function call.
9449   if (this->fn_->is_type_expression()
9450       && this->args_ != NULL
9451       && this->args_->size() == 1)
9452     return Expression::make_cast(this->fn_->type(), this->args_->front(),
9453                                  loc);
9454
9455   // Recognize a call to a builtin function.
9456   Func_expression* fne = this->fn_->func_expression();
9457   if (fne != NULL
9458       && fne->named_object()->is_function_declaration()
9459       && fne->named_object()->func_declaration_value()->type()->is_builtin())
9460     return new Builtin_call_expression(gogo, this->fn_, this->args_,
9461                                        this->is_varargs_, loc);
9462
9463   // Handle an argument which is a call to a function which returns
9464   // multiple results.
9465   if (this->args_ != NULL
9466       && this->args_->size() == 1
9467       && this->args_->front()->call_expression() != NULL
9468       && this->fn_->type()->function_type() != NULL)
9469     {
9470       Function_type* fntype = this->fn_->type()->function_type();
9471       size_t rc = this->args_->front()->call_expression()->result_count();
9472       if (rc > 1
9473           && fntype->parameters() != NULL
9474           && (fntype->parameters()->size() == rc
9475               || (fntype->is_varargs()
9476                   && fntype->parameters()->size() - 1 <= rc)))
9477         {
9478           Call_expression* call = this->args_->front()->call_expression();
9479           Expression_list* args = new Expression_list;
9480           for (size_t i = 0; i < rc; ++i)
9481             args->push_back(Expression::make_call_result(call, i));
9482           // We can't return a new call expression here, because this
9483           // one may be referenced by Call_result expressions.  We
9484           // also can't delete the old arguments, because we may still
9485           // traverse them somewhere up the call stack.  FIXME.
9486           this->args_ = args;
9487         }
9488     }
9489
9490   // If this call returns multiple results, create a temporary
9491   // variable for each result.
9492   size_t rc = this->result_count();
9493   if (rc > 1 && this->results_ == NULL)
9494     {
9495       std::vector<Temporary_statement*>* temps =
9496         new std::vector<Temporary_statement*>;
9497       temps->reserve(rc);
9498       const Typed_identifier_list* results =
9499         this->fn_->type()->function_type()->results();
9500       for (Typed_identifier_list::const_iterator p = results->begin();
9501            p != results->end();
9502            ++p)
9503         {
9504           Temporary_statement* temp = Statement::make_temporary(p->type(),
9505                                                                 NULL, loc);
9506           inserter->insert(temp);
9507           temps->push_back(temp);
9508         }
9509       this->results_ = temps;
9510     }
9511
9512   // Handle a call to a varargs function by packaging up the extra
9513   // parameters.
9514   if (this->fn_->type()->function_type() != NULL
9515       && this->fn_->type()->function_type()->is_varargs())
9516     {
9517       Function_type* fntype = this->fn_->type()->function_type();
9518       const Typed_identifier_list* parameters = fntype->parameters();
9519       go_assert(parameters != NULL && !parameters->empty());
9520       Type* varargs_type = parameters->back().type();
9521       this->lower_varargs(gogo, function, inserter, varargs_type,
9522                           parameters->size());
9523     }
9524
9525   // If this is call to a method, call the method directly passing the
9526   // object as the first parameter.
9527   Bound_method_expression* bme = this->fn_->bound_method_expression();
9528   if (bme != NULL)
9529     {
9530       Named_object* method = bme->method();
9531       Expression* first_arg = bme->first_argument();
9532
9533       // We always pass a pointer when calling a method.
9534       if (first_arg->type()->points_to() == NULL
9535           && !first_arg->type()->is_error())
9536         {
9537           first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9538           // We may need to create a temporary variable so that we can
9539           // take the address.  We can't do that here because it will
9540           // mess up the order of evaluation.
9541           Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9542           ue->set_create_temp();
9543         }
9544
9545       // If we are calling a method which was inherited from an
9546       // embedded struct, and the method did not get a stub, then the
9547       // first type may be wrong.
9548       Type* fatype = bme->first_argument_type();
9549       if (fatype != NULL)
9550         {
9551           if (fatype->points_to() == NULL)
9552             fatype = Type::make_pointer_type(fatype);
9553           first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9554         }
9555
9556       Expression_list* new_args = new Expression_list();
9557       new_args->push_back(first_arg);
9558       if (this->args_ != NULL)
9559         {
9560           for (Expression_list::const_iterator p = this->args_->begin();
9561                p != this->args_->end();
9562                ++p)
9563             new_args->push_back(*p);
9564         }
9565
9566       // We have to change in place because this structure may be
9567       // referenced by Call_result_expressions.  We can't delete the
9568       // old arguments, because we may be traversing them up in some
9569       // caller.  FIXME.
9570       this->args_ = new_args;
9571       this->fn_ = Expression::make_func_reference(method, NULL,
9572                                                   bme->location());
9573     }
9574
9575   return this;
9576 }
9577
9578 // Lower a call to a varargs function.  FUNCTION is the function in
9579 // which the call occurs--it's not the function we are calling.
9580 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9581 // PARAM_COUNT is the number of parameters of the function we are
9582 // calling; the last of these parameters will be the varargs
9583 // parameter.
9584
9585 void
9586 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9587                                Statement_inserter* inserter,
9588                                Type* varargs_type, size_t param_count)
9589 {
9590   if (this->varargs_are_lowered_)
9591     return;
9592
9593   Location loc = this->location();
9594
9595   go_assert(param_count > 0);
9596   go_assert(varargs_type->is_slice_type());
9597
9598   size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9599   if (arg_count < param_count - 1)
9600     {
9601       // Not enough arguments; will be caught in check_types.
9602       return;
9603     }
9604
9605   Expression_list* old_args = this->args_;
9606   Expression_list* new_args = new Expression_list();
9607   bool push_empty_arg = false;
9608   if (old_args == NULL || old_args->empty())
9609     {
9610       go_assert(param_count == 1);
9611       push_empty_arg = true;
9612     }
9613   else
9614     {
9615       Expression_list::const_iterator pa;
9616       int i = 1;
9617       for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9618         {
9619           if (static_cast<size_t>(i) == param_count)
9620             break;
9621           new_args->push_back(*pa);
9622         }
9623
9624       // We have reached the varargs parameter.
9625
9626       bool issued_error = false;
9627       if (pa == old_args->end())
9628         push_empty_arg = true;
9629       else if (pa + 1 == old_args->end() && this->is_varargs_)
9630         new_args->push_back(*pa);
9631       else if (this->is_varargs_)
9632         {
9633           this->report_error(_("too many arguments"));
9634           return;
9635         }
9636       else
9637         {
9638           Type* element_type = varargs_type->array_type()->element_type();
9639           Expression_list* vals = new Expression_list;
9640           for (; pa != old_args->end(); ++pa, ++i)
9641             {
9642               // Check types here so that we get a better message.
9643               Type* patype = (*pa)->type();
9644               Location paloc = (*pa)->location();
9645               if (!this->check_argument_type(i, element_type, patype,
9646                                              paloc, issued_error))
9647                 continue;
9648               vals->push_back(*pa);
9649             }
9650           Expression* val =
9651             Expression::make_slice_composite_literal(varargs_type, vals, loc);
9652           gogo->lower_expression(function, inserter, &val);
9653           new_args->push_back(val);
9654         }
9655     }
9656
9657   if (push_empty_arg)
9658     new_args->push_back(Expression::make_nil(loc));
9659
9660   // We can't return a new call expression here, because this one may
9661   // be referenced by Call_result expressions.  FIXME.  We can't
9662   // delete OLD_ARGS because we may have both a Call_expression and a
9663   // Builtin_call_expression which refer to them.  FIXME.
9664   this->args_ = new_args;
9665   this->varargs_are_lowered_ = true;
9666 }
9667
9668 // Get the function type.  This can return NULL in error cases.
9669
9670 Function_type*
9671 Call_expression::get_function_type() const
9672 {
9673   return this->fn_->type()->function_type();
9674 }
9675
9676 // Return the number of values which this call will return.
9677
9678 size_t
9679 Call_expression::result_count() const
9680 {
9681   const Function_type* fntype = this->get_function_type();
9682   if (fntype == NULL)
9683     return 0;
9684   if (fntype->results() == NULL)
9685     return 0;
9686   return fntype->results()->size();
9687 }
9688
9689 // Return the temporary which holds a result.
9690
9691 Temporary_statement*
9692 Call_expression::result(size_t i) const
9693 {
9694   if (this->results_ == NULL || this->results_->size() <= i)
9695     {
9696       go_assert(saw_errors());
9697       return NULL;
9698     }
9699   return (*this->results_)[i];
9700 }
9701
9702 // Return whether this is a call to the predeclared function recover.
9703
9704 bool
9705 Call_expression::is_recover_call() const
9706 {
9707   return this->do_is_recover_call();
9708 }
9709
9710 // Set the argument to the recover function.
9711
9712 void
9713 Call_expression::set_recover_arg(Expression* arg)
9714 {
9715   this->do_set_recover_arg(arg);
9716 }
9717
9718 // Virtual functions also implemented by Builtin_call_expression.
9719
9720 bool
9721 Call_expression::do_is_recover_call() const
9722 {
9723   return false;
9724 }
9725
9726 void
9727 Call_expression::do_set_recover_arg(Expression*)
9728 {
9729   go_unreachable();
9730 }
9731
9732 // We have found an error with this call expression; return true if
9733 // we should report it.
9734
9735 bool
9736 Call_expression::issue_error()
9737 {
9738   if (this->issued_error_)
9739     return false;
9740   else
9741     {
9742       this->issued_error_ = true;
9743       return true;
9744     }
9745 }
9746
9747 // Get the type.
9748
9749 Type*
9750 Call_expression::do_type()
9751 {
9752   if (this->type_ != NULL)
9753     return this->type_;
9754
9755   Type* ret;
9756   Function_type* fntype = this->get_function_type();
9757   if (fntype == NULL)
9758     return Type::make_error_type();
9759
9760   const Typed_identifier_list* results = fntype->results();
9761   if (results == NULL)
9762     ret = Type::make_void_type();
9763   else if (results->size() == 1)
9764     ret = results->begin()->type();
9765   else
9766     ret = Type::make_call_multiple_result_type(this);
9767
9768   this->type_ = ret;
9769
9770   return this->type_;
9771 }
9772
9773 // Determine types for a call expression.  We can use the function
9774 // parameter types to set the types of the arguments.
9775
9776 void
9777 Call_expression::do_determine_type(const Type_context*)
9778 {
9779   if (!this->determining_types())
9780     return;
9781
9782   this->fn_->determine_type_no_context();
9783   Function_type* fntype = this->get_function_type();
9784   const Typed_identifier_list* parameters = NULL;
9785   if (fntype != NULL)
9786     parameters = fntype->parameters();
9787   if (this->args_ != NULL)
9788     {
9789       Typed_identifier_list::const_iterator pt;
9790       if (parameters != NULL)
9791         pt = parameters->begin();
9792       bool first = true;
9793       for (Expression_list::const_iterator pa = this->args_->begin();
9794            pa != this->args_->end();
9795            ++pa)
9796         {
9797           if (first)
9798             {
9799               first = false;
9800               // If this is a method, the first argument is the
9801               // receiver.
9802               if (fntype != NULL && fntype->is_method())
9803                 {
9804                   Type* rtype = fntype->receiver()->type();
9805                   // The receiver is always passed as a pointer.
9806                   if (rtype->points_to() == NULL)
9807                     rtype = Type::make_pointer_type(rtype);
9808                   Type_context subcontext(rtype, false);
9809                   (*pa)->determine_type(&subcontext);
9810                   continue;
9811                 }
9812             }
9813
9814           if (parameters != NULL && pt != parameters->end())
9815             {
9816               Type_context subcontext(pt->type(), false);
9817               (*pa)->determine_type(&subcontext);
9818               ++pt;
9819             }
9820           else
9821             (*pa)->determine_type_no_context();
9822         }
9823     }
9824 }
9825
9826 // Called when determining types for a Call_expression.  Return true
9827 // if we should go ahead, false if they have already been determined.
9828
9829 bool
9830 Call_expression::determining_types()
9831 {
9832   if (this->types_are_determined_)
9833     return false;
9834   else
9835     {
9836       this->types_are_determined_ = true;
9837       return true;
9838     }
9839 }
9840
9841 // Check types for parameter I.
9842
9843 bool
9844 Call_expression::check_argument_type(int i, const Type* parameter_type,
9845                                      const Type* argument_type,
9846                                      Location argument_location,
9847                                      bool issued_error)
9848 {
9849   std::string reason;
9850   bool ok;
9851   if (this->are_hidden_fields_ok_)
9852     ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9853                                         &reason);
9854   else
9855     ok = Type::are_assignable(parameter_type, argument_type, &reason);
9856   if (!ok)
9857     {
9858       if (!issued_error)
9859         {
9860           if (reason.empty())
9861             error_at(argument_location, "argument %d has incompatible type", i);
9862           else
9863             error_at(argument_location,
9864                      "argument %d has incompatible type (%s)",
9865                      i, reason.c_str());
9866         }
9867       this->set_is_error();
9868       return false;
9869     }
9870   return true;
9871 }
9872
9873 // Check types.
9874
9875 void
9876 Call_expression::do_check_types(Gogo*)
9877 {
9878   Function_type* fntype = this->get_function_type();
9879   if (fntype == NULL)
9880     {
9881       if (!this->fn_->type()->is_error())
9882         this->report_error(_("expected function"));
9883       return;
9884     }
9885
9886   bool is_method = fntype->is_method();
9887   if (is_method)
9888     {
9889       go_assert(this->args_ != NULL && !this->args_->empty());
9890       Type* rtype = fntype->receiver()->type();
9891       Expression* first_arg = this->args_->front();
9892       // The language permits copying hidden fields for a method
9893       // receiver.  We dereference the values since receivers are
9894       // always passed as pointers.
9895       std::string reason;
9896       if (!Type::are_assignable_hidden_ok(rtype->deref(),
9897                                           first_arg->type()->deref(),
9898                                           &reason))
9899         {
9900           if (reason.empty())
9901             this->report_error(_("incompatible type for receiver"));
9902           else
9903             {
9904               error_at(this->location(),
9905                        "incompatible type for receiver (%s)",
9906                        reason.c_str());
9907               this->set_is_error();
9908             }
9909         }
9910     }
9911
9912   // Note that varargs was handled by the lower_varargs() method, so
9913   // we don't have to worry about it here.
9914
9915   const Typed_identifier_list* parameters = fntype->parameters();
9916   if (this->args_ == NULL)
9917     {
9918       if (parameters != NULL && !parameters->empty())
9919         this->report_error(_("not enough arguments"));
9920     }
9921   else if (parameters == NULL)
9922     {
9923       if (!is_method || this->args_->size() > 1)
9924         this->report_error(_("too many arguments"));
9925     }
9926   else
9927     {
9928       int i = 0;
9929       Expression_list::const_iterator pa = this->args_->begin();
9930       if (is_method)
9931         ++pa;
9932       for (Typed_identifier_list::const_iterator pt = parameters->begin();
9933            pt != parameters->end();
9934            ++pt, ++pa, ++i)
9935         {
9936           if (pa == this->args_->end())
9937             {
9938               this->report_error(_("not enough arguments"));
9939               return;
9940             }
9941           this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9942                                     (*pa)->location(), false);
9943         }
9944       if (pa != this->args_->end())
9945         this->report_error(_("too many arguments"));
9946     }
9947 }
9948
9949 // Return whether we have to use a temporary variable to ensure that
9950 // we evaluate this call expression in order.  If the call returns no
9951 // results then it will inevitably be executed last.
9952
9953 bool
9954 Call_expression::do_must_eval_in_order() const
9955 {
9956   return this->result_count() > 0;
9957 }
9958
9959 // Get the function and the first argument to use when calling an
9960 // interface method.
9961
9962 tree
9963 Call_expression::interface_method_function(
9964     Translate_context* context,
9965     Interface_field_reference_expression* interface_method,
9966     tree* first_arg_ptr)
9967 {
9968   tree expr = interface_method->expr()->get_tree(context);
9969   if (expr == error_mark_node)
9970     return error_mark_node;
9971   expr = save_expr(expr);
9972   tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9973   if (first_arg == error_mark_node)
9974     return error_mark_node;
9975   *first_arg_ptr = first_arg;
9976   return interface_method->get_function_tree(context, expr);
9977 }
9978
9979 // Build the call expression.
9980
9981 tree
9982 Call_expression::do_get_tree(Translate_context* context)
9983 {
9984   if (this->tree_ != NULL_TREE)
9985     return this->tree_;
9986
9987   Function_type* fntype = this->get_function_type();
9988   if (fntype == NULL)
9989     return error_mark_node;
9990
9991   if (this->fn_->is_error_expression())
9992     return error_mark_node;
9993
9994   Gogo* gogo = context->gogo();
9995   Location location = this->location();
9996
9997   Func_expression* func = this->fn_->func_expression();
9998   Interface_field_reference_expression* interface_method =
9999     this->fn_->interface_field_reference_expression();
10000   const bool has_closure = func != NULL && func->closure() != NULL;
10001   const bool is_interface_method = interface_method != NULL;
10002
10003   int nargs;
10004   tree* args;
10005   if (this->args_ == NULL || this->args_->empty())
10006     {
10007       nargs = is_interface_method ? 1 : 0;
10008       args = nargs == 0 ? NULL : new tree[nargs];
10009     }
10010   else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10011     {
10012       // Passing a receiver parameter.
10013       go_assert(!is_interface_method
10014                 && fntype->is_method()
10015                 && this->args_->size() == 1);
10016       nargs = 1;
10017       args = new tree[nargs];
10018       args[0] = this->args_->front()->get_tree(context);
10019     }
10020   else
10021     {
10022       const Typed_identifier_list* params = fntype->parameters();
10023
10024       nargs = this->args_->size();
10025       int i = is_interface_method ? 1 : 0;
10026       nargs += i;
10027       args = new tree[nargs];
10028
10029       Typed_identifier_list::const_iterator pp = params->begin();
10030       Expression_list::const_iterator pe = this->args_->begin();
10031       if (!is_interface_method && fntype->is_method())
10032         {
10033           args[i] = (*pe)->get_tree(context);
10034           ++pe;
10035           ++i;
10036         }
10037       for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10038         {
10039           go_assert(pp != params->end());
10040           tree arg_val = (*pe)->get_tree(context);
10041           args[i] = Expression::convert_for_assignment(context,
10042                                                        pp->type(),
10043                                                        (*pe)->type(),
10044                                                        arg_val,
10045                                                        location);
10046           if (args[i] == error_mark_node)
10047             {
10048               delete[] args;
10049               return error_mark_node;
10050             }
10051         }
10052       go_assert(pp == params->end());
10053       go_assert(i == nargs);
10054     }
10055
10056   tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
10057   if (rettype == error_mark_node)
10058     {
10059       delete[] args;
10060       return error_mark_node;
10061     }
10062
10063   tree fn;
10064   if (has_closure)
10065     fn = func->get_tree_without_closure(gogo);
10066   else if (!is_interface_method)
10067     fn = this->fn_->get_tree(context);
10068   else
10069     fn = this->interface_method_function(context, interface_method, &args[0]);
10070
10071   if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
10072     {
10073       delete[] args;
10074       return error_mark_node;
10075     }
10076
10077   tree fndecl = fn;
10078   if (TREE_CODE(fndecl) == ADDR_EXPR)
10079     fndecl = TREE_OPERAND(fndecl, 0);
10080
10081   // Add a type cast in case the type of the function is a recursive
10082   // type which refers to itself.
10083   if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
10084     {
10085       tree fnt = type_to_tree(fntype->get_backend(gogo));
10086       if (fnt == error_mark_node)
10087         return error_mark_node;
10088       fn = fold_convert_loc(location.gcc_location(), fnt, fn);
10089     }
10090
10091   // This is to support builtin math functions when using 80387 math.
10092   tree excess_type = NULL_TREE;
10093   if (optimize
10094       && TREE_CODE(fndecl) == FUNCTION_DECL
10095       && DECL_IS_BUILTIN(fndecl)
10096       && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
10097       && nargs > 0
10098       && ((SCALAR_FLOAT_TYPE_P(rettype)
10099            && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
10100           || (COMPLEX_FLOAT_TYPE_P(rettype)
10101               && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
10102     {
10103       excess_type = excess_precision_type(TREE_TYPE(args[0]));
10104       if (excess_type != NULL_TREE)
10105         {
10106           tree excess_fndecl = mathfn_built_in(excess_type,
10107                                                DECL_FUNCTION_CODE(fndecl));
10108           if (excess_fndecl == NULL_TREE)
10109             excess_type = NULL_TREE;
10110           else
10111             {
10112               fn = build_fold_addr_expr_loc(location.gcc_location(),
10113                                             excess_fndecl);
10114               for (int i = 0; i < nargs; ++i)
10115                 {
10116                   if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
10117                       || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
10118                     args[i] = ::convert(excess_type, args[i]);
10119                 }
10120             }
10121         }
10122     }
10123
10124   tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
10125                               fn, nargs, args);
10126   delete[] args;
10127
10128   SET_EXPR_LOCATION(ret, location.gcc_location());
10129
10130   if (has_closure)
10131     {
10132       tree closure_tree = func->closure()->get_tree(context);
10133       if (closure_tree != error_mark_node)
10134         CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
10135     }
10136
10137   // If this is a recursive function type which returns itself, as in
10138   //   type F func() F
10139   // we have used ptr_type_node for the return type.  Add a cast here
10140   // to the correct type.
10141   if (TREE_TYPE(ret) == ptr_type_node)
10142     {
10143       tree t = type_to_tree(this->type()->base()->get_backend(gogo));
10144       ret = fold_convert_loc(location.gcc_location(), t, ret);
10145     }
10146
10147   if (excess_type != NULL_TREE)
10148     {
10149       // Calling convert here can undo our excess precision change.
10150       // That may or may not be a bug in convert_to_real.
10151       ret = build1(NOP_EXPR, rettype, ret);
10152     }
10153
10154   if (this->results_ != NULL)
10155     ret = this->set_results(context, ret);
10156
10157   this->tree_ = ret;
10158
10159   return ret;
10160 }
10161
10162 // Set the result variables if this call returns multiple results.
10163
10164 tree
10165 Call_expression::set_results(Translate_context* context, tree call_tree)
10166 {
10167   tree stmt_list = NULL_TREE;
10168
10169   call_tree = save_expr(call_tree);
10170
10171   if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
10172     {
10173       go_assert(saw_errors());
10174       return call_tree;
10175     }
10176
10177   Location loc = this->location();
10178   tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
10179   size_t rc = this->result_count();
10180   for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
10181     {
10182       go_assert(field != NULL_TREE);
10183
10184       Temporary_statement* temp = this->result(i);
10185       if (temp == NULL)
10186         {
10187           go_assert(saw_errors());
10188           return error_mark_node;
10189         }
10190       Temporary_reference_expression* ref =
10191         Expression::make_temporary_reference(temp, loc);
10192       ref->set_is_lvalue();
10193       tree temp_tree = ref->get_tree(context);
10194       if (temp_tree == error_mark_node)
10195         continue;
10196
10197       tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
10198                                  TREE_TYPE(field), call_tree, field, NULL_TREE);
10199       tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
10200                                  void_type_node, temp_tree, val_tree);
10201
10202       append_to_statement_list(set_tree, &stmt_list);
10203     }
10204   go_assert(field == NULL_TREE);
10205
10206   return save_expr(stmt_list);
10207 }
10208
10209 // Dump ast representation for a call expressin.
10210
10211 void
10212 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10213 {
10214   this->fn_->dump_expression(ast_dump_context);
10215   ast_dump_context->ostream() << "(";
10216   if (args_ != NULL)
10217     ast_dump_context->dump_expression_list(this->args_);
10218
10219   ast_dump_context->ostream() << ") ";
10220 }
10221
10222 // Make a call expression.
10223
10224 Call_expression*
10225 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10226                       Location location)
10227 {
10228   return new Call_expression(fn, args, is_varargs, location);
10229 }
10230
10231 // A single result from a call which returns multiple results.
10232
10233 class Call_result_expression : public Expression
10234 {
10235  public:
10236   Call_result_expression(Call_expression* call, unsigned int index)
10237     : Expression(EXPRESSION_CALL_RESULT, call->location()),
10238       call_(call), index_(index)
10239   { }
10240
10241  protected:
10242   int
10243   do_traverse(Traverse*);
10244
10245   Type*
10246   do_type();
10247
10248   void
10249   do_determine_type(const Type_context*);
10250
10251   void
10252   do_check_types(Gogo*);
10253
10254   Expression*
10255   do_copy()
10256   {
10257     return new Call_result_expression(this->call_->call_expression(),
10258                                       this->index_);
10259   }
10260
10261   bool
10262   do_must_eval_in_order() const
10263   { return true; }
10264
10265   tree
10266   do_get_tree(Translate_context*);
10267
10268   void
10269   do_dump_expression(Ast_dump_context*) const;
10270
10271  private:
10272   // The underlying call expression.
10273   Expression* call_;
10274   // Which result we want.
10275   unsigned int index_;
10276 };
10277
10278 // Traverse a call result.
10279
10280 int
10281 Call_result_expression::do_traverse(Traverse* traverse)
10282 {
10283   if (traverse->remember_expression(this->call_))
10284     {
10285       // We have already traversed the call expression.
10286       return TRAVERSE_CONTINUE;
10287     }
10288   return Expression::traverse(&this->call_, traverse);
10289 }
10290
10291 // Get the type.
10292
10293 Type*
10294 Call_result_expression::do_type()
10295 {
10296   if (this->classification() == EXPRESSION_ERROR)
10297     return Type::make_error_type();
10298
10299   // THIS->CALL_ can be replaced with a temporary reference due to
10300   // Call_expression::do_must_eval_in_order when there is an error.
10301   Call_expression* ce = this->call_->call_expression();
10302   if (ce == NULL)
10303     {
10304       this->set_is_error();
10305       return Type::make_error_type();
10306     }
10307   Function_type* fntype = ce->get_function_type();
10308   if (fntype == NULL)
10309     {
10310       if (ce->issue_error())
10311         {
10312           if (!ce->fn()->type()->is_error())
10313             this->report_error(_("expected function"));
10314         }
10315       this->set_is_error();
10316       return Type::make_error_type();
10317     }
10318   const Typed_identifier_list* results = fntype->results();
10319   if (results == NULL || results->size() < 2)
10320     {
10321       if (ce->issue_error())
10322         this->report_error(_("number of results does not match "
10323                              "number of values"));
10324       return Type::make_error_type();
10325     }
10326   Typed_identifier_list::const_iterator pr = results->begin();
10327   for (unsigned int i = 0; i < this->index_; ++i)
10328     {
10329       if (pr == results->end())
10330         break;
10331       ++pr;
10332     }
10333   if (pr == results->end())
10334     {
10335       if (ce->issue_error())
10336         this->report_error(_("number of results does not match "
10337                              "number of values"));
10338       return Type::make_error_type();
10339     }
10340   return pr->type();
10341 }
10342
10343 // Check the type.  Just make sure that we trigger the warning in
10344 // do_type.
10345
10346 void
10347 Call_result_expression::do_check_types(Gogo*)
10348 {
10349   this->type();
10350 }
10351
10352 // Determine the type.  We have nothing to do here, but the 0 result
10353 // needs to pass down to the caller.
10354
10355 void
10356 Call_result_expression::do_determine_type(const Type_context*)
10357 {
10358   this->call_->determine_type_no_context();
10359 }
10360
10361 // Return the tree.  We just refer to the temporary set by the call
10362 // expression.  We don't do this at lowering time because it makes it
10363 // hard to evaluate the call at the right time.
10364
10365 tree
10366 Call_result_expression::do_get_tree(Translate_context* context)
10367 {
10368   Call_expression* ce = this->call_->call_expression();
10369   if (ce == NULL)
10370     {
10371       go_assert(this->call_->is_error_expression());
10372       return error_mark_node;
10373     }
10374   Temporary_statement* ts = ce->result(this->index_);
10375   if (ts == NULL)
10376     {
10377       go_assert(saw_errors());
10378       return error_mark_node;
10379     }
10380   Expression* ref = Expression::make_temporary_reference(ts, this->location());
10381   return ref->get_tree(context);
10382 }
10383
10384 // Dump ast representation for a call result expression.
10385
10386 void
10387 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10388     const
10389 {
10390   // FIXME: Wouldn't it be better if the call is assigned to a temporary 
10391   // (struct) and the fields are referenced instead.
10392   ast_dump_context->ostream() << this->index_ << "@(";
10393   ast_dump_context->dump_expression(this->call_);
10394   ast_dump_context->ostream() << ")";
10395 }
10396
10397 // Make a reference to a single result of a call which returns
10398 // multiple results.
10399
10400 Expression*
10401 Expression::make_call_result(Call_expression* call, unsigned int index)
10402 {
10403   return new Call_result_expression(call, index);
10404 }
10405
10406 // Class Index_expression.
10407
10408 // Traversal.
10409
10410 int
10411 Index_expression::do_traverse(Traverse* traverse)
10412 {
10413   if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10414       || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10415       || (this->end_ != NULL
10416           && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
10417     return TRAVERSE_EXIT;
10418   return TRAVERSE_CONTINUE;
10419 }
10420
10421 // Lower an index expression.  This converts the generic index
10422 // expression into an array index, a string index, or a map index.
10423
10424 Expression*
10425 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10426 {
10427   Location location = this->location();
10428   Expression* left = this->left_;
10429   Expression* start = this->start_;
10430   Expression* end = this->end_;
10431
10432   Type* type = left->type();
10433   if (type->is_error())
10434     return Expression::make_error(location);
10435   else if (left->is_type_expression())
10436     {
10437       error_at(location, "attempt to index type expression");
10438       return Expression::make_error(location);
10439     }
10440   else if (type->array_type() != NULL)
10441     return Expression::make_array_index(left, start, end, location);
10442   else if (type->points_to() != NULL
10443            && type->points_to()->array_type() != NULL
10444            && !type->points_to()->is_slice_type())
10445     {
10446       Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10447                                                  location);
10448       return Expression::make_array_index(deref, start, end, location);
10449     }
10450   else if (type->is_string_type())
10451     return Expression::make_string_index(left, start, end, location);
10452   else if (type->map_type() != NULL)
10453     {
10454       if (end != NULL)
10455         {
10456           error_at(location, "invalid slice of map");
10457           return Expression::make_error(location);
10458         }
10459       Map_index_expression* ret = Expression::make_map_index(left, start,
10460                                                              location);
10461       if (this->is_lvalue_)
10462         ret->set_is_lvalue();
10463       return ret;
10464     }
10465   else
10466     {
10467       error_at(location,
10468                "attempt to index object which is not array, string, or map");
10469       return Expression::make_error(location);
10470     }
10471 }
10472
10473 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
10474 // dump context
10475
10476 void
10477 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context, 
10478                                         const Expression* expr, 
10479                                         const Expression* start,
10480                                         const Expression* end)
10481 {
10482   expr->dump_expression(ast_dump_context);
10483   ast_dump_context->ostream() << "[";
10484   start->dump_expression(ast_dump_context);
10485   if (end != NULL)
10486     {
10487       ast_dump_context->ostream() << ":";
10488       end->dump_expression(ast_dump_context);
10489     }
10490   ast_dump_context->ostream() << "]";
10491 }
10492
10493 // Dump ast representation for an index expression.
10494
10495 void
10496 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
10497     const
10498 {
10499   Index_expression::dump_index_expression(ast_dump_context, this->left_, 
10500                                           this->start_, this->end_);
10501 }
10502
10503 // Make an index expression.
10504
10505 Expression*
10506 Expression::make_index(Expression* left, Expression* start, Expression* end,
10507                        Location location)
10508 {
10509   return new Index_expression(left, start, end, location);
10510 }
10511
10512 // An array index.  This is used for both indexing and slicing.
10513
10514 class Array_index_expression : public Expression
10515 {
10516  public:
10517   Array_index_expression(Expression* array, Expression* start,
10518                          Expression* end, Location location)
10519     : Expression(EXPRESSION_ARRAY_INDEX, location),
10520       array_(array), start_(start), end_(end), type_(NULL)
10521   { }
10522
10523  protected:
10524   int
10525   do_traverse(Traverse*);
10526
10527   Type*
10528   do_type();
10529
10530   void
10531   do_determine_type(const Type_context*);
10532
10533   void
10534   do_check_types(Gogo*);
10535
10536   Expression*
10537   do_copy()
10538   {
10539     return Expression::make_array_index(this->array_->copy(),
10540                                         this->start_->copy(),
10541                                         (this->end_ == NULL
10542                                          ? NULL
10543                                          : this->end_->copy()),
10544                                         this->location());
10545   }
10546
10547   bool
10548   do_must_eval_subexpressions_in_order(int* skip) const
10549   {
10550     *skip = 1;
10551     return true;
10552   }
10553
10554   bool
10555   do_is_addressable() const;
10556
10557   void
10558   do_address_taken(bool escapes)
10559   { this->array_->address_taken(escapes); }
10560
10561   tree
10562   do_get_tree(Translate_context*);
10563
10564   void
10565   do_dump_expression(Ast_dump_context*) const;
10566   
10567  private:
10568   // The array we are getting a value from.
10569   Expression* array_;
10570   // The start or only index.
10571   Expression* start_;
10572   // The end index of a slice.  This may be NULL for a simple array
10573   // index, or it may be a nil expression for the length of the array.
10574   Expression* end_;
10575   // The type of the expression.
10576   Type* type_;
10577 };
10578
10579 // Array index traversal.
10580
10581 int
10582 Array_index_expression::do_traverse(Traverse* traverse)
10583 {
10584   if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10585     return TRAVERSE_EXIT;
10586   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10587     return TRAVERSE_EXIT;
10588   if (this->end_ != NULL)
10589     {
10590       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10591         return TRAVERSE_EXIT;
10592     }
10593   return TRAVERSE_CONTINUE;
10594 }
10595
10596 // Return the type of an array index.
10597
10598 Type*
10599 Array_index_expression::do_type()
10600 {
10601   if (this->type_ == NULL)
10602     {
10603      Array_type* type = this->array_->type()->array_type();
10604       if (type == NULL)
10605         this->type_ = Type::make_error_type();
10606       else if (this->end_ == NULL)
10607         this->type_ = type->element_type();
10608       else if (type->is_slice_type())
10609         {
10610           // A slice of a slice has the same type as the original
10611           // slice.
10612           this->type_ = this->array_->type()->deref();
10613         }
10614       else
10615         {
10616           // A slice of an array is a slice.
10617           this->type_ = Type::make_array_type(type->element_type(), NULL);
10618         }
10619     }
10620   return this->type_;
10621 }
10622
10623 // Set the type of an array index.
10624
10625 void
10626 Array_index_expression::do_determine_type(const Type_context*)
10627 {
10628   this->array_->determine_type_no_context();
10629   this->start_->determine_type_no_context();
10630   if (this->end_ != NULL)
10631     this->end_->determine_type_no_context();
10632 }
10633
10634 // Check types of an array index.
10635
10636 void
10637 Array_index_expression::do_check_types(Gogo*)
10638 {
10639   if (this->start_->type()->integer_type() == NULL)
10640     this->report_error(_("index must be integer"));
10641   if (this->end_ != NULL
10642       && this->end_->type()->integer_type() == NULL
10643       && !this->end_->type()->is_error()
10644       && !this->end_->is_nil_expression()
10645       && !this->end_->is_error_expression())
10646     this->report_error(_("slice end must be integer"));
10647
10648   Array_type* array_type = this->array_->type()->array_type();
10649   if (array_type == NULL)
10650     {
10651       go_assert(this->array_->type()->is_error());
10652       return;
10653     }
10654
10655   unsigned int int_bits =
10656     Type::lookup_integer_type("int")->integer_type()->bits();
10657
10658   Type* dummy;
10659   mpz_t lval;
10660   mpz_init(lval);
10661   bool lval_valid = (array_type->length() != NULL
10662                      && array_type->length()->integer_constant_value(true,
10663                                                                      lval,
10664                                                                      &dummy));
10665   mpz_t ival;
10666   mpz_init(ival);
10667   if (this->start_->integer_constant_value(true, ival, &dummy))
10668     {
10669       if (mpz_sgn(ival) < 0
10670           || mpz_sizeinbase(ival, 2) >= int_bits
10671           || (lval_valid
10672               && (this->end_ == NULL
10673                   ? mpz_cmp(ival, lval) >= 0
10674                   : mpz_cmp(ival, lval) > 0)))
10675         {
10676           error_at(this->start_->location(), "array index out of bounds");
10677           this->set_is_error();
10678         }
10679     }
10680   if (this->end_ != NULL && !this->end_->is_nil_expression())
10681     {
10682       if (this->end_->integer_constant_value(true, ival, &dummy))
10683         {
10684           if (mpz_sgn(ival) < 0
10685               || mpz_sizeinbase(ival, 2) >= int_bits
10686               || (lval_valid && mpz_cmp(ival, lval) > 0))
10687             {
10688               error_at(this->end_->location(), "array index out of bounds");
10689               this->set_is_error();
10690             }
10691         }
10692     }
10693   mpz_clear(ival);
10694   mpz_clear(lval);
10695
10696   // A slice of an array requires an addressable array.  A slice of a
10697   // slice is always possible.
10698   if (this->end_ != NULL && !array_type->is_slice_type())
10699     {
10700       if (!this->array_->is_addressable())
10701         this->report_error(_("slice of unaddressable value"));
10702       else
10703         this->array_->address_taken(true);
10704     }
10705 }
10706
10707 // Return whether this expression is addressable.
10708
10709 bool
10710 Array_index_expression::do_is_addressable() const
10711 {
10712   // A slice expression is not addressable.
10713   if (this->end_ != NULL)
10714     return false;
10715
10716   // An index into a slice is addressable.
10717   if (this->array_->type()->is_slice_type())
10718     return true;
10719
10720   // An index into an array is addressable if the array is
10721   // addressable.
10722   return this->array_->is_addressable();
10723 }
10724
10725 // Get a tree for an array index.
10726
10727 tree
10728 Array_index_expression::do_get_tree(Translate_context* context)
10729 {
10730   Gogo* gogo = context->gogo();
10731   Location loc = this->location();
10732
10733   Array_type* array_type = this->array_->type()->array_type();
10734   if (array_type == NULL)
10735     {
10736       go_assert(this->array_->type()->is_error());
10737       return error_mark_node;
10738     }
10739
10740   tree type_tree = type_to_tree(array_type->get_backend(gogo));
10741   if (type_tree == error_mark_node)
10742     return error_mark_node;
10743
10744   tree array_tree = this->array_->get_tree(context);
10745   if (array_tree == error_mark_node)
10746     return error_mark_node;
10747
10748   if (array_type->length() == NULL && !DECL_P(array_tree))
10749     array_tree = save_expr(array_tree);
10750
10751   tree length_tree = NULL_TREE;
10752   if (this->end_ == NULL || this->end_->is_nil_expression())
10753     {
10754       length_tree = array_type->length_tree(gogo, array_tree);
10755       if (length_tree == error_mark_node)
10756         return error_mark_node;
10757       length_tree = save_expr(length_tree);
10758     }
10759
10760   tree capacity_tree = NULL_TREE;
10761   if (this->end_ != NULL)
10762     {
10763       capacity_tree = array_type->capacity_tree(gogo, array_tree);
10764       if (capacity_tree == error_mark_node)
10765         return error_mark_node;
10766       capacity_tree = save_expr(capacity_tree);
10767     }
10768
10769   tree length_type = (length_tree != NULL_TREE
10770                       ? TREE_TYPE(length_tree)
10771                       : TREE_TYPE(capacity_tree));
10772
10773   tree bad_index = boolean_false_node;
10774
10775   tree start_tree = this->start_->get_tree(context);
10776   if (start_tree == error_mark_node)
10777     return error_mark_node;
10778   if (!DECL_P(start_tree))
10779     start_tree = save_expr(start_tree);
10780   if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10781     start_tree = convert_to_integer(length_type, start_tree);
10782
10783   bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10784                                        loc);
10785
10786   start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10787   bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10788                               boolean_type_node, bad_index,
10789                               fold_build2_loc(loc.gcc_location(),
10790                                               (this->end_ == NULL
10791                                                ? GE_EXPR
10792                                                : GT_EXPR),
10793                                               boolean_type_node, start_tree,
10794                                               (this->end_ == NULL
10795                                                ? length_tree
10796                                                : capacity_tree)));
10797
10798   int code = (array_type->length() != NULL
10799               ? (this->end_ == NULL
10800                  ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10801                  : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10802               : (this->end_ == NULL
10803                  ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10804                  : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10805   tree crash = Gogo::runtime_error(code, loc);
10806
10807   if (this->end_ == NULL)
10808     {
10809       // Simple array indexing.  This has to return an l-value, so
10810       // wrap the index check into START_TREE.
10811       start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
10812                           build3(COND_EXPR, void_type_node,
10813                                  bad_index, crash, NULL_TREE),
10814                           start_tree);
10815       start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
10816
10817       if (array_type->length() != NULL)
10818         {
10819           // Fixed array.
10820           return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
10821                         start_tree, NULL_TREE, NULL_TREE);
10822         }
10823       else
10824         {
10825           // Open array.
10826           tree values = array_type->value_pointer_tree(gogo, array_tree);
10827           Type* element_type = array_type->element_type();
10828           Btype* belement_type = element_type->get_backend(gogo);
10829           tree element_type_tree = type_to_tree(belement_type);
10830           if (element_type_tree == error_mark_node)
10831             return error_mark_node;
10832           tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10833           tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10834                                         start_tree, element_size);
10835           tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10836                                      TREE_TYPE(values), values, offset);
10837           return build_fold_indirect_ref(ptr);
10838         }
10839     }
10840
10841   // Array slice.
10842
10843   tree end_tree;
10844   if (this->end_->is_nil_expression())
10845     end_tree = length_tree;
10846   else
10847     {
10848       end_tree = this->end_->get_tree(context);
10849       if (end_tree == error_mark_node)
10850         return error_mark_node;
10851       if (!DECL_P(end_tree))
10852         end_tree = save_expr(end_tree);
10853       if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10854         end_tree = convert_to_integer(length_type, end_tree);
10855
10856       bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
10857                                            loc);
10858
10859       end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
10860
10861       tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10862                                      boolean_type_node,
10863                                      fold_build2_loc(loc.gcc_location(),
10864                                                      LT_EXPR, boolean_type_node,
10865                                                      end_tree, start_tree),
10866                                      fold_build2_loc(loc.gcc_location(),
10867                                                      GT_EXPR, boolean_type_node,
10868                                                      end_tree, capacity_tree));
10869       bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10870                                   boolean_type_node, bad_index, bad_end);
10871     }
10872
10873   Type* element_type = array_type->element_type();
10874   tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
10875   if (element_type_tree == error_mark_node)
10876     return error_mark_node;
10877   tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10878
10879   tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10880                                 fold_convert_loc(loc.gcc_location(), sizetype,
10881                                                  start_tree),
10882                                 element_size);
10883
10884   tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
10885   if (value_pointer == error_mark_node)
10886     return error_mark_node;
10887
10888   value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10889                                   TREE_TYPE(value_pointer),
10890                                   value_pointer, offset);
10891
10892   tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10893                                             length_type, end_tree, start_tree);
10894
10895   tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10896                                               length_type, capacity_tree,
10897                                               start_tree);
10898
10899   tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
10900   go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
10901
10902   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
10903
10904   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
10905   tree field = TYPE_FIELDS(struct_tree);
10906   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
10907   elt->index = field;
10908   elt->value = value_pointer;
10909
10910   elt = VEC_quick_push(constructor_elt, init, NULL);
10911   field = DECL_CHAIN(field);
10912   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
10913   elt->index = field;
10914   elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10915                                 result_length_tree);
10916
10917   elt = VEC_quick_push(constructor_elt, init, NULL);
10918   field = DECL_CHAIN(field);
10919   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
10920   elt->index = field;
10921   elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10922                                 result_capacity_tree);
10923
10924   tree constructor = build_constructor(struct_tree, init);
10925
10926   if (TREE_CONSTANT(value_pointer)
10927       && TREE_CONSTANT(result_length_tree)
10928       && TREE_CONSTANT(result_capacity_tree))
10929     TREE_CONSTANT(constructor) = 1;
10930
10931   return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
10932                          TREE_TYPE(constructor),
10933                          build3(COND_EXPR, void_type_node,
10934                                 bad_index, crash, NULL_TREE),
10935                          constructor);
10936 }
10937
10938 // Dump ast representation for an array index expression.
10939
10940 void
10941 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
10942     const
10943 {
10944   Index_expression::dump_index_expression(ast_dump_context, this->array_, 
10945                                           this->start_, this->end_);
10946 }
10947
10948 // Make an array index expression.  END may be NULL.
10949
10950 Expression*
10951 Expression::make_array_index(Expression* array, Expression* start,
10952                              Expression* end, Location location)
10953 {
10954   return new Array_index_expression(array, start, end, location);
10955 }
10956
10957 // A string index.  This is used for both indexing and slicing.
10958
10959 class String_index_expression : public Expression
10960 {
10961  public:
10962   String_index_expression(Expression* string, Expression* start,
10963                           Expression* end, Location location)
10964     : Expression(EXPRESSION_STRING_INDEX, location),
10965       string_(string), start_(start), end_(end)
10966   { }
10967
10968  protected:
10969   int
10970   do_traverse(Traverse*);
10971
10972   Type*
10973   do_type();
10974
10975   void
10976   do_determine_type(const Type_context*);
10977
10978   void
10979   do_check_types(Gogo*);
10980
10981   Expression*
10982   do_copy()
10983   {
10984     return Expression::make_string_index(this->string_->copy(),
10985                                          this->start_->copy(),
10986                                          (this->end_ == NULL
10987                                           ? NULL
10988                                           : this->end_->copy()),
10989                                          this->location());
10990   }
10991
10992   bool
10993   do_must_eval_subexpressions_in_order(int* skip) const
10994   {
10995     *skip = 1;
10996     return true;
10997   }
10998
10999   tree
11000   do_get_tree(Translate_context*);
11001
11002   void
11003   do_dump_expression(Ast_dump_context*) const;
11004
11005  private:
11006   // The string we are getting a value from.
11007   Expression* string_;
11008   // The start or only index.
11009   Expression* start_;
11010   // The end index of a slice.  This may be NULL for a single index,
11011   // or it may be a nil expression for the length of the string.
11012   Expression* end_;
11013 };
11014
11015 // String index traversal.
11016
11017 int
11018 String_index_expression::do_traverse(Traverse* traverse)
11019 {
11020   if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11021     return TRAVERSE_EXIT;
11022   if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11023     return TRAVERSE_EXIT;
11024   if (this->end_ != NULL)
11025     {
11026       if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11027         return TRAVERSE_EXIT;
11028     }
11029   return TRAVERSE_CONTINUE;
11030 }
11031
11032 // Return the type of a string index.
11033
11034 Type*
11035 String_index_expression::do_type()
11036 {
11037   if (this->end_ == NULL)
11038     return Type::lookup_integer_type("uint8");
11039   else
11040     return this->string_->type();
11041 }
11042
11043 // Determine the type of a string index.
11044
11045 void
11046 String_index_expression::do_determine_type(const Type_context*)
11047 {
11048   this->string_->determine_type_no_context();
11049   this->start_->determine_type_no_context();
11050   if (this->end_ != NULL)
11051     this->end_->determine_type_no_context();
11052 }
11053
11054 // Check types of a string index.
11055
11056 void
11057 String_index_expression::do_check_types(Gogo*)
11058 {
11059   if (this->start_->type()->integer_type() == NULL)
11060     this->report_error(_("index must be integer"));
11061   if (this->end_ != NULL
11062       && this->end_->type()->integer_type() == NULL
11063       && !this->end_->is_nil_expression())
11064     this->report_error(_("slice end must be integer"));
11065
11066   std::string sval;
11067   bool sval_valid = this->string_->string_constant_value(&sval);
11068
11069   mpz_t ival;
11070   mpz_init(ival);
11071   Type* dummy;
11072   if (this->start_->integer_constant_value(true, ival, &dummy))
11073     {
11074       if (mpz_sgn(ival) < 0
11075           || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
11076         {
11077           error_at(this->start_->location(), "string index out of bounds");
11078           this->set_is_error();
11079         }
11080     }
11081   if (this->end_ != NULL && !this->end_->is_nil_expression())
11082     {
11083       if (this->end_->integer_constant_value(true, ival, &dummy))
11084         {
11085           if (mpz_sgn(ival) < 0
11086               || (sval_valid && mpz_cmp_ui(ival, sval.length()) > 0))
11087             {
11088               error_at(this->end_->location(), "string index out of bounds");
11089               this->set_is_error();
11090             }
11091         }
11092     }
11093   mpz_clear(ival);
11094 }
11095
11096 // Get a tree for a string index.
11097
11098 tree
11099 String_index_expression::do_get_tree(Translate_context* context)
11100 {
11101   Location loc = this->location();
11102
11103   tree string_tree = this->string_->get_tree(context);
11104   if (string_tree == error_mark_node)
11105     return error_mark_node;
11106
11107   if (this->string_->type()->points_to() != NULL)
11108     string_tree = build_fold_indirect_ref(string_tree);
11109   if (!DECL_P(string_tree))
11110     string_tree = save_expr(string_tree);
11111   tree string_type = TREE_TYPE(string_tree);
11112
11113   tree length_tree = String_type::length_tree(context->gogo(), string_tree);
11114   length_tree = save_expr(length_tree);
11115   tree length_type = TREE_TYPE(length_tree);
11116
11117   tree bad_index = boolean_false_node;
11118
11119   tree start_tree = this->start_->get_tree(context);
11120   if (start_tree == error_mark_node)
11121     return error_mark_node;
11122   if (!DECL_P(start_tree))
11123     start_tree = save_expr(start_tree);
11124   if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
11125     start_tree = convert_to_integer(length_type, start_tree);
11126
11127   bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
11128                                        loc);
11129
11130   start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
11131
11132   int code = (this->end_ == NULL
11133               ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11134               : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11135   tree crash = Gogo::runtime_error(code, loc);
11136
11137   if (this->end_ == NULL)
11138     {
11139       bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
11140                                   boolean_type_node, bad_index,
11141                                   fold_build2_loc(loc.gcc_location(), GE_EXPR,
11142                                                   boolean_type_node,
11143                                                   start_tree, length_tree));
11144
11145       tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
11146       tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
11147                                  TREE_TYPE(bytes_tree),
11148                                  bytes_tree,
11149                                  fold_convert_loc(loc.gcc_location(), sizetype,
11150                                                   start_tree));
11151       tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
11152
11153       return build2(COMPOUND_EXPR, TREE_TYPE(index),
11154                     build3(COND_EXPR, void_type_node,
11155                            bad_index, crash, NULL_TREE),
11156                     index);
11157     }
11158   else
11159     {
11160       tree end_tree;
11161       if (this->end_->is_nil_expression())
11162         end_tree = build_int_cst(length_type, -1);
11163       else
11164         {
11165           end_tree = this->end_->get_tree(context);
11166           if (end_tree == error_mark_node)
11167             return error_mark_node;
11168           if (!DECL_P(end_tree))
11169             end_tree = save_expr(end_tree);
11170           if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
11171             end_tree = convert_to_integer(length_type, end_tree);
11172
11173           bad_index = Expression::check_bounds(end_tree, length_type,
11174                                                bad_index, loc);
11175
11176           end_tree = fold_convert_loc(loc.gcc_location(), length_type,
11177                                       end_tree);
11178         }
11179
11180       static tree strslice_fndecl;
11181       tree ret = Gogo::call_builtin(&strslice_fndecl,
11182                                     loc,
11183                                     "__go_string_slice",
11184                                     3,
11185                                     string_type,
11186                                     string_type,
11187                                     string_tree,
11188                                     length_type,
11189                                     start_tree,
11190                                     length_type,
11191                                     end_tree);
11192       if (ret == error_mark_node)
11193         return error_mark_node;
11194       // This will panic if the bounds are out of range for the
11195       // string.
11196       TREE_NOTHROW(strslice_fndecl) = 0;
11197
11198       if (bad_index == boolean_false_node)
11199         return ret;
11200       else
11201         return build2(COMPOUND_EXPR, TREE_TYPE(ret),
11202                       build3(COND_EXPR, void_type_node,
11203                              bad_index, crash, NULL_TREE),
11204                       ret);
11205     }
11206 }
11207
11208 // Dump ast representation for a string index expression.
11209
11210 void
11211 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11212     const
11213 {
11214   Index_expression::dump_index_expression(ast_dump_context, this->string_, 
11215                                           this->start_, this->end_);
11216 }
11217
11218 // Make a string index expression.  END may be NULL.
11219
11220 Expression*
11221 Expression::make_string_index(Expression* string, Expression* start,
11222                               Expression* end, Location location)
11223 {
11224   return new String_index_expression(string, start, end, location);
11225 }
11226
11227 // Class Map_index.
11228
11229 // Get the type of the map.
11230
11231 Map_type*
11232 Map_index_expression::get_map_type() const
11233 {
11234   Map_type* mt = this->map_->type()->deref()->map_type();
11235   if (mt == NULL)
11236     go_assert(saw_errors());
11237   return mt;
11238 }
11239
11240 // Map index traversal.
11241
11242 int
11243 Map_index_expression::do_traverse(Traverse* traverse)
11244 {
11245   if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11246     return TRAVERSE_EXIT;
11247   return Expression::traverse(&this->index_, traverse);
11248 }
11249
11250 // Return the type of a map index.
11251
11252 Type*
11253 Map_index_expression::do_type()
11254 {
11255   Map_type* mt = this->get_map_type();
11256   if (mt == NULL)
11257     return Type::make_error_type();
11258   Type* type = mt->val_type();
11259   // If this map index is in a tuple assignment, we actually return a
11260   // pointer to the value type.  Tuple_map_assignment_statement is
11261   // responsible for handling this correctly.  We need to get the type
11262   // right in case this gets assigned to a temporary variable.
11263   if (this->is_in_tuple_assignment_)
11264     type = Type::make_pointer_type(type);
11265   return type;
11266 }
11267
11268 // Fix the type of a map index.
11269
11270 void
11271 Map_index_expression::do_determine_type(const Type_context*)
11272 {
11273   this->map_->determine_type_no_context();
11274   Map_type* mt = this->get_map_type();
11275   Type* key_type = mt == NULL ? NULL : mt->key_type();
11276   Type_context subcontext(key_type, false);
11277   this->index_->determine_type(&subcontext);
11278 }
11279
11280 // Check types of a map index.
11281
11282 void
11283 Map_index_expression::do_check_types(Gogo*)
11284 {
11285   std::string reason;
11286   Map_type* mt = this->get_map_type();
11287   if (mt == NULL)
11288     return;
11289   if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11290     {
11291       if (reason.empty())
11292         this->report_error(_("incompatible type for map index"));
11293       else
11294         {
11295           error_at(this->location(), "incompatible type for map index (%s)",
11296                    reason.c_str());
11297           this->set_is_error();
11298         }
11299     }
11300 }
11301
11302 // Get a tree for a map index.
11303
11304 tree
11305 Map_index_expression::do_get_tree(Translate_context* context)
11306 {
11307   Map_type* type = this->get_map_type();
11308   if (type == NULL)
11309     return error_mark_node;
11310
11311   tree valptr = this->get_value_pointer(context, this->is_lvalue_);
11312   if (valptr == error_mark_node)
11313     return error_mark_node;
11314   valptr = save_expr(valptr);
11315
11316   tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
11317
11318   if (this->is_lvalue_)
11319     return build_fold_indirect_ref(valptr);
11320   else if (this->is_in_tuple_assignment_)
11321     {
11322       // Tuple_map_assignment_statement is responsible for using this
11323       // appropriately.
11324       return valptr;
11325     }
11326   else
11327     {
11328       Gogo* gogo = context->gogo();
11329       Btype* val_btype = type->val_type()->get_backend(gogo);
11330       Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
11331       return fold_build3(COND_EXPR, val_type_tree,
11332                          fold_build2(EQ_EXPR, boolean_type_node, valptr,
11333                                      fold_convert(TREE_TYPE(valptr),
11334                                                   null_pointer_node)),
11335                          expr_to_tree(val_zero),
11336                          build_fold_indirect_ref(valptr));
11337     }
11338 }
11339
11340 // Get a tree for the map index.  This returns a tree which evaluates
11341 // to a pointer to a value.  The pointer will be NULL if the key is
11342 // not in the map.
11343
11344 tree
11345 Map_index_expression::get_value_pointer(Translate_context* context,
11346                                         bool insert)
11347 {
11348   Map_type* type = this->get_map_type();
11349   if (type == NULL)
11350     return error_mark_node;
11351
11352   tree map_tree = this->map_->get_tree(context);
11353   tree index_tree = this->index_->get_tree(context);
11354   index_tree = Expression::convert_for_assignment(context, type->key_type(),
11355                                                   this->index_->type(),
11356                                                   index_tree,
11357                                                   this->location());
11358   if (map_tree == error_mark_node || index_tree == error_mark_node)
11359     return error_mark_node;
11360
11361   if (this->map_->type()->points_to() != NULL)
11362     map_tree = build_fold_indirect_ref(map_tree);
11363
11364   // We need to pass in a pointer to the key, so stuff it into a
11365   // variable.
11366   tree tmp;
11367   tree make_tmp;
11368   if (current_function_decl != NULL)
11369     {
11370       tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
11371       DECL_IGNORED_P(tmp) = 0;
11372       DECL_INITIAL(tmp) = index_tree;
11373       make_tmp = build1(DECL_EXPR, void_type_node, tmp);
11374       TREE_ADDRESSABLE(tmp) = 1;
11375     }
11376   else
11377     {
11378       tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11379                        create_tmp_var_name("M"),
11380                        TREE_TYPE(index_tree));
11381       DECL_EXTERNAL(tmp) = 0;
11382       TREE_PUBLIC(tmp) = 0;
11383       TREE_STATIC(tmp) = 1;
11384       DECL_ARTIFICIAL(tmp) = 1;
11385       if (!TREE_CONSTANT(index_tree))
11386         make_tmp = fold_build2_loc(this->location().gcc_location(),
11387                                    INIT_EXPR, void_type_node,
11388                                    tmp, index_tree);
11389       else
11390         {
11391           TREE_READONLY(tmp) = 1;
11392           TREE_CONSTANT(tmp) = 1;
11393           DECL_INITIAL(tmp) = index_tree;
11394           make_tmp = NULL_TREE;
11395         }
11396       rest_of_decl_compilation(tmp, 1, 0);
11397     }
11398   tree tmpref =
11399     fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
11400                      build_fold_addr_expr_loc(this->location().gcc_location(),
11401                                               tmp));
11402
11403   static tree map_index_fndecl;
11404   tree call = Gogo::call_builtin(&map_index_fndecl,
11405                                  this->location(),
11406                                  "__go_map_index",
11407                                  3,
11408                                  const_ptr_type_node,
11409                                  TREE_TYPE(map_tree),
11410                                  map_tree,
11411                                  const_ptr_type_node,
11412                                  tmpref,
11413                                  boolean_type_node,
11414                                  (insert
11415                                   ? boolean_true_node
11416                                   : boolean_false_node));
11417   if (call == error_mark_node)
11418     return error_mark_node;
11419   // This can panic on a map of interface type if the interface holds
11420   // an uncomparable or unhashable type.
11421   TREE_NOTHROW(map_index_fndecl) = 0;
11422
11423   Type* val_type = type->val_type();
11424   tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
11425   if (val_type_tree == error_mark_node)
11426     return error_mark_node;
11427   tree ptr_val_type_tree = build_pointer_type(val_type_tree);
11428
11429   tree ret = fold_convert_loc(this->location().gcc_location(),
11430                               ptr_val_type_tree, call);
11431   if (make_tmp != NULL_TREE)
11432     ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
11433   return ret;
11434 }
11435
11436 // Dump ast representation for a map index expression
11437
11438 void
11439 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
11440     const
11441 {
11442   Index_expression::dump_index_expression(ast_dump_context, 
11443                                           this->map_, this->index_, NULL);
11444 }
11445
11446 // Make a map index expression.
11447
11448 Map_index_expression*
11449 Expression::make_map_index(Expression* map, Expression* index,
11450                            Location location)
11451 {
11452   return new Map_index_expression(map, index, location);
11453 }
11454
11455 // Class Field_reference_expression.
11456
11457 // Return the type of a field reference.
11458
11459 Type*
11460 Field_reference_expression::do_type()
11461 {
11462   Type* type = this->expr_->type();
11463   if (type->is_error())
11464     return type;
11465   Struct_type* struct_type = type->struct_type();
11466   go_assert(struct_type != NULL);
11467   return struct_type->field(this->field_index_)->type();
11468 }
11469
11470 // Check the types for a field reference.
11471
11472 void
11473 Field_reference_expression::do_check_types(Gogo*)
11474 {
11475   Type* type = this->expr_->type();
11476   if (type->is_error())
11477     return;
11478   Struct_type* struct_type = type->struct_type();
11479   go_assert(struct_type != NULL);
11480   go_assert(struct_type->field(this->field_index_) != NULL);
11481 }
11482
11483 // Get a tree for a field reference.
11484
11485 tree
11486 Field_reference_expression::do_get_tree(Translate_context* context)
11487 {
11488   tree struct_tree = this->expr_->get_tree(context);
11489   if (struct_tree == error_mark_node
11490       || TREE_TYPE(struct_tree) == error_mark_node)
11491     return error_mark_node;
11492   go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
11493   tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
11494   if (field == NULL_TREE)
11495     {
11496       // This can happen for a type which refers to itself indirectly
11497       // and then turns out to be erroneous.
11498       go_assert(saw_errors());
11499       return error_mark_node;
11500     }
11501   for (unsigned int i = this->field_index_; i > 0; --i)
11502     {
11503       field = DECL_CHAIN(field);
11504       go_assert(field != NULL_TREE);
11505     }
11506   if (TREE_TYPE(field) == error_mark_node)
11507     return error_mark_node;
11508   return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
11509                 NULL_TREE);
11510 }
11511
11512 // Dump ast representation for a field reference expression.
11513
11514 void
11515 Field_reference_expression::do_dump_expression(
11516     Ast_dump_context* ast_dump_context) const
11517 {
11518   this->expr_->dump_expression(ast_dump_context);
11519   ast_dump_context->ostream() << "." <<  this->field_index_;
11520 }
11521
11522 // Make a reference to a qualified identifier in an expression.
11523
11524 Field_reference_expression*
11525 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11526                                  Location location)
11527 {
11528   return new Field_reference_expression(expr, field_index, location);
11529 }
11530
11531 // Class Interface_field_reference_expression.
11532
11533 // Return a tree for the pointer to the function to call.
11534
11535 tree
11536 Interface_field_reference_expression::get_function_tree(Translate_context*,
11537                                                         tree expr)
11538 {
11539   if (this->expr_->type()->points_to() != NULL)
11540     expr = build_fold_indirect_ref(expr);
11541
11542   tree expr_type = TREE_TYPE(expr);
11543   go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
11544
11545   tree field = TYPE_FIELDS(expr_type);
11546   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
11547
11548   tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
11549   go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
11550
11551   table = build_fold_indirect_ref(table);
11552   go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
11553
11554   std::string name = Gogo::unpack_hidden_name(this->name_);
11555   for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
11556        field != NULL_TREE;
11557        field = DECL_CHAIN(field))
11558     {
11559       if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
11560         break;
11561     }
11562   go_assert(field != NULL_TREE);
11563
11564   return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
11565 }
11566
11567 // Return a tree for the first argument to pass to the interface
11568 // function.
11569
11570 tree
11571 Interface_field_reference_expression::get_underlying_object_tree(
11572     Translate_context*,
11573     tree expr)
11574 {
11575   if (this->expr_->type()->points_to() != NULL)
11576     expr = build_fold_indirect_ref(expr);
11577
11578   tree expr_type = TREE_TYPE(expr);
11579   go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
11580
11581   tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
11582   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
11583
11584   return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
11585 }
11586
11587 // Traversal.
11588
11589 int
11590 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11591 {
11592   return Expression::traverse(&this->expr_, traverse);
11593 }
11594
11595 // Return the type of an interface field reference.
11596
11597 Type*
11598 Interface_field_reference_expression::do_type()
11599 {
11600   Type* expr_type = this->expr_->type();
11601
11602   Type* points_to = expr_type->points_to();
11603   if (points_to != NULL)
11604     expr_type = points_to;
11605
11606   Interface_type* interface_type = expr_type->interface_type();
11607   if (interface_type == NULL)
11608     return Type::make_error_type();
11609
11610   const Typed_identifier* method = interface_type->find_method(this->name_);
11611   if (method == NULL)
11612     return Type::make_error_type();
11613
11614   return method->type();
11615 }
11616
11617 // Determine types.
11618
11619 void
11620 Interface_field_reference_expression::do_determine_type(const Type_context*)
11621 {
11622   this->expr_->determine_type_no_context();
11623 }
11624
11625 // Check the types for an interface field reference.
11626
11627 void
11628 Interface_field_reference_expression::do_check_types(Gogo*)
11629 {
11630   Type* type = this->expr_->type();
11631
11632   Type* points_to = type->points_to();
11633   if (points_to != NULL)
11634     type = points_to;
11635
11636   Interface_type* interface_type = type->interface_type();
11637   if (interface_type == NULL)
11638     {
11639       if (!type->is_error_type())
11640         this->report_error(_("expected interface or pointer to interface"));
11641     }
11642   else
11643     {
11644       const Typed_identifier* method =
11645         interface_type->find_method(this->name_);
11646       if (method == NULL)
11647         {
11648           error_at(this->location(), "method %qs not in interface",
11649                    Gogo::message_name(this->name_).c_str());
11650           this->set_is_error();
11651         }
11652     }
11653 }
11654
11655 // Get a tree for a reference to a field in an interface.  There is no
11656 // standard tree type representation for this: it's a function
11657 // attached to its first argument, like a Bound_method_expression.
11658 // The only places it may currently be used are in a Call_expression
11659 // or a Go_statement, which will take it apart directly.  So this has
11660 // nothing to do at present.
11661
11662 tree
11663 Interface_field_reference_expression::do_get_tree(Translate_context*)
11664 {
11665   go_unreachable();
11666 }
11667
11668 // Dump ast representation for an interface field reference.
11669
11670 void
11671 Interface_field_reference_expression::do_dump_expression(
11672     Ast_dump_context* ast_dump_context) const
11673 {
11674   this->expr_->dump_expression(ast_dump_context);
11675   ast_dump_context->ostream() << "." << this->name_;
11676 }
11677
11678 // Make a reference to a field in an interface.
11679
11680 Expression*
11681 Expression::make_interface_field_reference(Expression* expr,
11682                                            const std::string& field,
11683                                            Location location)
11684 {
11685   return new Interface_field_reference_expression(expr, field, location);
11686 }
11687
11688 // A general selector.  This is a Parser_expression for LEFT.NAME.  It
11689 // is lowered after we know the type of the left hand side.
11690
11691 class Selector_expression : public Parser_expression
11692 {
11693  public:
11694   Selector_expression(Expression* left, const std::string& name,
11695                       Location location)
11696     : Parser_expression(EXPRESSION_SELECTOR, location),
11697       left_(left), name_(name)
11698   { }
11699
11700  protected:
11701   int
11702   do_traverse(Traverse* traverse)
11703   { return Expression::traverse(&this->left_, traverse); }
11704
11705   Expression*
11706   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11707
11708   Expression*
11709   do_copy()
11710   {
11711     return new Selector_expression(this->left_->copy(), this->name_,
11712                                    this->location());
11713   }
11714
11715   void
11716   do_dump_expression(Ast_dump_context* ast_dump_context) const;
11717
11718  private:
11719   Expression*
11720   lower_method_expression(Gogo*);
11721
11722   // The expression on the left hand side.
11723   Expression* left_;
11724   // The name on the right hand side.
11725   std::string name_;
11726 };
11727
11728 // Lower a selector expression once we know the real type of the left
11729 // hand side.
11730
11731 Expression*
11732 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11733                               int)
11734 {
11735   Expression* left = this->left_;
11736   if (left->is_type_expression())
11737     return this->lower_method_expression(gogo);
11738   return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11739                                     this->location());
11740 }
11741
11742 // Lower a method expression T.M or (*T).M.  We turn this into a
11743 // function literal.
11744
11745 Expression*
11746 Selector_expression::lower_method_expression(Gogo* gogo)
11747 {
11748   Location location = this->location();
11749   Type* type = this->left_->type();
11750   const std::string& name(this->name_);
11751
11752   bool is_pointer;
11753   if (type->points_to() == NULL)
11754     is_pointer = false;
11755   else
11756     {
11757       is_pointer = true;
11758       type = type->points_to();
11759     }
11760   Named_type* nt = type->named_type();
11761   if (nt == NULL)
11762     {
11763       error_at(location,
11764                ("method expression requires named type or "
11765                 "pointer to named type"));
11766       return Expression::make_error(location);
11767     }
11768
11769   bool is_ambiguous;
11770   Method* method = nt->method_function(name, &is_ambiguous);
11771   const Typed_identifier* imethod = NULL;
11772   if (method == NULL && !is_pointer)
11773     {
11774       Interface_type* it = nt->interface_type();
11775       if (it != NULL)
11776         imethod = it->find_method(name);
11777     }
11778
11779   if (method == NULL && imethod == NULL)
11780     {
11781       if (!is_ambiguous)
11782         error_at(location, "type %<%s%s%> has no method %<%s%>",
11783                  is_pointer ? "*" : "",
11784                  nt->message_name().c_str(),
11785                  Gogo::message_name(name).c_str());
11786       else
11787         error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11788                  Gogo::message_name(name).c_str(),
11789                  is_pointer ? "*" : "",
11790                  nt->message_name().c_str());
11791       return Expression::make_error(location);
11792     }
11793
11794   if (method != NULL && !is_pointer && !method->is_value_method())
11795     {
11796       error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11797                nt->message_name().c_str(),
11798                Gogo::message_name(name).c_str());
11799       return Expression::make_error(location);
11800     }
11801
11802   // Build a new function type in which the receiver becomes the first
11803   // argument.
11804   Function_type* method_type;
11805   if (method != NULL)
11806     {
11807       method_type = method->type();
11808       go_assert(method_type->is_method());
11809     }
11810   else
11811     {
11812       method_type = imethod->type()->function_type();
11813       go_assert(method_type != NULL && !method_type->is_method());
11814     }
11815
11816   const char* const receiver_name = "$this";
11817   Typed_identifier_list* parameters = new Typed_identifier_list();
11818   parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11819                                          location));
11820
11821   const Typed_identifier_list* method_parameters = method_type->parameters();
11822   if (method_parameters != NULL)
11823     {
11824       int i = 0;
11825       for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11826            p != method_parameters->end();
11827            ++p, ++i)
11828         {
11829           if (!p->name().empty())
11830             parameters->push_back(*p);
11831           else
11832             {
11833               char buf[20];
11834               snprintf(buf, sizeof buf, "$param%d", i);
11835               parameters->push_back(Typed_identifier(buf, p->type(),
11836                                                      p->location()));
11837             }
11838         }
11839     }
11840
11841   const Typed_identifier_list* method_results = method_type->results();
11842   Typed_identifier_list* results;
11843   if (method_results == NULL)
11844     results = NULL;
11845   else
11846     {
11847       results = new Typed_identifier_list();
11848       for (Typed_identifier_list::const_iterator p = method_results->begin();
11849            p != method_results->end();
11850            ++p)
11851         results->push_back(*p);
11852     }
11853   
11854   Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11855                                                    location);
11856   if (method_type->is_varargs())
11857     fntype->set_is_varargs();
11858
11859   // We generate methods which always takes a pointer to the receiver
11860   // as their first argument.  If this is for a pointer type, we can
11861   // simply reuse the existing function.  We use an internal hack to
11862   // get the right type.
11863
11864   if (method != NULL && is_pointer)
11865     {
11866       Named_object* mno = (method->needs_stub_method()
11867                            ? method->stub_object()
11868                            : method->named_object());
11869       Expression* f = Expression::make_func_reference(mno, NULL, location);
11870       f = Expression::make_cast(fntype, f, location);
11871       Type_conversion_expression* tce =
11872         static_cast<Type_conversion_expression*>(f);
11873       tce->set_may_convert_function_types();
11874       return f;
11875     }
11876
11877   Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11878                                           location);
11879
11880   Named_object* vno = gogo->lookup(receiver_name, NULL);
11881   go_assert(vno != NULL);
11882   Expression* ve = Expression::make_var_reference(vno, location);
11883   Expression* bm;
11884   if (method != NULL)
11885     bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11886   else
11887     bm = Expression::make_interface_field_reference(ve, name, location);
11888
11889   // Even though we found the method above, if it has an error type we
11890   // may see an error here.
11891   if (bm->is_error_expression())
11892     {
11893       gogo->finish_function(location);
11894       return bm;
11895     }
11896
11897   Expression_list* args;
11898   if (parameters->size() <= 1)
11899     args = NULL;
11900   else
11901     {
11902       args = new Expression_list();
11903       Typed_identifier_list::const_iterator p = parameters->begin();
11904       ++p;
11905       for (; p != parameters->end(); ++p)
11906         {
11907           vno = gogo->lookup(p->name(), NULL);
11908           go_assert(vno != NULL);
11909           args->push_back(Expression::make_var_reference(vno, location));
11910         }
11911     }
11912
11913   gogo->start_block(location);
11914
11915   Call_expression* call = Expression::make_call(bm, args,
11916                                                 method_type->is_varargs(),
11917                                                 location);
11918
11919   size_t count = call->result_count();
11920   Statement* s;
11921   if (count == 0)
11922     s = Statement::make_statement(call, true);
11923   else
11924     {
11925       Expression_list* retvals = new Expression_list();
11926       if (count <= 1)
11927         retvals->push_back(call);
11928       else
11929         {
11930           for (size_t i = 0; i < count; ++i)
11931             retvals->push_back(Expression::make_call_result(call, i));
11932         }
11933       s = Statement::make_return_statement(retvals, location);
11934     }
11935   gogo->add_statement(s);
11936
11937   Block* b = gogo->finish_block(location);
11938
11939   gogo->add_block(b, location);
11940
11941   // Lower the call in case there are multiple results.
11942   gogo->lower_block(no, b);
11943
11944   gogo->finish_function(location);
11945
11946   return Expression::make_func_reference(no, NULL, location);
11947 }
11948
11949 // Dump the ast for a selector expression.
11950
11951 void
11952 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
11953     const
11954 {
11955   ast_dump_context->dump_expression(this->left_);
11956   ast_dump_context->ostream() << ".";
11957   ast_dump_context->ostream() << this->name_;
11958 }
11959                       
11960 // Make a selector expression.
11961
11962 Expression*
11963 Expression::make_selector(Expression* left, const std::string& name,
11964                           Location location)
11965 {
11966   return new Selector_expression(left, name, location);
11967 }
11968
11969 // Implement the builtin function new.
11970
11971 class Allocation_expression : public Expression
11972 {
11973  public:
11974   Allocation_expression(Type* type, Location location)
11975     : Expression(EXPRESSION_ALLOCATION, location),
11976       type_(type)
11977   { }
11978
11979  protected:
11980   int
11981   do_traverse(Traverse* traverse)
11982   { return Type::traverse(this->type_, traverse); }
11983
11984   Type*
11985   do_type()
11986   { return Type::make_pointer_type(this->type_); }
11987
11988   void
11989   do_determine_type(const Type_context*)
11990   { }
11991
11992   Expression*
11993   do_copy()
11994   { return new Allocation_expression(this->type_, this->location()); }
11995
11996   tree
11997   do_get_tree(Translate_context*);
11998
11999   void
12000   do_dump_expression(Ast_dump_context*) const;
12001   
12002  private:
12003   // The type we are allocating.
12004   Type* type_;
12005 };
12006
12007 // Return a tree for an allocation expression.
12008
12009 tree
12010 Allocation_expression::do_get_tree(Translate_context* context)
12011 {
12012   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
12013   if (type_tree == error_mark_node)
12014     return error_mark_node;
12015   tree size_tree = TYPE_SIZE_UNIT(type_tree);
12016   tree space = context->gogo()->allocate_memory(this->type_, size_tree,
12017                                                 this->location());
12018   if (space == error_mark_node)
12019     return error_mark_node;
12020   return fold_convert(build_pointer_type(type_tree), space);
12021 }
12022
12023 // Dump ast representation for an allocation expression.
12024
12025 void
12026 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
12027     const
12028 {
12029   ast_dump_context->ostream() << "new(";
12030   ast_dump_context->dump_type(this->type_);
12031   ast_dump_context->ostream() << ")";
12032 }
12033
12034 // Make an allocation expression.
12035
12036 Expression*
12037 Expression::make_allocation(Type* type, Location location)
12038 {
12039   return new Allocation_expression(type, location);
12040 }
12041
12042 // Construct a struct.
12043
12044 class Struct_construction_expression : public Expression
12045 {
12046  public:
12047   Struct_construction_expression(Type* type, Expression_list* vals,
12048                                  Location location)
12049     : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
12050       type_(type), vals_(vals)
12051   { }
12052
12053   // Return whether this is a constant initializer.
12054   bool
12055   is_constant_struct() const;
12056
12057  protected:
12058   int
12059   do_traverse(Traverse* traverse);
12060
12061   Type*
12062   do_type()
12063   { return this->type_; }
12064
12065   void
12066   do_determine_type(const Type_context*);
12067
12068   void
12069   do_check_types(Gogo*);
12070
12071   Expression*
12072   do_copy()
12073   {
12074     return new Struct_construction_expression(this->type_, this->vals_->copy(),
12075                                               this->location());
12076   }
12077
12078   tree
12079   do_get_tree(Translate_context*);
12080
12081   void
12082   do_export(Export*) const;
12083
12084   void
12085   do_dump_expression(Ast_dump_context*) const;
12086
12087  private:
12088   // The type of the struct to construct.
12089   Type* type_;
12090   // The list of values, in order of the fields in the struct.  A NULL
12091   // entry means that the field should be zero-initialized.
12092   Expression_list* vals_;
12093 };
12094
12095 // Traversal.
12096
12097 int
12098 Struct_construction_expression::do_traverse(Traverse* traverse)
12099 {
12100   if (this->vals_ != NULL
12101       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12102     return TRAVERSE_EXIT;
12103   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12104     return TRAVERSE_EXIT;
12105   return TRAVERSE_CONTINUE;
12106 }
12107
12108 // Return whether this is a constant initializer.
12109
12110 bool
12111 Struct_construction_expression::is_constant_struct() const
12112 {
12113   if (this->vals_ == NULL)
12114     return true;
12115   for (Expression_list::const_iterator pv = this->vals_->begin();
12116        pv != this->vals_->end();
12117        ++pv)
12118     {
12119       if (*pv != NULL
12120           && !(*pv)->is_constant()
12121           && (!(*pv)->is_composite_literal()
12122               || (*pv)->is_nonconstant_composite_literal()))
12123         return false;
12124     }
12125
12126   const Struct_field_list* fields = this->type_->struct_type()->fields();
12127   for (Struct_field_list::const_iterator pf = fields->begin();
12128        pf != fields->end();
12129        ++pf)
12130     {
12131       // There are no constant constructors for interfaces.
12132       if (pf->type()->interface_type() != NULL)
12133         return false;
12134     }
12135
12136   return true;
12137 }
12138
12139 // Final type determination.
12140
12141 void
12142 Struct_construction_expression::do_determine_type(const Type_context*)
12143 {
12144   if (this->vals_ == NULL)
12145     return;
12146   const Struct_field_list* fields = this->type_->struct_type()->fields();
12147   Expression_list::const_iterator pv = this->vals_->begin();
12148   for (Struct_field_list::const_iterator pf = fields->begin();
12149        pf != fields->end();
12150        ++pf, ++pv)
12151     {
12152       if (pv == this->vals_->end())
12153         return;
12154       if (*pv != NULL)
12155         {
12156           Type_context subcontext(pf->type(), false);
12157           (*pv)->determine_type(&subcontext);
12158         }
12159     }
12160   // Extra values are an error we will report elsewhere; we still want
12161   // to determine the type to avoid knockon errors.
12162   for (; pv != this->vals_->end(); ++pv)
12163     (*pv)->determine_type_no_context();
12164 }
12165
12166 // Check types.
12167
12168 void
12169 Struct_construction_expression::do_check_types(Gogo*)
12170 {
12171   if (this->vals_ == NULL)
12172     return;
12173
12174   Struct_type* st = this->type_->struct_type();
12175   if (this->vals_->size() > st->field_count())
12176     {
12177       this->report_error(_("too many expressions for struct"));
12178       return;
12179     }
12180
12181   const Struct_field_list* fields = st->fields();
12182   Expression_list::const_iterator pv = this->vals_->begin();
12183   int i = 0;
12184   for (Struct_field_list::const_iterator pf = fields->begin();
12185        pf != fields->end();
12186        ++pf, ++pv, ++i)
12187     {
12188       if (pv == this->vals_->end())
12189         {
12190           this->report_error(_("too few expressions for struct"));
12191           break;
12192         }
12193
12194       if (*pv == NULL)
12195         continue;
12196
12197       std::string reason;
12198       if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12199         {
12200           if (reason.empty())
12201             error_at((*pv)->location(),
12202                      "incompatible type for field %d in struct construction",
12203                      i + 1);
12204           else
12205             error_at((*pv)->location(),
12206                      ("incompatible type for field %d in "
12207                       "struct construction (%s)"),
12208                      i + 1, reason.c_str());
12209           this->set_is_error();
12210         }
12211     }
12212   go_assert(pv == this->vals_->end());
12213 }
12214
12215 // Return a tree for constructing a struct.
12216
12217 tree
12218 Struct_construction_expression::do_get_tree(Translate_context* context)
12219 {
12220   Gogo* gogo = context->gogo();
12221
12222   if (this->vals_ == NULL)
12223     {
12224       Btype* btype = this->type_->get_backend(gogo);
12225       return expr_to_tree(gogo->backend()->zero_expression(btype));
12226     }
12227
12228   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12229   if (type_tree == error_mark_node)
12230     return error_mark_node;
12231   go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12232
12233   bool is_constant = true;
12234   const Struct_field_list* fields = this->type_->struct_type()->fields();
12235   VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
12236                                             fields->size());
12237   Struct_field_list::const_iterator pf = fields->begin();
12238   Expression_list::const_iterator pv = this->vals_->begin();
12239   for (tree field = TYPE_FIELDS(type_tree);
12240        field != NULL_TREE;
12241        field = DECL_CHAIN(field), ++pf)
12242     {
12243       go_assert(pf != fields->end());
12244
12245       Btype* fbtype = pf->type()->get_backend(gogo);
12246
12247       tree val;
12248       if (pv == this->vals_->end())
12249         val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
12250       else if (*pv == NULL)
12251         {
12252           val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
12253           ++pv;
12254         }
12255       else
12256         {
12257           val = Expression::convert_for_assignment(context, pf->type(),
12258                                                    (*pv)->type(),
12259                                                    (*pv)->get_tree(context),
12260                                                    this->location());
12261           ++pv;
12262         }
12263
12264       if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
12265         return error_mark_node;
12266
12267       constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
12268       elt->index = field;
12269       elt->value = val;
12270       if (!TREE_CONSTANT(val))
12271         is_constant = false;
12272     }
12273   go_assert(pf == fields->end());
12274
12275   tree ret = build_constructor(type_tree, elts);
12276   if (is_constant)
12277     TREE_CONSTANT(ret) = 1;
12278   return ret;
12279 }
12280
12281 // Export a struct construction.
12282
12283 void
12284 Struct_construction_expression::do_export(Export* exp) const
12285 {
12286   exp->write_c_string("convert(");
12287   exp->write_type(this->type_);
12288   for (Expression_list::const_iterator pv = this->vals_->begin();
12289        pv != this->vals_->end();
12290        ++pv)
12291     {
12292       exp->write_c_string(", ");
12293       if (*pv != NULL)
12294         (*pv)->export_expression(exp);
12295     }
12296   exp->write_c_string(")");
12297 }
12298
12299 // Dump ast representation of a struct construction expression.
12300
12301 void
12302 Struct_construction_expression::do_dump_expression(
12303     Ast_dump_context* ast_dump_context) const
12304 {
12305   ast_dump_context->dump_type(this->type_);
12306   ast_dump_context->ostream() << "{";
12307   ast_dump_context->dump_expression_list(this->vals_);
12308   ast_dump_context->ostream() << "}";
12309 }
12310
12311 // Make a struct composite literal.  This used by the thunk code.
12312
12313 Expression*
12314 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12315                                           Location location)
12316 {
12317   go_assert(type->struct_type() != NULL);
12318   return new Struct_construction_expression(type, vals, location);
12319 }
12320
12321 // Construct an array.  This class is not used directly; instead we
12322 // use the child classes, Fixed_array_construction_expression and
12323 // Open_array_construction_expression.
12324
12325 class Array_construction_expression : public Expression
12326 {
12327  protected:
12328   Array_construction_expression(Expression_classification classification,
12329                                 Type* type, Expression_list* vals,
12330                                 Location location)
12331     : Expression(classification, location),
12332       type_(type), vals_(vals)
12333   { }
12334
12335  public:
12336   // Return whether this is a constant initializer.
12337   bool
12338   is_constant_array() const;
12339
12340   // Return the number of elements.
12341   size_t
12342   element_count() const
12343   { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12344
12345 protected:
12346   int
12347   do_traverse(Traverse* traverse);
12348
12349   Type*
12350   do_type()
12351   { return this->type_; }
12352
12353   void
12354   do_determine_type(const Type_context*);
12355
12356   void
12357   do_check_types(Gogo*);
12358
12359   void
12360   do_export(Export*) const;
12361
12362   // The list of values.
12363   Expression_list*
12364   vals()
12365   { return this->vals_; }
12366
12367   // Get a constructor tree for the array values.
12368   tree
12369   get_constructor_tree(Translate_context* context, tree type_tree);
12370
12371   void
12372   do_dump_expression(Ast_dump_context*) const;
12373
12374  private:
12375   // The type of the array to construct.
12376   Type* type_;
12377   // The list of values.
12378   Expression_list* vals_;
12379 };
12380
12381 // Traversal.
12382
12383 int
12384 Array_construction_expression::do_traverse(Traverse* traverse)
12385 {
12386   if (this->vals_ != NULL
12387       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12388     return TRAVERSE_EXIT;
12389   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12390     return TRAVERSE_EXIT;
12391   return TRAVERSE_CONTINUE;
12392 }
12393
12394 // Return whether this is a constant initializer.
12395
12396 bool
12397 Array_construction_expression::is_constant_array() const
12398 {
12399   if (this->vals_ == NULL)
12400     return true;
12401
12402   // There are no constant constructors for interfaces.
12403   if (this->type_->array_type()->element_type()->interface_type() != NULL)
12404     return false;
12405
12406   for (Expression_list::const_iterator pv = this->vals_->begin();
12407        pv != this->vals_->end();
12408        ++pv)
12409     {
12410       if (*pv != NULL
12411           && !(*pv)->is_constant()
12412           && (!(*pv)->is_composite_literal()
12413               || (*pv)->is_nonconstant_composite_literal()))
12414         return false;
12415     }
12416   return true;
12417 }
12418
12419 // Final type determination.
12420
12421 void
12422 Array_construction_expression::do_determine_type(const Type_context*)
12423 {
12424   if (this->vals_ == NULL)
12425     return;
12426   Type_context subcontext(this->type_->array_type()->element_type(), false);
12427   for (Expression_list::const_iterator pv = this->vals_->begin();
12428        pv != this->vals_->end();
12429        ++pv)
12430     {
12431       if (*pv != NULL)
12432         (*pv)->determine_type(&subcontext);
12433     }
12434 }
12435
12436 // Check types.
12437
12438 void
12439 Array_construction_expression::do_check_types(Gogo*)
12440 {
12441   if (this->vals_ == NULL)
12442     return;
12443
12444   Array_type* at = this->type_->array_type();
12445   int i = 0;
12446   Type* element_type = at->element_type();
12447   for (Expression_list::const_iterator pv = this->vals_->begin();
12448        pv != this->vals_->end();
12449        ++pv, ++i)
12450     {
12451       if (*pv != NULL
12452           && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12453         {
12454           error_at((*pv)->location(),
12455                    "incompatible type for element %d in composite literal",
12456                    i + 1);
12457           this->set_is_error();
12458         }
12459     }
12460
12461   Expression* length = at->length();
12462   if (length != NULL && !length->is_error_expression())
12463     {
12464       mpz_t val;
12465       mpz_init(val);
12466       Type* type;
12467       if (at->length()->integer_constant_value(true, val, &type))
12468         {
12469           if (this->vals_->size() > mpz_get_ui(val))
12470             this->report_error(_("too many elements in composite literal"));
12471         }
12472       mpz_clear(val);
12473     }
12474 }
12475
12476 // Get a constructor tree for the array values.
12477
12478 tree
12479 Array_construction_expression::get_constructor_tree(Translate_context* context,
12480                                                     tree type_tree)
12481 {
12482   VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12483                                               (this->vals_ == NULL
12484                                                ? 0
12485                                                : this->vals_->size()));
12486   Type* element_type = this->type_->array_type()->element_type();
12487   bool is_constant = true;
12488   if (this->vals_ != NULL)
12489     {
12490       size_t i = 0;
12491       for (Expression_list::const_iterator pv = this->vals_->begin();
12492            pv != this->vals_->end();
12493            ++pv, ++i)
12494         {
12495           constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
12496           elt->index = size_int(i);
12497           if (*pv == NULL)
12498             {
12499               Gogo* gogo = context->gogo();
12500               Btype* ebtype = element_type->get_backend(gogo);
12501               Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12502               elt->value = expr_to_tree(zv);
12503             }
12504           else
12505             {
12506               tree value_tree = (*pv)->get_tree(context);
12507               elt->value = Expression::convert_for_assignment(context,
12508                                                               element_type,
12509                                                               (*pv)->type(),
12510                                                               value_tree,
12511                                                               this->location());
12512             }
12513           if (elt->value == error_mark_node)
12514             return error_mark_node;
12515           if (!TREE_CONSTANT(elt->value))
12516             is_constant = false;
12517         }
12518     }
12519
12520   tree ret = build_constructor(type_tree, values);
12521   if (is_constant)
12522     TREE_CONSTANT(ret) = 1;
12523   return ret;
12524 }
12525
12526 // Export an array construction.
12527
12528 void
12529 Array_construction_expression::do_export(Export* exp) const
12530 {
12531   exp->write_c_string("convert(");
12532   exp->write_type(this->type_);
12533   if (this->vals_ != NULL)
12534     {
12535       for (Expression_list::const_iterator pv = this->vals_->begin();
12536            pv != this->vals_->end();
12537            ++pv)
12538         {
12539           exp->write_c_string(", ");
12540           if (*pv != NULL)
12541             (*pv)->export_expression(exp);
12542         }
12543     }
12544   exp->write_c_string(")");
12545 }
12546
12547 // Dump ast representation of an array construction expressin.
12548
12549 void
12550 Array_construction_expression::do_dump_expression(
12551     Ast_dump_context* ast_dump_context) const
12552 {
12553   Expression* length = this->type_->array_type() != NULL ?
12554                          this->type_->array_type()->length() : NULL;
12555
12556   ast_dump_context->ostream() << "[" ;
12557   if (length != NULL)
12558     {
12559       ast_dump_context->dump_expression(length);
12560     }
12561   ast_dump_context->ostream() << "]" ;
12562   ast_dump_context->dump_type(this->type_);
12563   ast_dump_context->ostream() << "{" ;
12564   ast_dump_context->dump_expression_list(this->vals_);
12565   ast_dump_context->ostream() << "}" ;
12566
12567 }
12568
12569 // Construct a fixed array.
12570
12571 class Fixed_array_construction_expression :
12572   public Array_construction_expression
12573 {
12574  public:
12575   Fixed_array_construction_expression(Type* type, Expression_list* vals,
12576                                       Location location)
12577     : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12578                                     type, vals, location)
12579   {
12580     go_assert(type->array_type() != NULL
12581                && type->array_type()->length() != NULL);
12582   }
12583
12584  protected:
12585   Expression*
12586   do_copy()
12587   {
12588     return new Fixed_array_construction_expression(this->type(),
12589                                                    (this->vals() == NULL
12590                                                     ? NULL
12591                                                     : this->vals()->copy()),
12592                                                    this->location());
12593   }
12594
12595   tree
12596   do_get_tree(Translate_context*);
12597
12598   void
12599   do_dump_expression(Ast_dump_context*);
12600 };
12601
12602 // Return a tree for constructing a fixed array.
12603
12604 tree
12605 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12606 {
12607   Type* type = this->type();
12608   Btype* btype = type->get_backend(context->gogo());
12609   return this->get_constructor_tree(context, type_to_tree(btype));
12610 }
12611
12612 // Dump ast representation of an array construction expressin.
12613
12614 void
12615 Fixed_array_construction_expression::do_dump_expression(
12616     Ast_dump_context* ast_dump_context)
12617 {
12618
12619   ast_dump_context->ostream() << "[";
12620   ast_dump_context->dump_expression (this->type()->array_type()->length());
12621   ast_dump_context->ostream() << "]";
12622   ast_dump_context->dump_type(this->type());
12623   ast_dump_context->ostream() << "{";
12624   ast_dump_context->dump_expression_list(this->vals());
12625   ast_dump_context->ostream() << "}";
12626
12627 }
12628 // Construct an open array.
12629
12630 class Open_array_construction_expression : public Array_construction_expression
12631 {
12632  public:
12633   Open_array_construction_expression(Type* type, Expression_list* vals,
12634                                      Location location)
12635     : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
12636                                     type, vals, location)
12637   {
12638     go_assert(type->array_type() != NULL
12639                && type->array_type()->length() == NULL);
12640   }
12641
12642  protected:
12643   // Note that taking the address of an open array literal is invalid.
12644
12645   Expression*
12646   do_copy()
12647   {
12648     return new Open_array_construction_expression(this->type(),
12649                                                   (this->vals() == NULL
12650                                                    ? NULL
12651                                                    : this->vals()->copy()),
12652                                                   this->location());
12653   }
12654
12655   tree
12656   do_get_tree(Translate_context*);
12657 };
12658
12659 // Return a tree for constructing an open array.
12660
12661 tree
12662 Open_array_construction_expression::do_get_tree(Translate_context* context)
12663 {
12664   Array_type* array_type = this->type()->array_type();
12665   if (array_type == NULL)
12666     {
12667       go_assert(this->type()->is_error());
12668       return error_mark_node;
12669     }
12670
12671   Type* element_type = array_type->element_type();
12672   Btype* belement_type = element_type->get_backend(context->gogo());
12673   tree element_type_tree = type_to_tree(belement_type);
12674   if (element_type_tree == error_mark_node)
12675     return error_mark_node;
12676
12677   tree values;
12678   tree length_tree;
12679   if (this->vals() == NULL || this->vals()->empty())
12680     {
12681       // We need to create a unique value.
12682       tree max = size_int(0);
12683       tree constructor_type = build_array_type(element_type_tree,
12684                                                build_index_type(max));
12685       if (constructor_type == error_mark_node)
12686         return error_mark_node;
12687       VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
12688       constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
12689       elt->index = size_int(0);
12690       Gogo* gogo = context->gogo();
12691       Btype* btype = element_type->get_backend(gogo);
12692       elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
12693       values = build_constructor(constructor_type, vec);
12694       if (TREE_CONSTANT(elt->value))
12695         TREE_CONSTANT(values) = 1;
12696       length_tree = size_int(0);
12697     }
12698   else
12699     {
12700       tree max = size_int(this->vals()->size() - 1);
12701       tree constructor_type = build_array_type(element_type_tree,
12702                                                build_index_type(max));
12703       if (constructor_type == error_mark_node)
12704         return error_mark_node;
12705       values = this->get_constructor_tree(context, constructor_type);
12706       length_tree = size_int(this->vals()->size());
12707     }
12708
12709   if (values == error_mark_node)
12710     return error_mark_node;
12711
12712   bool is_constant_initializer = TREE_CONSTANT(values);
12713
12714   // We have to copy the initial values into heap memory if we are in
12715   // a function or if the values are not constants.  We also have to
12716   // copy them if they may contain pointers in a non-constant context,
12717   // as otherwise the garbage collector won't see them.
12718   bool copy_to_heap = (context->function() != NULL
12719                        || !is_constant_initializer
12720                        || (element_type->has_pointer()
12721                            && !context->is_const()));
12722
12723   if (is_constant_initializer)
12724     {
12725       tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
12726                             create_tmp_var_name("C"), TREE_TYPE(values));
12727       DECL_EXTERNAL(tmp) = 0;
12728       TREE_PUBLIC(tmp) = 0;
12729       TREE_STATIC(tmp) = 1;
12730       DECL_ARTIFICIAL(tmp) = 1;
12731       if (copy_to_heap)
12732         {
12733           // If we are not copying the value to the heap, we will only
12734           // initialize the value once, so we can use this directly
12735           // rather than copying it.  In that case we can't make it
12736           // read-only, because the program is permitted to change it.
12737           TREE_READONLY(tmp) = 1;
12738           TREE_CONSTANT(tmp) = 1;
12739         }
12740       DECL_INITIAL(tmp) = values;
12741       rest_of_decl_compilation(tmp, 1, 0);
12742       values = tmp;
12743     }
12744
12745   tree space;
12746   tree set;
12747   if (!copy_to_heap)
12748     {
12749       // the initializer will only run once.
12750       space = build_fold_addr_expr(values);
12751       set = NULL_TREE;
12752     }
12753   else
12754     {
12755       tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
12756       space = context->gogo()->allocate_memory(element_type, memsize,
12757                                                this->location());
12758       space = save_expr(space);
12759
12760       tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
12761       tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12762                                              s);
12763       TREE_THIS_NOTRAP(ref) = 1;
12764       set = build2(MODIFY_EXPR, void_type_node, ref, values);
12765     }
12766
12767   // Build a constructor for the open array.
12768
12769   tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
12770   if (type_tree == error_mark_node)
12771     return error_mark_node;
12772   go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12773
12774   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
12775
12776   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
12777   tree field = TYPE_FIELDS(type_tree);
12778   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
12779   elt->index = field;
12780   elt->value = fold_convert(TREE_TYPE(field), space);
12781
12782   elt = VEC_quick_push(constructor_elt, init, NULL);
12783   field = DECL_CHAIN(field);
12784   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
12785   elt->index = field;
12786   elt->value = fold_convert(TREE_TYPE(field), length_tree);
12787
12788   elt = VEC_quick_push(constructor_elt, init, NULL);
12789   field = DECL_CHAIN(field);
12790   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
12791   elt->index = field;
12792   elt->value = fold_convert(TREE_TYPE(field), length_tree);
12793
12794   tree constructor = build_constructor(type_tree, init);
12795   if (constructor == error_mark_node)
12796     return error_mark_node;
12797   if (!copy_to_heap)
12798     TREE_CONSTANT(constructor) = 1;
12799
12800   if (set == NULL_TREE)
12801     return constructor;
12802   else
12803     return build2(COMPOUND_EXPR, type_tree, set, constructor);
12804 }
12805
12806 // Make a slice composite literal.  This is used by the type
12807 // descriptor code.
12808
12809 Expression*
12810 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12811                                          Location location)
12812 {
12813   go_assert(type->is_slice_type());
12814   return new Open_array_construction_expression(type, vals, location);
12815 }
12816
12817 // Construct a map.
12818
12819 class Map_construction_expression : public Expression
12820 {
12821  public:
12822   Map_construction_expression(Type* type, Expression_list* vals,
12823                               Location location)
12824     : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12825       type_(type), vals_(vals)
12826   { go_assert(vals == NULL || vals->size() % 2 == 0); }
12827
12828  protected:
12829   int
12830   do_traverse(Traverse* traverse);
12831
12832   Type*
12833   do_type()
12834   { return this->type_; }
12835
12836   void
12837   do_determine_type(const Type_context*);
12838
12839   void
12840   do_check_types(Gogo*);
12841
12842   Expression*
12843   do_copy()
12844   {
12845     return new Map_construction_expression(this->type_, this->vals_->copy(),
12846                                            this->location());
12847   }
12848
12849   tree
12850   do_get_tree(Translate_context*);
12851
12852   void
12853   do_export(Export*) const;
12854
12855   void
12856   do_dump_expression(Ast_dump_context*) const;
12857   
12858  private:
12859   // The type of the map to construct.
12860   Type* type_;
12861   // The list of values.
12862   Expression_list* vals_;
12863 };
12864
12865 // Traversal.
12866
12867 int
12868 Map_construction_expression::do_traverse(Traverse* traverse)
12869 {
12870   if (this->vals_ != NULL
12871       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12872     return TRAVERSE_EXIT;
12873   if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12874     return TRAVERSE_EXIT;
12875   return TRAVERSE_CONTINUE;
12876 }
12877
12878 // Final type determination.
12879
12880 void
12881 Map_construction_expression::do_determine_type(const Type_context*)
12882 {
12883   if (this->vals_ == NULL)
12884     return;
12885
12886   Map_type* mt = this->type_->map_type();
12887   Type_context key_context(mt->key_type(), false);
12888   Type_context val_context(mt->val_type(), false);
12889   for (Expression_list::const_iterator pv = this->vals_->begin();
12890        pv != this->vals_->end();
12891        ++pv)
12892     {
12893       (*pv)->determine_type(&key_context);
12894       ++pv;
12895       (*pv)->determine_type(&val_context);
12896     }
12897 }
12898
12899 // Check types.
12900
12901 void
12902 Map_construction_expression::do_check_types(Gogo*)
12903 {
12904   if (this->vals_ == NULL)
12905     return;
12906
12907   Map_type* mt = this->type_->map_type();
12908   int i = 0;
12909   Type* key_type = mt->key_type();
12910   Type* val_type = mt->val_type();
12911   for (Expression_list::const_iterator pv = this->vals_->begin();
12912        pv != this->vals_->end();
12913        ++pv, ++i)
12914     {
12915       if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12916         {
12917           error_at((*pv)->location(),
12918                    "incompatible type for element %d key in map construction",
12919                    i + 1);
12920           this->set_is_error();
12921         }
12922       ++pv;
12923       if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12924         {
12925           error_at((*pv)->location(),
12926                    ("incompatible type for element %d value "
12927                     "in map construction"),
12928                    i + 1);
12929           this->set_is_error();
12930         }
12931     }
12932 }
12933
12934 // Return a tree for constructing a map.
12935
12936 tree
12937 Map_construction_expression::do_get_tree(Translate_context* context)
12938 {
12939   Gogo* gogo = context->gogo();
12940   Location loc = this->location();
12941
12942   Map_type* mt = this->type_->map_type();
12943
12944   // Build a struct to hold the key and value.
12945   tree struct_type = make_node(RECORD_TYPE);
12946
12947   Type* key_type = mt->key_type();
12948   tree id = get_identifier("__key");
12949   tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12950   if (key_type_tree == error_mark_node)
12951     return error_mark_node;
12952   tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12953                               key_type_tree);
12954   DECL_CONTEXT(key_field) = struct_type;
12955   TYPE_FIELDS(struct_type) = key_field;
12956
12957   Type* val_type = mt->val_type();
12958   id = get_identifier("__val");
12959   tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12960   if (val_type_tree == error_mark_node)
12961     return error_mark_node;
12962   tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12963                               val_type_tree);
12964   DECL_CONTEXT(val_field) = struct_type;
12965   DECL_CHAIN(key_field) = val_field;
12966
12967   layout_type(struct_type);
12968
12969   bool is_constant = true;
12970   size_t i = 0;
12971   tree valaddr;
12972   tree make_tmp;
12973
12974   if (this->vals_ == NULL || this->vals_->empty())
12975     {
12976       valaddr = null_pointer_node;
12977       make_tmp = NULL_TREE;
12978     }
12979   else
12980     {
12981       VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12982                                                   this->vals_->size() / 2);
12983
12984       for (Expression_list::const_iterator pv = this->vals_->begin();
12985            pv != this->vals_->end();
12986            ++pv, ++i)
12987         {
12988           bool one_is_constant = true;
12989
12990           VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12991
12992           constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12993           elt->index = key_field;
12994           tree val_tree = (*pv)->get_tree(context);
12995           elt->value = Expression::convert_for_assignment(context, key_type,
12996                                                           (*pv)->type(),
12997                                                           val_tree, loc);
12998           if (elt->value == error_mark_node)
12999             return error_mark_node;
13000           if (!TREE_CONSTANT(elt->value))
13001             one_is_constant = false;
13002
13003           ++pv;
13004
13005           elt = VEC_quick_push(constructor_elt, one, NULL);
13006           elt->index = val_field;
13007           val_tree = (*pv)->get_tree(context);
13008           elt->value = Expression::convert_for_assignment(context, val_type,
13009                                                           (*pv)->type(),
13010                                                           val_tree, loc);
13011           if (elt->value == error_mark_node)
13012             return error_mark_node;
13013           if (!TREE_CONSTANT(elt->value))
13014             one_is_constant = false;
13015
13016           elt = VEC_quick_push(constructor_elt, values, NULL);
13017           elt->index = size_int(i);
13018           elt->value = build_constructor(struct_type, one);
13019           if (one_is_constant)
13020             TREE_CONSTANT(elt->value) = 1;
13021           else
13022             is_constant = false;
13023         }
13024
13025       tree index_type = build_index_type(size_int(i - 1));
13026       tree array_type = build_array_type(struct_type, index_type);
13027       tree init = build_constructor(array_type, values);
13028       if (is_constant)
13029         TREE_CONSTANT(init) = 1;
13030       tree tmp;
13031       if (current_function_decl != NULL)
13032         {
13033           tmp = create_tmp_var(array_type, get_name(array_type));
13034           DECL_INITIAL(tmp) = init;
13035           make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
13036                                      void_type_node, tmp);
13037           TREE_ADDRESSABLE(tmp) = 1;
13038         }
13039       else
13040         {
13041           tmp = build_decl(loc.gcc_location(), VAR_DECL,
13042                            create_tmp_var_name("M"), array_type);
13043           DECL_EXTERNAL(tmp) = 0;
13044           TREE_PUBLIC(tmp) = 0;
13045           TREE_STATIC(tmp) = 1;
13046           DECL_ARTIFICIAL(tmp) = 1;
13047           if (!TREE_CONSTANT(init))
13048             make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
13049                                        void_type_node, tmp, init);
13050           else
13051             {
13052               TREE_READONLY(tmp) = 1;
13053               TREE_CONSTANT(tmp) = 1;
13054               DECL_INITIAL(tmp) = init;
13055               make_tmp = NULL_TREE;
13056             }
13057           rest_of_decl_compilation(tmp, 1, 0);
13058         }
13059
13060       valaddr = build_fold_addr_expr(tmp);
13061     }
13062
13063   tree descriptor = mt->map_descriptor_pointer(gogo, loc);
13064
13065   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
13066   if (type_tree == error_mark_node)
13067     return error_mark_node;
13068
13069   static tree construct_map_fndecl;
13070   tree call = Gogo::call_builtin(&construct_map_fndecl,
13071                                  loc,
13072                                  "__go_construct_map",
13073                                  6,
13074                                  type_tree,
13075                                  TREE_TYPE(descriptor),
13076                                  descriptor,
13077                                  sizetype,
13078                                  size_int(i),
13079                                  sizetype,
13080                                  TYPE_SIZE_UNIT(struct_type),
13081                                  sizetype,
13082                                  byte_position(val_field),
13083                                  sizetype,
13084                                  TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
13085                                  const_ptr_type_node,
13086                                  fold_convert(const_ptr_type_node, valaddr));
13087   if (call == error_mark_node)
13088     return error_mark_node;
13089
13090   tree ret;
13091   if (make_tmp == NULL)
13092     ret = call;
13093   else
13094     ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
13095                           make_tmp, call);
13096   return ret;
13097 }
13098
13099 // Export an array construction.
13100
13101 void
13102 Map_construction_expression::do_export(Export* exp) const
13103 {
13104   exp->write_c_string("convert(");
13105   exp->write_type(this->type_);
13106   for (Expression_list::const_iterator pv = this->vals_->begin();
13107        pv != this->vals_->end();
13108        ++pv)
13109     {
13110       exp->write_c_string(", ");
13111       (*pv)->export_expression(exp);
13112     }
13113   exp->write_c_string(")");
13114 }
13115
13116 // Dump ast representation for a map construction expression.
13117
13118 void
13119 Map_construction_expression::do_dump_expression(
13120     Ast_dump_context* ast_dump_context) const
13121 {
13122   ast_dump_context->ostream() << "{" ;
13123   ast_dump_context->dump_expression_list(this->vals_, true);
13124   ast_dump_context->ostream() << "}";
13125 }
13126
13127 // A general composite literal.  This is lowered to a type specific
13128 // version.
13129
13130 class Composite_literal_expression : public Parser_expression
13131 {
13132  public:
13133   Composite_literal_expression(Type* type, int depth, bool has_keys,
13134                                Expression_list* vals, Location location)
13135     : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
13136       type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
13137   { }
13138
13139  protected:
13140   int
13141   do_traverse(Traverse* traverse);
13142
13143   Expression*
13144   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
13145
13146   Expression*
13147   do_copy()
13148   {
13149     return new Composite_literal_expression(this->type_, this->depth_,
13150                                             this->has_keys_,
13151                                             (this->vals_ == NULL
13152                                              ? NULL
13153                                              : this->vals_->copy()),
13154                                             this->location());
13155   }
13156
13157   void
13158   do_dump_expression(Ast_dump_context*) const;
13159   
13160  private:
13161   Expression*
13162   lower_struct(Gogo*, Type*);
13163
13164   Expression*
13165   lower_array(Type*);
13166
13167   Expression*
13168   make_array(Type*, Expression_list*);
13169
13170   Expression*
13171   lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
13172
13173   // The type of the composite literal.
13174   Type* type_;
13175   // The depth within a list of composite literals within a composite
13176   // literal, when the type is omitted.
13177   int depth_;
13178   // The values to put in the composite literal.
13179   Expression_list* vals_;
13180   // If this is true, then VALS_ is a list of pairs: a key and a
13181   // value.  In an array initializer, a missing key will be NULL.
13182   bool has_keys_;
13183 };
13184
13185 // Traversal.
13186
13187 int
13188 Composite_literal_expression::do_traverse(Traverse* traverse)
13189 {
13190   if (this->vals_ != NULL
13191       && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13192     return TRAVERSE_EXIT;
13193   return Type::traverse(this->type_, traverse);
13194 }
13195
13196 // Lower a generic composite literal into a specific version based on
13197 // the type.
13198
13199 Expression*
13200 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13201                                        Statement_inserter* inserter, int)
13202 {
13203   Type* type = this->type_;
13204
13205   for (int depth = this->depth_; depth > 0; --depth)
13206     {
13207       if (type->array_type() != NULL)
13208         type = type->array_type()->element_type();
13209       else if (type->map_type() != NULL)
13210         type = type->map_type()->val_type();
13211       else
13212         {
13213           if (!type->is_error())
13214             error_at(this->location(),
13215                      ("may only omit types within composite literals "
13216                       "of slice, array, or map type"));
13217           return Expression::make_error(this->location());
13218         }
13219     }
13220
13221   Type *pt = type->points_to();
13222   bool is_pointer = false;
13223   if (pt != NULL)
13224     {
13225       is_pointer = true;
13226       type = pt;
13227     }
13228
13229   Expression* ret;
13230   if (type->is_error())
13231     return Expression::make_error(this->location());
13232   else if (type->struct_type() != NULL)
13233     ret = this->lower_struct(gogo, type);
13234   else if (type->array_type() != NULL)
13235     ret = this->lower_array(type);
13236   else if (type->map_type() != NULL)
13237     ret = this->lower_map(gogo, function, inserter, type);
13238   else
13239     {
13240       error_at(this->location(),
13241                ("expected struct, slice, array, or map type "
13242                 "for composite literal"));
13243       return Expression::make_error(this->location());
13244     }
13245
13246   if (is_pointer)
13247     ret = Expression::make_heap_composite(ret, this->location());
13248
13249   return ret;
13250 }
13251
13252 // Lower a struct composite literal.
13253
13254 Expression*
13255 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13256 {
13257   Location location = this->location();
13258   Struct_type* st = type->struct_type();
13259   if (this->vals_ == NULL || !this->has_keys_)
13260     {
13261       if (this->vals_ != NULL
13262           && !this->vals_->empty()
13263           && type->named_type() != NULL
13264           && type->named_type()->named_object()->package() != NULL)
13265         {
13266           for (Struct_field_list::const_iterator pf = st->fields()->begin();
13267                pf != st->fields()->end();
13268                ++pf)
13269             {
13270               if (Gogo::is_hidden_name(pf->field_name()))
13271                 error_at(this->location(),
13272                          "assignment of unexported field %qs in %qs literal",
13273                          Gogo::message_name(pf->field_name()).c_str(),
13274                          type->named_type()->message_name().c_str());
13275             }
13276         }
13277
13278       return new Struct_construction_expression(type, this->vals_, location);
13279     }
13280
13281   size_t field_count = st->field_count();
13282   std::vector<Expression*> vals(field_count);
13283   Expression_list::const_iterator p = this->vals_->begin();
13284   while (p != this->vals_->end())
13285     {
13286       Expression* name_expr = *p;
13287
13288       ++p;
13289       go_assert(p != this->vals_->end());
13290       Expression* val = *p;
13291
13292       ++p;
13293
13294       if (name_expr == NULL)
13295         {
13296           error_at(val->location(), "mixture of field and value initializers");
13297           return Expression::make_error(location);
13298         }
13299
13300       bool bad_key = false;
13301       std::string name;
13302       const Named_object* no = NULL;
13303       switch (name_expr->classification())
13304         {
13305         case EXPRESSION_UNKNOWN_REFERENCE:
13306           name = name_expr->unknown_expression()->name();
13307           break;
13308
13309         case EXPRESSION_CONST_REFERENCE:
13310           no = static_cast<Const_expression*>(name_expr)->named_object();
13311           break;
13312
13313         case EXPRESSION_TYPE:
13314           {
13315             Type* t = name_expr->type();
13316             Named_type* nt = t->named_type();
13317             if (nt == NULL)
13318               bad_key = true;
13319             else
13320               no = nt->named_object();
13321           }
13322           break;
13323
13324         case EXPRESSION_VAR_REFERENCE:
13325           no = name_expr->var_expression()->named_object();
13326           break;
13327
13328         case EXPRESSION_FUNC_REFERENCE:
13329           no = name_expr->func_expression()->named_object();
13330           break;
13331
13332         case EXPRESSION_UNARY:
13333           // If there is a local variable around with the same name as
13334           // the field, and this occurs in the closure, then the
13335           // parser may turn the field reference into an indirection
13336           // through the closure.  FIXME: This is a mess.
13337           {
13338             bad_key = true;
13339             Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13340             if (ue->op() == OPERATOR_MULT)
13341               {
13342                 Field_reference_expression* fre =
13343                   ue->operand()->field_reference_expression();
13344                 if (fre != NULL)
13345                   {
13346                     Struct_type* st =
13347                       fre->expr()->type()->deref()->struct_type();
13348                     if (st != NULL)
13349                       {
13350                         const Struct_field* sf = st->field(fre->field_index());
13351                         name = sf->field_name();
13352
13353                         // See below.  FIXME.
13354                         if (!Gogo::is_hidden_name(name)
13355                             && name[0] >= 'a'
13356                             && name[0] <= 'z')
13357                           {
13358                             if (gogo->lookup_global(name.c_str()) != NULL)
13359                               name = gogo->pack_hidden_name(name, false);
13360                           }
13361
13362                         char buf[20];
13363                         snprintf(buf, sizeof buf, "%u", fre->field_index());
13364                         size_t buflen = strlen(buf);
13365                         if (name.compare(name.length() - buflen, buflen, buf)
13366                             == 0)
13367                           {
13368                             name = name.substr(0, name.length() - buflen);
13369                             bad_key = false;
13370                           }
13371                       }
13372                   }
13373               }
13374           }
13375           break;
13376
13377         default:
13378           bad_key = true;
13379           break;
13380         }
13381       if (bad_key)
13382         {
13383           error_at(name_expr->location(), "expected struct field name");
13384           return Expression::make_error(location);
13385         }
13386
13387       if (no != NULL)
13388         {
13389           name = no->name();
13390
13391           // A predefined name won't be packed.  If it starts with a
13392           // lower case letter we need to check for that case, because
13393           // the field name will be packed.  FIXME.
13394           if (!Gogo::is_hidden_name(name)
13395               && name[0] >= 'a'
13396               && name[0] <= 'z')
13397             {
13398               Named_object* gno = gogo->lookup_global(name.c_str());
13399               if (gno == no)
13400                 name = gogo->pack_hidden_name(name, false);
13401             }
13402         }
13403
13404       unsigned int index;
13405       const Struct_field* sf = st->find_local_field(name, &index);
13406       if (sf == NULL)
13407         {
13408           error_at(name_expr->location(), "unknown field %qs in %qs",
13409                    Gogo::message_name(name).c_str(),
13410                    (type->named_type() != NULL
13411                     ? type->named_type()->message_name().c_str()
13412                     : "unnamed struct"));
13413           return Expression::make_error(location);
13414         }
13415       if (vals[index] != NULL)
13416         {
13417           error_at(name_expr->location(),
13418                    "duplicate value for field %qs in %qs",
13419                    Gogo::message_name(name).c_str(),
13420                    (type->named_type() != NULL
13421                     ? type->named_type()->message_name().c_str()
13422                     : "unnamed struct"));
13423           return Expression::make_error(location);
13424         }
13425
13426       if (type->named_type() != NULL
13427           && type->named_type()->named_object()->package() != NULL
13428           && Gogo::is_hidden_name(sf->field_name()))
13429         error_at(name_expr->location(),
13430                  "assignment of unexported field %qs in %qs literal",
13431                  Gogo::message_name(sf->field_name()).c_str(),
13432                  type->named_type()->message_name().c_str());
13433
13434       vals[index] = val;
13435     }
13436
13437   Expression_list* list = new Expression_list;
13438   list->reserve(field_count);
13439   for (size_t i = 0; i < field_count; ++i)
13440     list->push_back(vals[i]);
13441
13442   return new Struct_construction_expression(type, list, location);
13443 }
13444
13445 // Lower an array composite literal.
13446
13447 Expression*
13448 Composite_literal_expression::lower_array(Type* type)
13449 {
13450   Location location = this->location();
13451   if (this->vals_ == NULL || !this->has_keys_)
13452     return this->make_array(type, this->vals_);
13453
13454   std::vector<Expression*> vals;
13455   vals.reserve(this->vals_->size());
13456   unsigned long index = 0;
13457   Expression_list::const_iterator p = this->vals_->begin();
13458   while (p != this->vals_->end())
13459     {
13460       Expression* index_expr = *p;
13461
13462       ++p;
13463       go_assert(p != this->vals_->end());
13464       Expression* val = *p;
13465
13466       ++p;
13467
13468       if (index_expr != NULL)
13469         {
13470           mpz_t ival;
13471           mpz_init(ival);
13472
13473           Type* dummy;
13474           if (!index_expr->integer_constant_value(true, ival, &dummy))
13475             {
13476               mpz_clear(ival);
13477               error_at(index_expr->location(),
13478                        "index expression is not integer constant");
13479               return Expression::make_error(location);
13480             }
13481
13482           if (mpz_sgn(ival) < 0)
13483             {
13484               mpz_clear(ival);
13485               error_at(index_expr->location(), "index expression is negative");
13486               return Expression::make_error(location);
13487             }
13488
13489           index = mpz_get_ui(ival);
13490           if (mpz_cmp_ui(ival, index) != 0)
13491             {
13492               mpz_clear(ival);
13493               error_at(index_expr->location(), "index value overflow");
13494               return Expression::make_error(location);
13495             }
13496
13497           Named_type* ntype = Type::lookup_integer_type("int");
13498           Integer_type* inttype = ntype->integer_type();
13499           mpz_t max;
13500           mpz_init_set_ui(max, 1);
13501           mpz_mul_2exp(max, max, inttype->bits() - 1);
13502           bool ok = mpz_cmp(ival, max) < 0;
13503           mpz_clear(max);
13504           if (!ok)
13505             {
13506               mpz_clear(ival);
13507               error_at(index_expr->location(), "index value overflow");
13508               return Expression::make_error(location);
13509             }
13510
13511           mpz_clear(ival);
13512
13513           // FIXME: Our representation isn't very good; this avoids
13514           // thrashing.
13515           if (index > 0x1000000)
13516             {
13517               error_at(index_expr->location(), "index too large for compiler");
13518               return Expression::make_error(location);
13519             }
13520         }
13521
13522       if (index == vals.size())
13523         vals.push_back(val);
13524       else
13525         {
13526           if (index > vals.size())
13527             {
13528               vals.reserve(index + 32);
13529               vals.resize(index + 1, static_cast<Expression*>(NULL));
13530             }
13531           if (vals[index] != NULL)
13532             {
13533               error_at((index_expr != NULL
13534                         ? index_expr->location()
13535                         : val->location()),
13536                        "duplicate value for index %lu",
13537                        index);
13538               return Expression::make_error(location);
13539             }
13540           vals[index] = val;
13541         }
13542
13543       ++index;
13544     }
13545
13546   size_t size = vals.size();
13547   Expression_list* list = new Expression_list;
13548   list->reserve(size);
13549   for (size_t i = 0; i < size; ++i)
13550     list->push_back(vals[i]);
13551
13552   return this->make_array(type, list);
13553 }
13554
13555 // Actually build the array composite literal. This handles
13556 // [...]{...}.
13557
13558 Expression*
13559 Composite_literal_expression::make_array(Type* type, Expression_list* vals)
13560 {
13561   Location location = this->location();
13562   Array_type* at = type->array_type();
13563   if (at->length() != NULL && at->length()->is_nil_expression())
13564     {
13565       size_t size = vals == NULL ? 0 : vals->size();
13566       mpz_t vlen;
13567       mpz_init_set_ui(vlen, size);
13568       Expression* elen = Expression::make_integer(&vlen, NULL, location);
13569       mpz_clear(vlen);
13570       at = Type::make_array_type(at->element_type(), elen);
13571       type = at;
13572     }
13573   if (at->length() != NULL)
13574     return new Fixed_array_construction_expression(type, vals, location);
13575   else
13576     return new Open_array_construction_expression(type, vals, location);
13577 }
13578
13579 // Lower a map composite literal.
13580
13581 Expression*
13582 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13583                                         Statement_inserter* inserter,
13584                                         Type* type)
13585 {
13586   Location location = this->location();
13587   if (this->vals_ != NULL)
13588     {
13589       if (!this->has_keys_)
13590         {
13591           error_at(location, "map composite literal must have keys");
13592           return Expression::make_error(location);
13593         }
13594
13595       for (Expression_list::iterator p = this->vals_->begin();
13596            p != this->vals_->end();
13597            p += 2)
13598         {
13599           if (*p == NULL)
13600             {
13601               ++p;
13602               error_at((*p)->location(),
13603                        "map composite literal must have keys for every value");
13604               return Expression::make_error(location);
13605             }
13606           // Make sure we have lowered the key; it may not have been
13607           // lowered in order to handle keys for struct composite
13608           // literals.  Lower it now to get the right error message.
13609           if ((*p)->unknown_expression() != NULL)
13610             {
13611               (*p)->unknown_expression()->clear_is_composite_literal_key();
13612               gogo->lower_expression(function, inserter, &*p);
13613               go_assert((*p)->is_error_expression());
13614               return Expression::make_error(location);
13615             }
13616         }
13617     }
13618
13619   return new Map_construction_expression(type, this->vals_, location);
13620 }
13621
13622 // Dump ast representation for a composite literal expression.
13623
13624 void
13625 Composite_literal_expression::do_dump_expression(
13626                                Ast_dump_context* ast_dump_context) const
13627 {
13628   ast_dump_context->ostream() << "composite(";
13629   ast_dump_context->dump_type(this->type_);
13630   ast_dump_context->ostream() << ", {";
13631   ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13632   ast_dump_context->ostream() << "})";
13633 }
13634
13635 // Make a composite literal expression.
13636
13637 Expression*
13638 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13639                                    Expression_list* vals,
13640                                    Location location)
13641 {
13642   return new Composite_literal_expression(type, depth, has_keys, vals,
13643                                           location);
13644 }
13645
13646 // Return whether this expression is a composite literal.
13647
13648 bool
13649 Expression::is_composite_literal() const
13650 {
13651   switch (this->classification_)
13652     {
13653     case EXPRESSION_COMPOSITE_LITERAL:
13654     case EXPRESSION_STRUCT_CONSTRUCTION:
13655     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13656     case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
13657     case EXPRESSION_MAP_CONSTRUCTION:
13658       return true;
13659     default:
13660       return false;
13661     }
13662 }
13663
13664 // Return whether this expression is a composite literal which is not
13665 // constant.
13666
13667 bool
13668 Expression::is_nonconstant_composite_literal() const
13669 {
13670   switch (this->classification_)
13671     {
13672     case EXPRESSION_STRUCT_CONSTRUCTION:
13673       {
13674         const Struct_construction_expression *psce =
13675           static_cast<const Struct_construction_expression*>(this);
13676         return !psce->is_constant_struct();
13677       }
13678     case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13679       {
13680         const Fixed_array_construction_expression *pace =
13681           static_cast<const Fixed_array_construction_expression*>(this);
13682         return !pace->is_constant_array();
13683       }
13684     case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
13685       {
13686         const Open_array_construction_expression *pace =
13687           static_cast<const Open_array_construction_expression*>(this);
13688         return !pace->is_constant_array();
13689       }
13690     case EXPRESSION_MAP_CONSTRUCTION:
13691       return true;
13692     default:
13693       return false;
13694     }
13695 }
13696
13697 // Return true if this is a reference to a local variable.
13698
13699 bool
13700 Expression::is_local_variable() const
13701 {
13702   const Var_expression* ve = this->var_expression();
13703   if (ve == NULL)
13704     return false;
13705   const Named_object* no = ve->named_object();
13706   return (no->is_result_variable()
13707           || (no->is_variable() && !no->var_value()->is_global()));
13708 }
13709
13710 // Class Type_guard_expression.
13711
13712 // Traversal.
13713
13714 int
13715 Type_guard_expression::do_traverse(Traverse* traverse)
13716 {
13717   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13718       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13719     return TRAVERSE_EXIT;
13720   return TRAVERSE_CONTINUE;
13721 }
13722
13723 // Check types of a type guard expression.  The expression must have
13724 // an interface type, but the actual type conversion is checked at run
13725 // time.
13726
13727 void
13728 Type_guard_expression::do_check_types(Gogo*)
13729 {
13730   // 6g permits using a type guard with unsafe.pointer; we are
13731   // compatible.
13732   Type* expr_type = this->expr_->type();
13733   if (expr_type->is_unsafe_pointer_type())
13734     {
13735       if (this->type_->points_to() == NULL
13736           && (this->type_->integer_type() == NULL
13737               || (this->type_->forwarded()
13738                   != Type::lookup_integer_type("uintptr"))))
13739         this->report_error(_("invalid unsafe.Pointer conversion"));
13740     }
13741   else if (this->type_->is_unsafe_pointer_type())
13742     {
13743       if (expr_type->points_to() == NULL
13744           && (expr_type->integer_type() == NULL
13745               || (expr_type->forwarded()
13746                   != Type::lookup_integer_type("uintptr"))))
13747         this->report_error(_("invalid unsafe.Pointer conversion"));
13748     }
13749   else if (expr_type->interface_type() == NULL)
13750     {
13751       if (!expr_type->is_error() && !this->type_->is_error())
13752         this->report_error(_("type assertion only valid for interface types"));
13753       this->set_is_error();
13754     }
13755   else if (this->type_->interface_type() == NULL)
13756     {
13757       std::string reason;
13758       if (!expr_type->interface_type()->implements_interface(this->type_,
13759                                                              &reason))
13760         {
13761           if (!this->type_->is_error())
13762             {
13763               if (reason.empty())
13764                 this->report_error(_("impossible type assertion: "
13765                                      "type does not implement interface"));
13766               else
13767                 error_at(this->location(),
13768                          ("impossible type assertion: "
13769                           "type does not implement interface (%s)"),
13770                          reason.c_str());
13771             }
13772           this->set_is_error();
13773         }
13774     }
13775 }
13776
13777 // Return a tree for a type guard expression.
13778
13779 tree
13780 Type_guard_expression::do_get_tree(Translate_context* context)
13781 {
13782   Gogo* gogo = context->gogo();
13783   tree expr_tree = this->expr_->get_tree(context);
13784   if (expr_tree == error_mark_node)
13785     return error_mark_node;
13786   Type* expr_type = this->expr_->type();
13787   if ((this->type_->is_unsafe_pointer_type()
13788        && (expr_type->points_to() != NULL
13789            || expr_type->integer_type() != NULL))
13790       || (expr_type->is_unsafe_pointer_type()
13791           && this->type_->points_to() != NULL))
13792     return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
13793                               expr_tree);
13794   else if (expr_type->is_unsafe_pointer_type()
13795            && this->type_->integer_type() != NULL)
13796     return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
13797                               expr_tree);
13798   else if (this->type_->interface_type() != NULL)
13799     return Expression::convert_interface_to_interface(context, this->type_,
13800                                                       this->expr_->type(),
13801                                                       expr_tree, true,
13802                                                       this->location());
13803   else
13804     return Expression::convert_for_assignment(context, this->type_,
13805                                               this->expr_->type(), expr_tree,
13806                                               this->location());
13807 }
13808
13809 // Dump ast representation for a type guard expression.
13810
13811 void
13812 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context) 
13813     const
13814 {
13815   this->expr_->dump_expression(ast_dump_context);
13816   ast_dump_context->ostream() <<  ".";
13817   ast_dump_context->dump_type(this->type_);
13818 }
13819
13820 // Make a type guard expression.
13821
13822 Expression*
13823 Expression::make_type_guard(Expression* expr, Type* type,
13824                             Location location)
13825 {
13826   return new Type_guard_expression(expr, type, location);
13827 }
13828
13829 // Class Heap_composite_expression.
13830
13831 // When you take the address of a composite literal, it is allocated
13832 // on the heap.  This class implements that.
13833
13834 class Heap_composite_expression : public Expression
13835 {
13836  public:
13837   Heap_composite_expression(Expression* expr, Location location)
13838     : Expression(EXPRESSION_HEAP_COMPOSITE, location),
13839       expr_(expr)
13840   { }
13841
13842  protected:
13843   int
13844   do_traverse(Traverse* traverse)
13845   { return Expression::traverse(&this->expr_, traverse); }
13846
13847   Type*
13848   do_type()
13849   { return Type::make_pointer_type(this->expr_->type()); }
13850
13851   void
13852   do_determine_type(const Type_context*)
13853   { this->expr_->determine_type_no_context(); }
13854
13855   Expression*
13856   do_copy()
13857   {
13858     return Expression::make_heap_composite(this->expr_->copy(),
13859                                            this->location());
13860   }
13861
13862   tree
13863   do_get_tree(Translate_context*);
13864
13865   // We only export global objects, and the parser does not generate
13866   // this in global scope.
13867   void
13868   do_export(Export*) const
13869   { go_unreachable(); }
13870
13871   void
13872   do_dump_expression(Ast_dump_context*) const;
13873
13874  private:
13875   // The composite literal which is being put on the heap.
13876   Expression* expr_;
13877 };
13878
13879 // Return a tree which allocates a composite literal on the heap.
13880
13881 tree
13882 Heap_composite_expression::do_get_tree(Translate_context* context)
13883 {
13884   tree expr_tree = this->expr_->get_tree(context);
13885   if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13886     return error_mark_node;
13887   tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13888   go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13889   tree space = context->gogo()->allocate_memory(this->expr_->type(),
13890                                                 expr_size, this->location());
13891   space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13892   space = save_expr(space);
13893   tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13894                                          space);
13895   TREE_THIS_NOTRAP(ref) = 1;
13896   tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13897                     build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13898                     space);
13899   SET_EXPR_LOCATION(ret, this->location().gcc_location());
13900   return ret;
13901 }
13902
13903 // Dump ast representation for a heap composite expression.
13904
13905 void
13906 Heap_composite_expression::do_dump_expression(
13907     Ast_dump_context* ast_dump_context) const
13908 {
13909   ast_dump_context->ostream() << "&(";
13910   ast_dump_context->dump_expression(this->expr_);
13911   ast_dump_context->ostream() << ")";
13912 }
13913
13914 // Allocate a composite literal on the heap.
13915
13916 Expression*
13917 Expression::make_heap_composite(Expression* expr, Location location)
13918 {
13919   return new Heap_composite_expression(expr, location);
13920 }
13921
13922 // Class Receive_expression.
13923
13924 // Return the type of a receive expression.
13925
13926 Type*
13927 Receive_expression::do_type()
13928 {
13929   Channel_type* channel_type = this->channel_->type()->channel_type();
13930   if (channel_type == NULL)
13931     return Type::make_error_type();
13932   return channel_type->element_type();
13933 }
13934
13935 // Check types for a receive expression.
13936
13937 void
13938 Receive_expression::do_check_types(Gogo*)
13939 {
13940   Type* type = this->channel_->type();
13941   if (type->is_error())
13942     {
13943       this->set_is_error();
13944       return;
13945     }
13946   if (type->channel_type() == NULL)
13947     {
13948       this->report_error(_("expected channel"));
13949       return;
13950     }
13951   if (!type->channel_type()->may_receive())
13952     {
13953       this->report_error(_("invalid receive on send-only channel"));
13954       return;
13955     }
13956 }
13957
13958 // Get a tree for a receive expression.
13959
13960 tree
13961 Receive_expression::do_get_tree(Translate_context* context)
13962 {
13963   Location loc = this->location();
13964
13965   Channel_type* channel_type = this->channel_->type()->channel_type();
13966   if (channel_type == NULL)
13967     {
13968       go_assert(this->channel_->type()->is_error());
13969       return error_mark_node;
13970     }
13971
13972   Expression* td = Expression::make_type_descriptor(channel_type, loc);
13973   tree td_tree = td->get_tree(context);
13974
13975   Type* element_type = channel_type->element_type();
13976   Btype* element_type_btype = element_type->get_backend(context->gogo());
13977   tree element_type_tree = type_to_tree(element_type_btype);
13978
13979   tree channel = this->channel_->get_tree(context);
13980   if (element_type_tree == error_mark_node || channel == error_mark_node)
13981     return error_mark_node;
13982
13983   return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13984 }
13985
13986 // Dump ast representation for a receive expression.
13987
13988 void
13989 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13990 {
13991   ast_dump_context->ostream() << " <- " ;
13992   ast_dump_context->dump_expression(channel_);
13993 }
13994
13995 // Make a receive expression.
13996
13997 Receive_expression*
13998 Expression::make_receive(Expression* channel, Location location)
13999 {
14000   return new Receive_expression(channel, location);
14001 }
14002
14003 // An expression which evaluates to a pointer to the type descriptor
14004 // of a type.
14005
14006 class Type_descriptor_expression : public Expression
14007 {
14008  public:
14009   Type_descriptor_expression(Type* type, Location location)
14010     : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14011       type_(type)
14012   { }
14013
14014  protected:
14015   Type*
14016   do_type()
14017   { return Type::make_type_descriptor_ptr_type(); }
14018
14019   void
14020   do_determine_type(const Type_context*)
14021   { }
14022
14023   Expression*
14024   do_copy()
14025   { return this; }
14026
14027   tree
14028   do_get_tree(Translate_context* context)
14029   {
14030     return this->type_->type_descriptor_pointer(context->gogo(),
14031                                                 this->location());
14032   }
14033
14034   void
14035   do_dump_expression(Ast_dump_context*) const;
14036
14037  private:
14038   // The type for which this is the descriptor.
14039   Type* type_;
14040 };
14041
14042 // Dump ast representation for a type descriptor expression.
14043
14044 void
14045 Type_descriptor_expression::do_dump_expression(
14046     Ast_dump_context* ast_dump_context) const
14047 {
14048   ast_dump_context->dump_type(this->type_);
14049 }
14050
14051 // Make a type descriptor expression.
14052
14053 Expression*
14054 Expression::make_type_descriptor(Type* type, Location location)
14055 {
14056   return new Type_descriptor_expression(type, location);
14057 }
14058
14059 // An expression which evaluates to some characteristic of a type.
14060 // This is only used to initialize fields of a type descriptor.  Using
14061 // a new expression class is slightly inefficient but gives us a good
14062 // separation between the frontend and the middle-end with regard to
14063 // how types are laid out.
14064
14065 class Type_info_expression : public Expression
14066 {
14067  public:
14068   Type_info_expression(Type* type, Type_info type_info)
14069     : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14070       type_(type), type_info_(type_info)
14071   { }
14072
14073  protected:
14074   Type*
14075   do_type();
14076
14077   void
14078   do_determine_type(const Type_context*)
14079   { }
14080
14081   Expression*
14082   do_copy()
14083   { return this; }
14084
14085   tree
14086   do_get_tree(Translate_context* context);
14087
14088   void
14089   do_dump_expression(Ast_dump_context*) const;
14090
14091  private:
14092   // The type for which we are getting information.
14093   Type* type_;
14094   // What information we want.
14095   Type_info type_info_;
14096 };
14097
14098 // The type is chosen to match what the type descriptor struct
14099 // expects.
14100
14101 Type*
14102 Type_info_expression::do_type()
14103 {
14104   switch (this->type_info_)
14105     {
14106     case TYPE_INFO_SIZE:
14107       return Type::lookup_integer_type("uintptr");
14108     case TYPE_INFO_ALIGNMENT:
14109     case TYPE_INFO_FIELD_ALIGNMENT:
14110       return Type::lookup_integer_type("uint8");
14111     default:
14112       go_unreachable();
14113     }
14114 }
14115
14116 // Return type information in GENERIC.
14117
14118 tree
14119 Type_info_expression::do_get_tree(Translate_context* context)
14120 {
14121   Btype* btype = this->type_->get_backend(context->gogo());
14122   Gogo* gogo = context->gogo();
14123   size_t val;
14124   switch (this->type_info_)
14125     {
14126     case TYPE_INFO_SIZE:
14127       val = gogo->backend()->type_size(btype);
14128       break;
14129     case TYPE_INFO_ALIGNMENT:
14130       val = gogo->backend()->type_alignment(btype);
14131       break;
14132     case TYPE_INFO_FIELD_ALIGNMENT:
14133       val = gogo->backend()->type_field_alignment(btype);
14134       break;
14135     default:
14136       go_unreachable();
14137     }
14138   tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14139   go_assert(val_type_tree != error_mark_node);
14140   return build_int_cstu(val_type_tree, val);
14141 }
14142
14143 // Dump ast representation for a type info expression.
14144
14145 void
14146 Type_info_expression::do_dump_expression(
14147     Ast_dump_context* ast_dump_context) const
14148 {
14149   ast_dump_context->ostream() << "typeinfo(";
14150   ast_dump_context->dump_type(this->type_);
14151   ast_dump_context->ostream() << ",";
14152   ast_dump_context->ostream() << 
14153     (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment" 
14154     : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14155     : this->type_info_ == TYPE_INFO_SIZE ? "size "
14156     : "unknown");
14157   ast_dump_context->ostream() << ")";
14158 }
14159
14160 // Make a type info expression.
14161
14162 Expression*
14163 Expression::make_type_info(Type* type, Type_info type_info)
14164 {
14165   return new Type_info_expression(type, type_info);
14166 }
14167
14168 // An expression which evaluates to the offset of a field within a
14169 // struct.  This, like Type_info_expression, q.v., is only used to
14170 // initialize fields of a type descriptor.
14171
14172 class Struct_field_offset_expression : public Expression
14173 {
14174  public:
14175   Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14176     : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14177                  Linemap::predeclared_location()),
14178       type_(type), field_(field)
14179   { }
14180
14181  protected:
14182   Type*
14183   do_type()
14184   { return Type::lookup_integer_type("uintptr"); }
14185
14186   void
14187   do_determine_type(const Type_context*)
14188   { }
14189
14190   Expression*
14191   do_copy()
14192   { return this; }
14193
14194   tree
14195   do_get_tree(Translate_context* context);
14196
14197   void
14198   do_dump_expression(Ast_dump_context*) const;
14199   
14200  private:
14201   // The type of the struct.
14202   Struct_type* type_;
14203   // The field.
14204   const Struct_field* field_;
14205 };
14206
14207 // Return a struct field offset in GENERIC.
14208
14209 tree
14210 Struct_field_offset_expression::do_get_tree(Translate_context* context)
14211 {
14212   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
14213   if (type_tree == error_mark_node)
14214     return error_mark_node;
14215
14216   tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
14217   go_assert(val_type_tree != error_mark_node);
14218
14219   const Struct_field_list* fields = this->type_->fields();
14220   tree struct_field_tree = TYPE_FIELDS(type_tree);
14221   Struct_field_list::const_iterator p;
14222   for (p = fields->begin();
14223        p != fields->end();
14224        ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14225     {
14226       go_assert(struct_field_tree != NULL_TREE);
14227       if (&*p == this->field_)
14228         break;
14229     }
14230   go_assert(&*p == this->field_);
14231
14232   return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14233                           byte_position(struct_field_tree));
14234 }
14235
14236 // Dump ast representation for a struct field offset expression.
14237
14238 void
14239 Struct_field_offset_expression::do_dump_expression(
14240     Ast_dump_context* ast_dump_context) const
14241 {
14242   ast_dump_context->ostream() <<  "unsafe.Offsetof(";
14243   ast_dump_context->dump_type(this->type_);
14244   ast_dump_context->ostream() << '.';
14245   ast_dump_context->ostream() <<
14246     Gogo::message_name(this->field_->field_name());
14247   ast_dump_context->ostream() << ")";
14248 }
14249
14250 // Make an expression for a struct field offset.
14251
14252 Expression*
14253 Expression::make_struct_field_offset(Struct_type* type,
14254                                      const Struct_field* field)
14255 {
14256   return new Struct_field_offset_expression(type, field);
14257 }
14258
14259 // An expression which evaluates to a pointer to the map descriptor of
14260 // a map type.
14261
14262 class Map_descriptor_expression : public Expression
14263 {
14264  public:
14265   Map_descriptor_expression(Map_type* type, Location location)
14266     : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14267       type_(type)
14268   { }
14269
14270  protected:
14271   Type*
14272   do_type()
14273   { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14274
14275   void
14276   do_determine_type(const Type_context*)
14277   { }
14278
14279   Expression*
14280   do_copy()
14281   { return this; }
14282
14283   tree
14284   do_get_tree(Translate_context* context)
14285   {
14286     return this->type_->map_descriptor_pointer(context->gogo(),
14287                                                this->location());
14288   }
14289
14290   void
14291   do_dump_expression(Ast_dump_context*) const;
14292  
14293  private:
14294   // The type for which this is the descriptor.
14295   Map_type* type_;
14296 };
14297
14298 // Dump ast representation for a map descriptor expression.
14299
14300 void
14301 Map_descriptor_expression::do_dump_expression(
14302     Ast_dump_context* ast_dump_context) const
14303 {
14304   ast_dump_context->ostream() << "map_descriptor(";
14305   ast_dump_context->dump_type(this->type_);
14306   ast_dump_context->ostream() << ")";
14307 }
14308
14309 // Make a map descriptor expression.
14310
14311 Expression*
14312 Expression::make_map_descriptor(Map_type* type, Location location)
14313 {
14314   return new Map_descriptor_expression(type, location);
14315 }
14316
14317 // An expression which evaluates to the address of an unnamed label.
14318
14319 class Label_addr_expression : public Expression
14320 {
14321  public:
14322   Label_addr_expression(Label* label, Location location)
14323     : Expression(EXPRESSION_LABEL_ADDR, location),
14324       label_(label)
14325   { }
14326
14327  protected:
14328   Type*
14329   do_type()
14330   { return Type::make_pointer_type(Type::make_void_type()); }
14331
14332   void
14333   do_determine_type(const Type_context*)
14334   { }
14335
14336   Expression*
14337   do_copy()
14338   { return new Label_addr_expression(this->label_, this->location()); }
14339
14340   tree
14341   do_get_tree(Translate_context* context)
14342   {
14343     return expr_to_tree(this->label_->get_addr(context, this->location()));
14344   }
14345
14346   void
14347   do_dump_expression(Ast_dump_context* ast_dump_context) const
14348   { ast_dump_context->ostream() << this->label_->name(); }
14349   
14350  private:
14351   // The label whose address we are taking.
14352   Label* label_;
14353 };
14354
14355 // Make an expression for the address of an unnamed label.
14356
14357 Expression*
14358 Expression::make_label_addr(Label* label, Location location)
14359 {
14360   return new Label_addr_expression(label, location);
14361 }
14362
14363 // Import an expression.  This comes at the end in order to see the
14364 // various class definitions.
14365
14366 Expression*
14367 Expression::import_expression(Import* imp)
14368 {
14369   int c = imp->peek_char();
14370   if (imp->match_c_string("- ")
14371       || imp->match_c_string("! ")
14372       || imp->match_c_string("^ "))
14373     return Unary_expression::do_import(imp);
14374   else if (c == '(')
14375     return Binary_expression::do_import(imp);
14376   else if (imp->match_c_string("true")
14377            || imp->match_c_string("false"))
14378     return Boolean_expression::do_import(imp);
14379   else if (c == '"')
14380     return String_expression::do_import(imp);
14381   else if (c == '-' || (c >= '0' && c <= '9'))
14382     {
14383       // This handles integers, floats and complex constants.
14384       return Integer_expression::do_import(imp);
14385     }
14386   else if (imp->match_c_string("nil"))
14387     return Nil_expression::do_import(imp);
14388   else if (imp->match_c_string("convert"))
14389     return Type_conversion_expression::do_import(imp);
14390   else
14391     {
14392       error_at(imp->location(), "import error: expected expression");
14393       return Expression::make_error(imp->location());
14394     }
14395 }
14396
14397 // Class Expression_list.
14398
14399 // Traverse the list.
14400
14401 int
14402 Expression_list::traverse(Traverse* traverse)
14403 {
14404   for (Expression_list::iterator p = this->begin();
14405        p != this->end();
14406        ++p)
14407     {
14408       if (*p != NULL)
14409         {
14410           if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14411             return TRAVERSE_EXIT;
14412         }
14413     }
14414   return TRAVERSE_CONTINUE;
14415 }
14416
14417 // Copy the list.
14418
14419 Expression_list*
14420 Expression_list::copy()
14421 {
14422   Expression_list* ret = new Expression_list();
14423   for (Expression_list::iterator p = this->begin();
14424        p != this->end();
14425        ++p)
14426     {
14427       if (*p == NULL)
14428         ret->push_back(NULL);
14429       else
14430         ret->push_back((*p)->copy());
14431     }
14432   return ret;
14433 }
14434
14435 // Return whether an expression list has an error expression.
14436
14437 bool
14438 Expression_list::contains_error() const
14439 {
14440   for (Expression_list::const_iterator p = this->begin();
14441        p != this->end();
14442        ++p)
14443     if (*p != NULL && (*p)->is_error_expression())
14444       return true;
14445   return false;
14446 }