OSDN Git Service

compiler: Don't crash for invalid constant types for && or ||.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / expressions.cc
1 // expressions.cc -- Go frontend expression handling.
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 #include "go-system.h"
8
9 #include <algorithm>
10
11 #include <gmp.h>
12
13 #ifndef ENABLE_BUILD_WITH_CXX
14 extern "C"
15 {
16 #endif
17
18 #include "toplev.h"
19 #include "intl.h"
20 #include "tree.h"
21 #include "gimple.h"
22 #include "tree-iterator.h"
23 #include "convert.h"
24 #include "real.h"
25 #include "realmpfr.h"
26
27 #ifndef ENABLE_BUILD_WITH_CXX
28 }
29 #endif
30
31 #include "go-c.h"
32 #include "gogo.h"
33 #include "types.h"
34 #include "export.h"
35 #include "import.h"
36 #include "statements.h"
37 #include "lex.h"
38 #include "runtime.h"
39 #include "backend.h"
40 #include "expressions.h"
41 #include "ast-dump.h"
42
43 // Class Expression.
44
45 Expression::Expression(Expression_classification classification,
46                        Location location)
47   : classification_(classification), location_(location)
48 {
49 }
50
51 Expression::~Expression()
52 {
53 }
54
55 // Traverse the expressions.
56
57 int
58 Expression::traverse(Expression** pexpr, Traverse* traverse)
59 {
60   Expression* expr = *pexpr;
61   if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
62     {
63       int t = traverse->expression(pexpr);
64       if (t == TRAVERSE_EXIT)
65         return TRAVERSE_EXIT;
66       else if (t == TRAVERSE_SKIP_COMPONENTS)
67         return TRAVERSE_CONTINUE;
68     }
69   return expr->do_traverse(traverse);
70 }
71
72 // Traverse subexpressions of this expression.
73
74 int
75 Expression::traverse_subexpressions(Traverse* traverse)
76 {
77   return this->do_traverse(traverse);
78 }
79
80 // Default implementation for do_traverse for child classes.
81
82 int
83 Expression::do_traverse(Traverse*)
84 {
85   return TRAVERSE_CONTINUE;
86 }
87
88 // This virtual function is called by the parser if the value of this
89 // expression is being discarded.  By default, we give an error.
90 // Expressions with side effects override.
91
92 void
93 Expression::do_discarding_value()
94 {
95   this->unused_value_error();
96 }
97
98 // This virtual function is called to export expressions.  This will
99 // only be used by expressions which may be constant.
100
101 void
102 Expression::do_export(Export*) const
103 {
104   go_unreachable();
105 }
106
107 // Give an error saying that the value of the expression is not used.
108
109 void
110 Expression::unused_value_error()
111 {
112   error_at(this->location(), "value computed is not used");
113 }
114
115 // Note that this expression is an error.  This is called by children
116 // when they discover an error.
117
118 void
119 Expression::set_is_error()
120 {
121   this->classification_ = EXPRESSION_ERROR;
122 }
123
124 // For children to call to report an error conveniently.
125
126 void
127 Expression::report_error(const char* msg)
128 {
129   error_at(this->location_, "%s", msg);
130   this->set_is_error();
131 }
132
133 // Set types of variables and constants.  This is implemented by the
134 // child class.
135
136 void
137 Expression::determine_type(const Type_context* context)
138 {
139   this->do_determine_type(context);
140 }
141
142 // Set types when there is no context.
143
144 void
145 Expression::determine_type_no_context()
146 {
147   Type_context context;
148   this->do_determine_type(&context);
149 }
150
151 // Return a tree handling any conversions which must be done during
152 // assignment.
153
154 tree
155 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
156                                    Type* rhs_type, tree rhs_tree,
157                                    Location location)
158 {
159   if (lhs_type->is_error() || rhs_type->is_error())
160     return error_mark_node;
161
162   if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
163     return error_mark_node;
164
165   Gogo* gogo = context->gogo();
166
167   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
168   if (lhs_type_tree == error_mark_node)
169     return error_mark_node;
170
171   if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
172     {
173       if (rhs_type->interface_type() == NULL)
174         return Expression::convert_type_to_interface(context, lhs_type,
175                                                      rhs_type, rhs_tree,
176                                                      location);
177       else
178         return Expression::convert_interface_to_interface(context, lhs_type,
179                                                           rhs_type, rhs_tree,
180                                                           false, location);
181     }
182   else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
183     return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
184                                                  rhs_tree, location);
185   else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
186     {
187       // Assigning nil to an open array.
188       go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
189
190       VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
191
192       constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
193       tree field = TYPE_FIELDS(lhs_type_tree);
194       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
195                         "__values") == 0);
196       elt->index = field;
197       elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
198
199       elt = VEC_quick_push(constructor_elt, init, NULL);
200       field = DECL_CHAIN(field);
201       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
202                         "__count") == 0);
203       elt->index = field;
204       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
205
206       elt = VEC_quick_push(constructor_elt, init, NULL);
207       field = DECL_CHAIN(field);
208       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
209                         "__capacity") == 0);
210       elt->index = field;
211       elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
212
213       tree val = build_constructor(lhs_type_tree, init);
214       TREE_CONSTANT(val) = 1;
215
216       return val;
217     }
218   else if (rhs_type->is_nil_type())
219     {
220       // The left hand side should be a pointer type at the tree
221       // level.
222       go_assert(POINTER_TYPE_P(lhs_type_tree));
223       return fold_convert(lhs_type_tree, null_pointer_node);
224     }
225   else if (lhs_type_tree == TREE_TYPE(rhs_tree))
226     {
227       // No conversion is needed.
228       return rhs_tree;
229     }
230   else if (POINTER_TYPE_P(lhs_type_tree)
231            || INTEGRAL_TYPE_P(lhs_type_tree)
232            || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
233            || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
234     return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
235   else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
236             && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
237            || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
238                && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
239     {
240       // Avoid confusion from zero sized variables which may be
241       // represented as non-zero-sized.
242       if (int_size_in_bytes(lhs_type_tree) == 0
243           || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
244         return rhs_tree;
245
246       // This conversion must be permitted by Go, or we wouldn't have
247       // gotten here.
248       go_assert(int_size_in_bytes(lhs_type_tree)
249                 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
250       return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
251                              lhs_type_tree, rhs_tree);
252     }
253   else
254     {
255       go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
256       return rhs_tree;
257     }
258 }
259
260 // Return a tree for a conversion from a non-interface type to an
261 // interface type.
262
263 tree
264 Expression::convert_type_to_interface(Translate_context* context,
265                                       Type* lhs_type, Type* rhs_type,
266                                       tree rhs_tree, Location location)
267 {
268   Gogo* gogo = context->gogo();
269   Interface_type* lhs_interface_type = lhs_type->interface_type();
270   bool lhs_is_empty = lhs_interface_type->is_empty();
271
272   // Since RHS_TYPE is a static type, we can create the interface
273   // method table at compile time.
274
275   // When setting an interface to nil, we just set both fields to
276   // NULL.
277   if (rhs_type->is_nil_type())
278     {
279       Btype* lhs_btype = lhs_type->get_backend(gogo);
280       return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
281     }
282
283   // This should have been checked already.
284   go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
285
286   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
287   if (lhs_type_tree == error_mark_node)
288     return error_mark_node;
289
290   // An interface is a tuple.  If LHS_TYPE is an empty interface type,
291   // then the first field is the type descriptor for RHS_TYPE.
292   // Otherwise it is the interface method table for RHS_TYPE.
293   tree first_field_value;
294   if (lhs_is_empty)
295     first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
296   else
297     {
298       // Build the interface method table for this interface and this
299       // object type: a list of function pointers for each interface
300       // method.
301       Named_type* rhs_named_type = rhs_type->named_type();
302       bool is_pointer = false;
303       if (rhs_named_type == NULL)
304         {
305           rhs_named_type = rhs_type->deref()->named_type();
306           is_pointer = true;
307         }
308       tree method_table;
309       if (rhs_named_type == NULL)
310         method_table = null_pointer_node;
311       else
312         method_table =
313           rhs_named_type->interface_method_table(gogo, lhs_interface_type,
314                                                  is_pointer);
315       first_field_value = fold_convert_loc(location.gcc_location(),
316                                            const_ptr_type_node, method_table);
317     }
318   if (first_field_value == error_mark_node)
319     return error_mark_node;
320
321   // Start building a constructor for the value we will return.
322
323   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
324
325   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
326   tree field = TYPE_FIELDS(lhs_type_tree);
327   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
328                     (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
329   elt->index = field;
330   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
331                                 first_field_value);
332
333   elt = VEC_quick_push(constructor_elt, init, NULL);
334   field = DECL_CHAIN(field);
335   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
336   elt->index = field;
337
338   if (rhs_type->points_to() != NULL)
339     {
340       //  We are assigning a pointer to the interface; the interface
341       // holds the pointer itself.
342       elt->value = rhs_tree;
343       return build_constructor(lhs_type_tree, init);
344     }
345
346   // We are assigning a non-pointer value to the interface; the
347   // interface gets a copy of the value in the heap.
348
349   tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
350
351   tree space = gogo->allocate_memory(rhs_type, object_size, location);
352   space = fold_convert_loc(location.gcc_location(),
353                            build_pointer_type(TREE_TYPE(rhs_tree)), space);
354   space = save_expr(space);
355
356   tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
357   TREE_THIS_NOTRAP(ref) = 1;
358   tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
359                              void_type_node, ref, rhs_tree);
360
361   elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
362                                 space);
363
364   return build2(COMPOUND_EXPR, lhs_type_tree, set,
365                 build_constructor(lhs_type_tree, init));
366 }
367
368 // Return a tree for the type descriptor of RHS_TREE, which has
369 // interface type RHS_TYPE.  If RHS_TREE is nil the result will be
370 // NULL.
371
372 tree
373 Expression::get_interface_type_descriptor(Translate_context*,
374                                           Type* rhs_type, tree rhs_tree,
375                                           Location location)
376 {
377   tree rhs_type_tree = TREE_TYPE(rhs_tree);
378   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
379   tree rhs_field = TYPE_FIELDS(rhs_type_tree);
380   tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
381                   NULL_TREE);
382   if (rhs_type->interface_type()->is_empty())
383     {
384       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
385                         "__type_descriptor") == 0);
386       return v;
387     }
388
389   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
390              == 0);
391   go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
392   v = save_expr(v);
393   tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
394   go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
395   tree f = TYPE_FIELDS(TREE_TYPE(v1));
396   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
397              == 0);
398   v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
399
400   tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
401                             v, fold_convert_loc(location.gcc_location(),
402                                                 TREE_TYPE(v),
403                                                 null_pointer_node));
404   tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
405                             null_pointer_node);
406   return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
407                          eq, n, v1);
408 }
409
410 // Return a tree for the conversion of an interface type to an
411 // interface type.
412
413 tree
414 Expression::convert_interface_to_interface(Translate_context* context,
415                                            Type *lhs_type, Type *rhs_type,
416                                            tree rhs_tree, bool for_type_guard,
417                                            Location location)
418 {
419   Gogo* gogo = context->gogo();
420   Interface_type* lhs_interface_type = lhs_type->interface_type();
421   bool lhs_is_empty = lhs_interface_type->is_empty();
422
423   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
424   if (lhs_type_tree == error_mark_node)
425     return error_mark_node;
426
427   // In the general case this requires runtime examination of the type
428   // method table to match it up with the interface methods.
429
430   // FIXME: If all of the methods in the right hand side interface
431   // also appear in the left hand side interface, then we don't need
432   // to do a runtime check, although we still need to build a new
433   // method table.
434
435   // Get the type descriptor for the right hand side.  This will be
436   // NULL for a nil interface.
437
438   if (!DECL_P(rhs_tree))
439     rhs_tree = save_expr(rhs_tree);
440
441   tree rhs_type_descriptor =
442     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
443                                               location);
444
445   // The result is going to be a two element constructor.
446
447   VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
448
449   constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
450   tree field = TYPE_FIELDS(lhs_type_tree);
451   elt->index = field;
452
453   if (for_type_guard)
454     {
455       // A type assertion fails when converting a nil interface.
456       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
457                                                                    location);
458       static tree assert_interface_decl;
459       tree call = Gogo::call_builtin(&assert_interface_decl,
460                                      location,
461                                      "__go_assert_interface",
462                                      2,
463                                      ptr_type_node,
464                                      TREE_TYPE(lhs_type_descriptor),
465                                      lhs_type_descriptor,
466                                      TREE_TYPE(rhs_type_descriptor),
467                                      rhs_type_descriptor);
468       if (call == error_mark_node)
469         return error_mark_node;
470       // This will panic if the interface conversion fails.
471       TREE_NOTHROW(assert_interface_decl) = 0;
472       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
473                                     call);
474     }
475   else if (lhs_is_empty)
476     {
477       // A convertion to an empty interface always succeeds, and the
478       // first field is just the type descriptor of the object.
479       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
480                         "__type_descriptor") == 0);
481       elt->value = fold_convert_loc(location.gcc_location(),
482                                     TREE_TYPE(field), rhs_type_descriptor);
483     }
484   else
485     {
486       // A conversion to a non-empty interface may fail, but unlike a
487       // type assertion converting nil will always succeed.
488       go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
489                  == 0);
490       tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
491                                                                    location);
492       static tree convert_interface_decl;
493       tree call = Gogo::call_builtin(&convert_interface_decl,
494                                      location,
495                                      "__go_convert_interface",
496                                      2,
497                                      ptr_type_node,
498                                      TREE_TYPE(lhs_type_descriptor),
499                                      lhs_type_descriptor,
500                                      TREE_TYPE(rhs_type_descriptor),
501                                      rhs_type_descriptor);
502       if (call == error_mark_node)
503         return error_mark_node;
504       // This will panic if the interface conversion fails.
505       TREE_NOTHROW(convert_interface_decl) = 0;
506       elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
507                                     call);
508     }
509
510   // The second field is simply the object pointer.
511
512   elt = VEC_quick_push(constructor_elt, init, NULL);
513   field = DECL_CHAIN(field);
514   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
515   elt->index = field;
516
517   tree rhs_type_tree = TREE_TYPE(rhs_tree);
518   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
519   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
520   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
521   elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
522                       NULL_TREE);
523
524   return build_constructor(lhs_type_tree, init);
525 }
526
527 // Return a tree for the conversion of an interface type to a
528 // non-interface type.
529
530 tree
531 Expression::convert_interface_to_type(Translate_context* context,
532                                       Type *lhs_type, Type* rhs_type,
533                                       tree rhs_tree, Location location)
534 {
535   Gogo* gogo = context->gogo();
536   tree rhs_type_tree = TREE_TYPE(rhs_tree);
537
538   tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
539   if (lhs_type_tree == error_mark_node)
540     return error_mark_node;
541
542   // Call a function to check that the type is valid.  The function
543   // will panic with an appropriate runtime type error if the type is
544   // not valid.
545
546   tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
547
548   if (!DECL_P(rhs_tree))
549     rhs_tree = save_expr(rhs_tree);
550
551   tree rhs_type_descriptor =
552     Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
553                                               location);
554
555   tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
556                                                                 location);
557
558   static tree check_interface_type_decl;
559   tree call = Gogo::call_builtin(&check_interface_type_decl,
560                                  location,
561                                  "__go_check_interface_type",
562                                  3,
563                                  void_type_node,
564                                  TREE_TYPE(lhs_type_descriptor),
565                                  lhs_type_descriptor,
566                                  TREE_TYPE(rhs_type_descriptor),
567                                  rhs_type_descriptor,
568                                  TREE_TYPE(rhs_inter_descriptor),
569                                  rhs_inter_descriptor);
570   if (call == error_mark_node)
571     return error_mark_node;
572   // This call will panic if the conversion is invalid.
573   TREE_NOTHROW(check_interface_type_decl) = 0;
574
575   // If the call succeeds, pull out the value.
576   go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
577   tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
578   go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
579   tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
580                     NULL_TREE);
581
582   // If the value is a pointer, then it is the value we want.
583   // Otherwise it points to the value.
584   if (lhs_type->points_to() == NULL)
585     {
586       val = fold_convert_loc(location.gcc_location(),
587                              build_pointer_type(lhs_type_tree), val);
588       val = build_fold_indirect_ref_loc(location.gcc_location(), val);
589     }
590
591   return build2(COMPOUND_EXPR, lhs_type_tree, call,
592                 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
593 }
594
595 // Convert an expression to a tree.  This is implemented by the child
596 // class.  Not that it is not in general safe to call this multiple
597 // times for a single expression, but that we don't catch such errors.
598
599 tree
600 Expression::get_tree(Translate_context* context)
601 {
602   // The child may have marked this expression as having an error.
603   if (this->classification_ == EXPRESSION_ERROR)
604     return error_mark_node;
605
606   return this->do_get_tree(context);
607 }
608
609 // Return a tree for VAL in TYPE.
610
611 tree
612 Expression::integer_constant_tree(mpz_t val, tree type)
613 {
614   if (type == error_mark_node)
615     return error_mark_node;
616   else if (TREE_CODE(type) == INTEGER_TYPE)
617     return double_int_to_tree(type,
618                               mpz_get_double_int(type, val, true));
619   else if (TREE_CODE(type) == REAL_TYPE)
620     {
621       mpfr_t fval;
622       mpfr_init_set_z(fval, val, GMP_RNDN);
623       tree ret = Expression::float_constant_tree(fval, type);
624       mpfr_clear(fval);
625       return ret;
626     }
627   else if (TREE_CODE(type) == COMPLEX_TYPE)
628     {
629       mpfr_t fval;
630       mpfr_init_set_z(fval, val, GMP_RNDN);
631       tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
632       mpfr_clear(fval);
633       tree imag = build_real_from_int_cst(TREE_TYPE(type),
634                                           integer_zero_node);
635       return build_complex(type, real, imag);
636     }
637   else
638     go_unreachable();
639 }
640
641 // Return a tree for VAL in TYPE.
642
643 tree
644 Expression::float_constant_tree(mpfr_t val, tree type)
645 {
646   if (type == error_mark_node)
647     return error_mark_node;
648   else if (TREE_CODE(type) == INTEGER_TYPE)
649     {
650       mpz_t ival;
651       mpz_init(ival);
652       mpfr_get_z(ival, val, GMP_RNDN);
653       tree ret = Expression::integer_constant_tree(ival, type);
654       mpz_clear(ival);
655       return ret;
656     }
657   else if (TREE_CODE(type) == REAL_TYPE)
658     {
659       REAL_VALUE_TYPE r1;
660       real_from_mpfr(&r1, val, type, GMP_RNDN);
661       REAL_VALUE_TYPE r2;
662       real_convert(&r2, TYPE_MODE(type), &r1);
663       return build_real(type, r2);
664     }
665   else if (TREE_CODE(type) == COMPLEX_TYPE)
666     {
667       REAL_VALUE_TYPE r1;
668       real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
669       REAL_VALUE_TYPE r2;
670       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
671       tree imag = build_real_from_int_cst(TREE_TYPE(type),
672                                           integer_zero_node);
673       return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
674     }
675   else
676     go_unreachable();
677 }
678
679 // Return a tree for REAL/IMAG in TYPE.
680
681 tree
682 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
683 {
684   if (type == error_mark_node)
685     return error_mark_node;
686   else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
687     return Expression::float_constant_tree(real, type);
688   else if (TREE_CODE(type) == COMPLEX_TYPE)
689     {
690       REAL_VALUE_TYPE r1;
691       real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
692       REAL_VALUE_TYPE r2;
693       real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
694
695       REAL_VALUE_TYPE r3;
696       real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
697       REAL_VALUE_TYPE r4;
698       real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
699
700       return build_complex(type, build_real(TREE_TYPE(type), r2),
701                            build_real(TREE_TYPE(type), r4));
702     }
703   else
704     go_unreachable();
705 }
706
707 // Return a tree which evaluates to true if VAL, of arbitrary integer
708 // type, is negative or is more than the maximum value of BOUND_TYPE.
709 // If SOFAR is not NULL, it is or'red into the result.  The return
710 // value may be NULL if SOFAR is NULL.
711
712 tree
713 Expression::check_bounds(tree val, tree bound_type, tree sofar,
714                          Location loc)
715 {
716   tree val_type = TREE_TYPE(val);
717   tree ret = NULL_TREE;
718
719   if (!TYPE_UNSIGNED(val_type))
720     {
721       ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
722                             build_int_cst(val_type, 0));
723       if (ret == boolean_false_node)
724         ret = NULL_TREE;
725     }
726
727   HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
728   HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
729   go_assert(val_type_size != -1 && bound_type_size != -1);
730   if (val_type_size > bound_type_size
731       || (val_type_size == bound_type_size
732           && TYPE_UNSIGNED(val_type)
733           && !TYPE_UNSIGNED(bound_type)))
734     {
735       tree max = TYPE_MAX_VALUE(bound_type);
736       tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
737                                  val, fold_convert_loc(loc.gcc_location(),
738                                                        val_type, max));
739       if (big == boolean_false_node)
740         ;
741       else if (ret == NULL_TREE)
742         ret = big;
743       else
744         ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
745                               boolean_type_node, ret, big);
746     }
747
748   if (ret == NULL_TREE)
749     return sofar;
750   else if (sofar == NULL_TREE)
751     return ret;
752   else
753     return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
754                            sofar, ret);
755 }
756
757 void
758 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
759 {
760   this->do_dump_expression(ast_dump_context);
761 }
762
763 // Error expressions.  This are used to avoid cascading errors.
764
765 class Error_expression : public Expression
766 {
767  public:
768   Error_expression(Location location)
769     : Expression(EXPRESSION_ERROR, location)
770   { }
771
772  protected:
773   bool
774   do_is_constant() const
775   { return true; }
776
777   bool
778   do_numeric_constant_value(Numeric_constant* nc) const
779   {
780     nc->set_unsigned_long(NULL, 0);
781     return true;
782   }
783
784   void
785   do_discarding_value()
786   { }
787
788   Type*
789   do_type()
790   { return Type::make_error_type(); }
791
792   void
793   do_determine_type(const Type_context*)
794   { }
795
796   Expression*
797   do_copy()
798   { return this; }
799
800   bool
801   do_is_addressable() const
802   { return true; }
803
804   tree
805   do_get_tree(Translate_context*)
806   { return error_mark_node; }
807
808   void
809   do_dump_expression(Ast_dump_context*) const;
810 };
811
812 // Dump the ast representation for an error expression to a dump context.
813
814 void
815 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
816 {
817   ast_dump_context->ostream() << "_Error_" ;
818 }
819
820 Expression*
821 Expression::make_error(Location location)
822 {
823   return new Error_expression(location);
824 }
825
826 // An expression which is really a type.  This is used during parsing.
827 // It is an error if these survive after lowering.
828
829 class
830 Type_expression : public Expression
831 {
832  public:
833   Type_expression(Type* type, Location location)
834     : Expression(EXPRESSION_TYPE, location),
835       type_(type)
836   { }
837
838  protected:
839   int
840   do_traverse(Traverse* traverse)
841   { return Type::traverse(this->type_, traverse); }
842
843   Type*
844   do_type()
845   { return this->type_; }
846
847   void
848   do_determine_type(const Type_context*)
849   { }
850
851   void
852   do_check_types(Gogo*)
853   { this->report_error(_("invalid use of type")); }
854
855   Expression*
856   do_copy()
857   { return this; }
858
859   tree
860   do_get_tree(Translate_context*)
861   { go_unreachable(); }
862
863   void do_dump_expression(Ast_dump_context*) const;
864  
865  private:
866   // The type which we are representing as an expression.
867   Type* type_;
868 };
869
870 void
871 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
872 {
873   ast_dump_context->dump_type(this->type_);
874 }
875
876 Expression*
877 Expression::make_type(Type* type, Location location)
878 {
879   return new Type_expression(type, location);
880 }
881
882 // Class Parser_expression.
883
884 Type*
885 Parser_expression::do_type()
886 {
887   // We should never really ask for the type of a Parser_expression.
888   // However, it can happen, at least when we have an invalid const
889   // whose initializer refers to the const itself.  In that case we
890   // may ask for the type when lowering the const itself.
891   go_assert(saw_errors());
892   return Type::make_error_type();
893 }
894
895 // Class Var_expression.
896
897 // Lower a variable expression.  Here we just make sure that the
898 // initialization expression of the variable has been lowered.  This
899 // ensures that we will be able to determine the type of the variable
900 // if necessary.
901
902 Expression*
903 Var_expression::do_lower(Gogo* gogo, Named_object* function,
904                          Statement_inserter* inserter, int)
905 {
906   if (this->variable_->is_variable())
907     {
908       Variable* var = this->variable_->var_value();
909       // This is either a local variable or a global variable.  A
910       // reference to a variable which is local to an enclosing
911       // function will be a reference to a field in a closure.
912       if (var->is_global())
913         {
914           function = NULL;
915           inserter = NULL;
916         }
917       var->lower_init_expression(gogo, function, inserter);
918     }
919   return this;
920 }
921
922 // Return the type of a reference to a variable.
923
924 Type*
925 Var_expression::do_type()
926 {
927   if (this->variable_->is_variable())
928     return this->variable_->var_value()->type();
929   else if (this->variable_->is_result_variable())
930     return this->variable_->result_var_value()->type();
931   else
932     go_unreachable();
933 }
934
935 // Determine the type of a reference to a variable.
936
937 void
938 Var_expression::do_determine_type(const Type_context*)
939 {
940   if (this->variable_->is_variable())
941     this->variable_->var_value()->determine_type();
942 }
943
944 // Something takes the address of this variable.  This means that we
945 // may want to move the variable onto the heap.
946
947 void
948 Var_expression::do_address_taken(bool escapes)
949 {
950   if (!escapes)
951     {
952       if (this->variable_->is_variable())
953         this->variable_->var_value()->set_non_escaping_address_taken();
954       else if (this->variable_->is_result_variable())
955         this->variable_->result_var_value()->set_non_escaping_address_taken();
956       else
957         go_unreachable();
958     }
959   else
960     {
961       if (this->variable_->is_variable())
962         this->variable_->var_value()->set_address_taken();
963       else if (this->variable_->is_result_variable())
964         this->variable_->result_var_value()->set_address_taken();
965       else
966         go_unreachable();
967     }
968 }
969
970 // Get the tree for a reference to a variable.
971
972 tree
973 Var_expression::do_get_tree(Translate_context* context)
974 {
975   Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
976                                                           context->function());
977   tree ret = var_to_tree(bvar);
978   if (ret == error_mark_node)
979     return error_mark_node;
980   bool is_in_heap;
981   if (this->variable_->is_variable())
982     is_in_heap = this->variable_->var_value()->is_in_heap();
983   else if (this->variable_->is_result_variable())
984     is_in_heap = this->variable_->result_var_value()->is_in_heap();
985   else
986     go_unreachable();
987   if (is_in_heap)
988     {
989       ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
990       TREE_THIS_NOTRAP(ret) = 1;
991     }
992   return ret;
993 }
994
995 // Ast dump for variable expression.
996
997 void
998 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
999 {
1000   ast_dump_context->ostream() << this->variable_->name() ;
1001 }
1002
1003 // Make a reference to a variable in an expression.
1004
1005 Expression*
1006 Expression::make_var_reference(Named_object* var, Location location)
1007 {
1008   if (var->is_sink())
1009     return Expression::make_sink(location);
1010
1011   // FIXME: Creating a new object for each reference to a variable is
1012   // wasteful.
1013   return new Var_expression(var, location);
1014 }
1015
1016 // Class Temporary_reference_expression.
1017
1018 // The type.
1019
1020 Type*
1021 Temporary_reference_expression::do_type()
1022 {
1023   return this->statement_->type();
1024 }
1025
1026 // Called if something takes the address of this temporary variable.
1027 // We never have to move temporary variables to the heap, but we do
1028 // need to know that they must live in the stack rather than in a
1029 // register.
1030
1031 void
1032 Temporary_reference_expression::do_address_taken(bool)
1033 {
1034   this->statement_->set_is_address_taken();
1035 }
1036
1037 // Get a tree referring to the variable.
1038
1039 tree
1040 Temporary_reference_expression::do_get_tree(Translate_context* context)
1041 {
1042   Bvariable* bvar = this->statement_->get_backend_variable(context);
1043
1044   // The gcc backend can't represent the same set of recursive types
1045   // that the Go frontend can.  In some cases this means that a
1046   // temporary variable won't have the right backend type.  Correct
1047   // that here by adding a type cast.  We need to use base() to push
1048   // the circularity down one level.
1049   tree ret = var_to_tree(bvar);
1050   if (!this->is_lvalue_
1051       && POINTER_TYPE_P(TREE_TYPE(ret))
1052       && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1053     {
1054       Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1055       tree type_tree = type_to_tree(type_btype);
1056       ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1057     }
1058   return ret;
1059 }
1060
1061 // Ast dump for temporary reference.
1062
1063 void
1064 Temporary_reference_expression::do_dump_expression(
1065                                 Ast_dump_context* ast_dump_context) const
1066 {
1067   ast_dump_context->dump_temp_variable_name(this->statement_);
1068 }
1069
1070 // Make a reference to a temporary variable.
1071
1072 Temporary_reference_expression*
1073 Expression::make_temporary_reference(Temporary_statement* statement,
1074                                      Location location)
1075 {
1076   return new Temporary_reference_expression(statement, location);
1077 }
1078
1079 // Class Set_and_use_temporary_expression.
1080
1081 // Return the type.
1082
1083 Type*
1084 Set_and_use_temporary_expression::do_type()
1085 {
1086   return this->statement_->type();
1087 }
1088
1089 // Take the address.
1090
1091 void
1092 Set_and_use_temporary_expression::do_address_taken(bool)
1093 {
1094   this->statement_->set_is_address_taken();
1095 }
1096
1097 // Return the backend representation.
1098
1099 tree
1100 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1101 {
1102   Bvariable* bvar = this->statement_->get_backend_variable(context);
1103   tree var_tree = var_to_tree(bvar);
1104   tree expr_tree = this->expr_->get_tree(context);
1105   if (var_tree == error_mark_node || expr_tree == error_mark_node)
1106     return error_mark_node;
1107   Location loc = this->location();
1108   return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1109                     build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1110                                var_tree, expr_tree),
1111                     var_tree);
1112 }
1113
1114 // Dump.
1115
1116 void
1117 Set_and_use_temporary_expression::do_dump_expression(
1118     Ast_dump_context* ast_dump_context) const
1119 {
1120   ast_dump_context->ostream() << '(';
1121   ast_dump_context->dump_temp_variable_name(this->statement_);
1122   ast_dump_context->ostream() << " = ";
1123   this->expr_->dump_expression(ast_dump_context);
1124   ast_dump_context->ostream() << ')';
1125 }
1126
1127 // Make a set-and-use temporary.
1128
1129 Set_and_use_temporary_expression*
1130 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1131                                        Expression* expr, Location location)
1132 {
1133   return new Set_and_use_temporary_expression(statement, expr, location);
1134 }
1135
1136 // A sink expression--a use of the blank identifier _.
1137
1138 class Sink_expression : public Expression
1139 {
1140  public:
1141   Sink_expression(Location location)
1142     : Expression(EXPRESSION_SINK, location),
1143       type_(NULL), var_(NULL_TREE)
1144   { }
1145
1146  protected:
1147   void
1148   do_discarding_value()
1149   { }
1150
1151   Type*
1152   do_type();
1153
1154   void
1155   do_determine_type(const Type_context*);
1156
1157   Expression*
1158   do_copy()
1159   { return new Sink_expression(this->location()); }
1160
1161   tree
1162   do_get_tree(Translate_context*);
1163
1164   void
1165   do_dump_expression(Ast_dump_context*) const;
1166
1167  private:
1168   // The type of this sink variable.
1169   Type* type_;
1170   // The temporary variable we generate.
1171   tree var_;
1172 };
1173
1174 // Return the type of a sink expression.
1175
1176 Type*
1177 Sink_expression::do_type()
1178 {
1179   if (this->type_ == NULL)
1180     return Type::make_sink_type();
1181   return this->type_;
1182 }
1183
1184 // Determine the type of a sink expression.
1185
1186 void
1187 Sink_expression::do_determine_type(const Type_context* context)
1188 {
1189   if (context->type != NULL)
1190     this->type_ = context->type;
1191 }
1192
1193 // Return a temporary variable for a sink expression.  This will
1194 // presumably be a write-only variable which the middle-end will drop.
1195
1196 tree
1197 Sink_expression::do_get_tree(Translate_context* context)
1198 {
1199   if (this->var_ == NULL_TREE)
1200     {
1201       go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1202       Btype* bt = this->type_->get_backend(context->gogo());
1203       this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1204     }
1205   return this->var_;
1206 }
1207
1208 // Ast dump for sink expression.
1209
1210 void
1211 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1212 {
1213   ast_dump_context->ostream() << "_" ;
1214 }
1215
1216 // Make a sink expression.
1217
1218 Expression*
1219 Expression::make_sink(Location location)
1220 {
1221   return new Sink_expression(location);
1222 }
1223
1224 // Class Func_expression.
1225
1226 // FIXME: Can a function expression appear in a constant expression?
1227 // The value is unchanging.  Initializing a constant to the address of
1228 // a function seems like it could work, though there might be little
1229 // point to it.
1230
1231 // Traversal.
1232
1233 int
1234 Func_expression::do_traverse(Traverse* traverse)
1235 {
1236   return (this->closure_ == NULL
1237           ? TRAVERSE_CONTINUE
1238           : Expression::traverse(&this->closure_, traverse));
1239 }
1240
1241 // Return the type of a function expression.
1242
1243 Type*
1244 Func_expression::do_type()
1245 {
1246   if (this->function_->is_function())
1247     return this->function_->func_value()->type();
1248   else if (this->function_->is_function_declaration())
1249     return this->function_->func_declaration_value()->type();
1250   else
1251     go_unreachable();
1252 }
1253
1254 // Get the tree for a function expression without evaluating the
1255 // closure.
1256
1257 tree
1258 Func_expression::get_tree_without_closure(Gogo* gogo)
1259 {
1260   Function_type* fntype;
1261   if (this->function_->is_function())
1262     fntype = this->function_->func_value()->type();
1263   else if (this->function_->is_function_declaration())
1264     fntype = this->function_->func_declaration_value()->type();
1265   else
1266     go_unreachable();
1267
1268   // Builtin functions are handled specially by Call_expression.  We
1269   // can't take their address.
1270   if (fntype->is_builtin())
1271     {
1272       error_at(this->location(),
1273                "invalid use of special builtin function %qs; must be called",
1274                this->function_->name().c_str());
1275       return error_mark_node;
1276     }
1277
1278   Named_object* no = this->function_;
1279
1280   tree id = no->get_id(gogo);
1281   if (id == error_mark_node)
1282     return error_mark_node;
1283
1284   tree fndecl;
1285   if (no->is_function())
1286     fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1287   else if (no->is_function_declaration())
1288     fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1289   else
1290     go_unreachable();
1291
1292   if (fndecl == error_mark_node)
1293     return error_mark_node;
1294
1295   return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1296 }
1297
1298 // Get the tree for a function expression.  This is used when we take
1299 // the address of a function rather than simply calling it.  If the
1300 // function has a closure, we must use a trampoline.
1301
1302 tree
1303 Func_expression::do_get_tree(Translate_context* context)
1304 {
1305   Gogo* gogo = context->gogo();
1306
1307   tree fnaddr = this->get_tree_without_closure(gogo);
1308   if (fnaddr == error_mark_node)
1309     return error_mark_node;
1310
1311   go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1312              && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1313   TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1314
1315   // If there is no closure, that is all have to do.
1316   if (this->closure_ == NULL)
1317     return fnaddr;
1318
1319   go_assert(this->function_->func_value()->enclosing() != NULL);
1320
1321   // Get the value of the closure.  This will be a pointer to space
1322   // allocated on the heap.
1323   tree closure_tree = this->closure_->get_tree(context);
1324   if (closure_tree == error_mark_node)
1325     return error_mark_node;
1326   go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1327
1328   // Now we need to build some code on the heap.  This code will load
1329   // the static chain pointer with the closure and then jump to the
1330   // body of the function.  The normal gcc approach is to build the
1331   // code on the stack.  Unfortunately we can not do that, as Go
1332   // permits us to return the function pointer.
1333
1334   return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1335 }
1336
1337 // Ast dump for function.
1338
1339 void
1340 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1341 {
1342   ast_dump_context->ostream() << this->function_->name();
1343   if (this->closure_ != NULL)
1344     {
1345       ast_dump_context->ostream() << " {closure =  ";
1346       this->closure_->dump_expression(ast_dump_context);
1347       ast_dump_context->ostream() << "}";
1348     }
1349 }
1350
1351 // Make a reference to a function in an expression.
1352
1353 Expression*
1354 Expression::make_func_reference(Named_object* function, Expression* closure,
1355                                 Location location)
1356 {
1357   return new Func_expression(function, closure, location);
1358 }
1359
1360 // Class Unknown_expression.
1361
1362 // Return the name of an unknown expression.
1363
1364 const std::string&
1365 Unknown_expression::name() const
1366 {
1367   return this->named_object_->name();
1368 }
1369
1370 // Lower a reference to an unknown name.
1371
1372 Expression*
1373 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1374 {
1375   Location location = this->location();
1376   Named_object* no = this->named_object_;
1377   Named_object* real;
1378   if (!no->is_unknown())
1379     real = no;
1380   else
1381     {
1382       real = no->unknown_value()->real_named_object();
1383       if (real == NULL)
1384         {
1385           if (this->is_composite_literal_key_)
1386             return this;
1387           if (!this->no_error_message_)
1388             error_at(location, "reference to undefined name %qs",
1389                      this->named_object_->message_name().c_str());
1390           return Expression::make_error(location);
1391         }
1392     }
1393   switch (real->classification())
1394     {
1395     case Named_object::NAMED_OBJECT_CONST:
1396       return Expression::make_const_reference(real, location);
1397     case Named_object::NAMED_OBJECT_TYPE:
1398       return Expression::make_type(real->type_value(), location);
1399     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1400       if (this->is_composite_literal_key_)
1401         return this;
1402       if (!this->no_error_message_)
1403         error_at(location, "reference to undefined type %qs",
1404                  real->message_name().c_str());
1405       return Expression::make_error(location);
1406     case Named_object::NAMED_OBJECT_VAR:
1407       real->var_value()->set_is_used();
1408       return Expression::make_var_reference(real, location);
1409     case Named_object::NAMED_OBJECT_FUNC:
1410     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1411       return Expression::make_func_reference(real, NULL, location);
1412     case Named_object::NAMED_OBJECT_PACKAGE:
1413       if (this->is_composite_literal_key_)
1414         return this;
1415       if (!this->no_error_message_)
1416         error_at(location, "unexpected reference to package");
1417       return Expression::make_error(location);
1418     default:
1419       go_unreachable();
1420     }
1421 }
1422
1423 // Dump the ast representation for an unknown expression to a dump context.
1424
1425 void
1426 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1427 {
1428   ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1429                               << ")";
1430 }
1431
1432 // Make a reference to an unknown name.
1433
1434 Unknown_expression*
1435 Expression::make_unknown_reference(Named_object* no, Location location)
1436 {
1437   return new Unknown_expression(no, location);
1438 }
1439
1440 // A boolean expression.
1441
1442 class Boolean_expression : public Expression
1443 {
1444  public:
1445   Boolean_expression(bool val, Location location)
1446     : Expression(EXPRESSION_BOOLEAN, location),
1447       val_(val), type_(NULL)
1448   { }
1449
1450   static Expression*
1451   do_import(Import*);
1452
1453  protected:
1454   bool
1455   do_is_constant() const
1456   { return true; }
1457
1458   Type*
1459   do_type();
1460
1461   void
1462   do_determine_type(const Type_context*);
1463
1464   Expression*
1465   do_copy()
1466   { return this; }
1467
1468   tree
1469   do_get_tree(Translate_context*)
1470   { return this->val_ ? boolean_true_node : boolean_false_node; }
1471
1472   void
1473   do_export(Export* exp) const
1474   { exp->write_c_string(this->val_ ? "true" : "false"); }
1475
1476   void
1477   do_dump_expression(Ast_dump_context* ast_dump_context) const
1478   { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1479   
1480  private:
1481   // The constant.
1482   bool val_;
1483   // The type as determined by context.
1484   Type* type_;
1485 };
1486
1487 // Get the type.
1488
1489 Type*
1490 Boolean_expression::do_type()
1491 {
1492   if (this->type_ == NULL)
1493     this->type_ = Type::make_boolean_type();
1494   return this->type_;
1495 }
1496
1497 // Set the type from the context.
1498
1499 void
1500 Boolean_expression::do_determine_type(const Type_context* context)
1501 {
1502   if (this->type_ != NULL && !this->type_->is_abstract())
1503     ;
1504   else if (context->type != NULL && context->type->is_boolean_type())
1505     this->type_ = context->type;
1506   else if (!context->may_be_abstract)
1507     this->type_ = Type::lookup_bool_type();
1508 }
1509
1510 // Import a boolean constant.
1511
1512 Expression*
1513 Boolean_expression::do_import(Import* imp)
1514 {
1515   if (imp->peek_char() == 't')
1516     {
1517       imp->require_c_string("true");
1518       return Expression::make_boolean(true, imp->location());
1519     }
1520   else
1521     {
1522       imp->require_c_string("false");
1523       return Expression::make_boolean(false, imp->location());
1524     }
1525 }
1526
1527 // Make a boolean expression.
1528
1529 Expression*
1530 Expression::make_boolean(bool val, Location location)
1531 {
1532   return new Boolean_expression(val, location);
1533 }
1534
1535 // Class String_expression.
1536
1537 // Get the type.
1538
1539 Type*
1540 String_expression::do_type()
1541 {
1542   if (this->type_ == NULL)
1543     this->type_ = Type::make_string_type();
1544   return this->type_;
1545 }
1546
1547 // Set the type from the context.
1548
1549 void
1550 String_expression::do_determine_type(const Type_context* context)
1551 {
1552   if (this->type_ != NULL && !this->type_->is_abstract())
1553     ;
1554   else if (context->type != NULL && context->type->is_string_type())
1555     this->type_ = context->type;
1556   else if (!context->may_be_abstract)
1557     this->type_ = Type::lookup_string_type();
1558 }
1559
1560 // Build a string constant.
1561
1562 tree
1563 String_expression::do_get_tree(Translate_context* context)
1564 {
1565   return context->gogo()->go_string_constant_tree(this->val_);
1566 }
1567
1568  // Write string literal to string dump.
1569
1570 void
1571 String_expression::export_string(String_dump* exp,
1572                                  const String_expression* str)
1573 {
1574   std::string s;
1575   s.reserve(str->val_.length() * 4 + 2);
1576   s += '"';
1577   for (std::string::const_iterator p = str->val_.begin();
1578        p != str->val_.end();
1579        ++p)
1580     {
1581       if (*p == '\\' || *p == '"')
1582         {
1583           s += '\\';
1584           s += *p;
1585         }
1586       else if (*p >= 0x20 && *p < 0x7f)
1587         s += *p;
1588       else if (*p == '\n')
1589         s += "\\n";
1590       else if (*p == '\t')
1591         s += "\\t";
1592       else
1593         {
1594           s += "\\x";
1595           unsigned char c = *p;
1596           unsigned int dig = c >> 4;
1597           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1598           dig = c & 0xf;
1599           s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1600         }
1601     }
1602   s += '"';
1603   exp->write_string(s);
1604 }
1605
1606 // Export a string expression.
1607
1608 void
1609 String_expression::do_export(Export* exp) const
1610 {
1611   String_expression::export_string(exp, this);
1612 }
1613
1614 // Import a string expression.
1615
1616 Expression*
1617 String_expression::do_import(Import* imp)
1618 {
1619   imp->require_c_string("\"");
1620   std::string val;
1621   while (true)
1622     {
1623       int c = imp->get_char();
1624       if (c == '"' || c == -1)
1625         break;
1626       if (c != '\\')
1627         val += static_cast<char>(c);
1628       else
1629         {
1630           c = imp->get_char();
1631           if (c == '\\' || c == '"')
1632             val += static_cast<char>(c);
1633           else if (c == 'n')
1634             val += '\n';
1635           else if (c == 't')
1636             val += '\t';
1637           else if (c == 'x')
1638             {
1639               c = imp->get_char();
1640               unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1641               c = imp->get_char();
1642               unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1643               char v = (vh << 4) | vl;
1644               val += v;
1645             }
1646           else
1647             {
1648               error_at(imp->location(), "bad string constant");
1649               return Expression::make_error(imp->location());
1650             }
1651         }
1652     }
1653   return Expression::make_string(val, imp->location());
1654 }
1655
1656 // Ast dump for string expression.
1657
1658 void
1659 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1660 {
1661   String_expression::export_string(ast_dump_context, this);
1662 }
1663
1664 // Make a string expression.
1665
1666 Expression*
1667 Expression::make_string(const std::string& val, Location location)
1668 {
1669   return new String_expression(val, location);
1670 }
1671
1672 // Make an integer expression.
1673
1674 class Integer_expression : public Expression
1675 {
1676  public:
1677   Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1678                      Location location)
1679     : Expression(EXPRESSION_INTEGER, location),
1680       type_(type), is_character_constant_(is_character_constant)
1681   { mpz_init_set(this->val_, *val); }
1682
1683   static Expression*
1684   do_import(Import*);
1685
1686   // Write VAL to string dump.
1687   static void
1688   export_integer(String_dump* exp, const mpz_t val);
1689
1690   // Write VAL to dump context.
1691   static void
1692   dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1693
1694  protected:
1695   bool
1696   do_is_constant() const
1697   { return true; }
1698
1699   bool
1700   do_numeric_constant_value(Numeric_constant* nc) const;
1701
1702   Type*
1703   do_type();
1704
1705   void
1706   do_determine_type(const Type_context* context);
1707
1708   void
1709   do_check_types(Gogo*);
1710
1711   tree
1712   do_get_tree(Translate_context*);
1713
1714   Expression*
1715   do_copy()
1716   {
1717     if (this->is_character_constant_)
1718       return Expression::make_character(&this->val_, this->type_,
1719                                         this->location());
1720     else
1721       return Expression::make_integer(&this->val_, this->type_,
1722                                       this->location());
1723   }
1724
1725   void
1726   do_export(Export*) const;
1727
1728   void
1729   do_dump_expression(Ast_dump_context*) const;
1730
1731  private:
1732   // The integer value.
1733   mpz_t val_;
1734   // The type so far.
1735   Type* type_;
1736   // Whether this is a character constant.
1737   bool is_character_constant_;
1738 };
1739
1740 // Return a numeric constant for this expression.  We have to mark
1741 // this as a character when appropriate.
1742
1743 bool
1744 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1745 {
1746   if (this->is_character_constant_)
1747     nc->set_rune(this->type_, this->val_);
1748   else
1749     nc->set_int(this->type_, this->val_);
1750   return true;
1751 }
1752
1753 // Return the current type.  If we haven't set the type yet, we return
1754 // an abstract integer type.
1755
1756 Type*
1757 Integer_expression::do_type()
1758 {
1759   if (this->type_ == NULL)
1760     {
1761       if (this->is_character_constant_)
1762         this->type_ = Type::make_abstract_character_type();
1763       else
1764         this->type_ = Type::make_abstract_integer_type();
1765     }
1766   return this->type_;
1767 }
1768
1769 // Set the type of the integer value.  Here we may switch from an
1770 // abstract type to a real type.
1771
1772 void
1773 Integer_expression::do_determine_type(const Type_context* context)
1774 {
1775   if (this->type_ != NULL && !this->type_->is_abstract())
1776     ;
1777   else if (context->type != NULL && context->type->is_numeric_type())
1778     this->type_ = context->type;
1779   else if (!context->may_be_abstract)
1780     {
1781       if (this->is_character_constant_)
1782         this->type_ = Type::lookup_integer_type("int32");
1783       else
1784         this->type_ = Type::lookup_integer_type("int");
1785     }
1786 }
1787
1788 // Check the type of an integer constant.
1789
1790 void
1791 Integer_expression::do_check_types(Gogo*)
1792 {
1793   Type* type = this->type_;
1794   if (type == NULL)
1795     return;
1796   Numeric_constant nc;
1797   if (this->is_character_constant_)
1798     nc.set_rune(NULL, this->val_);
1799   else
1800     nc.set_int(NULL, this->val_);
1801   if (!nc.set_type(type, true, this->location()))
1802     this->set_is_error();
1803 }
1804
1805 // Get a tree for an integer constant.
1806
1807 tree
1808 Integer_expression::do_get_tree(Translate_context* context)
1809 {
1810   Gogo* gogo = context->gogo();
1811   tree type;
1812   if (this->type_ != NULL && !this->type_->is_abstract())
1813     type = type_to_tree(this->type_->get_backend(gogo));
1814   else if (this->type_ != NULL && this->type_->float_type() != NULL)
1815     {
1816       // We are converting to an abstract floating point type.
1817       Type* ftype = Type::lookup_float_type("float64");
1818       type = type_to_tree(ftype->get_backend(gogo));
1819     }
1820   else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1821     {
1822       // We are converting to an abstract complex type.
1823       Type* ctype = Type::lookup_complex_type("complex128");
1824       type = type_to_tree(ctype->get_backend(gogo));
1825     }
1826   else
1827     {
1828       // If we still have an abstract type here, then this is being
1829       // used in a constant expression which didn't get reduced for
1830       // some reason.  Use a type which will fit the value.  We use <,
1831       // not <=, because we need an extra bit for the sign bit.
1832       int bits = mpz_sizeinbase(this->val_, 2);
1833       if (bits < INT_TYPE_SIZE)
1834         {
1835           Type* t = Type::lookup_integer_type("int");
1836           type = type_to_tree(t->get_backend(gogo));
1837         }
1838       else if (bits < 64)
1839         {
1840           Type* t = Type::lookup_integer_type("int64");
1841           type = type_to_tree(t->get_backend(gogo));
1842         }
1843       else
1844         type = long_long_integer_type_node;
1845     }
1846   return Expression::integer_constant_tree(this->val_, type);
1847 }
1848
1849 // Write VAL to export data.
1850
1851 void
1852 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1853 {
1854   char* s = mpz_get_str(NULL, 10, val);
1855   exp->write_c_string(s);
1856   free(s);
1857 }
1858
1859 // Export an integer in a constant expression.
1860
1861 void
1862 Integer_expression::do_export(Export* exp) const
1863 {
1864   Integer_expression::export_integer(exp, this->val_);
1865   if (this->is_character_constant_)
1866     exp->write_c_string("'");
1867   // A trailing space lets us reliably identify the end of the number.
1868   exp->write_c_string(" ");
1869 }
1870
1871 // Import an integer, floating point, or complex value.  This handles
1872 // all these types because they all start with digits.
1873
1874 Expression*
1875 Integer_expression::do_import(Import* imp)
1876 {
1877   std::string num = imp->read_identifier();
1878   imp->require_c_string(" ");
1879   if (!num.empty() && num[num.length() - 1] == 'i')
1880     {
1881       mpfr_t real;
1882       size_t plus_pos = num.find('+', 1);
1883       size_t minus_pos = num.find('-', 1);
1884       size_t pos;
1885       if (plus_pos == std::string::npos)
1886         pos = minus_pos;
1887       else if (minus_pos == std::string::npos)
1888         pos = plus_pos;
1889       else
1890         {
1891           error_at(imp->location(), "bad number in import data: %qs",
1892                    num.c_str());
1893           return Expression::make_error(imp->location());
1894         }
1895       if (pos == std::string::npos)
1896         mpfr_set_ui(real, 0, GMP_RNDN);
1897       else
1898         {
1899           std::string real_str = num.substr(0, pos);
1900           if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1901             {
1902               error_at(imp->location(), "bad number in import data: %qs",
1903                        real_str.c_str());
1904               return Expression::make_error(imp->location());
1905             }
1906         }
1907
1908       std::string imag_str;
1909       if (pos == std::string::npos)
1910         imag_str = num;
1911       else
1912         imag_str = num.substr(pos);
1913       imag_str = imag_str.substr(0, imag_str.size() - 1);
1914       mpfr_t imag;
1915       if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1916         {
1917           error_at(imp->location(), "bad number in import data: %qs",
1918                    imag_str.c_str());
1919           return Expression::make_error(imp->location());
1920         }
1921       Expression* ret = Expression::make_complex(&real, &imag, NULL,
1922                                                  imp->location());
1923       mpfr_clear(real);
1924       mpfr_clear(imag);
1925       return ret;
1926     }
1927   else if (num.find('.') == std::string::npos
1928            && num.find('E') == std::string::npos)
1929     {
1930       bool is_character_constant = (!num.empty()
1931                                     && num[num.length() - 1] == '\'');
1932       if (is_character_constant)
1933         num = num.substr(0, num.length() - 1);
1934       mpz_t val;
1935       if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1936         {
1937           error_at(imp->location(), "bad number in import data: %qs",
1938                    num.c_str());
1939           return Expression::make_error(imp->location());
1940         }
1941       Expression* ret;
1942       if (is_character_constant)
1943         ret = Expression::make_character(&val, NULL, imp->location());
1944       else
1945         ret = Expression::make_integer(&val, NULL, imp->location());
1946       mpz_clear(val);
1947       return ret;
1948     }
1949   else
1950     {
1951       mpfr_t val;
1952       if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1953         {
1954           error_at(imp->location(), "bad number in import data: %qs",
1955                    num.c_str());
1956           return Expression::make_error(imp->location());
1957         }
1958       Expression* ret = Expression::make_float(&val, NULL, imp->location());
1959       mpfr_clear(val);
1960       return ret;
1961     }
1962 }
1963 // Ast dump for integer expression.
1964
1965 void
1966 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1967 {
1968   if (this->is_character_constant_)
1969     ast_dump_context->ostream() << '\'';
1970   Integer_expression::export_integer(ast_dump_context, this->val_);
1971   if (this->is_character_constant_)
1972     ast_dump_context->ostream() << '\'';
1973 }
1974
1975 // Build a new integer value.
1976
1977 Expression*
1978 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1979 {
1980   return new Integer_expression(val, type, false, location);
1981 }
1982
1983 // Build a new character constant value.
1984
1985 Expression*
1986 Expression::make_character(const mpz_t* val, Type* type, Location location)
1987 {
1988   return new Integer_expression(val, type, true, location);
1989 }
1990
1991 // Floats.
1992
1993 class Float_expression : public Expression
1994 {
1995  public:
1996   Float_expression(const mpfr_t* val, Type* type, Location location)
1997     : Expression(EXPRESSION_FLOAT, location),
1998       type_(type)
1999   {
2000     mpfr_init_set(this->val_, *val, GMP_RNDN);
2001   }
2002
2003   // Write VAL to export data.
2004   static void
2005   export_float(String_dump* exp, const mpfr_t val);
2006
2007   // Write VAL to dump file.
2008   static void
2009   dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2010
2011  protected:
2012   bool
2013   do_is_constant() const
2014   { return true; }
2015
2016   bool
2017   do_numeric_constant_value(Numeric_constant* nc) const
2018   {
2019     nc->set_float(this->type_, this->val_);
2020     return true;
2021   }
2022
2023   Type*
2024   do_type();
2025
2026   void
2027   do_determine_type(const Type_context*);
2028
2029   void
2030   do_check_types(Gogo*);
2031
2032   Expression*
2033   do_copy()
2034   { return Expression::make_float(&this->val_, this->type_,
2035                                   this->location()); }
2036
2037   tree
2038   do_get_tree(Translate_context*);
2039
2040   void
2041   do_export(Export*) const;
2042
2043   void
2044   do_dump_expression(Ast_dump_context*) const;
2045
2046  private:
2047   // The floating point value.
2048   mpfr_t val_;
2049   // The type so far.
2050   Type* type_;
2051 };
2052
2053 // Return the current type.  If we haven't set the type yet, we return
2054 // an abstract float type.
2055
2056 Type*
2057 Float_expression::do_type()
2058 {
2059   if (this->type_ == NULL)
2060     this->type_ = Type::make_abstract_float_type();
2061   return this->type_;
2062 }
2063
2064 // Set the type of the float value.  Here we may switch from an
2065 // abstract type to a real type.
2066
2067 void
2068 Float_expression::do_determine_type(const Type_context* context)
2069 {
2070   if (this->type_ != NULL && !this->type_->is_abstract())
2071     ;
2072   else if (context->type != NULL
2073            && (context->type->integer_type() != NULL
2074                || context->type->float_type() != NULL
2075                || context->type->complex_type() != NULL))
2076     this->type_ = context->type;
2077   else if (!context->may_be_abstract)
2078     this->type_ = Type::lookup_float_type("float64");
2079 }
2080
2081 // Check the type of a float value.
2082
2083 void
2084 Float_expression::do_check_types(Gogo*)
2085 {
2086   Type* type = this->type_;
2087   if (type == NULL)
2088     return;
2089   Numeric_constant nc;
2090   nc.set_float(NULL, this->val_);
2091   if (!nc.set_type(this->type_, true, this->location()))
2092     this->set_is_error();
2093 }
2094
2095 // Get a tree for a float constant.
2096
2097 tree
2098 Float_expression::do_get_tree(Translate_context* context)
2099 {
2100   Gogo* gogo = context->gogo();
2101   tree type;
2102   if (this->type_ != NULL && !this->type_->is_abstract())
2103     type = type_to_tree(this->type_->get_backend(gogo));
2104   else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2105     {
2106       // We have an abstract integer type.  We just hope for the best.
2107       type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2108     }
2109   else
2110     {
2111       // If we still have an abstract type here, then this is being
2112       // used in a constant expression which didn't get reduced.  We
2113       // just use float64 and hope for the best.
2114       Type* ft = Type::lookup_float_type("float64");
2115       type = type_to_tree(ft->get_backend(gogo));
2116     }
2117   return Expression::float_constant_tree(this->val_, type);
2118 }
2119
2120 // Write a floating point number to a string dump.
2121
2122 void
2123 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2124 {
2125   mp_exp_t exponent;
2126   char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2127   if (*s == '-')
2128     exp->write_c_string("-");
2129   exp->write_c_string("0.");
2130   exp->write_c_string(*s == '-' ? s + 1 : s);
2131   mpfr_free_str(s);
2132   char buf[30];
2133   snprintf(buf, sizeof buf, "E%ld", exponent);
2134   exp->write_c_string(buf);
2135 }
2136
2137 // Export a floating point number in a constant expression.
2138
2139 void
2140 Float_expression::do_export(Export* exp) const
2141 {
2142   Float_expression::export_float(exp, this->val_);
2143   // A trailing space lets us reliably identify the end of the number.
2144   exp->write_c_string(" ");
2145 }
2146
2147 // Dump a floating point number to the dump file.
2148
2149 void
2150 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2151 {
2152   Float_expression::export_float(ast_dump_context, this->val_);
2153 }
2154
2155 // Make a float expression.
2156
2157 Expression*
2158 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2159 {
2160   return new Float_expression(val, type, location);
2161 }
2162
2163 // Complex numbers.
2164
2165 class Complex_expression : public Expression
2166 {
2167  public:
2168   Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2169                      Location location)
2170     : Expression(EXPRESSION_COMPLEX, location),
2171       type_(type)
2172   {
2173     mpfr_init_set(this->real_, *real, GMP_RNDN);
2174     mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2175   }
2176
2177   // Write REAL/IMAG to string dump.
2178   static void
2179   export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2180
2181   // Write REAL/IMAG to dump context.
2182   static void
2183   dump_complex(Ast_dump_context* ast_dump_context, 
2184                const mpfr_t real, const mpfr_t val);
2185   
2186  protected:
2187   bool
2188   do_is_constant() const
2189   { return true; }
2190
2191   bool
2192   do_numeric_constant_value(Numeric_constant* nc) const
2193   {
2194     nc->set_complex(this->type_, this->real_, this->imag_);
2195     return true;
2196   }
2197
2198   Type*
2199   do_type();
2200
2201   void
2202   do_determine_type(const Type_context*);
2203
2204   void
2205   do_check_types(Gogo*);
2206
2207   Expression*
2208   do_copy()
2209   {
2210     return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2211                                     this->location());
2212   }
2213
2214   tree
2215   do_get_tree(Translate_context*);
2216
2217   void
2218   do_export(Export*) const;
2219
2220   void
2221   do_dump_expression(Ast_dump_context*) const;
2222   
2223  private:
2224   // The real part.
2225   mpfr_t real_;
2226   // The imaginary part;
2227   mpfr_t imag_;
2228   // The type if known.
2229   Type* type_;
2230 };
2231
2232 // Return the current type.  If we haven't set the type yet, we return
2233 // an abstract complex type.
2234
2235 Type*
2236 Complex_expression::do_type()
2237 {
2238   if (this->type_ == NULL)
2239     this->type_ = Type::make_abstract_complex_type();
2240   return this->type_;
2241 }
2242
2243 // Set the type of the complex value.  Here we may switch from an
2244 // abstract type to a real type.
2245
2246 void
2247 Complex_expression::do_determine_type(const Type_context* context)
2248 {
2249   if (this->type_ != NULL && !this->type_->is_abstract())
2250     ;
2251   else if (context->type != NULL
2252            && context->type->complex_type() != NULL)
2253     this->type_ = context->type;
2254   else if (!context->may_be_abstract)
2255     this->type_ = Type::lookup_complex_type("complex128");
2256 }
2257
2258 // Check the type of a complex value.
2259
2260 void
2261 Complex_expression::do_check_types(Gogo*)
2262 {
2263   Type* type = this->type_;
2264   if (type == NULL)
2265     return;
2266   Numeric_constant nc;
2267   nc.set_complex(NULL, this->real_, this->imag_);
2268   if (!nc.set_type(this->type_, true, this->location()))
2269     this->set_is_error();
2270 }
2271
2272 // Get a tree for a complex constant.
2273
2274 tree
2275 Complex_expression::do_get_tree(Translate_context* context)
2276 {
2277   Gogo* gogo = context->gogo();
2278   tree type;
2279   if (this->type_ != NULL && !this->type_->is_abstract())
2280     type = type_to_tree(this->type_->get_backend(gogo));
2281   else
2282     {
2283       // If we still have an abstract type here, this this is being
2284       // used in a constant expression which didn't get reduced.  We
2285       // just use complex128 and hope for the best.
2286       Type* ct = Type::lookup_complex_type("complex128");
2287       type = type_to_tree(ct->get_backend(gogo));
2288     }
2289   return Expression::complex_constant_tree(this->real_, this->imag_, type);
2290 }
2291
2292 // Write REAL/IMAG to export data.
2293
2294 void
2295 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2296                                    const mpfr_t imag)
2297 {
2298   if (!mpfr_zero_p(real))
2299     {
2300       Float_expression::export_float(exp, real);
2301       if (mpfr_sgn(imag) > 0)
2302         exp->write_c_string("+");
2303     }
2304   Float_expression::export_float(exp, imag);
2305   exp->write_c_string("i");
2306 }
2307
2308 // Export a complex number in a constant expression.
2309
2310 void
2311 Complex_expression::do_export(Export* exp) const
2312 {
2313   Complex_expression::export_complex(exp, this->real_, this->imag_);
2314   // A trailing space lets us reliably identify the end of the number.
2315   exp->write_c_string(" ");
2316 }
2317
2318 // Dump a complex expression to the dump file.
2319
2320 void
2321 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2322 {
2323   Complex_expression::export_complex(ast_dump_context,
2324                                       this->real_,
2325                                       this->imag_);
2326 }
2327
2328 // Make a complex expression.
2329
2330 Expression*
2331 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2332                          Location location)
2333 {
2334   return new Complex_expression(real, imag, type, location);
2335 }
2336
2337 // Find a named object in an expression.
2338
2339 class Find_named_object : public Traverse
2340 {
2341  public:
2342   Find_named_object(Named_object* no)
2343     : Traverse(traverse_expressions),
2344       no_(no), found_(false)
2345   { }
2346
2347   // Whether we found the object.
2348   bool
2349   found() const
2350   { return this->found_; }
2351
2352  protected:
2353   int
2354   expression(Expression**);
2355
2356  private:
2357   // The object we are looking for.
2358   Named_object* no_;
2359   // Whether we found it.
2360   bool found_;
2361 };
2362
2363 // A reference to a const in an expression.
2364
2365 class Const_expression : public Expression
2366 {
2367  public:
2368   Const_expression(Named_object* constant, Location location)
2369     : Expression(EXPRESSION_CONST_REFERENCE, location),
2370       constant_(constant), type_(NULL), seen_(false)
2371   { }
2372
2373   Named_object*
2374   named_object()
2375   { return this->constant_; }
2376
2377   // Check that the initializer does not refer to the constant itself.
2378   void
2379   check_for_init_loop();
2380
2381  protected:
2382   int
2383   do_traverse(Traverse*);
2384
2385   Expression*
2386   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2387
2388   bool
2389   do_is_constant() const
2390   { return true; }
2391
2392   bool
2393   do_numeric_constant_value(Numeric_constant* nc) const;
2394
2395   bool
2396   do_string_constant_value(std::string* val) const;
2397
2398   Type*
2399   do_type();
2400
2401   // The type of a const is set by the declaration, not the use.
2402   void
2403   do_determine_type(const Type_context*);
2404
2405   void
2406   do_check_types(Gogo*);
2407
2408   Expression*
2409   do_copy()
2410   { return this; }
2411
2412   tree
2413   do_get_tree(Translate_context* context);
2414
2415   // When exporting a reference to a const as part of a const
2416   // expression, we export the value.  We ignore the fact that it has
2417   // a name.
2418   void
2419   do_export(Export* exp) const
2420   { this->constant_->const_value()->expr()->export_expression(exp); }
2421
2422   void
2423   do_dump_expression(Ast_dump_context*) const;
2424
2425  private:
2426   // The constant.
2427   Named_object* constant_;
2428   // The type of this reference.  This is used if the constant has an
2429   // abstract type.
2430   Type* type_;
2431   // Used to prevent infinite recursion when a constant incorrectly
2432   // refers to itself.
2433   mutable bool seen_;
2434 };
2435
2436 // Traversal.
2437
2438 int
2439 Const_expression::do_traverse(Traverse* traverse)
2440 {
2441   if (this->type_ != NULL)
2442     return Type::traverse(this->type_, traverse);
2443   return TRAVERSE_CONTINUE;
2444 }
2445
2446 // Lower a constant expression.  This is where we convert the
2447 // predeclared constant iota into an integer value.
2448
2449 Expression*
2450 Const_expression::do_lower(Gogo* gogo, Named_object*,
2451                            Statement_inserter*, int iota_value)
2452 {
2453   if (this->constant_->const_value()->expr()->classification()
2454       == EXPRESSION_IOTA)
2455     {
2456       if (iota_value == -1)
2457         {
2458           error_at(this->location(),
2459                    "iota is only defined in const declarations");
2460           iota_value = 0;
2461         }
2462       mpz_t val;
2463       mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2464       Expression* ret = Expression::make_integer(&val, NULL,
2465                                                  this->location());
2466       mpz_clear(val);
2467       return ret;
2468     }
2469
2470   // Make sure that the constant itself has been lowered.
2471   gogo->lower_constant(this->constant_);
2472
2473   return this;
2474 }
2475
2476 // Return a numeric constant value.
2477
2478 bool
2479 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2480 {
2481   if (this->seen_)
2482     return false;
2483
2484   Expression* e = this->constant_->const_value()->expr();
2485   
2486   this->seen_ = true;
2487
2488   bool r = e->numeric_constant_value(nc);
2489
2490   this->seen_ = false;
2491
2492   Type* ctype;
2493   if (this->type_ != NULL)
2494     ctype = this->type_;
2495   else
2496     ctype = this->constant_->const_value()->type();
2497   if (r && ctype != NULL)
2498     {
2499       if (!nc->set_type(ctype, false, this->location()))
2500         return false;
2501     }
2502
2503   return r;
2504 }
2505
2506 bool
2507 Const_expression::do_string_constant_value(std::string* val) const
2508 {
2509   if (this->seen_)
2510     return false;
2511
2512   Expression* e = this->constant_->const_value()->expr();
2513
2514   this->seen_ = true;
2515   bool ok = e->string_constant_value(val);
2516   this->seen_ = false;
2517
2518   return ok;
2519 }
2520
2521 // Return the type of the const reference.
2522
2523 Type*
2524 Const_expression::do_type()
2525 {
2526   if (this->type_ != NULL)
2527     return this->type_;
2528
2529   Named_constant* nc = this->constant_->const_value();
2530
2531   if (this->seen_ || nc->lowering())
2532     {
2533       this->report_error(_("constant refers to itself"));
2534       this->type_ = Type::make_error_type();
2535       return this->type_;
2536     }
2537
2538   this->seen_ = true;
2539
2540   Type* ret = nc->type();
2541
2542   if (ret != NULL)
2543     {
2544       this->seen_ = false;
2545       return ret;
2546     }
2547
2548   // During parsing, a named constant may have a NULL type, but we
2549   // must not return a NULL type here.
2550   ret = nc->expr()->type();
2551
2552   this->seen_ = false;
2553
2554   return ret;
2555 }
2556
2557 // Set the type of the const reference.
2558
2559 void
2560 Const_expression::do_determine_type(const Type_context* context)
2561 {
2562   Type* ctype = this->constant_->const_value()->type();
2563   Type* cetype = (ctype != NULL
2564                   ? ctype
2565                   : this->constant_->const_value()->expr()->type());
2566   if (ctype != NULL && !ctype->is_abstract())
2567     ;
2568   else if (context->type != NULL
2569            && context->type->is_numeric_type()
2570            && cetype->is_numeric_type())
2571     this->type_ = context->type;
2572   else if (context->type != NULL
2573            && context->type->is_string_type()
2574            && cetype->is_string_type())
2575     this->type_ = context->type;
2576   else if (context->type != NULL
2577            && context->type->is_boolean_type()
2578            && cetype->is_boolean_type())
2579     this->type_ = context->type;
2580   else if (!context->may_be_abstract)
2581     {
2582       if (cetype->is_abstract())
2583         cetype = cetype->make_non_abstract_type();
2584       this->type_ = cetype;
2585     }
2586 }
2587
2588 // Check for a loop in which the initializer of a constant refers to
2589 // the constant itself.
2590
2591 void
2592 Const_expression::check_for_init_loop()
2593 {
2594   if (this->type_ != NULL && this->type_->is_error())
2595     return;
2596
2597   if (this->seen_)
2598     {
2599       this->report_error(_("constant refers to itself"));
2600       this->type_ = Type::make_error_type();
2601       return;
2602     }
2603
2604   Expression* init = this->constant_->const_value()->expr();
2605   Find_named_object find_named_object(this->constant_);
2606
2607   this->seen_ = true;
2608   Expression::traverse(&init, &find_named_object);
2609   this->seen_ = false;
2610
2611   if (find_named_object.found())
2612     {
2613       if (this->type_ == NULL || !this->type_->is_error())
2614         {
2615           this->report_error(_("constant refers to itself"));
2616           this->type_ = Type::make_error_type();
2617         }
2618       return;
2619     }
2620 }
2621
2622 // Check types of a const reference.
2623
2624 void
2625 Const_expression::do_check_types(Gogo*)
2626 {
2627   if (this->type_ != NULL && this->type_->is_error())
2628     return;
2629
2630   this->check_for_init_loop();
2631
2632   // Check that numeric constant fits in type.
2633   if (this->type_ != NULL && this->type_->is_numeric_type())
2634     {
2635       Numeric_constant nc;
2636       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2637         {
2638           if (!nc.set_type(this->type_, true, this->location()))
2639             this->set_is_error();
2640         }
2641     }
2642 }
2643
2644 // Return a tree for the const reference.
2645
2646 tree
2647 Const_expression::do_get_tree(Translate_context* context)
2648 {
2649   Gogo* gogo = context->gogo();
2650   tree type_tree;
2651   if (this->type_ == NULL)
2652     type_tree = NULL_TREE;
2653   else
2654     {
2655       type_tree = type_to_tree(this->type_->get_backend(gogo));
2656       if (type_tree == error_mark_node)
2657         return error_mark_node;
2658     }
2659
2660   // If the type has been set for this expression, but the underlying
2661   // object is an abstract int or float, we try to get the abstract
2662   // value.  Otherwise we may lose something in the conversion.
2663   if (this->type_ != NULL
2664       && this->type_->is_numeric_type()
2665       && (this->constant_->const_value()->type() == NULL
2666           || this->constant_->const_value()->type()->is_abstract()))
2667     {
2668       Expression* expr = this->constant_->const_value()->expr();
2669       Numeric_constant nc;
2670       if (expr->numeric_constant_value(&nc)
2671           && nc.set_type(this->type_, false, this->location()))
2672         {
2673           Expression* e = nc.expression(this->location());
2674           return e->get_tree(context);
2675         }
2676     }
2677
2678   tree const_tree = this->constant_->get_tree(gogo, context->function());
2679   if (this->type_ == NULL
2680       || const_tree == error_mark_node
2681       || TREE_TYPE(const_tree) == error_mark_node)
2682     return const_tree;
2683
2684   tree ret;
2685   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2686     ret = fold_convert(type_tree, const_tree);
2687   else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2688     ret = fold(convert_to_integer(type_tree, const_tree));
2689   else if (TREE_CODE(type_tree) == REAL_TYPE)
2690     ret = fold(convert_to_real(type_tree, const_tree));
2691   else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2692     ret = fold(convert_to_complex(type_tree, const_tree));
2693   else
2694     go_unreachable();
2695   return ret;
2696 }
2697
2698 // Dump ast representation for constant expression.
2699
2700 void
2701 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2702 {
2703   ast_dump_context->ostream() << this->constant_->name();
2704 }
2705
2706 // Make a reference to a constant in an expression.
2707
2708 Expression*
2709 Expression::make_const_reference(Named_object* constant,
2710                                  Location location)
2711 {
2712   return new Const_expression(constant, location);
2713 }
2714
2715 // Find a named object in an expression.
2716
2717 int
2718 Find_named_object::expression(Expression** pexpr)
2719 {
2720   switch ((*pexpr)->classification())
2721     {
2722     case Expression::EXPRESSION_CONST_REFERENCE:
2723       {
2724         Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2725         if (ce->named_object() == this->no_)
2726           break;
2727
2728         // We need to check a constant initializer explicitly, as
2729         // loops here will not be caught by the loop checking for
2730         // variable initializers.
2731         ce->check_for_init_loop();
2732
2733         return TRAVERSE_CONTINUE;
2734       }
2735
2736     case Expression::EXPRESSION_VAR_REFERENCE:
2737       if ((*pexpr)->var_expression()->named_object() == this->no_)
2738         break;
2739       return TRAVERSE_CONTINUE;
2740     case Expression::EXPRESSION_FUNC_REFERENCE:
2741       if ((*pexpr)->func_expression()->named_object() == this->no_)
2742         break;
2743       return TRAVERSE_CONTINUE;
2744     default:
2745       return TRAVERSE_CONTINUE;
2746     }
2747   this->found_ = true;
2748   return TRAVERSE_EXIT;
2749 }
2750
2751 // The nil value.
2752
2753 class Nil_expression : public Expression
2754 {
2755  public:
2756   Nil_expression(Location location)
2757     : Expression(EXPRESSION_NIL, location)
2758   { }
2759
2760   static Expression*
2761   do_import(Import*);
2762
2763  protected:
2764   bool
2765   do_is_constant() const
2766   { return true; }
2767
2768   Type*
2769   do_type()
2770   { return Type::make_nil_type(); }
2771
2772   void
2773   do_determine_type(const Type_context*)
2774   { }
2775
2776   Expression*
2777   do_copy()
2778   { return this; }
2779
2780   tree
2781   do_get_tree(Translate_context*)
2782   { return null_pointer_node; }
2783
2784   void
2785   do_export(Export* exp) const
2786   { exp->write_c_string("nil"); }
2787
2788   void
2789   do_dump_expression(Ast_dump_context* ast_dump_context) const
2790   { ast_dump_context->ostream() << "nil"; }
2791 };
2792
2793 // Import a nil expression.
2794
2795 Expression*
2796 Nil_expression::do_import(Import* imp)
2797 {
2798   imp->require_c_string("nil");
2799   return Expression::make_nil(imp->location());
2800 }
2801
2802 // Make a nil expression.
2803
2804 Expression*
2805 Expression::make_nil(Location location)
2806 {
2807   return new Nil_expression(location);
2808 }
2809
2810 // The value of the predeclared constant iota.  This is little more
2811 // than a marker.  This will be lowered to an integer in
2812 // Const_expression::do_lower, which is where we know the value that
2813 // it should have.
2814
2815 class Iota_expression : public Parser_expression
2816 {
2817  public:
2818   Iota_expression(Location location)
2819     : Parser_expression(EXPRESSION_IOTA, location)
2820   { }
2821
2822  protected:
2823   Expression*
2824   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2825   { go_unreachable(); }
2826
2827   // There should only ever be one of these.
2828   Expression*
2829   do_copy()
2830   { go_unreachable(); }
2831   
2832   void
2833   do_dump_expression(Ast_dump_context* ast_dump_context) const
2834   { ast_dump_context->ostream() << "iota"; } 
2835 };
2836
2837 // Make an iota expression.  This is only called for one case: the
2838 // value of the predeclared constant iota.
2839
2840 Expression*
2841 Expression::make_iota()
2842 {
2843   static Iota_expression iota_expression(Linemap::unknown_location());
2844   return &iota_expression;
2845 }
2846
2847 // A type conversion expression.
2848
2849 class Type_conversion_expression : public Expression
2850 {
2851  public:
2852   Type_conversion_expression(Type* type, Expression* expr,
2853                              Location location)
2854     : Expression(EXPRESSION_CONVERSION, location),
2855       type_(type), expr_(expr), may_convert_function_types_(false)
2856   { }
2857
2858   // Return the type to which we are converting.
2859   Type*
2860   type() const
2861   { return this->type_; }
2862
2863   // Return the expression which we are converting.
2864   Expression*
2865   expr() const
2866   { return this->expr_; }
2867
2868   // Permit converting from one function type to another.  This is
2869   // used internally for method expressions.
2870   void
2871   set_may_convert_function_types()
2872   {
2873     this->may_convert_function_types_ = true;
2874   }
2875
2876   // Import a type conversion expression.
2877   static Expression*
2878   do_import(Import*);
2879
2880  protected:
2881   int
2882   do_traverse(Traverse* traverse);
2883
2884   Expression*
2885   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2886
2887   bool
2888   do_is_constant() const
2889   { return this->expr_->is_constant(); }
2890
2891   bool
2892   do_numeric_constant_value(Numeric_constant*) const;
2893
2894   bool
2895   do_string_constant_value(std::string*) const;
2896
2897   Type*
2898   do_type()
2899   { return this->type_; }
2900
2901   void
2902   do_determine_type(const Type_context*)
2903   {
2904     Type_context subcontext(this->type_, false);
2905     this->expr_->determine_type(&subcontext);
2906   }
2907
2908   void
2909   do_check_types(Gogo*);
2910
2911   Expression*
2912   do_copy()
2913   {
2914     return new Type_conversion_expression(this->type_, this->expr_->copy(),
2915                                           this->location());
2916   }
2917
2918   tree
2919   do_get_tree(Translate_context* context);
2920
2921   void
2922   do_export(Export*) const;
2923
2924   void
2925   do_dump_expression(Ast_dump_context*) const;
2926
2927  private:
2928   // The type to convert to.
2929   Type* type_;
2930   // The expression to convert.
2931   Expression* expr_;
2932   // True if this is permitted to convert function types.  This is
2933   // used internally for method expressions.
2934   bool may_convert_function_types_;
2935 };
2936
2937 // Traversal.
2938
2939 int
2940 Type_conversion_expression::do_traverse(Traverse* traverse)
2941 {
2942   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2943       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2944     return TRAVERSE_EXIT;
2945   return TRAVERSE_CONTINUE;
2946 }
2947
2948 // Convert to a constant at lowering time.
2949
2950 Expression*
2951 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2952                                      Statement_inserter*, int)
2953 {
2954   Type* type = this->type_;
2955   Expression* val = this->expr_;
2956   Location location = this->location();
2957
2958   if (type->is_numeric_type())
2959     {
2960       Numeric_constant nc;
2961       if (val->numeric_constant_value(&nc))
2962         {
2963           if (!nc.set_type(type, true, location))
2964             return Expression::make_error(location);
2965           return nc.expression(location);
2966         }
2967     }
2968
2969   if (type->is_slice_type())
2970     {
2971       Type* element_type = type->array_type()->element_type()->forwarded();
2972       bool is_byte = (element_type->integer_type() != NULL
2973                       && element_type->integer_type()->is_byte());
2974       bool is_rune = (element_type->integer_type() != NULL
2975                       && element_type->integer_type()->is_rune());
2976       if (is_byte || is_rune)
2977         {
2978           std::string s;
2979           if (val->string_constant_value(&s))
2980             {
2981               Expression_list* vals = new Expression_list();
2982               if (is_byte)
2983                 {
2984                   for (std::string::const_iterator p = s.begin();
2985                        p != s.end();
2986                        p++)
2987                     {
2988                       mpz_t val;
2989                       mpz_init_set_ui(val, static_cast<unsigned char>(*p));
2990                       Expression* v = Expression::make_integer(&val,
2991                                                                element_type,
2992                                                                location);
2993                       vals->push_back(v);
2994                       mpz_clear(val);
2995                     }
2996                 }
2997               else
2998                 {
2999                   const char *p = s.data();
3000                   const char *pend = s.data() + s.length();
3001                   while (p < pend)
3002                     {
3003                       unsigned int c;
3004                       int adv = Lex::fetch_char(p, &c);
3005                       if (adv == 0)
3006                         {
3007                           warning_at(this->location(), 0,
3008                                      "invalid UTF-8 encoding");
3009                           adv = 1;
3010                         }
3011                       p += adv;
3012                       mpz_t val;
3013                       mpz_init_set_ui(val, c);
3014                       Expression* v = Expression::make_integer(&val,
3015                                                                element_type,
3016                                                                location);
3017                       vals->push_back(v);
3018                       mpz_clear(val);
3019                     }
3020                 }
3021
3022               return Expression::make_slice_composite_literal(type, vals,
3023                                                               location);
3024             }
3025         }
3026     }
3027
3028   return this;
3029 }
3030
3031 // Return the constant numeric value if there is one.
3032
3033 bool
3034 Type_conversion_expression::do_numeric_constant_value(
3035     Numeric_constant* nc) const
3036 {
3037   if (!this->type_->is_numeric_type())
3038     return false;
3039   if (!this->expr_->numeric_constant_value(nc))
3040     return false;
3041   return nc->set_type(this->type_, false, this->location());
3042 }
3043
3044 // Return the constant string value if there is one.
3045
3046 bool
3047 Type_conversion_expression::do_string_constant_value(std::string* val) const
3048 {
3049   if (this->type_->is_string_type()
3050       && this->expr_->type()->integer_type() != NULL)
3051     {
3052       Numeric_constant nc;
3053       if (this->expr_->numeric_constant_value(&nc))
3054         {
3055           unsigned long ival;
3056           if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3057             {
3058               val->clear();
3059               Lex::append_char(ival, true, val, this->location());
3060               return true;
3061             }
3062         }
3063     }
3064
3065   // FIXME: Could handle conversion from const []int here.
3066
3067   return false;
3068 }
3069
3070 // Check that types are convertible.
3071
3072 void
3073 Type_conversion_expression::do_check_types(Gogo*)
3074 {
3075   Type* type = this->type_;
3076   Type* expr_type = this->expr_->type();
3077   std::string reason;
3078
3079   if (type->is_error() || expr_type->is_error())
3080     {
3081       this->set_is_error();
3082       return;
3083     }
3084
3085   if (this->may_convert_function_types_
3086       && type->function_type() != NULL
3087       && expr_type->function_type() != NULL)
3088     return;
3089
3090   if (Type::are_convertible(type, expr_type, &reason))
3091     return;
3092
3093   error_at(this->location(), "%s", reason.c_str());
3094   this->set_is_error();
3095 }
3096
3097 // Get a tree for a type conversion.
3098
3099 tree
3100 Type_conversion_expression::do_get_tree(Translate_context* context)
3101 {
3102   Gogo* gogo = context->gogo();
3103   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3104   tree expr_tree = this->expr_->get_tree(context);
3105
3106   if (type_tree == error_mark_node
3107       || expr_tree == error_mark_node
3108       || TREE_TYPE(expr_tree) == error_mark_node)
3109     return error_mark_node;
3110
3111   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3112     return fold_convert(type_tree, expr_tree);
3113
3114   Type* type = this->type_;
3115   Type* expr_type = this->expr_->type();
3116   tree ret;
3117   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3118     ret = Expression::convert_for_assignment(context, type, expr_type,
3119                                              expr_tree, this->location());
3120   else if (type->integer_type() != NULL)
3121     {
3122       if (expr_type->integer_type() != NULL
3123           || expr_type->float_type() != NULL
3124           || expr_type->is_unsafe_pointer_type())
3125         ret = fold(convert_to_integer(type_tree, expr_tree));
3126       else
3127         go_unreachable();
3128     }
3129   else if (type->float_type() != NULL)
3130     {
3131       if (expr_type->integer_type() != NULL
3132           || expr_type->float_type() != NULL)
3133         ret = fold(convert_to_real(type_tree, expr_tree));
3134       else
3135         go_unreachable();
3136     }
3137   else if (type->complex_type() != NULL)
3138     {
3139       if (expr_type->complex_type() != NULL)
3140         ret = fold(convert_to_complex(type_tree, expr_tree));
3141       else
3142         go_unreachable();
3143     }
3144   else if (type->is_string_type()
3145            && expr_type->integer_type() != NULL)
3146     {
3147       expr_tree = fold_convert(integer_type_node, expr_tree);
3148       if (host_integerp(expr_tree, 0))
3149         {
3150           HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3151           std::string s;
3152           Lex::append_char(intval, true, &s, this->location());
3153           Expression* se = Expression::make_string(s, this->location());
3154           return se->get_tree(context);
3155         }
3156
3157       static tree int_to_string_fndecl;
3158       ret = Gogo::call_builtin(&int_to_string_fndecl,
3159                                this->location(),
3160                                "__go_int_to_string",
3161                                1,
3162                                type_tree,
3163                                integer_type_node,
3164                                fold_convert(integer_type_node, expr_tree));
3165     }
3166   else if (type->is_string_type() && expr_type->is_slice_type())
3167     {
3168       if (!DECL_P(expr_tree))
3169         expr_tree = save_expr(expr_tree);
3170       Array_type* a = expr_type->array_type();
3171       Type* e = a->element_type()->forwarded();
3172       go_assert(e->integer_type() != NULL);
3173       tree valptr = fold_convert(const_ptr_type_node,
3174                                  a->value_pointer_tree(gogo, expr_tree));
3175       tree len = a->length_tree(gogo, expr_tree);
3176       len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3177                              len);
3178       if (e->integer_type()->is_byte())
3179         {
3180           static tree byte_array_to_string_fndecl;
3181           ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3182                                    this->location(),
3183                                    "__go_byte_array_to_string",
3184                                    2,
3185                                    type_tree,
3186                                    const_ptr_type_node,
3187                                    valptr,
3188                                    integer_type_node,
3189                                    len);
3190         }
3191       else
3192         {
3193           go_assert(e->integer_type()->is_rune());
3194           static tree int_array_to_string_fndecl;
3195           ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3196                                    this->location(),
3197                                    "__go_int_array_to_string",
3198                                    2,
3199                                    type_tree,
3200                                    const_ptr_type_node,
3201                                    valptr,
3202                                    integer_type_node,
3203                                    len);
3204         }
3205     }
3206   else if (type->is_slice_type() && expr_type->is_string_type())
3207     {
3208       Type* e = type->array_type()->element_type()->forwarded();
3209       go_assert(e->integer_type() != NULL);
3210       if (e->integer_type()->is_byte())
3211         {
3212           tree string_to_byte_array_fndecl = NULL_TREE;
3213           ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3214                                    this->location(),
3215                                    "__go_string_to_byte_array",
3216                                    1,
3217                                    type_tree,
3218                                    TREE_TYPE(expr_tree),
3219                                    expr_tree);
3220         }
3221       else
3222         {
3223           go_assert(e->integer_type()->is_rune());
3224           tree string_to_int_array_fndecl = NULL_TREE;
3225           ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3226                                    this->location(),
3227                                    "__go_string_to_int_array",
3228                                    1,
3229                                    type_tree,
3230                                    TREE_TYPE(expr_tree),
3231                                    expr_tree);
3232         }
3233     }
3234   else if ((type->is_unsafe_pointer_type()
3235             && expr_type->points_to() != NULL)
3236            || (expr_type->is_unsafe_pointer_type()
3237                && type->points_to() != NULL))
3238     ret = fold_convert(type_tree, expr_tree);
3239   else if (type->is_unsafe_pointer_type()
3240            && expr_type->integer_type() != NULL)
3241     ret = convert_to_pointer(type_tree, expr_tree);
3242   else if (this->may_convert_function_types_
3243            && type->function_type() != NULL
3244            && expr_type->function_type() != NULL)
3245     ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3246                            expr_tree);
3247   else
3248     ret = Expression::convert_for_assignment(context, type, expr_type,
3249                                              expr_tree, this->location());
3250
3251   return ret;
3252 }
3253
3254 // Output a type conversion in a constant expression.
3255
3256 void
3257 Type_conversion_expression::do_export(Export* exp) const
3258 {
3259   exp->write_c_string("convert(");
3260   exp->write_type(this->type_);
3261   exp->write_c_string(", ");
3262   this->expr_->export_expression(exp);
3263   exp->write_c_string(")");
3264 }
3265
3266 // Import a type conversion or a struct construction.
3267
3268 Expression*
3269 Type_conversion_expression::do_import(Import* imp)
3270 {
3271   imp->require_c_string("convert(");
3272   Type* type = imp->read_type();
3273   imp->require_c_string(", ");
3274   Expression* val = Expression::import_expression(imp);
3275   imp->require_c_string(")");
3276   return Expression::make_cast(type, val, imp->location());
3277 }
3278
3279 // Dump ast representation for a type conversion expression.
3280
3281 void
3282 Type_conversion_expression::do_dump_expression(
3283     Ast_dump_context* ast_dump_context) const
3284 {
3285   ast_dump_context->dump_type(this->type_);
3286   ast_dump_context->ostream() << "(";
3287   ast_dump_context->dump_expression(this->expr_);
3288   ast_dump_context->ostream() << ") ";
3289 }
3290
3291 // Make a type cast expression.
3292
3293 Expression*
3294 Expression::make_cast(Type* type, Expression* val, Location location)
3295 {
3296   if (type->is_error_type() || val->is_error_expression())
3297     return Expression::make_error(location);
3298   return new Type_conversion_expression(type, val, location);
3299 }
3300
3301 // An unsafe type conversion, used to pass values to builtin functions.
3302
3303 class Unsafe_type_conversion_expression : public Expression
3304 {
3305  public:
3306   Unsafe_type_conversion_expression(Type* type, Expression* expr,
3307                                     Location location)
3308     : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3309       type_(type), expr_(expr)
3310   { }
3311
3312  protected:
3313   int
3314   do_traverse(Traverse* traverse);
3315
3316   Type*
3317   do_type()
3318   { return this->type_; }
3319
3320   void
3321   do_determine_type(const Type_context*)
3322   { this->expr_->determine_type_no_context(); }
3323
3324   Expression*
3325   do_copy()
3326   {
3327     return new Unsafe_type_conversion_expression(this->type_,
3328                                                  this->expr_->copy(),
3329                                                  this->location());
3330   }
3331
3332   tree
3333   do_get_tree(Translate_context*);
3334
3335   void
3336   do_dump_expression(Ast_dump_context*) const;
3337
3338  private:
3339   // The type to convert to.
3340   Type* type_;
3341   // The expression to convert.
3342   Expression* expr_;
3343 };
3344
3345 // Traversal.
3346
3347 int
3348 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3349 {
3350   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3351       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3352     return TRAVERSE_EXIT;
3353   return TRAVERSE_CONTINUE;
3354 }
3355
3356 // Convert to backend representation.
3357
3358 tree
3359 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3360 {
3361   // We are only called for a limited number of cases.
3362
3363   Type* t = this->type_;
3364   Type* et = this->expr_->type();
3365
3366   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3367   tree expr_tree = this->expr_->get_tree(context);
3368   if (type_tree == error_mark_node || expr_tree == error_mark_node)
3369     return error_mark_node;
3370
3371   Location loc = this->location();
3372
3373   bool use_view_convert = false;
3374   if (t->is_slice_type())
3375     {
3376       go_assert(et->is_slice_type());
3377       use_view_convert = true;
3378     }
3379   else if (t->map_type() != NULL)
3380     go_assert(et->map_type() != NULL);
3381   else if (t->channel_type() != NULL)
3382     go_assert(et->channel_type() != NULL);
3383   else if (t->points_to() != NULL)
3384     go_assert(et->points_to() != NULL || et->is_nil_type());
3385   else if (et->is_unsafe_pointer_type())
3386     go_assert(t->points_to() != NULL);
3387   else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3388     {
3389       go_assert(et->interface_type() != NULL
3390                  && !et->interface_type()->is_empty());
3391       use_view_convert = true;
3392     }
3393   else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3394     {
3395       go_assert(et->interface_type() != NULL
3396                  && et->interface_type()->is_empty());
3397       use_view_convert = true;
3398     }
3399   else if (t->integer_type() != NULL)
3400     {
3401       go_assert(et->is_boolean_type()
3402                  || et->integer_type() != NULL
3403                  || et->function_type() != NULL
3404                  || et->points_to() != NULL
3405                  || et->map_type() != NULL
3406                  || et->channel_type() != NULL);
3407       return convert_to_integer(type_tree, expr_tree);
3408     }
3409   else
3410     go_unreachable();
3411
3412   if (use_view_convert)
3413     return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3414                            expr_tree);
3415   else
3416     return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3417 }
3418
3419 // Dump ast representation for an unsafe type conversion expression.
3420
3421 void
3422 Unsafe_type_conversion_expression::do_dump_expression(
3423     Ast_dump_context* ast_dump_context) const
3424 {
3425   ast_dump_context->dump_type(this->type_);
3426   ast_dump_context->ostream() << "(";
3427   ast_dump_context->dump_expression(this->expr_);
3428   ast_dump_context->ostream() << ") ";
3429 }
3430
3431 // Make an unsafe type conversion expression.
3432
3433 Expression*
3434 Expression::make_unsafe_cast(Type* type, Expression* expr,
3435                              Location location)
3436 {
3437   return new Unsafe_type_conversion_expression(type, expr, location);
3438 }
3439
3440 // Unary expressions.
3441
3442 class Unary_expression : public Expression
3443 {
3444  public:
3445   Unary_expression(Operator op, Expression* expr, Location location)
3446     : Expression(EXPRESSION_UNARY, location),
3447       op_(op), escapes_(true), create_temp_(false), expr_(expr)
3448   { }
3449
3450   // Return the operator.
3451   Operator
3452   op() const
3453   { return this->op_; }
3454
3455   // Return the operand.
3456   Expression*
3457   operand() const
3458   { return this->expr_; }
3459
3460   // Record that an address expression does not escape.
3461   void
3462   set_does_not_escape()
3463   {
3464     go_assert(this->op_ == OPERATOR_AND);
3465     this->escapes_ = false;
3466   }
3467
3468   // Record that this is an address expression which should create a
3469   // temporary variable if necessary.  This is used for method calls.
3470   void
3471   set_create_temp()
3472   {
3473     go_assert(this->op_ == OPERATOR_AND);
3474     this->create_temp_ = true;
3475   }
3476
3477   // Apply unary opcode OP to UNC, setting NC.  Return true if this
3478   // could be done, false if not.  Issue errors for overflow.
3479   static bool
3480   eval_constant(Operator op, const Numeric_constant* unc,
3481                 Location, Numeric_constant* nc);
3482
3483   static Expression*
3484   do_import(Import*);
3485
3486  protected:
3487   int
3488   do_traverse(Traverse* traverse)
3489   { return Expression::traverse(&this->expr_, traverse); }
3490
3491   Expression*
3492   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3493
3494   bool
3495   do_is_constant() const;
3496
3497   bool
3498   do_numeric_constant_value(Numeric_constant*) const;
3499
3500   Type*
3501   do_type();
3502
3503   void
3504   do_determine_type(const Type_context*);
3505
3506   void
3507   do_check_types(Gogo*);
3508
3509   Expression*
3510   do_copy()
3511   {
3512     return Expression::make_unary(this->op_, this->expr_->copy(),
3513                                   this->location());
3514   }
3515
3516   bool
3517   do_must_eval_subexpressions_in_order(int*) const
3518   { return this->op_ == OPERATOR_MULT; }
3519
3520   bool
3521   do_is_addressable() const
3522   { return this->op_ == OPERATOR_MULT; }
3523
3524   tree
3525   do_get_tree(Translate_context*);
3526
3527   void
3528   do_export(Export*) const;
3529