OSDN Git Service

945f379465ae161fd91127145f180b1e3aab65ae
[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
2408   Type*
2409   do_type();
2410
2411   // The type of a const is set by the declaration, not the use.
2412   void
2413   do_determine_type(const Type_context*);
2414
2415   void
2416   do_check_types(Gogo*);
2417
2418   Expression*
2419   do_copy()
2420   { return this; }
2421
2422   tree
2423   do_get_tree(Translate_context* context);
2424
2425   // When exporting a reference to a const as part of a const
2426   // expression, we export the value.  We ignore the fact that it has
2427   // a name.
2428   void
2429   do_export(Export* exp) const
2430   { this->constant_->const_value()->expr()->export_expression(exp); }
2431
2432   void
2433   do_dump_expression(Ast_dump_context*) const;
2434
2435  private:
2436   // The constant.
2437   Named_object* constant_;
2438   // The type of this reference.  This is used if the constant has an
2439   // abstract type.
2440   Type* type_;
2441   // Used to prevent infinite recursion when a constant incorrectly
2442   // refers to itself.
2443   mutable bool seen_;
2444 };
2445
2446 // Traversal.
2447
2448 int
2449 Const_expression::do_traverse(Traverse* traverse)
2450 {
2451   if (this->type_ != NULL)
2452     return Type::traverse(this->type_, traverse);
2453   return TRAVERSE_CONTINUE;
2454 }
2455
2456 // Lower a constant expression.  This is where we convert the
2457 // predeclared constant iota into an integer value.
2458
2459 Expression*
2460 Const_expression::do_lower(Gogo* gogo, Named_object*,
2461                            Statement_inserter*, int iota_value)
2462 {
2463   if (this->constant_->const_value()->expr()->classification()
2464       == EXPRESSION_IOTA)
2465     {
2466       if (iota_value == -1)
2467         {
2468           error_at(this->location(),
2469                    "iota is only defined in const declarations");
2470           iota_value = 0;
2471         }
2472       mpz_t val;
2473       mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2474       Expression* ret = Expression::make_integer(&val, NULL,
2475                                                  this->location());
2476       mpz_clear(val);
2477       return ret;
2478     }
2479
2480   // Make sure that the constant itself has been lowered.
2481   gogo->lower_constant(this->constant_);
2482
2483   return this;
2484 }
2485
2486 // Return a numeric constant value.
2487
2488 bool
2489 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2490 {
2491   if (this->seen_)
2492     return false;
2493
2494   Expression* e = this->constant_->const_value()->expr();
2495   
2496   this->seen_ = true;
2497
2498   bool r = e->numeric_constant_value(nc);
2499
2500   this->seen_ = false;
2501
2502   Type* ctype;
2503   if (this->type_ != NULL)
2504     ctype = this->type_;
2505   else
2506     ctype = this->constant_->const_value()->type();
2507   if (r && ctype != NULL)
2508     {
2509       if (!nc->set_type(ctype, false, this->location()))
2510         return false;
2511     }
2512
2513   return r;
2514 }
2515
2516 bool
2517 Const_expression::do_string_constant_value(std::string* val) const
2518 {
2519   if (this->seen_)
2520     return false;
2521
2522   Expression* e = this->constant_->const_value()->expr();
2523
2524   this->seen_ = true;
2525   bool ok = e->string_constant_value(val);
2526   this->seen_ = false;
2527
2528   return ok;
2529 }
2530
2531 // Return the type of the const reference.
2532
2533 Type*
2534 Const_expression::do_type()
2535 {
2536   if (this->type_ != NULL)
2537     return this->type_;
2538
2539   Named_constant* nc = this->constant_->const_value();
2540
2541   if (this->seen_ || nc->lowering())
2542     {
2543       this->report_error(_("constant refers to itself"));
2544       this->type_ = Type::make_error_type();
2545       return this->type_;
2546     }
2547
2548   this->seen_ = true;
2549
2550   Type* ret = nc->type();
2551
2552   if (ret != NULL)
2553     {
2554       this->seen_ = false;
2555       return ret;
2556     }
2557
2558   // During parsing, a named constant may have a NULL type, but we
2559   // must not return a NULL type here.
2560   ret = nc->expr()->type();
2561
2562   this->seen_ = false;
2563
2564   return ret;
2565 }
2566
2567 // Set the type of the const reference.
2568
2569 void
2570 Const_expression::do_determine_type(const Type_context* context)
2571 {
2572   Type* ctype = this->constant_->const_value()->type();
2573   Type* cetype = (ctype != NULL
2574                   ? ctype
2575                   : this->constant_->const_value()->expr()->type());
2576   if (ctype != NULL && !ctype->is_abstract())
2577     ;
2578   else if (context->type != NULL
2579            && context->type->is_numeric_type()
2580            && cetype->is_numeric_type())
2581     this->type_ = context->type;
2582   else if (context->type != NULL
2583            && context->type->is_string_type()
2584            && cetype->is_string_type())
2585     this->type_ = context->type;
2586   else if (context->type != NULL
2587            && context->type->is_boolean_type()
2588            && cetype->is_boolean_type())
2589     this->type_ = context->type;
2590   else if (!context->may_be_abstract)
2591     {
2592       if (cetype->is_abstract())
2593         cetype = cetype->make_non_abstract_type();
2594       this->type_ = cetype;
2595     }
2596 }
2597
2598 // Check for a loop in which the initializer of a constant refers to
2599 // the constant itself.
2600
2601 void
2602 Const_expression::check_for_init_loop()
2603 {
2604   if (this->type_ != NULL && this->type_->is_error())
2605     return;
2606
2607   if (this->seen_)
2608     {
2609       this->report_error(_("constant refers to itself"));
2610       this->type_ = Type::make_error_type();
2611       return;
2612     }
2613
2614   Expression* init = this->constant_->const_value()->expr();
2615   Find_named_object find_named_object(this->constant_);
2616
2617   this->seen_ = true;
2618   Expression::traverse(&init, &find_named_object);
2619   this->seen_ = false;
2620
2621   if (find_named_object.found())
2622     {
2623       if (this->type_ == NULL || !this->type_->is_error())
2624         {
2625           this->report_error(_("constant refers to itself"));
2626           this->type_ = Type::make_error_type();
2627         }
2628       return;
2629     }
2630 }
2631
2632 // Check types of a const reference.
2633
2634 void
2635 Const_expression::do_check_types(Gogo*)
2636 {
2637   if (this->type_ != NULL && this->type_->is_error())
2638     return;
2639
2640   this->check_for_init_loop();
2641
2642   // Check that numeric constant fits in type.
2643   if (this->type_ != NULL && this->type_->is_numeric_type())
2644     {
2645       Numeric_constant nc;
2646       if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2647         {
2648           if (!nc.set_type(this->type_, true, this->location()))
2649             this->set_is_error();
2650         }
2651     }
2652 }
2653
2654 // Return a tree for the const reference.
2655
2656 tree
2657 Const_expression::do_get_tree(Translate_context* context)
2658 {
2659   Gogo* gogo = context->gogo();
2660   tree type_tree;
2661   if (this->type_ == NULL)
2662     type_tree = NULL_TREE;
2663   else
2664     {
2665       type_tree = type_to_tree(this->type_->get_backend(gogo));
2666       if (type_tree == error_mark_node)
2667         return error_mark_node;
2668     }
2669
2670   // If the type has been set for this expression, but the underlying
2671   // object is an abstract int or float, we try to get the abstract
2672   // value.  Otherwise we may lose something in the conversion.
2673   if (this->type_ != NULL
2674       && this->type_->is_numeric_type()
2675       && (this->constant_->const_value()->type() == NULL
2676           || this->constant_->const_value()->type()->is_abstract()))
2677     {
2678       Expression* expr = this->constant_->const_value()->expr();
2679       Numeric_constant nc;
2680       if (expr->numeric_constant_value(&nc)
2681           && nc.set_type(this->type_, false, this->location()))
2682         {
2683           Expression* e = nc.expression(this->location());
2684           return e->get_tree(context);
2685         }
2686     }
2687
2688   tree const_tree = this->constant_->get_tree(gogo, context->function());
2689   if (this->type_ == NULL
2690       || const_tree == error_mark_node
2691       || TREE_TYPE(const_tree) == error_mark_node)
2692     return const_tree;
2693
2694   tree ret;
2695   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2696     ret = fold_convert(type_tree, const_tree);
2697   else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2698     ret = fold(convert_to_integer(type_tree, const_tree));
2699   else if (TREE_CODE(type_tree) == REAL_TYPE)
2700     ret = fold(convert_to_real(type_tree, const_tree));
2701   else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2702     ret = fold(convert_to_complex(type_tree, const_tree));
2703   else
2704     go_unreachable();
2705   return ret;
2706 }
2707
2708 // Dump ast representation for constant expression.
2709
2710 void
2711 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2712 {
2713   ast_dump_context->ostream() << this->constant_->name();
2714 }
2715
2716 // Make a reference to a constant in an expression.
2717
2718 Expression*
2719 Expression::make_const_reference(Named_object* constant,
2720                                  Location location)
2721 {
2722   return new Const_expression(constant, location);
2723 }
2724
2725 // Find a named object in an expression.
2726
2727 int
2728 Find_named_object::expression(Expression** pexpr)
2729 {
2730   switch ((*pexpr)->classification())
2731     {
2732     case Expression::EXPRESSION_CONST_REFERENCE:
2733       {
2734         Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2735         if (ce->named_object() == this->no_)
2736           break;
2737
2738         // We need to check a constant initializer explicitly, as
2739         // loops here will not be caught by the loop checking for
2740         // variable initializers.
2741         ce->check_for_init_loop();
2742
2743         return TRAVERSE_CONTINUE;
2744       }
2745
2746     case Expression::EXPRESSION_VAR_REFERENCE:
2747       if ((*pexpr)->var_expression()->named_object() == this->no_)
2748         break;
2749       return TRAVERSE_CONTINUE;
2750     case Expression::EXPRESSION_FUNC_REFERENCE:
2751       if ((*pexpr)->func_expression()->named_object() == this->no_)
2752         break;
2753       return TRAVERSE_CONTINUE;
2754     default:
2755       return TRAVERSE_CONTINUE;
2756     }
2757   this->found_ = true;
2758   return TRAVERSE_EXIT;
2759 }
2760
2761 // The nil value.
2762
2763 class Nil_expression : public Expression
2764 {
2765  public:
2766   Nil_expression(Location location)
2767     : Expression(EXPRESSION_NIL, location)
2768   { }
2769
2770   static Expression*
2771   do_import(Import*);
2772
2773  protected:
2774   bool
2775   do_is_constant() const
2776   { return true; }
2777
2778   Type*
2779   do_type()
2780   { return Type::make_nil_type(); }
2781
2782   void
2783   do_determine_type(const Type_context*)
2784   { }
2785
2786   Expression*
2787   do_copy()
2788   { return this; }
2789
2790   tree
2791   do_get_tree(Translate_context*)
2792   { return null_pointer_node; }
2793
2794   void
2795   do_export(Export* exp) const
2796   { exp->write_c_string("nil"); }
2797
2798   void
2799   do_dump_expression(Ast_dump_context* ast_dump_context) const
2800   { ast_dump_context->ostream() << "nil"; }
2801 };
2802
2803 // Import a nil expression.
2804
2805 Expression*
2806 Nil_expression::do_import(Import* imp)
2807 {
2808   imp->require_c_string("nil");
2809   return Expression::make_nil(imp->location());
2810 }
2811
2812 // Make a nil expression.
2813
2814 Expression*
2815 Expression::make_nil(Location location)
2816 {
2817   return new Nil_expression(location);
2818 }
2819
2820 // The value of the predeclared constant iota.  This is little more
2821 // than a marker.  This will be lowered to an integer in
2822 // Const_expression::do_lower, which is where we know the value that
2823 // it should have.
2824
2825 class Iota_expression : public Parser_expression
2826 {
2827  public:
2828   Iota_expression(Location location)
2829     : Parser_expression(EXPRESSION_IOTA, location)
2830   { }
2831
2832  protected:
2833   Expression*
2834   do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2835   { go_unreachable(); }
2836
2837   // There should only ever be one of these.
2838   Expression*
2839   do_copy()
2840   { go_unreachable(); }
2841   
2842   void
2843   do_dump_expression(Ast_dump_context* ast_dump_context) const
2844   { ast_dump_context->ostream() << "iota"; } 
2845 };
2846
2847 // Make an iota expression.  This is only called for one case: the
2848 // value of the predeclared constant iota.
2849
2850 Expression*
2851 Expression::make_iota()
2852 {
2853   static Iota_expression iota_expression(Linemap::unknown_location());
2854   return &iota_expression;
2855 }
2856
2857 // A type conversion expression.
2858
2859 class Type_conversion_expression : public Expression
2860 {
2861  public:
2862   Type_conversion_expression(Type* type, Expression* expr,
2863                              Location location)
2864     : Expression(EXPRESSION_CONVERSION, location),
2865       type_(type), expr_(expr), may_convert_function_types_(false)
2866   { }
2867
2868   // Return the type to which we are converting.
2869   Type*
2870   type() const
2871   { return this->type_; }
2872
2873   // Return the expression which we are converting.
2874   Expression*
2875   expr() const
2876   { return this->expr_; }
2877
2878   // Permit converting from one function type to another.  This is
2879   // used internally for method expressions.
2880   void
2881   set_may_convert_function_types()
2882   {
2883     this->may_convert_function_types_ = true;
2884   }
2885
2886   // Import a type conversion expression.
2887   static Expression*
2888   do_import(Import*);
2889
2890  protected:
2891   int
2892   do_traverse(Traverse* traverse);
2893
2894   Expression*
2895   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2896
2897   bool
2898   do_is_constant() const
2899   { return this->expr_->is_constant(); }
2900
2901   bool
2902   do_numeric_constant_value(Numeric_constant*) const;
2903
2904   bool
2905   do_string_constant_value(std::string*) const;
2906
2907   Type*
2908   do_type()
2909   { return this->type_; }
2910
2911   void
2912   do_determine_type(const Type_context*)
2913   {
2914     Type_context subcontext(this->type_, false);
2915     this->expr_->determine_type(&subcontext);
2916   }
2917
2918   void
2919   do_check_types(Gogo*);
2920
2921   Expression*
2922   do_copy()
2923   {
2924     return new Type_conversion_expression(this->type_, this->expr_->copy(),
2925                                           this->location());
2926   }
2927
2928   tree
2929   do_get_tree(Translate_context* context);
2930
2931   void
2932   do_export(Export*) const;
2933
2934   void
2935   do_dump_expression(Ast_dump_context*) const;
2936
2937  private:
2938   // The type to convert to.
2939   Type* type_;
2940   // The expression to convert.
2941   Expression* expr_;
2942   // True if this is permitted to convert function types.  This is
2943   // used internally for method expressions.
2944   bool may_convert_function_types_;
2945 };
2946
2947 // Traversal.
2948
2949 int
2950 Type_conversion_expression::do_traverse(Traverse* traverse)
2951 {
2952   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2953       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2954     return TRAVERSE_EXIT;
2955   return TRAVERSE_CONTINUE;
2956 }
2957
2958 // Convert to a constant at lowering time.
2959
2960 Expression*
2961 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2962                                      Statement_inserter*, int)
2963 {
2964   Type* type = this->type_;
2965   Expression* val = this->expr_;
2966   Location location = this->location();
2967
2968   if (type->is_numeric_type())
2969     {
2970       Numeric_constant nc;
2971       if (val->numeric_constant_value(&nc))
2972         {
2973           if (!nc.set_type(type, true, location))
2974             return Expression::make_error(location);
2975           return nc.expression(location);
2976         }
2977     }
2978
2979   if (type->is_slice_type())
2980     {
2981       Type* element_type = type->array_type()->element_type()->forwarded();
2982       bool is_byte = (element_type->integer_type() != NULL
2983                       && element_type->integer_type()->is_byte());
2984       bool is_rune = (element_type->integer_type() != NULL
2985                       && element_type->integer_type()->is_rune());
2986       if (is_byte || is_rune)
2987         {
2988           std::string s;
2989           if (val->string_constant_value(&s))
2990             {
2991               Expression_list* vals = new Expression_list();
2992               if (is_byte)
2993                 {
2994                   for (std::string::const_iterator p = s.begin();
2995                        p != s.end();
2996                        p++)
2997                     {
2998                       mpz_t val;
2999                       mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3000                       Expression* v = Expression::make_integer(&val,
3001                                                                element_type,
3002                                                                location);
3003                       vals->push_back(v);
3004                       mpz_clear(val);
3005                     }
3006                 }
3007               else
3008                 {
3009                   const char *p = s.data();
3010                   const char *pend = s.data() + s.length();
3011                   while (p < pend)
3012                     {
3013                       unsigned int c;
3014                       int adv = Lex::fetch_char(p, &c);
3015                       if (adv == 0)
3016                         {
3017                           warning_at(this->location(), 0,
3018                                      "invalid UTF-8 encoding");
3019                           adv = 1;
3020                         }
3021                       p += adv;
3022                       mpz_t val;
3023                       mpz_init_set_ui(val, c);
3024                       Expression* v = Expression::make_integer(&val,
3025                                                                element_type,
3026                                                                location);
3027                       vals->push_back(v);
3028                       mpz_clear(val);
3029                     }
3030                 }
3031
3032               return Expression::make_slice_composite_literal(type, vals,
3033                                                               location);
3034             }
3035         }
3036     }
3037
3038   return this;
3039 }
3040
3041 // Return the constant numeric value if there is one.
3042
3043 bool
3044 Type_conversion_expression::do_numeric_constant_value(
3045     Numeric_constant* nc) const
3046 {
3047   if (!this->type_->is_numeric_type())
3048     return false;
3049   if (!this->expr_->numeric_constant_value(nc))
3050     return false;
3051   return nc->set_type(this->type_, false, this->location());
3052 }
3053
3054 // Return the constant string value if there is one.
3055
3056 bool
3057 Type_conversion_expression::do_string_constant_value(std::string* val) const
3058 {
3059   if (this->type_->is_string_type()
3060       && this->expr_->type()->integer_type() != NULL)
3061     {
3062       Numeric_constant nc;
3063       if (this->expr_->numeric_constant_value(&nc))
3064         {
3065           unsigned long ival;
3066           if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3067             {
3068               val->clear();
3069               Lex::append_char(ival, true, val, this->location());
3070               return true;
3071             }
3072         }
3073     }
3074
3075   // FIXME: Could handle conversion from const []int here.
3076
3077   return false;
3078 }
3079
3080 // Check that types are convertible.
3081
3082 void
3083 Type_conversion_expression::do_check_types(Gogo*)
3084 {
3085   Type* type = this->type_;
3086   Type* expr_type = this->expr_->type();
3087   std::string reason;
3088
3089   if (type->is_error() || expr_type->is_error())
3090     {
3091       this->set_is_error();
3092       return;
3093     }
3094
3095   if (this->may_convert_function_types_
3096       && type->function_type() != NULL
3097       && expr_type->function_type() != NULL)
3098     return;
3099
3100   if (Type::are_convertible(type, expr_type, &reason))
3101     return;
3102
3103   error_at(this->location(), "%s", reason.c_str());
3104   this->set_is_error();
3105 }
3106
3107 // Get a tree for a type conversion.
3108
3109 tree
3110 Type_conversion_expression::do_get_tree(Translate_context* context)
3111 {
3112   Gogo* gogo = context->gogo();
3113   tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3114   tree expr_tree = this->expr_->get_tree(context);
3115
3116   if (type_tree == error_mark_node
3117       || expr_tree == error_mark_node
3118       || TREE_TYPE(expr_tree) == error_mark_node)
3119     return error_mark_node;
3120
3121   if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3122     return fold_convert(type_tree, expr_tree);
3123
3124   Type* type = this->type_;
3125   Type* expr_type = this->expr_->type();
3126   tree ret;
3127   if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3128     ret = Expression::convert_for_assignment(context, type, expr_type,
3129                                              expr_tree, this->location());
3130   else if (type->integer_type() != NULL)
3131     {
3132       if (expr_type->integer_type() != NULL
3133           || expr_type->float_type() != NULL
3134           || expr_type->is_unsafe_pointer_type())
3135         ret = fold(convert_to_integer(type_tree, expr_tree));
3136       else
3137         go_unreachable();
3138     }
3139   else if (type->float_type() != NULL)
3140     {
3141       if (expr_type->integer_type() != NULL
3142           || expr_type->float_type() != NULL)
3143         ret = fold(convert_to_real(type_tree, expr_tree));
3144       else
3145         go_unreachable();
3146     }
3147   else if (type->complex_type() != NULL)
3148     {
3149       if (expr_type->complex_type() != NULL)
3150         ret = fold(convert_to_complex(type_tree, expr_tree));
3151       else
3152         go_unreachable();
3153     }
3154   else if (type->is_string_type()
3155            && expr_type->integer_type() != NULL)
3156     {
3157       expr_tree = fold_convert(integer_type_node, expr_tree);
3158       if (host_integerp(expr_tree, 0))
3159         {
3160           HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3161           std::string s;
3162           Lex::append_char(intval, true, &s, this->location());
3163           Expression* se = Expression::make_string(s, this->location());
3164           return se->get_tree(context);
3165         }
3166
3167       static tree int_to_string_fndecl;
3168       ret = Gogo::call_builtin(&int_to_string_fndecl,
3169                                this->location(),
3170                                "__go_int_to_string",
3171                                1,
3172                                type_tree,
3173                                integer_type_node,
3174                                fold_convert(integer_type_node, expr_tree));
3175     }
3176   else if (type->is_string_type() && expr_type->is_slice_type())
3177     {
3178       if (!DECL_P(expr_tree))
3179         expr_tree = save_expr(expr_tree);
3180       Array_type* a = expr_type->array_type();
3181       Type* e = a->element_type()->forwarded();
3182       go_assert(e->integer_type() != NULL);
3183       tree valptr = fold_convert(const_ptr_type_node,
3184                                  a->value_pointer_tree(gogo, expr_tree));
3185       tree len = a->length_tree(gogo, expr_tree);
3186       len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3187                              len);
3188       if (e->integer_type()->is_byte())
3189         {
3190           static tree byte_array_to_string_fndecl;
3191           ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3192                                    this->location(),
3193                                    "__go_byte_array_to_string",
3194                                    2,
3195                                    type_tree,
3196                                    const_ptr_type_node,
3197                                    valptr,
3198                                    integer_type_node,
3199                                    len);
3200         }
3201       else
3202         {
3203           go_assert(e->integer_type()->is_rune());
3204           static tree int_array_to_string_fndecl;
3205           ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3206                                    this->location(),
3207                                    "__go_int_array_to_string",
3208                                    2,
3209                                    type_tree,
3210                                    const_ptr_type_node,
3211                                    valptr,
3212                                    integer_type_node,
3213                                    len);
3214         }
3215     }
3216   else if (type->is_slice_type() && expr_type->is_string_type())
3217     {
3218       Type* e = type->array_type()->element_type()->forwarded();
3219       go_assert(e->integer_type() != NULL);
3220       if (e->integer_type()->is_byte())
3221         {
3222           tree string_to_byte_array_fndecl = NULL_TREE;
3223           ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3224                                    this->location(),
3225                                    "__go_string_to_byte_array",
3226                                    1,
3227                                    type_tree,
3228                                    TREE_TYPE(expr_tree),
3229                                    expr_tree);
3230         }
3231       else
3232         {
3233           go_assert(e->integer_type()->is_rune());
3234           tree string_to_int_array_fndecl = NULL_TREE;
3235           ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3236                                    this->location(),
3237                                    "__go_string_to_int_array",
3238                                    1,
3239                                    type_tree,
3240                                    TREE_TYPE(expr_tree),
3241                                    expr_tree);
3242         }
3243     }
3244   else if ((type->is_unsafe_pointer_type()
3245             && expr_type->points_to() != NULL)
3246            || (expr_type->is_unsafe_pointer_type()
3247                && type->points_to() != NULL))
3248     ret = fold_convert(type_tree, expr_tree);
3249   else if (type->is_unsafe_pointer_type()
3250            && expr_type->integer_type() != NULL)
3251     ret = convert_to_pointer(type_tree, expr_tree);
3252   else if (this->may_convert_function_types_
3253            && type->function_type() != NULL
3254            && expr_type->function_type() != NULL)
3255     ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3256                            expr_tree);
3257   else
3258     ret = Expression::convert_for_assignment(context, type, expr_type,
3259                                              expr_tree, this->location());
3260
3261   return ret;
3262 }
3263
3264 // Output a type conversion in a constant expression.
3265
3266 void
3267 Type_conversion_expression::do_export(Export* exp) const
3268 {
3269   exp->write_c_string("convert(");
3270   exp->write_type(this->type_);
3271   exp->write_c_string(", ");
3272   this->expr_->export_expression(exp);
3273   exp->write_c_string(")");
3274 }
3275
3276 // Import a type conversion or a struct construction.
3277
3278 Expression*
3279 Type_conversion_expression::do_import(Import* imp)
3280 {
3281   imp->require_c_string("convert(");
3282   Type* type = imp->read_type();
3283   imp->require_c_string(", ");
3284   Expression* val = Expression::import_expression(imp);
3285   imp->require_c_string(")");
3286   return Expression::make_cast(type, val, imp->location());
3287 }
3288
3289 // Dump ast representation for a type conversion expression.
3290
3291 void
3292 Type_conversion_expression::do_dump_expression(
3293     Ast_dump_context* ast_dump_context) const
3294 {
3295   ast_dump_context->dump_type(this->type_);
3296   ast_dump_context->ostream() << "(";
3297   ast_dump_context->dump_expression(this->expr_);
3298   ast_dump_context->ostream() << ") ";
3299 }
3300
3301 // Make a type cast expression.
3302
3303 Expression*
3304 Expression::make_cast(Type* type, Expression* val, Location location)
3305 {
3306   if (type->is_error_type() || val->is_error_expression())
3307     return Expression::make_error(location);
3308   return new Type_conversion_expression(type, val, location);
3309 }
3310
3311 // An unsafe type conversion, used to pass values to builtin functions.
3312
3313 class Unsafe_type_conversion_expression : public Expression
3314 {
3315  public:
3316   Unsafe_type_conversion_expression(Type* type, Expression* expr,
3317                                     Location location)
3318     : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3319       type_(type), expr_(expr)
3320   { }
3321
3322  protected:
3323   int
3324   do_traverse(Traverse* traverse);
3325
3326   Type*
3327   do_type()
3328   { return this->type_; }
3329
3330   void
3331   do_determine_type(const Type_context*)
3332   { this->expr_->determine_type_no_context(); }
3333
3334   Expression*
3335   do_copy()
3336   {
3337     return new Unsafe_type_conversion_expression(this->type_,
3338                                                  this->expr_->copy(),
3339                                                  this->location());
3340   }
3341
3342   tree
3343   do_get_tree(Translate_context*);
3344
3345   void
3346   do_dump_expression(Ast_dump_context*) const;
3347
3348  private:
3349   // The type to convert to.
3350   Type* type_;
3351   // The expression to convert.
3352   Expression* expr_;
3353 };
3354
3355 // Traversal.
3356
3357 int
3358 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3359 {
3360   if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3361       || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3362     return TRAVERSE_EXIT;
3363   return TRAVERSE_CONTINUE;
3364 }
3365
3366 // Convert to backend representation.
3367
3368 tree
3369 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3370 {
3371   // We are only called for a limited number of cases.
3372
3373   Type* t = this->type_;
3374   Type* et = this->expr_->type();
3375
3376   tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3377   tree expr_tree = this->expr_->get_tree(context);
3378   if (type_tree == error_mark_node || expr_tree == error_mark_node)
3379     return error_mark_node;
3380
3381   Location loc = this->location();
3382
3383   bool use_view_convert = false;
3384   if (t->is_slice_type())
3385     {
3386       go_assert(et->is_slice_type());
3387       use_view_convert = true;
3388     }
3389   else if (t->map_type() != NULL)
3390     go_assert(et->map_type() != NULL);
3391   else if (t->channel_type() != NULL)
3392     go_assert(et->channel_type() != NULL);
3393   else if (t->points_to() != NULL)
3394     go_assert(et->points_to() != NULL || et->is_nil_type());
3395   else if (et->is_unsafe_pointer_type())
3396     go_assert(t->points_to() != NULL);
3397   else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3398     {
3399       go_assert(et->interface_type() != NULL
3400                  && !et->interface_type()->is_empty());
3401       use_view_convert = true;
3402     }
3403   else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3404     {
3405       go_assert(et->interface_type() != NULL
3406                  && et->interface_type()->is_empty());
3407       use_view_convert = true;
3408     }
3409   else if (t->integer_type() != NULL)
3410     {
3411       go_assert(et->is_boolean_type()
3412                  || et->integer_type() != NULL
3413                  || et->function_type() != NULL
3414                  || et->points_to() != NULL
3415                  || et->map_type() != NULL
3416                  || et->channel_type() != NULL);
3417       return convert_to_integer(type_tree, expr_tree);
3418     }
3419   else
3420     go_unreachable();
3421
3422   if (use_view_convert)
3423     return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3424                            expr_tree);
3425   else
3426     return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3427 }
3428
3429 // Dump ast representation for an unsafe type conversion expression.
3430
3431 void
3432 Unsafe_type_conversion_expression::do_dump_expression(
3433     Ast_dump_context* ast_dump_context) const
3434 {
3435   ast_dump_context->dump_type(this->type_);
3436   ast_dump_context->ostream() << "(";
3437   ast_dump_context->dump_expression(this->expr_);
3438   ast_dump_context->ostream() << ") ";
3439 }
3440
3441 // Make an unsafe type conversion expression.
3442
3443 Expression*
3444 Expression::make_unsafe_cast(Type* type, Expression* expr,
3445                              Location location)
3446 {
3447   return new Unsafe_type_conversion_expression(type, expr, location);
3448 }
3449
3450 // Unary expressions.
3451
3452 class Unary_expression : public Expression
3453 {
3454  public:
3455   Unary_expression(Operator op, Expression* expr, Location location)
3456     : Expression(EXPRESSION_UNARY, location),
3457       op_(op), escapes_(true), create_temp_(false), expr_(expr)
3458   { }
3459
3460   // Return the operator.
3461   Operator
3462   op() const
3463   { return this->op_; }
3464
3465   // Return the operand.
3466   Expression*
3467   operand() const
3468   { return this->expr_; }
3469
3470   // Record that an address expression does not escape.
3471   void
3472   set_does_not_escape()
3473   {
3474     go_assert(this->op_ == OPERATOR_AND);
3475     this->escapes_ = false;
3476   }
3477
3478   // Record that this is an address expression which should create a
3479   // temporary variable if necessary.  This is used for method calls.
3480   void
3481   set_create_temp()
3482   {
3483     go_assert(this->op_ == OPERATOR_AND);
3484     this->create_temp_ = true;
3485   }
3486
3487   // Apply unary opcode OP to UNC, setting NC.  Return true if this
3488   // could be done, false if not.  Issue errors for overflow.
3489   static bool
3490   eval_constant(Operator op, const Numeric_constant* unc,
3491                 Location, Numeric_constant* nc);
3492
3493   static Expression*
3494   do_import(Import*);
3495
3496  protected:
3497   int
3498   do_traverse(Traverse* traverse)
3499   { return Expression::traverse(&this->expr_, traverse); }
3500
3501   Expression*
3502   do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3503
3504   bool
3505   do_is_constant() const;
3506
3507   bool
3508   do_numeric_constant_value(Numeric_constant*) const;
3509
3510   Type*
3511   do_type();
3512
3513   void
3514   do_determine_type(const Type_context*);
3515
3516   void
3517   do_check_types(Gogo*);
3518
3519   Expression*
3520   do_copy()
3521   {
3522     return Expression::make_unary(this->op_, this->expr_->copy(),
3523                                   this->location());
3524   }
3525
3526   bool
3527   do_must_eval_subexpressions_in_order(int*) const
3528   { return this->op_ == OPERATOR_MULT; }
3529
3530   bool
3531   do_is_addressable() const
3532   { return this->op_ == OPERATOR_MULT; }
3533
3534   tree
3535   do_get_tree(Translate_context*);
3536
3537   void
3538   do_export(Export*) const;
3539
3540   void
3541   do_dump_expression(Ast_dump_context*) const;
3542
3543  private:
3544   // The unary operator to apply.
3545   Operator op_;
3546   // Normally true.  False if this is an address expression which does
3547   // not escape the current function.
3548   bool escapes_;
3549   // True if this is an address expression which should create a
3550   // temporary variable if necessary.
3551   bool create_temp_;
3552   // The operand.
3553   Expression* expr_;
3554 };
3555
3556 // If we are taking the address of a composite literal, and the
3557 // contents are not constant, then we want to make a heap composite
3558 // instead.
3559
3560 Expression*
3561 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3562 {
3563   Location loc = this->location();
3564   Operator op = this->op_;
3565   Expression* expr = this->expr_;
3566
3567   if (op == OPERATOR_MULT && expr->is_type_expression())
3568     return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3569
3570   // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
3571   // moving x to the heap.  FIXME: Is it worth doing a real escape
3572   // analysis here?  This case is found in math/unsafe.go and is
3573   // therefore worth special casing.
3574   if (op == OPERATOR_MULT)
3575     {
3576       Expression* e = expr;
3577       while (e->classification() == EXPRESSION_CONVERSION)
3578         {
3579           Type_conversion_expression* te
3580             = static_cast<Type_conversion_expression*>(e);
3581           e = te->expr();
3582         }
3583
3584       if (e->classification() == EXPRESSION_UNARY)
3585         {
3586           Unary_expression* ue = static_cast<Unary_expression*>(e);
3587           if (ue->op_ == OPERATOR_AND)
3588             {
3589               if (e == expr)
3590                 {
3591                   // *&x == x.
3592                   return ue->expr_;
3593                 }
3594               ue->set_does_not_escape();
3595             }
3596         }
3597     }
3598
3599   // Catching an invalid indirection of unsafe.Pointer here avoid
3600   // having to deal with TYPE_VOID in other places.
3601   if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3602     {
3603       error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3604       return Expression::make_error(this->location());
3605     }
3606
3607   if (op == OPERATOR_PLUS || op == OPERATOR_MINUS
3608       || op == OPERATOR_NOT || op == OPERATOR_XOR)
3609     {
3610       Numeric_constant nc;
3611       if (expr->numeric_constant_value(&nc))
3612         {
3613           Numeric_constant result;
3614           if (Unary_expression::eval_constant(op, &nc, loc, &result))
3615             return result.expression(loc);
3616         }
3617     }
3618
3619   return this;
3620 }
3621
3622 // Return whether a unary expression is a constant.
3623
3624 bool
3625 Unary_expression::do_is_constant() const
3626 {
3627   if (this->op_ == OPERATOR_MULT)
3628     {
3629       // Indirecting through a pointer is only constant if the object
3630       // to which the expression points is constant, but we currently
3631       // have no way to determine that.
3632       return false;
3633     }
3634   else if (this->op_ == OPERATOR_AND)
3635     {
3636       // Taking the address of a variable is constant if it is a
3637       // global variable, not constant otherwise.  In other cases
3638       // taking the address is probably not a constant.
3639       Var_expression* ve = this->expr_->var_expression();
3640       if (ve != NULL)
3641         {
3642           Named_object* no = ve->named_object();
3643           return no->is_variable() && no->var_value()->is_global();
3644         }
3645       return false;
3646     }
3647   else
3648     return this->expr_->is_constant();
3649 }
3650
3651 // Apply unary opcode OP to UNC, setting NC.  Return true if this
3652 // could be done, false if not.  Issue errors for overflow.
3653
3654 bool
3655 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3656                                 Location location, Numeric_constant* nc)
3657 {
3658   switch (op)
3659     {
3660     case OPERATOR_PLUS:
3661       *nc = *unc;
3662       return true;
3663
3664     case OPERATOR_MINUS:
3665       if (unc->is_int() || unc->is_rune())
3666         break;
3667       else if (unc->is_float())
3668         {
3669           mpfr_t uval;
3670           unc->get_float(&uval);
3671           mpfr_t val;
3672           mpfr_init(val);
3673           mpfr_neg(val, uval, GMP_RNDN);
3674           nc->set_float(unc->type(), val);
3675           mpfr_clear(uval);
3676           mpfr_clear(val);
3677           return true;
3678         }
3679       else if (unc->is_complex())
3680         {
3681           mpfr_t ureal, uimag;
3682           unc->get_complex(&ureal, &uimag);
3683           mpfr_t real, imag;
3684           mpfr_init(real);
3685           mpfr_init(imag);
3686           mpfr_neg(real, ureal, GMP_RNDN);
3687           mpfr_neg(imag, uimag, GMP_RNDN);
3688           nc->set_complex(unc->type(), real, imag);
3689           mpfr_clear(ureal);
3690           mpfr_clear(uimag);
3691           mpfr_clear(real);
3692           mpfr_clear(imag);
3693           return true;
3694         }
3695       else
3696         go_unreachable();
3697
3698     case OPERATOR_NOT:
3699     case OPERATOR_XOR:
3700       break;
3701
3702     case OPERATOR_AND:
3703     case OPERATOR_MULT:
3704       return false;
3705
3706     default:
3707       go_unreachable();
3708     }
3709
3710   if (!unc->is_int() && !unc->is_rune())
3711     return false;
3712
3713   mpz_t uval;
3714   unc->get_int(&uval);
3715   mpz_t val;
3716   mpz_init(val);
3717
3718   switch (op)
3719     {
3720     case OPERATOR_MINUS:
3721       mpz_neg(val, uval);
3722       break;
3723
3724     case OPERATOR_NOT:
3725       mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3726       break;
3727
3728     case OPERATOR_XOR:
3729       {
3730         Type* utype = unc->type();
3731         if (utype->integer_type() == NULL
3732             || utype->integer_type()->is_abstract())
3733           mpz_com(val, uval);
3734         else
3735           {
3736             // The number of HOST_WIDE_INTs that it takes to represent
3737             // UVAL.
3738             size_t count = ((mpz_sizeinbase(uval, 2)
3739                              + HOST_BITS_PER_WIDE_INT
3740                              - 1)
3741                             / HOST_BITS_PER_WIDE_INT);
3742
3743             unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3744             memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3745
3746             size_t obits = utype->integer_type()->bits();
3747
3748             if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3749               {
3750                 mpz_t adj;
3751                 mpz_init_set_ui(adj, 1);
3752                 mpz_mul_2exp(adj, adj, obits);
3753                 mpz_add(uval, uval, adj);
3754                 mpz_clear(adj);
3755               }
3756
3757             size_t ecount;
3758             mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3759             go_assert(ecount <= count);
3760
3761             // Trim down to the number of words required by the type.
3762             size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3763                              / HOST_BITS_PER_WIDE_INT);
3764             go_assert(ocount <= count);
3765
3766             for (size_t i = 0; i < ocount; ++i)
3767               phwi[i] = ~phwi[i];
3768
3769             size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3770             if (clearbits != 0)
3771               phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3772                                    >> clearbits);
3773
3774             mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3775
3776             if (!utype->integer_type()->is_unsigned()
3777                 && mpz_tstbit(val, obits - 1))
3778               {
3779                 mpz_t adj;
3780                 mpz_init_set_ui(adj, 1);
3781                 mpz_mul_2exp(adj, adj, obits);
3782                 mpz_sub(val, val, adj);
3783                 mpz_clear(adj);
3784               }
3785
3786             delete[] phwi;
3787           }
3788       }
3789       break;
3790
3791     default:
3792       go_unreachable();
3793     }
3794
3795   if (unc->is_rune())
3796     nc->set_rune(NULL, val);
3797   else
3798     nc->set_int(NULL, val);
3799
3800   mpz_clear(uval);
3801   mpz_clear(val);
3802
3803   return nc->set_type(unc->type(), true, location);
3804 }
3805
3806 // Return the integral constant value of a unary expression, if it has one.
3807
3808 bool
3809 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3810 {
3811   Numeric_constant unc;
3812   if (!this->expr_->numeric_constant_value(&unc))
3813     return false;
3814   return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3815                                          nc);
3816 }
3817
3818 // Return the type of a unary expression.
3819
3820 Type*
3821 Unary_expression::do_type()
3822 {
3823   switch (this->op_)
3824     {
3825     case OPERATOR_PLUS:
3826     case OPERATOR_MINUS:
3827     case OPERATOR_NOT:
3828     case OPERATOR_XOR:
3829       return this->expr_->type();
3830
3831     case OPERATOR_AND:
3832       return Type::make_pointer_type(this->expr_->type());
3833
3834     case OPERATOR_MULT:
3835       {
3836         Type* subtype = this->expr_->type();
3837         Type* points_to = subtype->points_to();
3838         if (points_to == NULL)
3839           return Type::make_error_type();
3840         return points_to;
3841       }
3842
3843     default:
3844       go_unreachable();
3845     }
3846 }
3847
3848 // Determine abstract types for a unary expression.
3849
3850 void
3851 Unary_expression::do_determine_type(const Type_context* context)
3852 {
3853   switch (this->op_)
3854     {
3855     case OPERATOR_PLUS:
3856     case OPERATOR_MINUS:
3857     case OPERATOR_NOT:
3858     case OPERATOR_XOR:
3859       this->expr_->determine_type(context);
3860       break;
3861
3862     case OPERATOR_AND:
3863       // Taking the address of something.
3864       {
3865         Type* subtype = (context->type == NULL
3866                          ? NULL
3867                          : context->type->points_to());
3868         Type_context subcontext(subtype, false);
3869         this->expr_->determine_type(&subcontext);
3870       }
3871       break;
3872
3873     case OPERATOR_MULT:
3874       // Indirecting through a pointer.
3875       {
3876         Type* subtype = (context->type == NULL
3877                          ? NULL
3878                          : Type::make_pointer_type(context->type));
3879         Type_context subcontext(subtype, false);
3880         this->expr_->determine_type(&subcontext);
3881       }
3882       break;
3883
3884     default:
3885       go_unreachable();
3886     }
3887 }
3888
3889 // Check types for a unary expression.
3890
3891 void
3892 Unary_expression::do_check_types(Gogo*)
3893 {
3894   Type* type = this->expr_->type();
3895   if (type->is_error())
3896     {
3897       this->set_is_error();
3898       return;
3899     }
3900
3901   switch (this->op_)
3902     {
3903     case OPERATOR_PLUS:
3904     case OPERATOR_MINUS:
3905       if (type->integer_type() == NULL
3906           && type->float_type() == NULL
3907           && type->complex_type() == NULL)
3908         this->report_error(_("expected numeric type"));
3909       break;
3910
3911     case OPERATOR_NOT:
3912     case OPERATOR_XOR:
3913       if (type->integer_type() == NULL
3914           && !type->is_boolean_type())
3915         this->report_error(_("expected integer or boolean type"));
3916       break;
3917
3918     case OPERATOR_AND:
3919       if (!this->expr_->is_addressable())
3920         {
3921           if (!this->create_temp_)
3922             this->report_error(_("invalid operand for unary %<&%>"));
3923         }
3924       else
3925         this->expr_->address_taken(this->escapes_);
3926       break;
3927
3928     case OPERATOR_MULT:
3929       // Indirecting through a pointer.
3930       if (type->points_to() == NULL)
3931         this->report_error(_("expected pointer"));
3932       break;
3933
3934     default:
3935       go_unreachable();
3936     }
3937 }
3938
3939 // Get a tree for a unary expression.
3940
3941 tree
3942 Unary_expression::do_get_tree(Translate_context* context)
3943 {
3944   Location loc = this->location();
3945
3946   // Taking the address of a set-and-use-temporary expression requires
3947   // setting the temporary and then taking the address.
3948   if (this->op_ == OPERATOR_AND)
3949     {
3950       Set_and_use_temporary_expression* sut =
3951         this->expr_->set_and_use_temporary_expression();
3952       if (sut != NULL)
3953         {
3954           Temporary_statement* temp = sut->temporary();
3955           Bvariable* bvar = temp->get_backend_variable(context);
3956           tree var_tree = var_to_tree(bvar);
3957           Expression* val = sut->expression();
3958           tree val_tree = val->get_tree(context);
3959           if (var_tree == error_mark_node || val_tree == error_mark_node)
3960             return error_mark_node;
3961           tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3962                                                     var_tree);
3963           return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3964                             TREE_TYPE(addr_tree),
3965                             build2_loc(sut->location().gcc_location(),
3966                                        MODIFY_EXPR, void_type_node,
3967                                        var_tree, val_tree),
3968                             addr_tree);
3969         }
3970     }
3971
3972   tree expr = this->expr_->get_tree(context);
3973   if (expr == error_mark_node)
3974     return error_mark_node;
3975
3976   switch (this->op_)
3977     {
3978     case OPERATOR_PLUS:
3979       return expr;
3980
3981     case OPERATOR_MINUS:
3982       {
3983         tree type = TREE_TYPE(expr);
3984         tree compute_type = excess_precision_type(type);
3985         if (compute_type != NULL_TREE)
3986           expr = ::convert(compute_type, expr);
3987         tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3988                                    (compute_type != NULL_TREE
3989                                     ? compute_type
3990                                     : type),
3991                                    expr);
3992         if (compute_type != NULL_TREE)
3993           ret = ::convert(type, ret);
3994         return ret;
3995       }
3996
3997     case OPERATOR_NOT:
3998       if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
3999         return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4000                                TREE_TYPE(expr), expr);
4001       else
4002         return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4003                                expr, build_int_cst(TREE_TYPE(expr), 0));
4004
4005     case OPERATOR_XOR:
4006       return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4007                              expr);
4008
4009     case OPERATOR_AND:
4010       if (!this->create_temp_)
4011         {
4012           // We should not see a non-constant constructor here; cases
4013           // where we would see one should have been moved onto the
4014           // heap at parse time.  Taking the address of a nonconstant
4015           // constructor will not do what the programmer expects.
4016           go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4017           go_assert(TREE_CODE(expr) != ADDR_EXPR);
4018         }
4019
4020       // Build a decl for a constant constructor.
4021       if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4022         {
4023           tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4024                                  create_tmp_var_name("C"), TREE_TYPE(expr));
4025           DECL_EXTERNAL(decl) = 0;
4026           TREE_PUBLIC(decl) = 0;
4027           TREE_READONLY(decl) = 1;
4028           TREE_CONSTANT(decl) = 1;
4029           TREE_STATIC(decl) = 1;
4030           TREE_ADDRESSABLE(decl) = 1;
4031           DECL_ARTIFICIAL(decl) = 1;
4032           DECL_INITIAL(decl) = expr;
4033           rest_of_decl_compilation(decl, 1, 0);
4034           expr = decl;
4035         }
4036
4037       if (this->create_temp_
4038           && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4039           && !DECL_P(expr)
4040           && TREE_CODE(expr) != INDIRECT_REF
4041           && TREE_CODE(expr) != COMPONENT_REF)
4042         {
4043           tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4044           DECL_IGNORED_P(tmp) = 1;
4045           DECL_INITIAL(tmp) = expr;
4046           TREE_ADDRESSABLE(tmp) = 1;
4047           return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4048                             build_pointer_type(TREE_TYPE(expr)),
4049                             build1_loc(loc.gcc_location(), DECL_EXPR,
4050                                        void_type_node, tmp),
4051                             build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4052         }
4053
4054       return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4055
4056     case OPERATOR_MULT:
4057       {
4058         go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4059
4060         // If we are dereferencing the pointer to a large struct, we
4061         // need to check for nil.  We don't bother to check for small
4062         // structs because we expect the system to crash on a nil
4063         // pointer dereference.
4064         tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4065         if (!VOID_TYPE_P(target_type_tree))
4066           {
4067             HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4068             if (s == -1 || s >= 4096)
4069               {
4070                 if (!DECL_P(expr))
4071                   expr = save_expr(expr);
4072                 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4073                                                boolean_type_node,
4074                                                expr,
4075                                                fold_convert(TREE_TYPE(expr),
4076                                                             null_pointer_node));
4077                 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4078                                                  loc);
4079                 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4080                                        TREE_TYPE(expr), build3(COND_EXPR,
4081                                                                void_type_node,
4082                                                                compare, crash,
4083                                                                NULL_TREE),
4084                                        expr);
4085               }
4086           }
4087
4088         // If the type of EXPR is a recursive pointer type, then we
4089         // need to insert a cast before indirecting.
4090         if (VOID_TYPE_P(target_type_tree))
4091           {
4092             Type* pt = this->expr_->type()->points_to();
4093             tree ind = type_to_tree(pt->get_backend(context->gogo()));
4094             expr = fold_convert_loc(loc.gcc_location(),
4095                                     build_pointer_type(ind), expr);
4096           }
4097
4098         return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4099       }
4100
4101     default:
4102       go_unreachable();