OSDN Git Service

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