OSDN Git Service

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