OSDN Git Service

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