compiler: Correct types when type conversion makes backend call.
[gcc.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 "toplev.h"
12 #include "intl.h"
13 #include "tree.h"
14 #include "gimple.h"
15 #include "tree-iterator.h"
16 #include "convert.h"
17 #include "real.h"
18 #include "realmpfr.h"
19
20 #include "go-c.h"
21 #include "gogo.h"
22 #include "types.h"
23 #include "export.h"
24 #include "import.h"
25 #include "statements.h"
26 #include "lex.h"
27 #include "runtime.h"
28 #include "backend.h"
29 #include "expressions.h"
30 #include "ast-dump.h"
31
32 // Class Expression.
33
34 Expression::Expression(Expression_classification classification,
35 Location location)
36 : classification_(classification), location_(location)
37 {
38 }
39
40 Expression::~Expression()
41 {
42 }
43
44 // Traverse the expressions.
45
46 int
47 Expression::traverse(Expression** pexpr, Traverse* traverse)
48 {
49 Expression* expr = *pexpr;
50 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
51 {
52 int t = traverse->expression(pexpr);
53 if (t == TRAVERSE_EXIT)
54 return TRAVERSE_EXIT;
55 else if (t == TRAVERSE_SKIP_COMPONENTS)
56 return TRAVERSE_CONTINUE;
57 }
58 return expr->do_traverse(traverse);
59 }
60
61 // Traverse subexpressions of this expression.
62
63 int
64 Expression::traverse_subexpressions(Traverse* traverse)
65 {
66 return this->do_traverse(traverse);
67 }
68
69 // Default implementation for do_traverse for child classes.
70
71 int
72 Expression::do_traverse(Traverse*)
73 {
74 return TRAVERSE_CONTINUE;
75 }
76
77 // This virtual function is called by the parser if the value of this
78 // expression is being discarded. By default, we give an error.
79 // Expressions with side effects override.
80
81 bool
82 Expression::do_discarding_value()
83 {
84 this->unused_value_error();
85 return false;
86 }
87
88 // This virtual function is called to export expressions. This will
89 // only be used by expressions which may be constant.
90
91 void
92 Expression::do_export(Export*) const
93 {
94 go_unreachable();
95 }
96
97 // Give an error saying that the value of the expression is not used.
98
99 void
100 Expression::unused_value_error()
101 {
102 this->report_error(_("value computed is not used"));
103 }
104
105 // Note that this expression is an error. This is called by children
106 // when they discover an error.
107
108 void
109 Expression::set_is_error()
110 {
111 this->classification_ = EXPRESSION_ERROR;
112 }
113
114 // For children to call to report an error conveniently.
115
116 void
117 Expression::report_error(const char* msg)
118 {
119 error_at(this->location_, "%s", msg);
120 this->set_is_error();
121 }
122
123 // Set types of variables and constants. This is implemented by the
124 // child class.
125
126 void
127 Expression::determine_type(const Type_context* context)
128 {
129 this->do_determine_type(context);
130 }
131
132 // Set types when there is no context.
133
134 void
135 Expression::determine_type_no_context()
136 {
137 Type_context context;
138 this->do_determine_type(&context);
139 }
140
141 // Return a tree handling any conversions which must be done during
142 // assignment.
143
144 tree
145 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
146 Type* rhs_type, tree rhs_tree,
147 Location location)
148 {
149 if (lhs_type->is_error() || rhs_type->is_error())
150 return error_mark_node;
151
152 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
153 return error_mark_node;
154
155 Gogo* gogo = context->gogo();
156
157 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
158 if (lhs_type_tree == error_mark_node)
159 return error_mark_node;
160
161 if (lhs_type->forwarded() != rhs_type->forwarded()
162 && lhs_type->interface_type() != NULL)
163 {
164 if (rhs_type->interface_type() == NULL)
165 return Expression::convert_type_to_interface(context, lhs_type,
166 rhs_type, rhs_tree,
167 location);
168 else
169 return Expression::convert_interface_to_interface(context, lhs_type,
170 rhs_type, rhs_tree,
171 false, location);
172 }
173 else if (lhs_type->forwarded() != rhs_type->forwarded()
174 && rhs_type->interface_type() != NULL)
175 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
176 rhs_tree, location);
177 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
178 {
179 // Assigning nil to an open array.
180 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
181
182 vec<constructor_elt, va_gc> *init;
183 vec_alloc(init, 3);
184
185 constructor_elt empty = {NULL, NULL};
186 constructor_elt* elt = init->quick_push(empty);
187 tree field = TYPE_FIELDS(lhs_type_tree);
188 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
189 "__values") == 0);
190 elt->index = field;
191 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
192
193 elt = init->quick_push(empty);
194 field = DECL_CHAIN(field);
195 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
196 "__count") == 0);
197 elt->index = field;
198 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
199
200 elt = init->quick_push(empty);
201 field = DECL_CHAIN(field);
202 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
203 "__capacity") == 0);
204 elt->index = field;
205 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
206
207 tree val = build_constructor(lhs_type_tree, init);
208 TREE_CONSTANT(val) = 1;
209
210 return val;
211 }
212 else if (rhs_type->is_nil_type())
213 {
214 // The left hand side should be a pointer type at the tree
215 // level.
216 go_assert(POINTER_TYPE_P(lhs_type_tree));
217 return fold_convert(lhs_type_tree, null_pointer_node);
218 }
219 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
220 {
221 // No conversion is needed.
222 return rhs_tree;
223 }
224 else if (POINTER_TYPE_P(lhs_type_tree)
225 || INTEGRAL_TYPE_P(lhs_type_tree)
226 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
227 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
228 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
229 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
230 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
231 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
232 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
233 {
234 // Avoid confusion from zero sized variables which may be
235 // represented as non-zero-sized.
236 if (int_size_in_bytes(lhs_type_tree) == 0
237 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
238 return rhs_tree;
239
240 // This conversion must be permitted by Go, or we wouldn't have
241 // gotten here.
242 go_assert(int_size_in_bytes(lhs_type_tree)
243 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
244 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
245 lhs_type_tree, rhs_tree);
246 }
247 else
248 {
249 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
250 return rhs_tree;
251 }
252 }
253
254 // Return a tree for a conversion from a non-interface type to an
255 // interface type.
256
257 tree
258 Expression::convert_type_to_interface(Translate_context* context,
259 Type* lhs_type, Type* rhs_type,
260 tree rhs_tree, Location location)
261 {
262 Gogo* gogo = context->gogo();
263 Interface_type* lhs_interface_type = lhs_type->interface_type();
264 bool lhs_is_empty = lhs_interface_type->is_empty();
265
266 // Since RHS_TYPE is a static type, we can create the interface
267 // method table at compile time.
268
269 // When setting an interface to nil, we just set both fields to
270 // NULL.
271 if (rhs_type->is_nil_type())
272 {
273 Btype* lhs_btype = lhs_type->get_backend(gogo);
274 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
275 }
276
277 // This should have been checked already.
278 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
279
280 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
281 if (lhs_type_tree == error_mark_node)
282 return error_mark_node;
283
284 // An interface is a tuple. If LHS_TYPE is an empty interface type,
285 // then the first field is the type descriptor for RHS_TYPE.
286 // Otherwise it is the interface method table for RHS_TYPE.
287 tree first_field_value;
288 if (lhs_is_empty)
289 {
290 Bexpression* rhs_bexpr =
291 rhs_type->type_descriptor_pointer(gogo, location);
292 first_field_value = expr_to_tree(rhs_bexpr);
293 }
294 else
295 {
296 // Build the interface method table for this interface and this
297 // object type: a list of function pointers for each interface
298 // method.
299 Named_type* rhs_named_type = rhs_type->named_type();
300 Struct_type* rhs_struct_type = rhs_type->struct_type();
301 bool is_pointer = false;
302 if (rhs_named_type == NULL && rhs_struct_type == NULL)
303 {
304 rhs_named_type = rhs_type->deref()->named_type();
305 rhs_struct_type = rhs_type->deref()->struct_type();
306 is_pointer = true;
307 }
308 tree method_table;
309 if (rhs_named_type != NULL)
310 method_table =
311 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
312 is_pointer);
313 else if (rhs_struct_type != NULL)
314 method_table =
315 rhs_struct_type->interface_method_table(gogo, lhs_interface_type,
316 is_pointer);
317 else
318 method_table = null_pointer_node;
319 first_field_value = fold_convert_loc(location.gcc_location(),
320 const_ptr_type_node, method_table);
321 }
322 if (first_field_value == error_mark_node)
323 return error_mark_node;
324
325 // Start building a constructor for the value we will return.
326
327 vec<constructor_elt, va_gc> *init;
328 vec_alloc(init, 2);
329
330 constructor_elt empty = {NULL, NULL};
331 constructor_elt* elt = init->quick_push(empty);
332 tree field = TYPE_FIELDS(lhs_type_tree);
333 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
334 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
335 elt->index = field;
336 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
337 first_field_value);
338
339 elt = init->quick_push(empty);
340 field = DECL_CHAIN(field);
341 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
342 elt->index = field;
343
344 if (rhs_type->points_to() != NULL)
345 {
346 // We are assigning a pointer to the interface; the interface
347 // holds the pointer itself.
348 elt->value = rhs_tree;
349 return build_constructor(lhs_type_tree, init);
350 }
351
352 // We are assigning a non-pointer value to the interface; the
353 // interface gets a copy of the value in the heap.
354
355 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
356
357 tree space = gogo->allocate_memory(rhs_type, object_size, location);
358 space = fold_convert_loc(location.gcc_location(),
359 build_pointer_type(TREE_TYPE(rhs_tree)), space);
360 space = save_expr(space);
361
362 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
363 TREE_THIS_NOTRAP(ref) = 1;
364 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
365 void_type_node, ref, rhs_tree);
366
367 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
368 space);
369
370 return build2(COMPOUND_EXPR, lhs_type_tree, set,
371 build_constructor(lhs_type_tree, init));
372 }
373
374 // Return a tree for the type descriptor of RHS_TREE, which has
375 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
376 // NULL.
377
378 tree
379 Expression::get_interface_type_descriptor(Translate_context*,
380 Type* rhs_type, tree rhs_tree,
381 Location location)
382 {
383 tree rhs_type_tree = TREE_TYPE(rhs_tree);
384 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
385 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
386 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
387 NULL_TREE);
388 if (rhs_type->interface_type()->is_empty())
389 {
390 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
391 "__type_descriptor") == 0);
392 return v;
393 }
394
395 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
396 == 0);
397 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
398 v = save_expr(v);
399 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
400 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
401 tree f = TYPE_FIELDS(TREE_TYPE(v1));
402 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
403 == 0);
404 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
405
406 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
407 v, fold_convert_loc(location.gcc_location(),
408 TREE_TYPE(v),
409 null_pointer_node));
410 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
411 null_pointer_node);
412 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
413 eq, n, v1);
414 }
415
416 // Return a tree for the conversion of an interface type to an
417 // interface type.
418
419 tree
420 Expression::convert_interface_to_interface(Translate_context* context,
421 Type *lhs_type, Type *rhs_type,
422 tree rhs_tree, bool for_type_guard,
423 Location location)
424 {
425 Gogo* gogo = context->gogo();
426 Interface_type* lhs_interface_type = lhs_type->interface_type();
427 bool lhs_is_empty = lhs_interface_type->is_empty();
428
429 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
430 if (lhs_type_tree == error_mark_node)
431 return error_mark_node;
432
433 // In the general case this requires runtime examination of the type
434 // method table to match it up with the interface methods.
435
436 // FIXME: If all of the methods in the right hand side interface
437 // also appear in the left hand side interface, then we don't need
438 // to do a runtime check, although we still need to build a new
439 // method table.
440
441 // Get the type descriptor for the right hand side. This will be
442 // NULL for a nil interface.
443
444 if (!DECL_P(rhs_tree))
445 rhs_tree = save_expr(rhs_tree);
446
447 tree rhs_type_descriptor =
448 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
449 location);
450
451 // The result is going to be a two element constructor.
452
453 vec<constructor_elt, va_gc> *init;
454 vec_alloc (init, 2);
455
456 constructor_elt empty = {NULL, NULL};
457 constructor_elt* elt = init->quick_push(empty);
458 tree field = TYPE_FIELDS(lhs_type_tree);
459 elt->index = field;
460
461 if (for_type_guard)
462 {
463 // A type assertion fails when converting a nil interface.
464 Bexpression* lhs_type_expr = lhs_type->type_descriptor_pointer(gogo,
465 location);
466 tree lhs_type_descriptor = expr_to_tree(lhs_type_expr);
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 Bexpression* lhs_type_expr = lhs_type->type_descriptor_pointer(gogo,
500 location);
501 tree lhs_type_descriptor = expr_to_tree(lhs_type_expr);
502
503 static tree convert_interface_decl;
504 tree call = Gogo::call_builtin(&convert_interface_decl,
505 location,
506 "__go_convert_interface",
507 2,
508 ptr_type_node,
509 TREE_TYPE(lhs_type_descriptor),
510 lhs_type_descriptor,
511 TREE_TYPE(rhs_type_descriptor),
512 rhs_type_descriptor);
513 if (call == error_mark_node)
514 return error_mark_node;
515 // This will panic if the interface conversion fails.
516 TREE_NOTHROW(convert_interface_decl) = 0;
517 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
518 call);
519 }
520
521 // The second field is simply the object pointer.
522
523 elt = init->quick_push(empty);
524 field = DECL_CHAIN(field);
525 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
526 elt->index = field;
527
528 tree rhs_type_tree = TREE_TYPE(rhs_tree);
529 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
530 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
531 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
532 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
533 NULL_TREE);
534
535 return build_constructor(lhs_type_tree, init);
536 }
537
538 // Return a tree for the conversion of an interface type to a
539 // non-interface type.
540
541 tree
542 Expression::convert_interface_to_type(Translate_context* context,
543 Type *lhs_type, Type* rhs_type,
544 tree rhs_tree, Location location)
545 {
546 Gogo* gogo = context->gogo();
547 tree rhs_type_tree = TREE_TYPE(rhs_tree);
548
549 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
550 if (lhs_type_tree == error_mark_node)
551 return error_mark_node;
552
553 // Call a function to check that the type is valid. The function
554 // will panic with an appropriate runtime type error if the type is
555 // not valid.
556 Bexpression* lhs_type_expr = lhs_type->type_descriptor_pointer(gogo,
557 location);
558 tree lhs_type_descriptor = expr_to_tree(lhs_type_expr);
559
560 if (!DECL_P(rhs_tree))
561 rhs_tree = save_expr(rhs_tree);
562
563 tree rhs_type_descriptor =
564 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
565 location);
566
567 Bexpression* rhs_inter_expr = rhs_type->type_descriptor_pointer(gogo,
568 location);
569 tree rhs_inter_descriptor = expr_to_tree(rhs_inter_expr);
570
571 static tree check_interface_type_decl;
572 tree call = Gogo::call_builtin(&check_interface_type_decl,
573 location,
574 "__go_check_interface_type",
575 3,
576 void_type_node,
577 TREE_TYPE(lhs_type_descriptor),
578 lhs_type_descriptor,
579 TREE_TYPE(rhs_type_descriptor),
580 rhs_type_descriptor,
581 TREE_TYPE(rhs_inter_descriptor),
582 rhs_inter_descriptor);
583 if (call == error_mark_node)
584 return error_mark_node;
585 // This call will panic if the conversion is invalid.
586 TREE_NOTHROW(check_interface_type_decl) = 0;
587
588 // If the call succeeds, pull out the value.
589 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
590 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
591 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
592 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
593 NULL_TREE);
594
595 // If the value is a pointer, then it is the value we want.
596 // Otherwise it points to the value.
597 if (lhs_type->points_to() == NULL)
598 {
599 val = fold_convert_loc(location.gcc_location(),
600 build_pointer_type(lhs_type_tree), val);
601 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
602 }
603
604 return build2(COMPOUND_EXPR, lhs_type_tree, call,
605 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
606 }
607
608 // Convert an expression to a tree. This is implemented by the child
609 // class. Not that it is not in general safe to call this multiple
610 // times for a single expression, but that we don't catch such errors.
611
612 tree
613 Expression::get_tree(Translate_context* context)
614 {
615 // The child may have marked this expression as having an error.
616 if (this->classification_ == EXPRESSION_ERROR)
617 return error_mark_node;
618
619 return this->do_get_tree(context);
620 }
621
622 // Return a backend expression for VAL.
623 Bexpression*
624 Expression::backend_numeric_constant_expression(Translate_context* context,
625 Numeric_constant* val)
626 {
627 Gogo* gogo = context->gogo();
628 Type* type = val->type();
629 if (type == NULL)
630 return gogo->backend()->error_expression();
631
632 Btype* btype = type->get_backend(gogo);
633 Bexpression* ret;
634 if (type->integer_type() != NULL)
635 {
636 mpz_t ival;
637 if (!val->to_int(&ival))
638 {
639 go_assert(saw_errors());
640 return gogo->backend()->error_expression();
641 }
642 ret = gogo->backend()->integer_constant_expression(btype, ival);
643 mpz_clear(ival);
644 }
645 else if (type->float_type() != NULL)
646 {
647 mpfr_t fval;
648 if (!val->to_float(&fval))
649 {
650 go_assert(saw_errors());
651 return gogo->backend()->error_expression();
652 }
653 ret = gogo->backend()->float_constant_expression(btype, fval);
654 mpfr_clear(fval);
655 }
656 else if (type->complex_type() != NULL)
657 {
658 mpfr_t real;
659 mpfr_t imag;
660 if (!val->to_complex(&real, &imag))
661 {
662 go_assert(saw_errors());
663 return gogo->backend()->error_expression();
664 }
665 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
666 mpfr_clear(real);
667 mpfr_clear(imag);
668 }
669 else
670 go_unreachable();
671
672 return ret;
673 }
674
675 // Return a tree which evaluates to true if VAL, of arbitrary integer
676 // type, is negative or is more than the maximum value of BOUND_TYPE.
677 // If SOFAR is not NULL, it is or'red into the result. The return
678 // value may be NULL if SOFAR is NULL.
679
680 tree
681 Expression::check_bounds(tree val, tree bound_type, tree sofar,
682 Location loc)
683 {
684 tree val_type = TREE_TYPE(val);
685 tree ret = NULL_TREE;
686
687 if (!TYPE_UNSIGNED(val_type))
688 {
689 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
690 build_int_cst(val_type, 0));
691 if (ret == boolean_false_node)
692 ret = NULL_TREE;
693 }
694
695 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
696 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
697 go_assert(val_type_size != -1 && bound_type_size != -1);
698 if (val_type_size > bound_type_size
699 || (val_type_size == bound_type_size
700 && TYPE_UNSIGNED(val_type)
701 && !TYPE_UNSIGNED(bound_type)))
702 {
703 tree max = TYPE_MAX_VALUE(bound_type);
704 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
705 val, fold_convert_loc(loc.gcc_location(),
706 val_type, max));
707 if (big == boolean_false_node)
708 ;
709 else if (ret == NULL_TREE)
710 ret = big;
711 else
712 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
713 boolean_type_node, ret, big);
714 }
715
716 if (ret == NULL_TREE)
717 return sofar;
718 else if (sofar == NULL_TREE)
719 return ret;
720 else
721 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
722 sofar, ret);
723 }
724
725 void
726 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
727 {
728 this->do_dump_expression(ast_dump_context);
729 }
730
731 // Error expressions. This are used to avoid cascading errors.
732
733 class Error_expression : public Expression
734 {
735 public:
736 Error_expression(Location location)
737 : Expression(EXPRESSION_ERROR, location)
738 { }
739
740 protected:
741 bool
742 do_is_constant() const
743 { return true; }
744
745 bool
746 do_numeric_constant_value(Numeric_constant* nc) const
747 {
748 nc->set_unsigned_long(NULL, 0);
749 return true;
750 }
751
752 bool
753 do_discarding_value()
754 { return true; }
755
756 Type*
757 do_type()
758 { return Type::make_error_type(); }
759
760 void
761 do_determine_type(const Type_context*)
762 { }
763
764 Expression*
765 do_copy()
766 { return this; }
767
768 bool
769 do_is_addressable() const
770 { return true; }
771
772 tree
773 do_get_tree(Translate_context*)
774 { return error_mark_node; }
775
776 void
777 do_dump_expression(Ast_dump_context*) const;
778 };
779
780 // Dump the ast representation for an error expression to a dump context.
781
782 void
783 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
784 {
785 ast_dump_context->ostream() << "_Error_" ;
786 }
787
788 Expression*
789 Expression::make_error(Location location)
790 {
791 return new Error_expression(location);
792 }
793
794 // An expression which is really a type. This is used during parsing.
795 // It is an error if these survive after lowering.
796
797 class
798 Type_expression : public Expression
799 {
800 public:
801 Type_expression(Type* type, Location location)
802 : Expression(EXPRESSION_TYPE, location),
803 type_(type)
804 { }
805
806 protected:
807 int
808 do_traverse(Traverse* traverse)
809 { return Type::traverse(this->type_, traverse); }
810
811 Type*
812 do_type()
813 { return this->type_; }
814
815 void
816 do_determine_type(const Type_context*)
817 { }
818
819 void
820 do_check_types(Gogo*)
821 { this->report_error(_("invalid use of type")); }
822
823 Expression*
824 do_copy()
825 { return this; }
826
827 tree
828 do_get_tree(Translate_context*)
829 { go_unreachable(); }
830
831 void do_dump_expression(Ast_dump_context*) const;
832
833 private:
834 // The type which we are representing as an expression.
835 Type* type_;
836 };
837
838 void
839 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
840 {
841 ast_dump_context->dump_type(this->type_);
842 }
843
844 Expression*
845 Expression::make_type(Type* type, Location location)
846 {
847 return new Type_expression(type, location);
848 }
849
850 // Class Parser_expression.
851
852 Type*
853 Parser_expression::do_type()
854 {
855 // We should never really ask for the type of a Parser_expression.
856 // However, it can happen, at least when we have an invalid const
857 // whose initializer refers to the const itself. In that case we
858 // may ask for the type when lowering the const itself.
859 go_assert(saw_errors());
860 return Type::make_error_type();
861 }
862
863 // Class Var_expression.
864
865 // Lower a variable expression. Here we just make sure that the
866 // initialization expression of the variable has been lowered. This
867 // ensures that we will be able to determine the type of the variable
868 // if necessary.
869
870 Expression*
871 Var_expression::do_lower(Gogo* gogo, Named_object* function,
872 Statement_inserter* inserter, int)
873 {
874 if (this->variable_->is_variable())
875 {
876 Variable* var = this->variable_->var_value();
877 // This is either a local variable or a global variable. A
878 // reference to a variable which is local to an enclosing
879 // function will be a reference to a field in a closure.
880 if (var->is_global())
881 {
882 function = NULL;
883 inserter = NULL;
884 }
885 var->lower_init_expression(gogo, function, inserter);
886 }
887 return this;
888 }
889
890 // Return the type of a reference to a variable.
891
892 Type*
893 Var_expression::do_type()
894 {
895 if (this->variable_->is_variable())
896 return this->variable_->var_value()->type();
897 else if (this->variable_->is_result_variable())
898 return this->variable_->result_var_value()->type();
899 else
900 go_unreachable();
901 }
902
903 // Determine the type of a reference to a variable.
904
905 void
906 Var_expression::do_determine_type(const Type_context*)
907 {
908 if (this->variable_->is_variable())
909 this->variable_->var_value()->determine_type();
910 }
911
912 // Something takes the address of this variable. This means that we
913 // may want to move the variable onto the heap.
914
915 void
916 Var_expression::do_address_taken(bool escapes)
917 {
918 if (!escapes)
919 {
920 if (this->variable_->is_variable())
921 this->variable_->var_value()->set_non_escaping_address_taken();
922 else if (this->variable_->is_result_variable())
923 this->variable_->result_var_value()->set_non_escaping_address_taken();
924 else
925 go_unreachable();
926 }
927 else
928 {
929 if (this->variable_->is_variable())
930 this->variable_->var_value()->set_address_taken();
931 else if (this->variable_->is_result_variable())
932 this->variable_->result_var_value()->set_address_taken();
933 else
934 go_unreachable();
935 }
936 }
937
938 // Get the tree for a reference to a variable.
939
940 tree
941 Var_expression::do_get_tree(Translate_context* context)
942 {
943 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
944 context->function());
945 bool is_in_heap;
946 Location loc = this->location();
947 if (this->variable_->is_variable())
948 is_in_heap = this->variable_->var_value()->is_in_heap();
949 else if (this->variable_->is_result_variable())
950 is_in_heap = this->variable_->result_var_value()->is_in_heap();
951 else
952 go_unreachable();
953
954 Bexpression* ret = context->backend()->var_expression(bvar, loc);
955 if (is_in_heap)
956 ret = context->backend()->indirect_expression(ret, true, loc);
957 return expr_to_tree(ret);
958 }
959
960 // Ast dump for variable expression.
961
962 void
963 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
964 {
965 ast_dump_context->ostream() << this->variable_->name() ;
966 }
967
968 // Make a reference to a variable in an expression.
969
970 Expression*
971 Expression::make_var_reference(Named_object* var, Location location)
972 {
973 if (var->is_sink())
974 return Expression::make_sink(location);
975
976 // FIXME: Creating a new object for each reference to a variable is
977 // wasteful.
978 return new Var_expression(var, location);
979 }
980
981 // Class Temporary_reference_expression.
982
983 // The type.
984
985 Type*
986 Temporary_reference_expression::do_type()
987 {
988 return this->statement_->type();
989 }
990
991 // Called if something takes the address of this temporary variable.
992 // We never have to move temporary variables to the heap, but we do
993 // need to know that they must live in the stack rather than in a
994 // register.
995
996 void
997 Temporary_reference_expression::do_address_taken(bool)
998 {
999 this->statement_->set_is_address_taken();
1000 }
1001
1002 // Get a tree referring to the variable.
1003
1004 tree
1005 Temporary_reference_expression::do_get_tree(Translate_context* context)
1006 {
1007 Gogo* gogo = context->gogo();
1008 Bvariable* bvar = this->statement_->get_backend_variable(context);
1009 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
1010
1011 // The backend can't always represent the same set of recursive types
1012 // that the Go frontend can. In some cases this means that a
1013 // temporary variable won't have the right backend type. Correct
1014 // that here by adding a type cast. We need to use base() to push
1015 // the circularity down one level.
1016 Type* stype = this->statement_->type();
1017 if (!this->is_lvalue_
1018 && stype->has_pointer()
1019 && stype->deref()->is_void_type())
1020 {
1021 Btype* btype = this->type()->base()->get_backend(gogo);
1022 ret = gogo->backend()->convert_expression(btype, ret, this->location());
1023 }
1024 return expr_to_tree(ret);
1025 }
1026
1027 // Ast dump for temporary reference.
1028
1029 void
1030 Temporary_reference_expression::do_dump_expression(
1031 Ast_dump_context* ast_dump_context) const
1032 {
1033 ast_dump_context->dump_temp_variable_name(this->statement_);
1034 }
1035
1036 // Make a reference to a temporary variable.
1037
1038 Temporary_reference_expression*
1039 Expression::make_temporary_reference(Temporary_statement* statement,
1040 Location location)
1041 {
1042 return new Temporary_reference_expression(statement, location);
1043 }
1044
1045 // Class Set_and_use_temporary_expression.
1046
1047 // Return the type.
1048
1049 Type*
1050 Set_and_use_temporary_expression::do_type()
1051 {
1052 return this->statement_->type();
1053 }
1054
1055 // Determine the type of the expression.
1056
1057 void
1058 Set_and_use_temporary_expression::do_determine_type(
1059 const Type_context* context)
1060 {
1061 this->expr_->determine_type(context);
1062 }
1063
1064 // Take the address.
1065
1066 void
1067 Set_and_use_temporary_expression::do_address_taken(bool)
1068 {
1069 this->statement_->set_is_address_taken();
1070 }
1071
1072 // Return the backend representation.
1073
1074 tree
1075 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1076 {
1077 Bvariable* bvar = this->statement_->get_backend_variable(context);
1078 tree var_tree = var_to_tree(bvar);
1079 tree expr_tree = this->expr_->get_tree(context);
1080 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1081 return error_mark_node;
1082 Location loc = this->location();
1083 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1084 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1085 var_tree, expr_tree),
1086 var_tree);
1087 }
1088
1089 // Dump.
1090
1091 void
1092 Set_and_use_temporary_expression::do_dump_expression(
1093 Ast_dump_context* ast_dump_context) const
1094 {
1095 ast_dump_context->ostream() << '(';
1096 ast_dump_context->dump_temp_variable_name(this->statement_);
1097 ast_dump_context->ostream() << " = ";
1098 this->expr_->dump_expression(ast_dump_context);
1099 ast_dump_context->ostream() << ')';
1100 }
1101
1102 // Make a set-and-use temporary.
1103
1104 Set_and_use_temporary_expression*
1105 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1106 Expression* expr, Location location)
1107 {
1108 return new Set_and_use_temporary_expression(statement, expr, location);
1109 }
1110
1111 // A sink expression--a use of the blank identifier _.
1112
1113 class Sink_expression : public Expression
1114 {
1115 public:
1116 Sink_expression(Location location)
1117 : Expression(EXPRESSION_SINK, location),
1118 type_(NULL), var_(NULL_TREE)
1119 { }
1120
1121 protected:
1122 bool
1123 do_discarding_value()
1124 { return true; }
1125
1126 Type*
1127 do_type();
1128
1129 void
1130 do_determine_type(const Type_context*);
1131
1132 Expression*
1133 do_copy()
1134 { return new Sink_expression(this->location()); }
1135
1136 tree
1137 do_get_tree(Translate_context*);
1138
1139 void
1140 do_dump_expression(Ast_dump_context*) const;
1141
1142 private:
1143 // The type of this sink variable.
1144 Type* type_;
1145 // The temporary variable we generate.
1146 tree var_;
1147 };
1148
1149 // Return the type of a sink expression.
1150
1151 Type*
1152 Sink_expression::do_type()
1153 {
1154 if (this->type_ == NULL)
1155 return Type::make_sink_type();
1156 return this->type_;
1157 }
1158
1159 // Determine the type of a sink expression.
1160
1161 void
1162 Sink_expression::do_determine_type(const Type_context* context)
1163 {
1164 if (context->type != NULL)
1165 this->type_ = context->type;
1166 }
1167
1168 // Return a temporary variable for a sink expression. This will
1169 // presumably be a write-only variable which the middle-end will drop.
1170
1171 tree
1172 Sink_expression::do_get_tree(Translate_context* context)
1173 {
1174 if (this->var_ == NULL_TREE)
1175 {
1176 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1177 Btype* bt = this->type_->get_backend(context->gogo());
1178 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1179 }
1180 return this->var_;
1181 }
1182
1183 // Ast dump for sink expression.
1184
1185 void
1186 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1187 {
1188 ast_dump_context->ostream() << "_" ;
1189 }
1190
1191 // Make a sink expression.
1192
1193 Expression*
1194 Expression::make_sink(Location location)
1195 {
1196 return new Sink_expression(location);
1197 }
1198
1199 // Class Func_expression.
1200
1201 // FIXME: Can a function expression appear in a constant expression?
1202 // The value is unchanging. Initializing a constant to the address of
1203 // a function seems like it could work, though there might be little
1204 // point to it.
1205
1206 // Traversal.
1207
1208 int
1209 Func_expression::do_traverse(Traverse* traverse)
1210 {
1211 return (this->closure_ == NULL
1212 ? TRAVERSE_CONTINUE
1213 : Expression::traverse(&this->closure_, traverse));
1214 }
1215
1216 // Return the type of a function expression.
1217
1218 Type*
1219 Func_expression::do_type()
1220 {
1221 if (this->function_->is_function())
1222 return this->function_->func_value()->type();
1223 else if (this->function_->is_function_declaration())
1224 return this->function_->func_declaration_value()->type();
1225 else
1226 go_unreachable();
1227 }
1228
1229 // Get the tree for the code of a function expression.
1230
1231 Bexpression*
1232 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1233 {
1234 Function_type* fntype;
1235 if (no->is_function())
1236 fntype = no->func_value()->type();
1237 else if (no->is_function_declaration())
1238 fntype = no->func_declaration_value()->type();
1239 else
1240 go_unreachable();
1241
1242 // Builtin functions are handled specially by Call_expression. We
1243 // can't take their address.
1244 if (fntype->is_builtin())
1245 {
1246 error_at(loc,
1247 "invalid use of special builtin function %qs; must be called",
1248 no->message_name().c_str());
1249 return gogo->backend()->error_expression();
1250 }
1251
1252 Bfunction* fndecl;
1253 if (no->is_function())
1254 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1255 else if (no->is_function_declaration())
1256 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1257 else
1258 go_unreachable();
1259
1260 return gogo->backend()->function_code_expression(fndecl, loc);
1261 }
1262
1263 // Get the tree for a function expression. This is used when we take
1264 // the address of a function rather than simply calling it. A func
1265 // value is represented as a pointer to a block of memory. The first
1266 // word of that memory is a pointer to the function code. The
1267 // remaining parts of that memory are the addresses of variables that
1268 // the function closes over.
1269
1270 tree
1271 Func_expression::do_get_tree(Translate_context* context)
1272 {
1273 // If there is no closure, just use the function descriptor.
1274 if (this->closure_ == NULL)
1275 {
1276 Gogo* gogo = context->gogo();
1277 Named_object* no = this->function_;
1278 Expression* descriptor;
1279 if (no->is_function())
1280 descriptor = no->func_value()->descriptor(gogo, no);
1281 else if (no->is_function_declaration())
1282 {
1283 if (no->func_declaration_value()->type()->is_builtin())
1284 {
1285 error_at(this->location(),
1286 ("invalid use of special builtin function %qs; "
1287 "must be called"),
1288 no->message_name().c_str());
1289 return error_mark_node;
1290 }
1291 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1292 }
1293 else
1294 go_unreachable();
1295
1296 tree dtree = descriptor->get_tree(context);
1297 if (dtree == error_mark_node)
1298 return error_mark_node;
1299 return build_fold_addr_expr_loc(this->location().gcc_location(), dtree);
1300 }
1301
1302 go_assert(this->function_->func_value()->enclosing() != NULL);
1303
1304 // If there is a closure, then the closure is itself the function
1305 // expression. It is a pointer to a struct whose first field points
1306 // to the function code and whose remaining fields are the addresses
1307 // of the closed-over variables.
1308 return this->closure_->get_tree(context);
1309 }
1310
1311 // Ast dump for function.
1312
1313 void
1314 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1315 {
1316 ast_dump_context->ostream() << this->function_->name();
1317 if (this->closure_ != NULL)
1318 {
1319 ast_dump_context->ostream() << " {closure = ";
1320 this->closure_->dump_expression(ast_dump_context);
1321 ast_dump_context->ostream() << "}";
1322 }
1323 }
1324
1325 // Make a reference to a function in an expression.
1326
1327 Expression*
1328 Expression::make_func_reference(Named_object* function, Expression* closure,
1329 Location location)
1330 {
1331 return new Func_expression(function, closure, location);
1332 }
1333
1334 // Class Func_descriptor_expression.
1335
1336 // Constructor.
1337
1338 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1339 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1340 fn_(fn), dvar_(NULL)
1341 {
1342 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1343 }
1344
1345 // Traversal.
1346
1347 int
1348 Func_descriptor_expression::do_traverse(Traverse*)
1349 {
1350 return TRAVERSE_CONTINUE;
1351 }
1352
1353 // All function descriptors have the same type.
1354
1355 Type* Func_descriptor_expression::descriptor_type;
1356
1357 void
1358 Func_descriptor_expression::make_func_descriptor_type()
1359 {
1360 if (Func_descriptor_expression::descriptor_type != NULL)
1361 return;
1362 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1363 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1364 Func_descriptor_expression::descriptor_type =
1365 Type::make_builtin_named_type("functionDescriptor", struct_type);
1366 }
1367
1368 Type*
1369 Func_descriptor_expression::do_type()
1370 {
1371 Func_descriptor_expression::make_func_descriptor_type();
1372 return Func_descriptor_expression::descriptor_type;
1373 }
1374
1375 // The tree for a function descriptor.
1376
1377 tree
1378 Func_descriptor_expression::do_get_tree(Translate_context* context)
1379 {
1380 if (this->dvar_ != NULL)
1381 return var_to_tree(this->dvar_);
1382
1383 Gogo* gogo = context->gogo();
1384 Named_object* no = this->fn_;
1385 Location loc = no->location();
1386
1387 std::string var_name;
1388 if (no->package() == NULL)
1389 var_name = gogo->pkgpath_symbol();
1390 else
1391 var_name = no->package()->pkgpath_symbol();
1392 var_name.push_back('.');
1393 var_name.append(Gogo::unpack_hidden_name(no->name()));
1394 var_name.append("$descriptor");
1395
1396 Btype* btype = this->type()->get_backend(gogo);
1397
1398 Bvariable* bvar;
1399 if (no->package() != NULL
1400 || Linemap::is_predeclared_location(no->location()))
1401 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1402 loc);
1403 else
1404 {
1405 Location bloc = Linemap::predeclared_location();
1406 bool is_hidden = ((no->is_function()
1407 && no->func_value()->enclosing() != NULL)
1408 || Gogo::is_thunk(no));
1409 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1410 btype, bloc);
1411 Expression_list* vals = new Expression_list();
1412 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1413 Expression* init =
1414 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1415 Translate_context bcontext(gogo, NULL, NULL, NULL);
1416 bcontext.set_is_const();
1417 Bexpression* binit = tree_to_expr(init->get_tree(&bcontext));
1418 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1419 false, btype, bloc, binit);
1420 }
1421
1422 this->dvar_ = bvar;
1423 return var_to_tree(bvar);
1424 }
1425
1426 // Print a function descriptor expression.
1427
1428 void
1429 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1430 {
1431 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1432 }
1433
1434 // Make a function descriptor expression.
1435
1436 Func_descriptor_expression*
1437 Expression::make_func_descriptor(Named_object* fn)
1438 {
1439 return new Func_descriptor_expression(fn);
1440 }
1441
1442 // Make the function descriptor type, so that it can be converted.
1443
1444 void
1445 Expression::make_func_descriptor_type()
1446 {
1447 Func_descriptor_expression::make_func_descriptor_type();
1448 }
1449
1450 // A reference to just the code of a function.
1451
1452 class Func_code_reference_expression : public Expression
1453 {
1454 public:
1455 Func_code_reference_expression(Named_object* function, Location location)
1456 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1457 function_(function)
1458 { }
1459
1460 protected:
1461 int
1462 do_traverse(Traverse*)
1463 { return TRAVERSE_CONTINUE; }
1464
1465 Type*
1466 do_type()
1467 { return Type::make_pointer_type(Type::make_void_type()); }
1468
1469 void
1470 do_determine_type(const Type_context*)
1471 { }
1472
1473 Expression*
1474 do_copy()
1475 {
1476 return Expression::make_func_code_reference(this->function_,
1477 this->location());
1478 }
1479
1480 tree
1481 do_get_tree(Translate_context*);
1482
1483 void
1484 do_dump_expression(Ast_dump_context* context) const
1485 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1486
1487 private:
1488 // The function.
1489 Named_object* function_;
1490 };
1491
1492 // Get the tree for a reference to function code.
1493
1494 tree
1495 Func_code_reference_expression::do_get_tree(Translate_context* context)
1496 {
1497 Bexpression* ret =
1498 Func_expression::get_code_pointer(context->gogo(), this->function_,
1499 this->location());
1500 return expr_to_tree(ret);
1501 }
1502
1503 // Make a reference to the code of a function.
1504
1505 Expression*
1506 Expression::make_func_code_reference(Named_object* function, Location location)
1507 {
1508 return new Func_code_reference_expression(function, location);
1509 }
1510
1511 // Class Unknown_expression.
1512
1513 // Return the name of an unknown expression.
1514
1515 const std::string&
1516 Unknown_expression::name() const
1517 {
1518 return this->named_object_->name();
1519 }
1520
1521 // Lower a reference to an unknown name.
1522
1523 Expression*
1524 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1525 {
1526 Location location = this->location();
1527 Named_object* no = this->named_object_;
1528 Named_object* real;
1529 if (!no->is_unknown())
1530 real = no;
1531 else
1532 {
1533 real = no->unknown_value()->real_named_object();
1534 if (real == NULL)
1535 {
1536 if (this->is_composite_literal_key_)
1537 return this;
1538 if (!this->no_error_message_)
1539 error_at(location, "reference to undefined name %qs",
1540 this->named_object_->message_name().c_str());
1541 return Expression::make_error(location);
1542 }
1543 }
1544 switch (real->classification())
1545 {
1546 case Named_object::NAMED_OBJECT_CONST:
1547 return Expression::make_const_reference(real, location);
1548 case Named_object::NAMED_OBJECT_TYPE:
1549 return Expression::make_type(real->type_value(), location);
1550 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1551 if (this->is_composite_literal_key_)
1552 return this;
1553 if (!this->no_error_message_)
1554 error_at(location, "reference to undefined type %qs",
1555 real->message_name().c_str());
1556 return Expression::make_error(location);
1557 case Named_object::NAMED_OBJECT_VAR:
1558 real->var_value()->set_is_used();
1559 return Expression::make_var_reference(real, location);
1560 case Named_object::NAMED_OBJECT_FUNC:
1561 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1562 return Expression::make_func_reference(real, NULL, location);
1563 case Named_object::NAMED_OBJECT_PACKAGE:
1564 if (this->is_composite_literal_key_)
1565 return this;
1566 if (!this->no_error_message_)
1567 error_at(location, "unexpected reference to package");
1568 return Expression::make_error(location);
1569 default:
1570 go_unreachable();
1571 }
1572 }
1573
1574 // Dump the ast representation for an unknown expression to a dump context.
1575
1576 void
1577 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1578 {
1579 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1580 << ")";
1581 }
1582
1583 // Make a reference to an unknown name.
1584
1585 Unknown_expression*
1586 Expression::make_unknown_reference(Named_object* no, Location location)
1587 {
1588 return new Unknown_expression(no, location);
1589 }
1590
1591 // A boolean expression.
1592
1593 class Boolean_expression : public Expression
1594 {
1595 public:
1596 Boolean_expression(bool val, Location location)
1597 : Expression(EXPRESSION_BOOLEAN, location),
1598 val_(val), type_(NULL)
1599 { }
1600
1601 static Expression*
1602 do_import(Import*);
1603
1604 protected:
1605 bool
1606 do_is_constant() const
1607 { return true; }
1608
1609 Type*
1610 do_type();
1611
1612 void
1613 do_determine_type(const Type_context*);
1614
1615 Expression*
1616 do_copy()
1617 { return this; }
1618
1619 tree
1620 do_get_tree(Translate_context*)
1621 { return this->val_ ? boolean_true_node : boolean_false_node; }
1622
1623 void
1624 do_export(Export* exp) const
1625 { exp->write_c_string(this->val_ ? "true" : "false"); }
1626
1627 void
1628 do_dump_expression(Ast_dump_context* ast_dump_context) const
1629 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1630
1631 private:
1632 // The constant.
1633 bool val_;
1634 // The type as determined by context.
1635 Type* type_;
1636 };
1637
1638 // Get the type.
1639
1640 Type*
1641 Boolean_expression::do_type()
1642 {
1643 if (this->type_ == NULL)
1644 this->type_ = Type::make_boolean_type();
1645 return this->type_;
1646 }
1647
1648 // Set the type from the context.
1649
1650 void
1651 Boolean_expression::do_determine_type(const Type_context* context)
1652 {
1653 if (this->type_ != NULL && !this->type_->is_abstract())
1654 ;
1655 else if (context->type != NULL && context->type->is_boolean_type())
1656 this->type_ = context->type;
1657 else if (!context->may_be_abstract)
1658 this->type_ = Type::lookup_bool_type();
1659 }
1660
1661 // Import a boolean constant.
1662
1663 Expression*
1664 Boolean_expression::do_import(Import* imp)
1665 {
1666 if (imp->peek_char() == 't')
1667 {
1668 imp->require_c_string("true");
1669 return Expression::make_boolean(true, imp->location());
1670 }
1671 else
1672 {
1673 imp->require_c_string("false");
1674 return Expression::make_boolean(false, imp->location());
1675 }
1676 }
1677
1678 // Make a boolean expression.
1679
1680 Expression*
1681 Expression::make_boolean(bool val, Location location)
1682 {
1683 return new Boolean_expression(val, location);
1684 }
1685
1686 // Class String_expression.
1687
1688 // Get the type.
1689
1690 Type*
1691 String_expression::do_type()
1692 {
1693 if (this->type_ == NULL)
1694 this->type_ = Type::make_string_type();
1695 return this->type_;
1696 }
1697
1698 // Set the type from the context.
1699
1700 void
1701 String_expression::do_determine_type(const Type_context* context)
1702 {
1703 if (this->type_ != NULL && !this->type_->is_abstract())
1704 ;
1705 else if (context->type != NULL && context->type->is_string_type())
1706 this->type_ = context->type;
1707 else if (!context->may_be_abstract)
1708 this->type_ = Type::lookup_string_type();
1709 }
1710
1711 // Build a string constant.
1712
1713 tree
1714 String_expression::do_get_tree(Translate_context* context)
1715 {
1716 return context->gogo()->go_string_constant_tree(this->val_);
1717 }
1718
1719 // Write string literal to string dump.
1720
1721 void
1722 String_expression::export_string(String_dump* exp,
1723 const String_expression* str)
1724 {
1725 std::string s;
1726 s.reserve(str->val_.length() * 4 + 2);
1727 s += '"';
1728 for (std::string::const_iterator p = str->val_.begin();
1729 p != str->val_.end();
1730 ++p)
1731 {
1732 if (*p == '\\' || *p == '"')
1733 {
1734 s += '\\';
1735 s += *p;
1736 }
1737 else if (*p >= 0x20 && *p < 0x7f)
1738 s += *p;
1739 else if (*p == '\n')
1740 s += "\\n";
1741 else if (*p == '\t')
1742 s += "\\t";
1743 else
1744 {
1745 s += "\\x";
1746 unsigned char c = *p;
1747 unsigned int dig = c >> 4;
1748 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1749 dig = c & 0xf;
1750 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1751 }
1752 }
1753 s += '"';
1754 exp->write_string(s);
1755 }
1756
1757 // Export a string expression.
1758
1759 void
1760 String_expression::do_export(Export* exp) const
1761 {
1762 String_expression::export_string(exp, this);
1763 }
1764
1765 // Import a string expression.
1766
1767 Expression*
1768 String_expression::do_import(Import* imp)
1769 {
1770 imp->require_c_string("\"");
1771 std::string val;
1772 while (true)
1773 {
1774 int c = imp->get_char();
1775 if (c == '"' || c == -1)
1776 break;
1777 if (c != '\\')
1778 val += static_cast<char>(c);
1779 else
1780 {
1781 c = imp->get_char();
1782 if (c == '\\' || c == '"')
1783 val += static_cast<char>(c);
1784 else if (c == 'n')
1785 val += '\n';
1786 else if (c == 't')
1787 val += '\t';
1788 else if (c == 'x')
1789 {
1790 c = imp->get_char();
1791 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1792 c = imp->get_char();
1793 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1794 char v = (vh << 4) | vl;
1795 val += v;
1796 }
1797 else
1798 {
1799 error_at(imp->location(), "bad string constant");
1800 return Expression::make_error(imp->location());
1801 }
1802 }
1803 }
1804 return Expression::make_string(val, imp->location());
1805 }
1806
1807 // Ast dump for string expression.
1808
1809 void
1810 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1811 {
1812 String_expression::export_string(ast_dump_context, this);
1813 }
1814
1815 // Make a string expression.
1816
1817 Expression*
1818 Expression::make_string(const std::string& val, Location location)
1819 {
1820 return new String_expression(val, location);
1821 }
1822
1823 // Make an integer expression.
1824
1825 class Integer_expression : public Expression
1826 {
1827 public:
1828 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1829 Location location)
1830 : Expression(EXPRESSION_INTEGER, location),
1831 type_(type), is_character_constant_(is_character_constant)
1832 { mpz_init_set(this->val_, *val); }
1833
1834 static Expression*
1835 do_import(Import*);
1836
1837 // Write VAL to string dump.
1838 static void
1839 export_integer(String_dump* exp, const mpz_t val);
1840
1841 // Write VAL to dump context.
1842 static void
1843 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1844
1845 protected:
1846 bool
1847 do_is_constant() const
1848 { return true; }
1849
1850 bool
1851 do_numeric_constant_value(Numeric_constant* nc) const;
1852
1853 Type*
1854 do_type();
1855
1856 void
1857 do_determine_type(const Type_context* context);
1858
1859 void
1860 do_check_types(Gogo*);
1861
1862 tree
1863 do_get_tree(Translate_context*);
1864
1865 Expression*
1866 do_copy()
1867 {
1868 if (this->is_character_constant_)
1869 return Expression::make_character(&this->val_, this->type_,
1870 this->location());
1871 else
1872 return Expression::make_integer(&this->val_, this->type_,
1873 this->location());
1874 }
1875
1876 void
1877 do_export(Export*) const;
1878
1879 void
1880 do_dump_expression(Ast_dump_context*) const;
1881
1882 private:
1883 // The integer value.
1884 mpz_t val_;
1885 // The type so far.
1886 Type* type_;
1887 // Whether this is a character constant.
1888 bool is_character_constant_;
1889 };
1890
1891 // Return a numeric constant for this expression. We have to mark
1892 // this as a character when appropriate.
1893
1894 bool
1895 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1896 {
1897 if (this->is_character_constant_)
1898 nc->set_rune(this->type_, this->val_);
1899 else
1900 nc->set_int(this->type_, this->val_);
1901 return true;
1902 }
1903
1904 // Return the current type. If we haven't set the type yet, we return
1905 // an abstract integer type.
1906
1907 Type*
1908 Integer_expression::do_type()
1909 {
1910 if (this->type_ == NULL)
1911 {
1912 if (this->is_character_constant_)
1913 this->type_ = Type::make_abstract_character_type();
1914 else
1915 this->type_ = Type::make_abstract_integer_type();
1916 }
1917 return this->type_;
1918 }
1919
1920 // Set the type of the integer value. Here we may switch from an
1921 // abstract type to a real type.
1922
1923 void
1924 Integer_expression::do_determine_type(const Type_context* context)
1925 {
1926 if (this->type_ != NULL && !this->type_->is_abstract())
1927 ;
1928 else if (context->type != NULL && context->type->is_numeric_type())
1929 this->type_ = context->type;
1930 else if (!context->may_be_abstract)
1931 {
1932 if (this->is_character_constant_)
1933 this->type_ = Type::lookup_integer_type("int32");
1934 else
1935 this->type_ = Type::lookup_integer_type("int");
1936 }
1937 }
1938
1939 // Check the type of an integer constant.
1940
1941 void
1942 Integer_expression::do_check_types(Gogo*)
1943 {
1944 Type* type = this->type_;
1945 if (type == NULL)
1946 return;
1947 Numeric_constant nc;
1948 if (this->is_character_constant_)
1949 nc.set_rune(NULL, this->val_);
1950 else
1951 nc.set_int(NULL, this->val_);
1952 if (!nc.set_type(type, true, this->location()))
1953 this->set_is_error();
1954 }
1955
1956 // Get a tree for an integer constant.
1957
1958 tree
1959 Integer_expression::do_get_tree(Translate_context* context)
1960 {
1961 Type* resolved_type = NULL;
1962 if (this->type_ != NULL && !this->type_->is_abstract())
1963 resolved_type = this->type_;
1964 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1965 {
1966 // We are converting to an abstract floating point type.
1967 resolved_type = Type::lookup_float_type("float64");
1968 }
1969 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1970 {
1971 // We are converting to an abstract complex type.
1972 resolved_type = Type::lookup_complex_type("complex128");
1973 }
1974 else
1975 {
1976 // If we still have an abstract type here, then this is being
1977 // used in a constant expression which didn't get reduced for
1978 // some reason. Use a type which will fit the value. We use <,
1979 // not <=, because we need an extra bit for the sign bit.
1980 int bits = mpz_sizeinbase(this->val_, 2);
1981 Type* int_type = Type::lookup_integer_type("int");
1982 if (bits < int_type->integer_type()->bits())
1983 resolved_type = int_type;
1984 else if (bits < 64)
1985 resolved_type = Type::lookup_integer_type("int64");
1986 else
1987 {
1988 if (!saw_errors())
1989 error_at(this->location(),
1990 "unknown type for large integer constant");
1991 Bexpression* ret = context->gogo()->backend()->error_expression();
1992 return expr_to_tree(ret);
1993 }
1994 }
1995 Numeric_constant nc;
1996 nc.set_int(resolved_type, this->val_);
1997 Bexpression* ret =
1998 Expression::backend_numeric_constant_expression(context, &nc);
1999 return expr_to_tree(ret);
2000 }
2001
2002 // Write VAL to export data.
2003
2004 void
2005 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2006 {
2007 char* s = mpz_get_str(NULL, 10, val);
2008 exp->write_c_string(s);
2009 free(s);
2010 }
2011
2012 // Export an integer in a constant expression.
2013
2014 void
2015 Integer_expression::do_export(Export* exp) const
2016 {
2017 Integer_expression::export_integer(exp, this->val_);
2018 if (this->is_character_constant_)
2019 exp->write_c_string("'");
2020 // A trailing space lets us reliably identify the end of the number.
2021 exp->write_c_string(" ");
2022 }
2023
2024 // Import an integer, floating point, or complex value. This handles
2025 // all these types because they all start with digits.
2026
2027 Expression*
2028 Integer_expression::do_import(Import* imp)
2029 {
2030 std::string num = imp->read_identifier();
2031 imp->require_c_string(" ");
2032 if (!num.empty() && num[num.length() - 1] == 'i')
2033 {
2034 mpfr_t real;
2035 size_t plus_pos = num.find('+', 1);
2036 size_t minus_pos = num.find('-', 1);
2037 size_t pos;
2038 if (plus_pos == std::string::npos)
2039 pos = minus_pos;
2040 else if (minus_pos == std::string::npos)
2041 pos = plus_pos;
2042 else
2043 {
2044 error_at(imp->location(), "bad number in import data: %qs",
2045 num.c_str());
2046 return Expression::make_error(imp->location());
2047 }
2048 if (pos == std::string::npos)
2049 mpfr_set_ui(real, 0, GMP_RNDN);
2050 else
2051 {
2052 std::string real_str = num.substr(0, pos);
2053 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2054 {
2055 error_at(imp->location(), "bad number in import data: %qs",
2056 real_str.c_str());
2057 return Expression::make_error(imp->location());
2058 }
2059 }
2060
2061 std::string imag_str;
2062 if (pos == std::string::npos)
2063 imag_str = num;
2064 else
2065 imag_str = num.substr(pos);
2066 imag_str = imag_str.substr(0, imag_str.size() - 1);
2067 mpfr_t imag;
2068 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2069 {
2070 error_at(imp->location(), "bad number in import data: %qs",
2071 imag_str.c_str());
2072 return Expression::make_error(imp->location());
2073 }
2074 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2075 imp->location());
2076 mpfr_clear(real);
2077 mpfr_clear(imag);
2078 return ret;
2079 }
2080 else if (num.find('.') == std::string::npos
2081 && num.find('E') == std::string::npos)
2082 {
2083 bool is_character_constant = (!num.empty()
2084 && num[num.length() - 1] == '\'');
2085 if (is_character_constant)
2086 num = num.substr(0, num.length() - 1);
2087 mpz_t val;
2088 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2089 {
2090 error_at(imp->location(), "bad number in import data: %qs",
2091 num.c_str());
2092 return Expression::make_error(imp->location());
2093 }
2094 Expression* ret;
2095 if (is_character_constant)
2096 ret = Expression::make_character(&val, NULL, imp->location());
2097 else
2098 ret = Expression::make_integer(&val, NULL, imp->location());
2099 mpz_clear(val);
2100 return ret;
2101 }
2102 else
2103 {
2104 mpfr_t val;
2105 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2106 {
2107 error_at(imp->location(), "bad number in import data: %qs",
2108 num.c_str());
2109 return Expression::make_error(imp->location());
2110 }
2111 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2112 mpfr_clear(val);
2113 return ret;
2114 }
2115 }
2116 // Ast dump for integer expression.
2117
2118 void
2119 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2120 {
2121 if (this->is_character_constant_)
2122 ast_dump_context->ostream() << '\'';
2123 Integer_expression::export_integer(ast_dump_context, this->val_);
2124 if (this->is_character_constant_)
2125 ast_dump_context->ostream() << '\'';
2126 }
2127
2128 // Build a new integer value.
2129
2130 Expression*
2131 Expression::make_integer(const mpz_t* val, Type* type, Location location)
2132 {
2133 return new Integer_expression(val, type, false, location);
2134 }
2135
2136 // Build a new character constant value.
2137
2138 Expression*
2139 Expression::make_character(const mpz_t* val, Type* type, Location location)
2140 {
2141 return new Integer_expression(val, type, true, location);
2142 }
2143
2144 // Floats.
2145
2146 class Float_expression : public Expression
2147 {
2148 public:
2149 Float_expression(const mpfr_t* val, Type* type, Location location)
2150 : Expression(EXPRESSION_FLOAT, location),
2151 type_(type)
2152 {
2153 mpfr_init_set(this->val_, *val, GMP_RNDN);
2154 }
2155
2156 // Write VAL to export data.
2157 static void
2158 export_float(String_dump* exp, const mpfr_t val);
2159
2160 // Write VAL to dump file.
2161 static void
2162 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2163
2164 protected:
2165 bool
2166 do_is_constant() const
2167 { return true; }
2168
2169 bool
2170 do_numeric_constant_value(Numeric_constant* nc) const
2171 {
2172 nc->set_float(this->type_, this->val_);
2173 return true;
2174 }
2175
2176 Type*
2177 do_type();
2178
2179 void
2180 do_determine_type(const Type_context*);
2181
2182 void
2183 do_check_types(Gogo*);
2184
2185 Expression*
2186 do_copy()
2187 { return Expression::make_float(&this->val_, this->type_,
2188 this->location()); }
2189
2190 tree
2191 do_get_tree(Translate_context*);
2192
2193 void
2194 do_export(Export*) const;
2195
2196 void
2197 do_dump_expression(Ast_dump_context*) const;
2198
2199 private:
2200 // The floating point value.
2201 mpfr_t val_;
2202 // The type so far.
2203 Type* type_;
2204 };
2205
2206 // Return the current type. If we haven't set the type yet, we return
2207 // an abstract float type.
2208
2209 Type*
2210 Float_expression::do_type()
2211 {
2212 if (this->type_ == NULL)
2213 this->type_ = Type::make_abstract_float_type();
2214 return this->type_;
2215 }
2216
2217 // Set the type of the float value. Here we may switch from an
2218 // abstract type to a real type.
2219
2220 void
2221 Float_expression::do_determine_type(const Type_context* context)
2222 {
2223 if (this->type_ != NULL && !this->type_->is_abstract())
2224 ;
2225 else if (context->type != NULL
2226 && (context->type->integer_type() != NULL
2227 || context->type->float_type() != NULL
2228 || context->type->complex_type() != NULL))
2229 this->type_ = context->type;
2230 else if (!context->may_be_abstract)
2231 this->type_ = Type::lookup_float_type("float64");
2232 }
2233
2234 // Check the type of a float value.
2235
2236 void
2237 Float_expression::do_check_types(Gogo*)
2238 {
2239 Type* type = this->type_;
2240 if (type == NULL)
2241 return;
2242 Numeric_constant nc;
2243 nc.set_float(NULL, this->val_);
2244 if (!nc.set_type(this->type_, true, this->location()))
2245 this->set_is_error();
2246 }
2247
2248 // Get a tree for a float constant.
2249
2250 tree
2251 Float_expression::do_get_tree(Translate_context* context)
2252 {
2253 Type* resolved_type;
2254 if (this->type_ != NULL && !this->type_->is_abstract())
2255 resolved_type = this->type_;
2256 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2257 {
2258 // We have an abstract integer type. We just hope for the best.
2259 resolved_type = Type::lookup_integer_type("int");
2260 }
2261 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2262 {
2263 // We are converting to an abstract complex type.
2264 resolved_type = Type::lookup_complex_type("complex128");
2265 }
2266 else
2267 {
2268 // If we still have an abstract type here, then this is being
2269 // used in a constant expression which didn't get reduced. We
2270 // just use float64 and hope for the best.
2271 resolved_type = Type::lookup_float_type("float64");
2272 }
2273
2274 Numeric_constant nc;
2275 nc.set_float(resolved_type, this->val_);
2276 Bexpression* ret =
2277 Expression::backend_numeric_constant_expression(context, &nc);
2278 return expr_to_tree(ret);
2279 }
2280
2281 // Write a floating point number to a string dump.
2282
2283 void
2284 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2285 {
2286 mp_exp_t exponent;
2287 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2288 if (*s == '-')
2289 exp->write_c_string("-");
2290 exp->write_c_string("0.");
2291 exp->write_c_string(*s == '-' ? s + 1 : s);
2292 mpfr_free_str(s);
2293 char buf[30];
2294 snprintf(buf, sizeof buf, "E%ld", exponent);
2295 exp->write_c_string(buf);
2296 }
2297
2298 // Export a floating point number in a constant expression.
2299
2300 void
2301 Float_expression::do_export(Export* exp) const
2302 {
2303 Float_expression::export_float(exp, this->val_);
2304 // A trailing space lets us reliably identify the end of the number.
2305 exp->write_c_string(" ");
2306 }
2307
2308 // Dump a floating point number to the dump file.
2309
2310 void
2311 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2312 {
2313 Float_expression::export_float(ast_dump_context, this->val_);
2314 }
2315
2316 // Make a float expression.
2317
2318 Expression*
2319 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2320 {
2321 return new Float_expression(val, type, location);
2322 }
2323
2324 // Complex numbers.
2325
2326 class Complex_expression : public Expression
2327 {
2328 public:
2329 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2330 Location location)
2331 : Expression(EXPRESSION_COMPLEX, location),
2332 type_(type)
2333 {
2334 mpfr_init_set(this->real_, *real, GMP_RNDN);
2335 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2336 }
2337
2338 // Write REAL/IMAG to string dump.
2339 static void
2340 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2341
2342 // Write REAL/IMAG to dump context.
2343 static void
2344 dump_complex(Ast_dump_context* ast_dump_context,
2345 const mpfr_t real, const mpfr_t val);
2346
2347 protected:
2348 bool
2349 do_is_constant() const
2350 { return true; }
2351
2352 bool
2353 do_numeric_constant_value(Numeric_constant* nc) const
2354 {
2355 nc->set_complex(this->type_, this->real_, this->imag_);
2356 return true;
2357 }
2358
2359 Type*
2360 do_type();
2361
2362 void
2363 do_determine_type(const Type_context*);
2364
2365 void
2366 do_check_types(Gogo*);
2367
2368 Expression*
2369 do_copy()
2370 {
2371 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2372 this->location());
2373 }
2374
2375 tree
2376 do_get_tree(Translate_context*);
2377
2378 void
2379 do_export(Export*) const;
2380
2381 void
2382 do_dump_expression(Ast_dump_context*) const;
2383
2384 private:
2385 // The real part.
2386 mpfr_t real_;
2387 // The imaginary part;
2388 mpfr_t imag_;
2389 // The type if known.
2390 Type* type_;
2391 };
2392
2393 // Return the current type. If we haven't set the type yet, we return
2394 // an abstract complex type.
2395
2396 Type*
2397 Complex_expression::do_type()
2398 {
2399 if (this->type_ == NULL)
2400 this->type_ = Type::make_abstract_complex_type();
2401 return this->type_;
2402 }
2403
2404 // Set the type of the complex value. Here we may switch from an
2405 // abstract type to a real type.
2406
2407 void
2408 Complex_expression::do_determine_type(const Type_context* context)
2409 {
2410 if (this->type_ != NULL && !this->type_->is_abstract())
2411 ;
2412 else if (context->type != NULL
2413 && context->type->complex_type() != NULL)
2414 this->type_ = context->type;
2415 else if (!context->may_be_abstract)
2416 this->type_ = Type::lookup_complex_type("complex128");
2417 }
2418
2419 // Check the type of a complex value.
2420
2421 void
2422 Complex_expression::do_check_types(Gogo*)
2423 {
2424 Type* type = this->type_;
2425 if (type == NULL)
2426 return;
2427 Numeric_constant nc;
2428 nc.set_complex(NULL, this->real_, this->imag_);
2429 if (!nc.set_type(this->type_, true, this->location()))
2430 this->set_is_error();
2431 }
2432
2433 // Get a tree for a complex constant.
2434
2435 tree
2436 Complex_expression::do_get_tree(Translate_context* context)
2437 {
2438 Type* resolved_type;
2439 if (this->type_ != NULL && !this->type_->is_abstract())
2440 resolved_type = this->type_;
2441 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2442 {
2443 // We are converting to an abstract integer type.
2444 resolved_type = Type::lookup_integer_type("int");
2445 }
2446 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2447 {
2448 // We are converting to an abstract float type.
2449 resolved_type = Type::lookup_float_type("float64");
2450 }
2451 else
2452 {
2453 // If we still have an abstract type here, this this is being
2454 // used in a constant expression which didn't get reduced. We
2455 // just use complex128 and hope for the best.
2456 resolved_type = Type::lookup_complex_type("complex128");
2457 }
2458
2459 Numeric_constant nc;
2460 nc.set_complex(resolved_type, this->real_, this->imag_);
2461 Bexpression* ret =
2462 Expression::backend_numeric_constant_expression(context, &nc);
2463 return expr_to_tree(ret);
2464 }
2465
2466 // Write REAL/IMAG to export data.
2467
2468 void
2469 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2470 const mpfr_t imag)
2471 {
2472 if (!mpfr_zero_p(real))
2473 {
2474 Float_expression::export_float(exp, real);
2475 if (mpfr_sgn(imag) > 0)
2476 exp->write_c_string("+");
2477 }
2478 Float_expression::export_float(exp, imag);
2479 exp->write_c_string("i");
2480 }
2481
2482 // Export a complex number in a constant expression.
2483
2484 void
2485 Complex_expression::do_export(Export* exp) const
2486 {
2487 Complex_expression::export_complex(exp, this->real_, this->imag_);
2488 // A trailing space lets us reliably identify the end of the number.
2489 exp->write_c_string(" ");
2490 }
2491
2492 // Dump a complex expression to the dump file.
2493
2494 void
2495 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2496 {
2497 Complex_expression::export_complex(ast_dump_context,
2498 this->real_,
2499 this->imag_);
2500 }
2501
2502 // Make a complex expression.
2503
2504 Expression*
2505 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2506 Location location)
2507 {
2508 return new Complex_expression(real, imag, type, location);
2509 }
2510
2511 // Find a named object in an expression.
2512
2513 class Find_named_object : public Traverse
2514 {
2515 public:
2516 Find_named_object(Named_object* no)
2517 : Traverse(traverse_expressions),
2518 no_(no), found_(false)
2519 { }
2520
2521 // Whether we found the object.
2522 bool
2523 found() const
2524 { return this->found_; }
2525
2526 protected:
2527 int
2528 expression(Expression**);
2529
2530 private:
2531 // The object we are looking for.
2532 Named_object* no_;
2533 // Whether we found it.
2534 bool found_;
2535 };
2536
2537 // A reference to a const in an expression.
2538
2539 class Const_expression : public Expression
2540 {
2541 public:
2542 Const_expression(Named_object* constant, Location location)
2543 : Expression(EXPRESSION_CONST_REFERENCE, location),
2544 constant_(constant), type_(NULL), seen_(false)
2545 { }
2546
2547 Named_object*
2548 named_object()
2549 { return this->constant_; }
2550
2551 // Check that the initializer does not refer to the constant itself.
2552 void
2553 check_for_init_loop();
2554
2555 protected:
2556 int
2557 do_traverse(Traverse*);
2558
2559 Expression*
2560 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2561
2562 bool
2563 do_is_constant() const
2564 { return true; }
2565
2566 bool
2567 do_numeric_constant_value(Numeric_constant* nc) const;
2568
2569 bool
2570 do_string_constant_value(std::string* val) const;
2571
2572 Type*
2573 do_type();
2574
2575 // The type of a const is set by the declaration, not the use.
2576 void
2577 do_determine_type(const Type_context*);
2578
2579 void
2580 do_check_types(Gogo*);
2581
2582 Expression*
2583 do_copy()
2584 { return this; }
2585
2586 tree
2587 do_get_tree(Translate_context* context);
2588
2589 // When exporting a reference to a const as part of a const
2590 // expression, we export the value. We ignore the fact that it has
2591 // a name.
2592 void
2593 do_export(Export* exp) const
2594 { this->constant_->const_value()->expr()->export_expression(exp); }
2595
2596 void
2597 do_dump_expression(Ast_dump_context*) const;
2598
2599 private:
2600 // The constant.
2601 Named_object* constant_;
2602 // The type of this reference. This is used if the constant has an
2603 // abstract type.
2604 Type* type_;
2605 // Used to prevent infinite recursion when a constant incorrectly
2606 // refers to itself.
2607 mutable bool seen_;
2608 };
2609
2610 // Traversal.
2611
2612 int
2613 Const_expression::do_traverse(Traverse* traverse)
2614 {
2615 if (this->type_ != NULL)
2616 return Type::traverse(this->type_, traverse);
2617 return TRAVERSE_CONTINUE;
2618 }
2619
2620 // Lower a constant expression. This is where we convert the
2621 // predeclared constant iota into an integer value.
2622
2623 Expression*
2624 Const_expression::do_lower(Gogo* gogo, Named_object*,
2625 Statement_inserter*, int iota_value)
2626 {
2627 if (this->constant_->const_value()->expr()->classification()
2628 == EXPRESSION_IOTA)
2629 {
2630 if (iota_value == -1)
2631 {
2632 error_at(this->location(),
2633 "iota is only defined in const declarations");
2634 iota_value = 0;
2635 }
2636 mpz_t val;
2637 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2638 Expression* ret = Expression::make_integer(&val, NULL,
2639 this->location());
2640 mpz_clear(val);
2641 return ret;
2642 }
2643
2644 // Make sure that the constant itself has been lowered.
2645 gogo->lower_constant(this->constant_);
2646
2647 return this;
2648 }
2649
2650 // Return a numeric constant value.
2651
2652 bool
2653 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2654 {
2655 if (this->seen_)
2656 return false;
2657
2658 Expression* e = this->constant_->const_value()->expr();
2659
2660 this->seen_ = true;
2661
2662 bool r = e->numeric_constant_value(nc);
2663
2664 this->seen_ = false;
2665
2666 Type* ctype;
2667 if (this->type_ != NULL)
2668 ctype = this->type_;
2669 else
2670 ctype = this->constant_->const_value()->type();
2671 if (r && ctype != NULL)
2672 {
2673 if (!nc->set_type(ctype, false, this->location()))
2674 return false;
2675 }
2676
2677 return r;
2678 }
2679
2680 bool
2681 Const_expression::do_string_constant_value(std::string* val) const
2682 {
2683 if (this->seen_)
2684 return false;
2685
2686 Expression* e = this->constant_->const_value()->expr();
2687
2688 this->seen_ = true;
2689 bool ok = e->string_constant_value(val);
2690 this->seen_ = false;
2691
2692 return ok;
2693 }
2694
2695 // Return the type of the const reference.
2696
2697 Type*
2698 Const_expression::do_type()
2699 {
2700 if (this->type_ != NULL)
2701 return this->type_;
2702
2703 Named_constant* nc = this->constant_->const_value();
2704
2705 if (this->seen_ || nc->lowering())
2706 {
2707 this->report_error(_("constant refers to itself"));
2708 this->type_ = Type::make_error_type();
2709 return this->type_;
2710 }
2711
2712 this->seen_ = true;
2713
2714 Type* ret = nc->type();
2715
2716 if (ret != NULL)
2717 {
2718 this->seen_ = false;
2719 return ret;
2720 }
2721
2722 // During parsing, a named constant may have a NULL type, but we
2723 // must not return a NULL type here.
2724 ret = nc->expr()->type();
2725
2726 this->seen_ = false;
2727
2728 return ret;
2729 }
2730
2731 // Set the type of the const reference.
2732
2733 void
2734 Const_expression::do_determine_type(const Type_context* context)
2735 {
2736 Type* ctype = this->constant_->const_value()->type();
2737 Type* cetype = (ctype != NULL
2738 ? ctype
2739 : this->constant_->const_value()->expr()->type());
2740 if (ctype != NULL && !ctype->is_abstract())
2741 ;
2742 else if (context->type != NULL
2743 && context->type->is_numeric_type()
2744 && cetype->is_numeric_type())
2745 this->type_ = context->type;
2746 else if (context->type != NULL
2747 && context->type->is_string_type()
2748 && cetype->is_string_type())
2749 this->type_ = context->type;
2750 else if (context->type != NULL
2751 && context->type->is_boolean_type()
2752 && cetype->is_boolean_type())
2753 this->type_ = context->type;
2754 else if (!context->may_be_abstract)
2755 {
2756 if (cetype->is_abstract())
2757 cetype = cetype->make_non_abstract_type();
2758 this->type_ = cetype;
2759 }
2760 }
2761
2762 // Check for a loop in which the initializer of a constant refers to
2763 // the constant itself.
2764
2765 void
2766 Const_expression::check_for_init_loop()
2767 {
2768 if (this->type_ != NULL && this->type_->is_error())
2769 return;
2770
2771 if (this->seen_)
2772 {
2773 this->report_error(_("constant refers to itself"));
2774 this->type_ = Type::make_error_type();
2775 return;
2776 }
2777
2778 Expression* init = this->constant_->const_value()->expr();
2779 Find_named_object find_named_object(this->constant_);
2780
2781 this->seen_ = true;
2782 Expression::traverse(&init, &find_named_object);
2783 this->seen_ = false;
2784
2785 if (find_named_object.found())
2786 {
2787 if (this->type_ == NULL || !this->type_->is_error())
2788 {
2789 this->report_error(_("constant refers to itself"));
2790 this->type_ = Type::make_error_type();
2791 }
2792 return;
2793 }
2794 }
2795
2796 // Check types of a const reference.
2797
2798 void
2799 Const_expression::do_check_types(Gogo*)
2800 {
2801 if (this->type_ != NULL && this->type_->is_error())
2802 return;
2803
2804 this->check_for_init_loop();
2805
2806 // Check that numeric constant fits in type.
2807 if (this->type_ != NULL && this->type_->is_numeric_type())
2808 {
2809 Numeric_constant nc;
2810 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2811 {
2812 if (!nc.set_type(this->type_, true, this->location()))
2813 this->set_is_error();
2814 }
2815 }
2816 }
2817
2818 // Return a tree for the const reference.
2819
2820 tree
2821 Const_expression::do_get_tree(Translate_context* context)
2822 {
2823 Gogo* gogo = context->gogo();
2824 tree type_tree;
2825 if (this->type_ == NULL)
2826 type_tree = NULL_TREE;
2827 else
2828 {
2829 type_tree = type_to_tree(this->type_->get_backend(gogo));
2830 if (type_tree == error_mark_node)
2831 return error_mark_node;
2832 }
2833
2834 // If the type has been set for this expression, but the underlying
2835 // object is an abstract int or float, we try to get the abstract
2836 // value. Otherwise we may lose something in the conversion.
2837 if (this->type_ != NULL
2838 && this->type_->is_numeric_type()
2839 && (this->constant_->const_value()->type() == NULL
2840 || this->constant_->const_value()->type()->is_abstract()))
2841 {
2842 Expression* expr = this->constant_->const_value()->expr();
2843 Numeric_constant nc;
2844 if (expr->numeric_constant_value(&nc)
2845 && nc.set_type(this->type_, false, this->location()))
2846 {
2847 Expression* e = nc.expression(this->location());
2848 return e->get_tree(context);
2849 }
2850 }
2851
2852 tree const_tree = this->constant_->get_tree(gogo, context->function());
2853 if (this->type_ == NULL
2854 || const_tree == error_mark_node
2855 || TREE_TYPE(const_tree) == error_mark_node)
2856 return const_tree;
2857
2858 tree ret;
2859 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2860 ret = fold_convert(type_tree, const_tree);
2861 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2862 ret = fold(convert_to_integer(type_tree, const_tree));
2863 else if (TREE_CODE(type_tree) == REAL_TYPE)
2864 ret = fold(convert_to_real(type_tree, const_tree));
2865 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2866 ret = fold(convert_to_complex(type_tree, const_tree));
2867 else
2868 go_unreachable();
2869 return ret;
2870 }
2871
2872 // Dump ast representation for constant expression.
2873
2874 void
2875 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2876 {
2877 ast_dump_context->ostream() << this->constant_->name();
2878 }
2879
2880 // Make a reference to a constant in an expression.
2881
2882 Expression*
2883 Expression::make_const_reference(Named_object* constant,
2884 Location location)
2885 {
2886 return new Const_expression(constant, location);
2887 }
2888
2889 // Find a named object in an expression.
2890
2891 int
2892 Find_named_object::expression(Expression** pexpr)
2893 {
2894 switch ((*pexpr)->classification())
2895 {
2896 case Expression::EXPRESSION_CONST_REFERENCE:
2897 {
2898 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2899 if (ce->named_object() == this->no_)
2900 break;
2901
2902 // We need to check a constant initializer explicitly, as
2903 // loops here will not be caught by the loop checking for
2904 // variable initializers.
2905 ce->check_for_init_loop();
2906
2907 return TRAVERSE_CONTINUE;
2908 }
2909
2910 case Expression::EXPRESSION_VAR_REFERENCE:
2911 if ((*pexpr)->var_expression()->named_object() == this->no_)
2912 break;
2913 return TRAVERSE_CONTINUE;
2914 case Expression::EXPRESSION_FUNC_REFERENCE:
2915 if ((*pexpr)->func_expression()->named_object() == this->no_)
2916 break;
2917 return TRAVERSE_CONTINUE;
2918 default:
2919 return TRAVERSE_CONTINUE;
2920 }
2921 this->found_ = true;
2922 return TRAVERSE_EXIT;
2923 }
2924
2925 // The nil value.
2926
2927 class Nil_expression : public Expression
2928 {
2929 public:
2930 Nil_expression(Location location)
2931 : Expression(EXPRESSION_NIL, location)
2932 { }
2933
2934 static Expression*
2935 do_import(Import*);
2936
2937 protected:
2938 bool
2939 do_is_constant() const
2940 { return true; }
2941
2942 Type*
2943 do_type()
2944 { return Type::make_nil_type(); }
2945
2946 void
2947 do_determine_type(const Type_context*)
2948 { }
2949
2950 Expression*
2951 do_copy()
2952 { return this; }
2953
2954 tree
2955 do_get_tree(Translate_context*)
2956 { return null_pointer_node; }
2957
2958 void
2959 do_export(Export* exp) const
2960 { exp->write_c_string("nil"); }
2961
2962 void
2963 do_dump_expression(Ast_dump_context* ast_dump_context) const
2964 { ast_dump_context->ostream() << "nil"; }
2965 };
2966
2967 // Import a nil expression.
2968
2969 Expression*
2970 Nil_expression::do_import(Import* imp)
2971 {
2972 imp->require_c_string("nil");
2973 return Expression::make_nil(imp->location());
2974 }
2975
2976 // Make a nil expression.
2977
2978 Expression*
2979 Expression::make_nil(Location location)
2980 {
2981 return new Nil_expression(location);
2982 }
2983
2984 // The value of the predeclared constant iota. This is little more
2985 // than a marker. This will be lowered to an integer in
2986 // Const_expression::do_lower, which is where we know the value that
2987 // it should have.
2988
2989 class Iota_expression : public Parser_expression
2990 {
2991 public:
2992 Iota_expression(Location location)
2993 : Parser_expression(EXPRESSION_IOTA, location)
2994 { }
2995
2996 protected:
2997 Expression*
2998 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2999 { go_unreachable(); }
3000
3001 // There should only ever be one of these.
3002 Expression*
3003 do_copy()
3004 { go_unreachable(); }
3005
3006 void
3007 do_dump_expression(Ast_dump_context* ast_dump_context) const
3008 { ast_dump_context->ostream() << "iota"; }
3009 };
3010
3011 // Make an iota expression. This is only called for one case: the
3012 // value of the predeclared constant iota.
3013
3014 Expression*
3015 Expression::make_iota()
3016 {
3017 static Iota_expression iota_expression(Linemap::unknown_location());
3018 return &iota_expression;
3019 }
3020
3021 // A type conversion expression.
3022
3023 class Type_conversion_expression : public Expression
3024 {
3025 public:
3026 Type_conversion_expression(Type* type, Expression* expr,
3027 Location location)
3028 : Expression(EXPRESSION_CONVERSION, location),
3029 type_(type), expr_(expr), may_convert_function_types_(false)
3030 { }
3031
3032 // Return the type to which we are converting.
3033 Type*
3034 type() const
3035 { return this->type_; }
3036
3037 // Return the expression which we are converting.
3038 Expression*
3039 expr() const
3040 { return this->expr_; }
3041
3042 // Permit converting from one function type to another. This is
3043 // used internally for method expressions.
3044 void
3045 set_may_convert_function_types()
3046 {
3047 this->may_convert_function_types_ = true;
3048 }
3049
3050 // Import a type conversion expression.
3051 static Expression*
3052 do_import(Import*);
3053
3054 protected:
3055 int
3056 do_traverse(Traverse* traverse);
3057
3058 Expression*
3059 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3060
3061 bool
3062 do_is_constant() const;
3063
3064 bool
3065 do_numeric_constant_value(Numeric_constant*) const;
3066
3067 bool
3068 do_string_constant_value(std::string*) const;
3069
3070 Type*
3071 do_type()
3072 { return this->type_; }
3073
3074 void
3075 do_determine_type(const Type_context*)
3076 {
3077 Type_context subcontext(this->type_, false);
3078 this->expr_->determine_type(&subcontext);
3079 }
3080
3081 void
3082 do_check_types(Gogo*);
3083
3084 Expression*
3085 do_copy()
3086 {
3087 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3088 this->location());
3089 }
3090
3091 tree
3092 do_get_tree(Translate_context* context);
3093
3094 void
3095 do_export(Export*) const;
3096
3097 void
3098 do_dump_expression(Ast_dump_context*) const;
3099
3100 private:
3101 // The type to convert to.
3102 Type* type_;
3103 // The expression to convert.
3104 Expression* expr_;
3105 // True if this is permitted to convert function types. This is
3106 // used internally for method expressions.
3107 bool may_convert_function_types_;
3108 };
3109
3110 // Traversal.
3111
3112 int
3113 Type_conversion_expression::do_traverse(Traverse* traverse)
3114 {
3115 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3116 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3117 return TRAVERSE_EXIT;
3118 return TRAVERSE_CONTINUE;
3119 }
3120
3121 // Convert to a constant at lowering time.
3122
3123 Expression*
3124 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3125 Statement_inserter*, int)
3126 {
3127 Type* type = this->type_;
3128 Expression* val = this->expr_;
3129 Location location = this->location();
3130
3131 if (type->is_numeric_type())
3132 {
3133 Numeric_constant nc;
3134 if (val->numeric_constant_value(&nc))
3135 {
3136 if (!nc.set_type(type, true, location))
3137 return Expression::make_error(location);
3138 return nc.expression(location);
3139 }
3140 }
3141
3142 if (type->is_slice_type())
3143 {
3144 Type* element_type = type->array_type()->element_type()->forwarded();
3145 bool is_byte = (element_type->integer_type() != NULL
3146 && element_type->integer_type()->is_byte());
3147 bool is_rune = (element_type->integer_type() != NULL
3148 && element_type->integer_type()->is_rune());
3149 if (is_byte || is_rune)
3150 {
3151 std::string s;
3152 if (val->string_constant_value(&s))
3153 {
3154 Expression_list* vals = new Expression_list();
3155 if (is_byte)
3156 {
3157 for (std::string::const_iterator p = s.begin();
3158 p != s.end();
3159 p++)
3160 {
3161 mpz_t val;
3162 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3163 Expression* v = Expression::make_integer(&val,
3164 element_type,
3165 location);
3166 vals->push_back(v);
3167 mpz_clear(val);
3168 }
3169 }
3170 else
3171 {
3172 const char *p = s.data();
3173 const char *pend = s.data() + s.length();
3174 while (p < pend)
3175 {
3176 unsigned int c;
3177 int adv = Lex::fetch_char(p, &c);
3178 if (adv == 0)
3179 {
3180 warning_at(this->location(), 0,
3181 "invalid UTF-8 encoding");
3182 adv = 1;
3183 }
3184 p += adv;
3185 mpz_t val;
3186 mpz_init_set_ui(val, c);
3187 Expression* v = Expression::make_integer(&val,
3188 element_type,
3189 location);
3190 vals->push_back(v);
3191 mpz_clear(val);
3192 }
3193 }
3194
3195 return Expression::make_slice_composite_literal(type, vals,
3196 location);
3197 }
3198 }
3199 }
3200
3201 return this;
3202 }
3203
3204 // Return whether a type conversion is a constant.
3205
3206 bool
3207 Type_conversion_expression::do_is_constant() const
3208 {
3209 if (!this->expr_->is_constant())
3210 return false;
3211
3212 // A conversion to a type that may not be used as a constant is not
3213 // a constant. For example, []byte(nil).
3214 Type* type = this->type_;
3215 if (type->integer_type() == NULL
3216 && type->float_type() == NULL
3217 && type->complex_type() == NULL
3218 && !type->is_boolean_type()
3219 && !type->is_string_type())
3220 return false;
3221
3222 return true;
3223 }
3224
3225 // Return the constant numeric value if there is one.
3226
3227 bool
3228 Type_conversion_expression::do_numeric_constant_value(
3229 Numeric_constant* nc) const
3230 {
3231 if (!this->type_->is_numeric_type())
3232 return false;
3233 if (!this->expr_->numeric_constant_value(nc))
3234 return false;
3235 return nc->set_type(this->type_, false, this->location());
3236 }
3237
3238 // Return the constant string value if there is one.
3239
3240 bool
3241 Type_conversion_expression::do_string_constant_value(std::string* val) const
3242 {
3243 if (this->type_->is_string_type()
3244 && this->expr_->type()->integer_type() != NULL)
3245 {
3246 Numeric_constant nc;
3247 if (this->expr_->numeric_constant_value(&nc))
3248 {
3249 unsigned long ival;
3250 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3251 {
3252 val->clear();
3253 Lex::append_char(ival, true, val, this->location());
3254 return true;
3255 }
3256 }
3257 }
3258
3259 // FIXME: Could handle conversion from const []int here.
3260
3261 return false;
3262 }
3263
3264 // Check that types are convertible.
3265
3266 void
3267 Type_conversion_expression::do_check_types(Gogo*)
3268 {
3269 Type* type = this->type_;
3270 Type* expr_type = this->expr_->type();
3271 std::string reason;
3272
3273 if (type->is_error() || expr_type->is_error())
3274 {
3275 this->set_is_error();
3276 return;
3277 }
3278
3279 if (this->may_convert_function_types_
3280 && type->function_type() != NULL
3281 && expr_type->function_type() != NULL)
3282 return;
3283
3284 if (Type::are_convertible(type, expr_type, &reason))
3285 return;
3286
3287 error_at(this->location(), "%s", reason.c_str());
3288 this->set_is_error();
3289 }
3290
3291 // Get a tree for a type conversion.
3292
3293 tree
3294 Type_conversion_expression::do_get_tree(Translate_context* context)
3295 {
3296 Gogo* gogo = context->gogo();
3297 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3298 tree expr_tree = this->expr_->get_tree(context);
3299
3300 if (type_tree == error_mark_node
3301 || expr_tree == error_mark_node
3302 || TREE_TYPE(expr_tree) == error_mark_node)
3303 return error_mark_node;
3304
3305 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3306 return fold_convert(type_tree, expr_tree);
3307
3308 Type* type = this->type_;
3309 Type* expr_type = this->expr_->type();
3310 tree ret;
3311 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3312 ret = Expression::convert_for_assignment(context, type, expr_type,
3313 expr_tree, this->location());
3314 else if (type->integer_type() != NULL)
3315 {
3316 if (expr_type->integer_type() != NULL
3317 || expr_type->float_type() != NULL
3318 || expr_type->is_unsafe_pointer_type())
3319 ret = fold(convert_to_integer(type_tree, expr_tree));
3320 else
3321 go_unreachable();
3322 }
3323 else if (type->float_type() != NULL)
3324 {
3325 if (expr_type->integer_type() != NULL
3326 || expr_type->float_type() != NULL)
3327 ret = fold(convert_to_real(type_tree, expr_tree));
3328 else
3329 go_unreachable();
3330 }
3331 else if (type->complex_type() != NULL)
3332 {
3333 if (expr_type->complex_type() != NULL)
3334 ret = fold(convert_to_complex(type_tree, expr_tree));
3335 else
3336 go_unreachable();
3337 }
3338 else if (type->is_string_type()
3339 && expr_type->integer_type() != NULL)
3340 {
3341 Type* int_type = Type::lookup_integer_type("int");
3342 tree int_type_tree = type_to_tree(int_type->get_backend(gogo));
3343
3344 expr_tree = fold_convert(int_type_tree, expr_tree);
3345 if (host_integerp(expr_tree, 0))
3346 {
3347 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3348 std::string s;
3349 Lex::append_char(intval, true, &s, this->location());
3350 Expression* se = Expression::make_string(s, this->location());
3351 return se->get_tree(context);
3352 }
3353
3354 Expression* i2s_expr =
3355 Runtime::make_call(Runtime::INT_TO_STRING, this->location(), 1,
3356 this->expr_);
3357 i2s_expr = Expression::make_cast(type, i2s_expr, this->location());
3358 ret = i2s_expr->get_tree(context);
3359 }
3360 else if (type->is_string_type() && expr_type->is_slice_type())
3361 {
3362 if (!DECL_P(expr_tree))
3363 expr_tree = save_expr(expr_tree);
3364
3365 Type* int_type = Type::lookup_integer_type("int");
3366 tree int_type_tree = type_to_tree(int_type->get_backend(gogo));
3367
3368 Array_type* a = expr_type->array_type();
3369 Type* e = a->element_type()->forwarded();
3370 go_assert(e->integer_type() != NULL);
3371 tree valptr = fold_convert(const_ptr_type_node,
3372 a->value_pointer_tree(gogo, expr_tree));
3373 tree len = a->length_tree(gogo, expr_tree);
3374 len = fold_convert_loc(this->location().gcc_location(), int_type_tree,
3375 len);
3376 if (e->integer_type()->is_byte())
3377 {
3378 static tree byte_array_to_string_fndecl;
3379 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3380 this->location(),
3381 "__go_byte_array_to_string",
3382 2,
3383 type_tree,
3384 const_ptr_type_node,
3385 valptr,
3386 int_type_tree,
3387 len);
3388 }
3389 else
3390 {
3391 go_assert(e->integer_type()->is_rune());
3392 static tree int_array_to_string_fndecl;
3393 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3394 this->location(),
3395 "__go_int_array_to_string",
3396 2,
3397 type_tree,
3398 const_ptr_type_node,
3399 valptr,
3400 int_type_tree,
3401 len);
3402 }
3403 }
3404 else if (type->is_slice_type() && expr_type->is_string_type())
3405 {
3406 Type* e = type->array_type()->element_type()->forwarded();
3407 go_assert(e->integer_type() != NULL);
3408
3409 Expression* s2a_expr;
3410 if (e->integer_type()->is_byte())
3411 s2a_expr = Runtime::make_call(Runtime::STRING_TO_BYTE_ARRAY,
3412 this->location(), 1, this->expr_);
3413 else
3414 {
3415 go_assert(e->integer_type()->is_rune());
3416 s2a_expr = Runtime::make_call(Runtime::STRING_TO_INT_ARRAY,
3417 this->location(), 1, this->expr_);
3418 }
3419 s2a_expr = Expression::make_unsafe_cast(type, s2a_expr,
3420 this->location());
3421 ret = s2a_expr->get_tree(context);
3422 }
3423 else if ((type->is_unsafe_pointer_type()
3424 && expr_type->points_to() != NULL)
3425 || (expr_type->is_unsafe_pointer_type()
3426 && type->points_to() != NULL))
3427 ret = fold_convert(type_tree, expr_tree);
3428 else if (type->is_unsafe_pointer_type()
3429 && expr_type->integer_type() != NULL)
3430 ret = convert_to_pointer(type_tree, expr_tree);
3431 else if (this->may_convert_function_types_
3432 && type->function_type() != NULL
3433 && expr_type->function_type() != NULL)
3434 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3435 expr_tree);
3436 else
3437 ret = Expression::convert_for_assignment(context, type, expr_type,
3438 expr_tree, this->location());
3439
3440 return ret;
3441 }
3442
3443 // Output a type conversion in a constant expression.
3444
3445 void
3446 Type_conversion_expression::do_export(Export* exp) const
3447 {
3448 exp->write_c_string("convert(");
3449 exp->write_type(this->type_);
3450 exp->write_c_string(", ");
3451 this->expr_->export_expression(exp);
3452 exp->write_c_string(")");
3453 }
3454
3455 // Import a type conversion or a struct construction.
3456
3457 Expression*
3458 Type_conversion_expression::do_import(Import* imp)
3459 {
3460 imp->require_c_string("convert(");
3461 Type* type = imp->read_type();
3462 imp->require_c_string(", ");
3463 Expression* val = Expression::import_expression(imp);
3464 imp->require_c_string(")");
3465 return Expression::make_cast(type, val, imp->location());
3466 }
3467
3468 // Dump ast representation for a type conversion expression.
3469
3470 void
3471 Type_conversion_expression::do_dump_expression(
3472 Ast_dump_context* ast_dump_context) const
3473 {
3474 ast_dump_context->dump_type(this->type_);
3475 ast_dump_context->ostream() << "(";
3476 ast_dump_context->dump_expression(this->expr_);
3477 ast_dump_context->ostream() << ") ";
3478 }
3479
3480 // Make a type cast expression.
3481
3482 Expression*
3483 Expression::make_cast(Type* type, Expression* val, Location location)
3484 {
3485 if (type->is_error_type() || val->is_error_expression())
3486 return Expression::make_error(location);
3487 return new Type_conversion_expression(type, val, location);
3488 }
3489
3490 // An unsafe type conversion, used to pass values to builtin functions.
3491
3492 class Unsafe_type_conversion_expression : public Expression
3493 {
3494 public:
3495 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3496 Location location)
3497 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3498 type_(type), expr_(expr)
3499 { }
3500
3501 protected:
3502 int
3503 do_traverse(Traverse* traverse);
3504
3505 Type*
3506 do_type()
3507 { return this->type_; }
3508
3509 void
3510 do_determine_type(const Type_context*)
3511 { this->expr_->determine_type_no_context(); }
3512
3513 Expression*
3514 do_copy()
3515 {
3516 return new Unsafe_type_conversion_expression(this->type_,
3517 this->expr_->copy(),
3518 this->location());
3519 }
3520
3521 tree
3522 do_get_tree(Translate_context*);
3523
3524 void
3525 do_dump_expression(Ast_dump_context*) const;
3526
3527 private:
3528 // The type to convert to.
3529 Type* type_;
3530 // The expression to convert.
3531 Expression* expr_;
3532 };
3533
3534 // Traversal.
3535
3536 int
3537 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3538 {
3539 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3540 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3541 return TRAVERSE_EXIT;
3542 return TRAVERSE_CONTINUE;
3543 }
3544
3545 // Convert to backend representation.
3546
3547 tree
3548 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3549 {
3550 // We are only called for a limited number of cases.
3551
3552 Type* t = this->type_;
3553 Type* et = this->expr_->type();
3554
3555 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3556 tree expr_tree = this->expr_->get_tree(context);
3557 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3558 return error_mark_node;
3559
3560 Location loc = this->location();
3561
3562 bool use_view_convert = false;
3563 if (t->is_slice_type())
3564 {
3565 go_assert(et->is_slice_type());
3566 use_view_convert = true;
3567 }
3568 else if (t->map_type() != NULL)
3569 go_assert(et->map_type() != NULL);
3570 else if (t->channel_type() != NULL)
3571 go_assert(et->channel_type() != NULL);
3572 else if (t->points_to() != NULL)
3573 go_assert(et->points_to() != NULL || et->is_nil_type());
3574 else if (et->is_unsafe_pointer_type())
3575 go_assert(t->points_to() != NULL);
3576 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3577 {
3578 go_assert(et->interface_type() != NULL
3579 && !et->interface_type()->is_empty());
3580 use_view_convert = true;
3581 }
3582 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3583 {
3584 go_assert(et->interface_type() != NULL
3585 && et->interface_type()->is_empty());
3586 use_view_convert = true;
3587 }
3588 else if (t->integer_type() != NULL)
3589 {
3590 go_assert(et->is_boolean_type()
3591 || et->integer_type() != NULL
3592 || et->function_type() != NULL
3593 || et->points_to() != NULL
3594 || et->map_type() != NULL
3595 || et->channel_type() != NULL);
3596 return convert_to_integer(type_tree, expr_tree);
3597 }
3598 else
3599 go_unreachable();
3600
3601 if (use_view_convert)
3602 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3603 expr_tree);
3604 else
3605 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3606 }
3607
3608 // Dump ast representation for an unsafe type conversion expression.
3609
3610 void
3611 Unsafe_type_conversion_expression::do_dump_expression(
3612 Ast_dump_context* ast_dump_context) const
3613 {
3614 ast_dump_context->dump_type(this->type_);
3615 ast_dump_context->ostream() << "(";
3616 ast_dump_context->dump_expression(this->expr_);
3617 ast_dump_context->ostream() << ") ";
3618 }
3619
3620 // Make an unsafe type conversion expression.
3621
3622 Expression*
3623 Expression::make_unsafe_cast(Type* type, Expression* expr,
3624 Location location)
3625 {
3626 return new Unsafe_type_conversion_expression(type, expr, location);
3627 }
3628
3629 // Unary expressions.
3630
3631 class Unary_expression : public Expression
3632 {
3633 public:
3634 Unary_expression(Operator op, Expression* expr, Location location)
3635 : Expression(EXPRESSION_UNARY, location),
3636 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3637 { }
3638
3639 // Return the operator.
3640 Operator
3641 op() const
3642 { return this->op_; }
3643
3644 // Return the operand.
3645 Expression*
3646 operand() const
3647 { return this->expr_; }
3648
3649 // Record that an address expression does not escape.
3650 void
3651 set_does_not_escape()
3652 {
3653 go_assert(this->op_ == OPERATOR_AND);
3654 this->escapes_ = false;
3655 }
3656
3657 // Record that this is an address expression which should create a
3658 // temporary variable if necessary. This is used for method calls.
3659 void
3660 set_create_temp()
3661 {
3662 go_assert(this->op_ == OPERATOR_AND);
3663 this->create_temp_ = true;
3664 }
3665
3666 // Apply unary opcode OP to UNC, setting NC. Return true if this
3667 // could be done, false if not. Issue errors for overflow.
3668 static bool
3669 eval_constant(Operator op, const Numeric_constant* unc,
3670 Location, Numeric_constant* nc);
3671
3672 static Expression*
3673 do_import(Import*);
3674
3675 protected:
3676 int
3677 do_traverse(Traverse* traverse)
3678 { return Expression::traverse(&this->expr_, traverse); }
3679
3680 Expression*
3681 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3682
3683 bool
3684 do_is_constant() const;
3685
3686 bool
3687 do_numeric_constant_value(Numeric_constant*) const;
3688
3689 Type*
3690 do_type();
3691
3692 void
3693 do_determine_type(const Type_context*);
3694
3695 void
3696 do_check_types(Gogo*);
3697
3698 Expression*
3699 do_copy()
3700 {
3701 return Expression::make_unary(this->op_, this->expr_->copy(),
3702 this->location());
3703 }
3704
3705 bool
3706 do_must_eval_subexpressions_in_order(int*) const
3707 { return this->op_ == OPERATOR_MULT; }
3708
3709 bool
3710 do_is_addressable() const
3711 { return this->op_ == OPERATOR_MULT; }
3712
3713 tree
3714 do_get_tree(Translate_context*);
3715
3716 void
3717 do_export(Export*) const;
3718
3719 void
3720 do_dump_expression(Ast_dump_context*) const;
3721
3722 private:
3723 // The unary operator to apply.
3724 Operator op_;
3725 // Normally true. False if this is an address expression which does
3726 // not escape the current function.
3727 bool escapes_;
3728 // True if this is an address expression which should create a
3729 // temporary variable if necessary.
3730 bool create_temp_;
3731 // The operand.
3732 Expression* expr_;
3733 };
3734
3735 // If we are taking the address of a composite literal, and the
3736 // contents are not constant, then we want to make a heap composite
3737 // instead.
3738
3739 Expression*
3740 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3741 {
3742 Location loc = this->location();
3743 Operator op = this->op_;
3744 Expression* expr = this->expr_;
3745
3746 if (op == OPERATOR_MULT && expr->is_type_expression())
3747 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3748
3749 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3750 // moving x to the heap. FIXME: Is it worth doing a real escape
3751 // analysis here? This case is found in math/unsafe.go and is
3752 // therefore worth special casing.
3753 if (op == OPERATOR_MULT)
3754 {
3755 Expression* e = expr;
3756 while (e->classification() == EXPRESSION_CONVERSION)
3757 {
3758 Type_conversion_expression* te
3759 = static_cast<Type_conversion_expression*>(e);
3760 e = te->expr();
3761 }
3762
3763 if (e->classification() == EXPRESSION_UNARY)
3764 {
3765 Unary_expression* ue = static_cast<Unary_expression*>(e);
3766 if (ue->op_ == OPERATOR_AND)
3767 {
3768 if (e == expr)
3769 {
3770 // *&x == x.
3771 return ue->expr_;
3772 }
3773 ue->set_does_not_escape();
3774 }
3775 }
3776 }
3777
3778 // Catching an invalid indirection of unsafe.Pointer here avoid
3779 // having to deal with TYPE_VOID in other places.
3780 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3781 {
3782 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3783 return Expression::make_error(this->location());
3784 }
3785
3786 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3787 {
3788 Numeric_constant nc;
3789 if (expr->numeric_constant_value(&nc))
3790 {
3791 Numeric_constant result;
3792 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3793 return result.expression(loc);
3794 }
3795 }
3796
3797 return this;
3798 }
3799
3800 // Return whether a unary expression is a constant.
3801
3802 bool
3803 Unary_expression::do_is_constant() const
3804 {
3805 if (this->op_ == OPERATOR_MULT)
3806 {
3807 // Indirecting through a pointer is only constant if the object
3808 // to which the expression points is constant, but we currently
3809 // have no way to determine that.
3810 return false;
3811 }
3812 else if (this->op_ == OPERATOR_AND)
3813 {
3814 // Taking the address of a variable is constant if it is a
3815 // global variable, not constant otherwise. In other cases
3816 // taking the address is probably not a constant.
3817 Var_expression* ve = this->expr_->var_expression();
3818 if (ve != NULL)
3819 {
3820 Named_object* no = ve->named_object();
3821 return no->is_variable() && no->var_value()->is_global();
3822 }
3823 return false;
3824 }
3825 else
3826 return this->expr_->is_constant();
3827 }
3828
3829 // Apply unary opcode OP to UNC, setting NC. Return true if this
3830 // could be done, false if not. Issue errors for overflow.
3831
3832 bool
3833 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3834 Location location, Numeric_constant* nc)
3835 {
3836 switch (op)
3837 {
3838 case OPERATOR_PLUS:
3839 *nc = *unc;
3840 return true;
3841
3842 case OPERATOR_MINUS:
3843 if (unc->is_int() || unc->is_rune())
3844 break;
3845 else if (unc->is_float())
3846 {
3847 mpfr_t uval;
3848 unc->get_float(&uval);
3849 mpfr_t val;
3850 mpfr_init(val);
3851 mpfr_neg(val, uval, GMP_RNDN);
3852 nc->set_float(unc->type(), val);
3853 mpfr_clear(uval);
3854 mpfr_clear(val);
3855 return true;
3856 }
3857 else if (unc->is_complex())
3858 {
3859 mpfr_t ureal, uimag;
3860 unc->get_complex(&ureal, &uimag);
3861 mpfr_t real, imag;
3862 mpfr_init(real);
3863 mpfr_init(imag);
3864 mpfr_neg(real, ureal, GMP_RNDN);
3865 mpfr_neg(imag, uimag, GMP_RNDN);
3866 nc->set_complex(unc->type(), real, imag);
3867 mpfr_clear(ureal);
3868 mpfr_clear(uimag);
3869 mpfr_clear(real);
3870 mpfr_clear(imag);
3871 return true;
3872 }
3873 else
3874 go_unreachable();
3875
3876 case OPERATOR_XOR:
3877 break;
3878
3879 case OPERATOR_NOT:
3880 case OPERATOR_AND:
3881 case OPERATOR_MULT:
3882 return false;
3883
3884 default:
3885 go_unreachable();
3886 }
3887
3888 if (!unc->is_int() && !unc->is_rune())
3889 return false;
3890
3891 mpz_t uval;
3892 if (unc->is_rune())
3893 unc->get_rune(&uval);
3894 else
3895 unc->get_int(&uval);
3896 mpz_t val;
3897 mpz_init(val);
3898
3899 switch (op)
3900 {
3901 case OPERATOR_MINUS:
3902 mpz_neg(val, uval);
3903 break;
3904
3905 case OPERATOR_NOT:
3906 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3907 break;
3908
3909 case OPERATOR_XOR:
3910 {
3911 Type* utype = unc->type();
3912 if (utype->integer_type() == NULL
3913 || utype->integer_type()->is_abstract())
3914 mpz_com(val, uval);
3915 else
3916 {
3917 // The number of HOST_WIDE_INTs that it takes to represent
3918 // UVAL.
3919 size_t count = ((mpz_sizeinbase(uval, 2)
3920 + HOST_BITS_PER_WIDE_INT
3921 - 1)
3922 / HOST_BITS_PER_WIDE_INT);
3923
3924 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3925 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3926
3927 size_t obits = utype->integer_type()->bits();
3928
3929 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3930 {
3931 mpz_t adj;
3932 mpz_init_set_ui(adj, 1);
3933 mpz_mul_2exp(adj, adj, obits);
3934 mpz_add(uval, uval, adj);
3935 mpz_clear(adj);
3936 }
3937
3938 size_t ecount;
3939 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3940 go_assert(ecount <= count);
3941
3942 // Trim down to the number of words required by the type.
3943 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3944 / HOST_BITS_PER_WIDE_INT);
3945 go_assert(ocount <= count);
3946
3947 for (size_t i = 0; i < ocount; ++i)
3948 phwi[i] = ~phwi[i];
3949
3950 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3951 if (clearbits != 0)
3952 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3953 >> clearbits);
3954
3955 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3956
3957 if (!utype->integer_type()->is_unsigned()
3958 && mpz_tstbit(val, obits - 1))
3959 {
3960 mpz_t adj;
3961 mpz_init_set_ui(adj, 1);
3962 mpz_mul_2exp(adj, adj, obits);
3963 mpz_sub(val, val, adj);
3964 mpz_clear(adj);
3965 }
3966
3967 delete[] phwi;
3968 }
3969 }
3970 break;
3971
3972 default:
3973 go_unreachable();
3974 }
3975
3976 if (unc->is_rune())
3977 nc->set_rune(NULL, val);
3978 else
3979 nc->set_int(NULL, val);
3980
3981 mpz_clear(uval);
3982 mpz_clear(val);
3983
3984 return nc->set_type(unc->type(), true, location);
3985 }
3986
3987 // Return the integral constant value of a unary expression, if it has one.
3988
3989 bool
3990 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3991 {
3992 Numeric_constant unc;
3993 if (!this->expr_->numeric_constant_value(&unc))
3994 return false;
3995 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3996 nc);
3997 }
3998
3999 // Return the type of a unary expression.
4000
4001 Type*
4002 Unary_expression::do_type()
4003 {
4004 switch (this->op_)
4005 {
4006 case OPERATOR_PLUS:
4007 case OPERATOR_MINUS:
4008 case OPERATOR_NOT:
4009 case OPERATOR_XOR:
4010 return this->expr_->type();
4011
4012 case OPERATOR_AND:
4013 return Type::make_pointer_type(this->expr_->type());
4014
4015 case OPERATOR_MULT:
4016 {
4017 Type* subtype = this->expr_->type();
4018 Type* points_to = subtype->points_to();
4019 if (points_to == NULL)
4020 return Type::make_error_type();
4021 return points_to;
4022 }
4023
4024 default:
4025 go_unreachable();
4026 }
4027 }
4028
4029 // Determine abstract types for a unary expression.
4030
4031 void
4032 Unary_expression::do_determine_type(const Type_context* context)
4033 {
4034 switch (this->op_)
4035 {
4036 case OPERATOR_PLUS:
4037 case OPERATOR_MINUS:
4038 case OPERATOR_NOT:
4039 case OPERATOR_XOR:
4040 this->expr_->determine_type(context);
4041 break;
4042
4043 case OPERATOR_AND:
4044 // Taking the address of something.
4045 {
4046 Type* subtype = (context->type == NULL
4047 ? NULL
4048 : context->type->points_to());
4049 Type_context subcontext(subtype, false);
4050 this->expr_->determine_type(&subcontext);
4051 }
4052 break;
4053
4054 case OPERATOR_MULT:
4055 // Indirecting through a pointer.
4056 {
4057 Type* subtype = (context->type == NULL
4058 ? NULL
4059 : Type::make_pointer_type(context->type));
4060 Type_context subcontext(subtype, false);
4061 this->expr_->determine_type(&subcontext);
4062 }
4063 break;
4064
4065 default:
4066 go_unreachable();
4067 }
4068 }
4069
4070 // Check types for a unary expression.
4071
4072 void
4073 Unary_expression::do_check_types(Gogo*)
4074 {
4075 Type* type = this->expr_->type();
4076 if (type->is_error())
4077 {
4078 this->set_is_error();
4079 return;
4080 }
4081
4082 switch (this->op_)
4083 {
4084 case OPERATOR_PLUS:
4085 case OPERATOR_MINUS:
4086 if (type->integer_type() == NULL
4087 && type->float_type() == NULL
4088 && type->complex_type() == NULL)
4089 this->report_error(_("expected numeric type"));
4090 break;
4091
4092 case OPERATOR_NOT:
4093 if (!type->is_boolean_type())
4094 this->report_error(_("expected boolean type"));
4095 break;
4096
4097 case OPERATOR_XOR:
4098 if (type->integer_type() == NULL
4099 && !type->is_boolean_type())
4100 this->report_error(_("expected integer or boolean type"));
4101 break;
4102
4103 case OPERATOR_AND:
4104 if (!this->expr_->is_addressable())
4105 {
4106 if (!this->create_temp_)
4107 this->report_error(_("invalid operand for unary %<&%>"));
4108 }
4109 else
4110 this->expr_->address_taken(this->escapes_);
4111 break;
4112
4113 case OPERATOR_MULT:
4114 // Indirecting through a pointer.
4115 if (type->points_to() == NULL)
4116 this->report_error(_("expected pointer"));
4117 break;
4118
4119 default:
4120 go_unreachable();
4121 }
4122 }
4123
4124 // Get a tree for a unary expression.
4125
4126 tree
4127 Unary_expression::do_get_tree(Translate_context* context)
4128 {
4129 Gogo* gogo = context->gogo();
4130 Location loc = this->location();
4131
4132 // Taking the address of a set-and-use-temporary expression requires
4133 // setting the temporary and then taking the address.
4134 if (this->op_ == OPERATOR_AND)
4135 {
4136 Set_and_use_temporary_expression* sut =
4137 this->expr_->set_and_use_temporary_expression();
4138 if (sut != NULL)
4139 {
4140 Temporary_statement* temp = sut->temporary();
4141 Bvariable* bvar = temp->get_backend_variable(context);
4142 tree var_tree = var_to_tree(bvar);
4143 Expression* val = sut->expression();
4144 tree val_tree = val->get_tree(context);
4145 if (var_tree == error_mark_node || val_tree == error_mark_node)
4146 return error_mark_node;
4147 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
4148 var_tree);
4149 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4150 TREE_TYPE(addr_tree),
4151 build2_loc(sut->location().gcc_location(),
4152 MODIFY_EXPR, void_type_node,
4153 var_tree, val_tree),
4154 addr_tree);
4155 }
4156 }
4157
4158 tree expr = this->expr_->get_tree(context);
4159 if (expr == error_mark_node)
4160 return error_mark_node;
4161
4162 switch (this->op_)
4163 {
4164 case OPERATOR_PLUS:
4165 return expr;
4166
4167 case OPERATOR_MINUS:
4168 {
4169 tree type = TREE_TYPE(expr);
4170 tree compute_type = excess_precision_type(type);
4171 if (compute_type != NULL_TREE)
4172 expr = ::convert(compute_type, expr);
4173 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
4174 (compute_type != NULL_TREE
4175 ? compute_type
4176 : type),
4177 expr);
4178 if (compute_type != NULL_TREE)
4179 ret = ::convert(type, ret);
4180 return ret;
4181 }
4182
4183 case OPERATOR_NOT:
4184 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
4185 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4186 TREE_TYPE(expr), expr);
4187 else
4188 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4189 expr, build_int_cst(TREE_TYPE(expr), 0));
4190
4191 case OPERATOR_XOR:
4192 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4193 expr);
4194
4195 case OPERATOR_AND:
4196 if (!this->create_temp_)
4197 {
4198 // We should not see a non-constant constructor here; cases
4199 // where we would see one should have been moved onto the
4200 // heap at parse time. Taking the address of a nonconstant
4201 // constructor will not do what the programmer expects.
4202 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4203 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4204 }
4205
4206 // Build a decl for a constant constructor.
4207 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4208 {
4209 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4210 create_tmp_var_name("C"), TREE_TYPE(expr));
4211 DECL_EXTERNAL(decl) = 0;
4212 TREE_PUBLIC(decl) = 0;
4213 TREE_READONLY(decl) = 1;
4214 TREE_CONSTANT(decl) = 1;
4215 TREE_STATIC(decl) = 1;
4216 TREE_ADDRESSABLE(decl) = 1;
4217 DECL_ARTIFICIAL(decl) = 1;
4218 DECL_INITIAL(decl) = expr;
4219 rest_of_decl_compilation(decl, 1, 0);
4220 expr = decl;
4221 }
4222
4223 if (this->create_temp_
4224 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4225 && (TREE_CODE(expr) == CONST_DECL || !DECL_P(expr))
4226 && TREE_CODE(expr) != INDIRECT_REF
4227 && TREE_CODE(expr) != COMPONENT_REF)
4228 {
4229 if (current_function_decl != NULL)
4230 {
4231 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4232 DECL_IGNORED_P(tmp) = 1;
4233 DECL_INITIAL(tmp) = expr;
4234 TREE_ADDRESSABLE(tmp) = 1;
4235 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4236 build_pointer_type(TREE_TYPE(expr)),
4237 build1_loc(loc.gcc_location(), DECL_EXPR,
4238 void_type_node, tmp),
4239 build_fold_addr_expr_loc(loc.gcc_location(),
4240 tmp));
4241 }
4242 else
4243 {
4244 tree tmp = build_decl(loc.gcc_location(), VAR_DECL,
4245 create_tmp_var_name("A"), TREE_TYPE(expr));
4246 DECL_EXTERNAL(tmp) = 0;
4247 TREE_PUBLIC(tmp) = 0;
4248 TREE_STATIC(tmp) = 1;
4249 DECL_ARTIFICIAL(tmp) = 1;
4250 TREE_ADDRESSABLE(tmp) = 1;
4251 tree make_tmp;
4252 if (!TREE_CONSTANT(expr))
4253 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
4254 void_type_node, tmp, expr);
4255 else
4256 {
4257 TREE_READONLY(tmp) = 1;
4258 TREE_CONSTANT(tmp) = 1;
4259 DECL_INITIAL(tmp) = expr;
4260 make_tmp = NULL_TREE;
4261 }
4262 rest_of_decl_compilation(tmp, 1, 0);
4263 tree addr = build_fold_addr_expr_loc(loc.gcc_location(), tmp);
4264 if (make_tmp == NULL_TREE)
4265 return addr;
4266 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4267 TREE_TYPE(addr), make_tmp, addr);
4268 }
4269 }
4270
4271 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4272
4273 case OPERATOR_MULT:
4274 {
4275 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4276
4277 // If we are dereferencing the pointer to a large struct, we
4278 // need to check for nil. We don't bother to check for small
4279 // structs because we expect the system to crash on a nil
4280 // pointer dereference.
4281 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4282 if (!VOID_TYPE_P(target_type_tree))
4283 {
4284 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4285 if (s == -1 || s >= 4096)
4286 {
4287 if (!DECL_P(expr))
4288 expr = save_expr(expr);
4289 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4290 boolean_type_node,
4291 expr,
4292 fold_convert(TREE_TYPE(expr),
4293 null_pointer_node));
4294 tree crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4295 loc);
4296 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4297 TREE_TYPE(expr), build3(COND_EXPR,
4298 void_type_node,
4299 compare, crash,
4300 NULL_TREE),
4301 expr);
4302 }
4303 }
4304
4305 // If the type of EXPR is a recursive pointer type, then we
4306 // need to insert a cast before indirecting.
4307 if (VOID_TYPE_P(target_type_tree))
4308 {
4309 Type* pt = this->expr_->type()->points_to();
4310 tree ind = type_to_tree(pt->get_backend(gogo));
4311 expr = fold_convert_loc(loc.gcc_location(),
4312 build_pointer_type(ind), expr);
4313 }
4314
4315 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4316 }
4317
4318 default:
4319 go_unreachable();
4320 }
4321 }
4322
4323 // Export a unary expression.
4324
4325 void
4326 Unary_expression::do_export(Export* exp) const
4327 {
4328 switch (this->op_)
4329 {
4330 case OPERATOR_PLUS:
4331 exp->write_c_string("+ ");
4332 break;
4333 case OPERATOR_MINUS:
4334 exp->write_c_string("- ");
4335 break;
4336 case OPERATOR_NOT:
4337 exp->write_c_string("! ");
4338 break;
4339 case OPERATOR_XOR:
4340 exp->write_c_string("^ ");
4341 break;
4342 case OPERATOR_AND:
4343 case OPERATOR_MULT:
4344 default:
4345 go_unreachable();
4346 }
4347 this->expr_->export_expression(exp);
4348 }
4349
4350 // Import a unary expression.
4351
4352 Expression*
4353 Unary_expression::do_import(Import* imp)
4354 {
4355 Operator op;
4356 switch (imp->get_char())
4357 {
4358 case '+':
4359 op = OPERATOR_PLUS;
4360 break;
4361 case '-':
4362 op = OPERATOR_MINUS;
4363 break;
4364 case '!':
4365 op = OPERATOR_NOT;
4366 break;
4367 case '^':
4368 op = OPERATOR_XOR;
4369 break;
4370 default:
4371 go_unreachable();
4372 }
4373 imp->require_c_string(" ");
4374 Expression* expr = Expression::import_expression(imp);
4375 return Expression::make_unary(op, expr, imp->location());
4376 }
4377
4378 // Dump ast representation of an unary expression.
4379
4380 void
4381 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4382 {
4383 ast_dump_context->dump_operator(this->op_);
4384 ast_dump_context->ostream() << "(";
4385 ast_dump_context->dump_expression(this->expr_);
4386 ast_dump_context->ostream() << ") ";
4387 }
4388
4389 // Make a unary expression.
4390
4391 Expression*
4392 Expression::make_unary(Operator op, Expression* expr, Location location)
4393 {
4394 return new Unary_expression(op, expr, location);
4395 }
4396
4397 // If this is an indirection through a pointer, return the expression
4398 // being pointed through. Otherwise return this.
4399
4400 Expression*
4401 Expression::deref()
4402 {
4403 if (this->classification_ == EXPRESSION_UNARY)
4404 {
4405 Unary_expression* ue = static_cast<Unary_expression*>(this);
4406 if (ue->op() == OPERATOR_MULT)
4407 return ue->operand();
4408 }
4409 return this;
4410 }
4411
4412 // Class Binary_expression.
4413
4414 // Traversal.
4415
4416 int
4417 Binary_expression::do_traverse(Traverse* traverse)
4418 {
4419 int t = Expression::traverse(&this->left_, traverse);
4420 if (t == TRAVERSE_EXIT)
4421 return TRAVERSE_EXIT;
4422 return Expression::traverse(&this->right_, traverse);
4423 }
4424
4425 // Return the type to use for a binary operation on operands of
4426 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4427 // such may be NULL or abstract.
4428
4429 bool
4430 Binary_expression::operation_type(Operator op, Type* left_type,
4431 Type* right_type, Type** result_type)
4432 {
4433 if (left_type != right_type
4434 && !left_type->is_abstract()
4435 && !right_type->is_abstract()
4436 && left_type->base() != right_type->base()
4437 && op != OPERATOR_LSHIFT
4438 && op != OPERATOR_RSHIFT)
4439 {
4440 // May be a type error--let it be diagnosed elsewhere.
4441 return false;
4442 }
4443
4444 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4445 {
4446 if (left_type->integer_type() != NULL)
4447 *result_type = left_type;
4448 else
4449 *result_type = Type::make_abstract_integer_type();
4450 }
4451 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4452 *result_type = left_type;
4453 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4454 *result_type = right_type;
4455 else if (!left_type->is_abstract())
4456 *result_type = left_type;
4457 else if (!right_type->is_abstract())
4458 *result_type = right_type;
4459 else if (left_type->complex_type() != NULL)
4460 *result_type = left_type;
4461 else if (right_type->complex_type() != NULL)
4462 *result_type = right_type;
4463 else if (left_type->float_type() != NULL)
4464 *result_type = left_type;
4465 else if (right_type->float_type() != NULL)
4466 *result_type = right_type;
4467 else if (left_type->integer_type() != NULL
4468 && left_type->integer_type()->is_rune())
4469 *result_type = left_type;
4470 else if (right_type->integer_type() != NULL
4471 && right_type->integer_type()->is_rune())
4472 *result_type = right_type;
4473 else
4474 *result_type = left_type;
4475
4476 return true;
4477 }
4478
4479 // Convert an integer comparison code and an operator to a boolean
4480 // value.
4481
4482 bool
4483 Binary_expression::cmp_to_bool(Operator op, int cmp)
4484 {
4485 switch (op)
4486 {
4487 case OPERATOR_EQEQ:
4488 return cmp == 0;
4489 break;
4490 case OPERATOR_NOTEQ:
4491 return cmp != 0;
4492 break;
4493 case OPERATOR_LT:
4494 return cmp < 0;
4495 break;
4496 case OPERATOR_LE:
4497 return cmp <= 0;
4498 case OPERATOR_GT:
4499 return cmp > 0;
4500 case OPERATOR_GE:
4501 return cmp >= 0;
4502 default:
4503 go_unreachable();
4504 }
4505 }
4506
4507 // Compare constants according to OP.
4508
4509 bool
4510 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4511 Numeric_constant* right_nc,
4512 Location location, bool* result)
4513 {
4514 Type* left_type = left_nc->type();
4515 Type* right_type = right_nc->type();
4516
4517 Type* type;
4518 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4519 return false;
4520
4521 // When comparing an untyped operand to a typed operand, we are
4522 // effectively coercing the untyped operand to the other operand's
4523 // type, so make sure that is valid.
4524 if (!left_nc->set_type(type, true, location)
4525 || !right_nc->set_type(type, true, location))
4526 return false;
4527
4528 bool ret;
4529 int cmp;
4530 if (type->complex_type() != NULL)
4531 {
4532 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4533 return false;
4534 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4535 }
4536 else if (type->float_type() != NULL)
4537 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4538 else
4539 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4540
4541 if (ret)
4542 *result = Binary_expression::cmp_to_bool(op, cmp);
4543
4544 return ret;
4545 }
4546
4547 // Compare integer constants.
4548
4549 bool
4550 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4551 const Numeric_constant* right_nc,
4552 int* cmp)
4553 {
4554 mpz_t left_val;
4555 if (!left_nc->to_int(&left_val))
4556 return false;
4557 mpz_t right_val;
4558 if (!right_nc->to_int(&right_val))
4559 {
4560 mpz_clear(left_val);
4561 return false;
4562 }
4563
4564 *cmp = mpz_cmp(left_val, right_val);
4565
4566 mpz_clear(left_val);
4567 mpz_clear(right_val);
4568
4569 return true;
4570 }
4571
4572 // Compare floating point constants.
4573
4574 bool
4575 Binary_expression::compare_float(const Numeric_constant* left_nc,
4576 const Numeric_constant* right_nc,
4577 int* cmp)
4578 {
4579 mpfr_t left_val;
4580 if (!left_nc->to_float(&left_val))
4581 return false;
4582 mpfr_t right_val;
4583 if (!right_nc->to_float(&right_val))
4584 {
4585 mpfr_clear(left_val);
4586 return false;
4587 }
4588
4589 // We already coerced both operands to the same type. If that type
4590 // is not an abstract type, we need to round the values accordingly.
4591 Type* type = left_nc->type();
4592 if (!type->is_abstract() && type->float_type() != NULL)
4593 {
4594 int bits = type->float_type()->bits();
4595 mpfr_prec_round(left_val, bits, GMP_RNDN);
4596 mpfr_prec_round(right_val, bits, GMP_RNDN);
4597 }
4598
4599 *cmp = mpfr_cmp(left_val, right_val);
4600
4601 mpfr_clear(left_val);
4602 mpfr_clear(right_val);
4603
4604 return true;
4605 }
4606
4607 // Compare complex constants. Complex numbers may only be compared
4608 // for equality.
4609
4610 bool
4611 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4612 const Numeric_constant* right_nc,
4613 int* cmp)
4614 {
4615 mpfr_t left_real, left_imag;
4616 if (!left_nc->to_complex(&left_real, &left_imag))
4617 return false;
4618 mpfr_t right_real, right_imag;
4619 if (!right_nc->to_complex(&right_real, &right_imag))
4620 {
4621 mpfr_clear(left_real);
4622 mpfr_clear(left_imag);
4623 return false;
4624 }
4625
4626 // We already coerced both operands to the same type. If that type
4627 // is not an abstract type, we need to round the values accordingly.
4628 Type* type = left_nc->type();
4629 if (!type->is_abstract() && type->complex_type() != NULL)
4630 {
4631 int bits = type->complex_type()->bits();
4632 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4633 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4634 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4635 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4636 }
4637
4638 *cmp = (mpfr_cmp(left_real, right_real) != 0
4639 || mpfr_cmp(left_imag, right_imag) != 0);
4640
4641 mpfr_clear(left_real);
4642 mpfr_clear(left_imag);
4643 mpfr_clear(right_real);
4644 mpfr_clear(right_imag);
4645
4646 return true;
4647 }
4648
4649 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4650 // true if this could be done, false if not. Issue errors at LOCATION
4651 // as appropriate.
4652
4653 bool
4654 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4655 Numeric_constant* right_nc,
4656 Location location, Numeric_constant* nc)
4657 {
4658 switch (op)
4659 {
4660 case OPERATOR_OROR:
4661 case OPERATOR_ANDAND:
4662 case OPERATOR_EQEQ:
4663 case OPERATOR_NOTEQ:
4664 case OPERATOR_LT:
4665 case OPERATOR_LE:
4666 case OPERATOR_GT:
4667 case OPERATOR_GE:
4668 // These return boolean values, not numeric.
4669 return false;
4670 default:
4671 break;
4672 }
4673
4674 Type* left_type = left_nc->type();
4675 Type* right_type = right_nc->type();
4676
4677 Type* type;
4678 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4679 return false;
4680
4681 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4682
4683 // When combining an untyped operand with a typed operand, we are
4684 // effectively coercing the untyped operand to the other operand's
4685 // type, so make sure that is valid.
4686 if (!left_nc->set_type(type, true, location))
4687 return false;
4688 if (!is_shift && !right_nc->set_type(type, true, location))
4689 return false;
4690
4691 bool r;
4692 if (type->complex_type() != NULL)
4693 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4694 else if (type->float_type() != NULL)
4695 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4696 else
4697 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4698
4699 if (r)
4700 r = nc->set_type(type, true, location);
4701
4702 return r;
4703 }
4704
4705 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4706 // integer operations. Return true if this could be done, false if
4707 // not.
4708
4709 bool
4710 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4711 const Numeric_constant* right_nc,
4712 Location location, Numeric_constant* nc)
4713 {
4714 mpz_t left_val;
4715 if (!left_nc->to_int(&left_val))
4716 return false;
4717 mpz_t right_val;
4718 if (!right_nc->to_int(&right_val))
4719 {
4720 mpz_clear(left_val);
4721 return false;
4722 }
4723
4724 mpz_t val;
4725 mpz_init(val);
4726
4727 switch (op)
4728 {
4729 case OPERATOR_PLUS:
4730 mpz_add(val, left_val, right_val);
4731 break;
4732 case OPERATOR_MINUS:
4733 mpz_sub(val, left_val, right_val);
4734 break;
4735 case OPERATOR_OR:
4736 mpz_ior(val, left_val, right_val);
4737 break;
4738 case OPERATOR_XOR:
4739 mpz_xor(val, left_val, right_val);
4740 break;
4741 case OPERATOR_MULT:
4742 mpz_mul(val, left_val, right_val);
4743 break;
4744 case OPERATOR_DIV:
4745 if (mpz_sgn(right_val) != 0)
4746 mpz_tdiv_q(val, left_val, right_val);
4747 else
4748 {
4749 error_at(location, "division by zero");
4750 mpz_set_ui(val, 0);
4751 }
4752 break;
4753 case OPERATOR_MOD:
4754 if (mpz_sgn(right_val) != 0)
4755 mpz_tdiv_r(val, left_val, right_val);
4756 else
4757 {
4758 error_at(location, "division by zero");
4759 mpz_set_ui(val, 0);
4760 }
4761 break;
4762 case OPERATOR_LSHIFT:
4763 {
4764 unsigned long shift = mpz_get_ui(right_val);
4765 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4766 mpz_mul_2exp(val, left_val, shift);
4767 else
4768 {
4769 error_at(location, "shift count overflow");
4770 mpz_set_ui(val, 0);
4771 }
4772 break;
4773 }
4774 break;
4775 case OPERATOR_RSHIFT:
4776 {
4777 unsigned long shift = mpz_get_ui(right_val);
4778 if (mpz_cmp_ui(right_val, shift) != 0)
4779 {
4780 error_at(location, "shift count overflow");
4781 mpz_set_ui(val, 0);
4782 }
4783 else
4784 {
4785 if (mpz_cmp_ui(left_val, 0) >= 0)
4786 mpz_tdiv_q_2exp(val, left_val, shift);
4787 else
4788 mpz_fdiv_q_2exp(val, left_val, shift);
4789 }
4790 break;
4791 }
4792 break;
4793 case OPERATOR_AND:
4794 mpz_and(val, left_val, right_val);
4795 break;
4796 case OPERATOR_BITCLEAR:
4797 {
4798 mpz_t tval;
4799 mpz_init(tval);
4800 mpz_com(tval, right_val);
4801 mpz_and(val, left_val, tval);
4802 mpz_clear(tval);
4803 }
4804 break;
4805 default:
4806 go_unreachable();
4807 }
4808
4809 mpz_clear(left_val);
4810 mpz_clear(right_val);
4811
4812 if (left_nc->is_rune()
4813 || (op != OPERATOR_LSHIFT
4814 && op != OPERATOR_RSHIFT
4815 && right_nc->is_rune()))
4816 nc->set_rune(NULL, val);
4817 else
4818 nc->set_int(NULL, val);
4819
4820 mpz_clear(val);
4821
4822 return true;
4823 }
4824
4825 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4826 // floating point operations. Return true if this could be done,
4827 // false if not.
4828
4829 bool
4830 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4831 const Numeric_constant* right_nc,
4832 Location location, Numeric_constant* nc)
4833 {
4834 mpfr_t left_val;
4835 if (!left_nc->to_float(&left_val))
4836 return false;
4837 mpfr_t right_val;
4838 if (!right_nc->to_float(&right_val))
4839 {
4840 mpfr_clear(left_val);
4841 return false;
4842 }
4843
4844 mpfr_t val;
4845 mpfr_init(val);
4846
4847 bool ret = true;
4848 switch (op)
4849 {
4850 case OPERATOR_PLUS:
4851 mpfr_add(val, left_val, right_val, GMP_RNDN);
4852 break;
4853 case OPERATOR_MINUS:
4854 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4855 break;
4856 case OPERATOR_OR:
4857 case OPERATOR_XOR:
4858 case OPERATOR_AND:
4859 case OPERATOR_BITCLEAR:
4860 case OPERATOR_MOD:
4861 case OPERATOR_LSHIFT:
4862 case OPERATOR_RSHIFT:
4863 mpfr_set_ui(val, 0, GMP_RNDN);
4864 ret = false;
4865 break;
4866 case OPERATOR_MULT:
4867 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4868 break;
4869 case OPERATOR_DIV:
4870 if (!mpfr_zero_p(right_val))
4871 mpfr_div(val, left_val, right_val, GMP_RNDN);
4872 else
4873 {
4874 error_at(location, "division by zero");
4875 mpfr_set_ui(val, 0, GMP_RNDN);
4876 }
4877 break;
4878 default:
4879 go_unreachable();
4880 }
4881
4882 mpfr_clear(left_val);
4883 mpfr_clear(right_val);
4884
4885 nc->set_float(NULL, val);
4886 mpfr_clear(val);
4887
4888 return ret;
4889 }
4890
4891 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4892 // complex operations. Return true if this could be done, false if
4893 // not.
4894
4895 bool
4896 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4897 const Numeric_constant* right_nc,
4898 Location location, Numeric_constant* nc)
4899 {
4900 mpfr_t left_real, left_imag;
4901 if (!left_nc->to_complex(&left_real, &left_imag))
4902 return false;
4903 mpfr_t right_real, right_imag;
4904 if (!right_nc->to_complex(&right_real, &right_imag))
4905 {
4906 mpfr_clear(left_real);
4907 mpfr_clear(left_imag);
4908 return false;
4909 }
4910
4911 mpfr_t real, imag;
4912 mpfr_init(real);
4913 mpfr_init(imag);
4914
4915 bool ret = true;
4916 switch (op)
4917 {
4918 case OPERATOR_PLUS:
4919 mpfr_add(real, left_real, right_real, GMP_RNDN);
4920 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4921 break;
4922 case OPERATOR_MINUS:
4923 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4924 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4925 break;
4926 case OPERATOR_OR:
4927 case OPERATOR_XOR:
4928 case OPERATOR_AND:
4929 case OPERATOR_BITCLEAR:
4930 case OPERATOR_MOD:
4931 case OPERATOR_LSHIFT:
4932 case OPERATOR_RSHIFT:
4933 mpfr_set_ui(real, 0, GMP_RNDN);
4934 mpfr_set_ui(imag, 0, GMP_RNDN);
4935 ret = false;
4936 break;
4937 case OPERATOR_MULT:
4938 {
4939 // You might think that multiplying two complex numbers would
4940 // be simple, and you would be right, until you start to think
4941 // about getting the right answer for infinity. If one
4942 // operand here is infinity and the other is anything other
4943 // than zero or NaN, then we are going to wind up subtracting
4944 // two infinity values. That will give us a NaN, but the
4945 // correct answer is infinity.
4946
4947 mpfr_t lrrr;
4948 mpfr_init(lrrr);
4949 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4950
4951 mpfr_t lrri;
4952 mpfr_init(lrri);
4953 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4954
4955 mpfr_t lirr;
4956 mpfr_init(lirr);
4957 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4958
4959 mpfr_t liri;
4960 mpfr_init(liri);
4961 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4962
4963 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4964 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4965
4966 // If we get NaN on both sides, check whether it should really
4967 // be infinity. The rule is that if either side of the
4968 // complex number is infinity, then the whole value is
4969 // infinity, even if the other side is NaN. So the only case
4970 // we have to fix is the one in which both sides are NaN.
4971 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4972 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4973 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4974 {
4975 bool is_infinity = false;
4976
4977 mpfr_t lr;
4978 mpfr_t li;
4979 mpfr_init_set(lr, left_real, GMP_RNDN);
4980 mpfr_init_set(li, left_imag, GMP_RNDN);
4981
4982 mpfr_t rr;
4983 mpfr_t ri;
4984 mpfr_init_set(rr, right_real, GMP_RNDN);
4985 mpfr_init_set(ri, right_imag, GMP_RNDN);
4986
4987 // If the left side is infinity, then the result is
4988 // infinity.
4989 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4990 {
4991 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4992 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4993 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4994 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4995 if (mpfr_nan_p(rr))
4996 {
4997 mpfr_set_ui(rr, 0, GMP_RNDN);
4998 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4999 }
5000 if (mpfr_nan_p(ri))
5001 {
5002 mpfr_set_ui(ri, 0, GMP_RNDN);
5003 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5004 }
5005 is_infinity = true;
5006 }
5007
5008 // If the right side is infinity, then the result is
5009 // infinity.
5010 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
5011 {
5012 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5013 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5014 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5015 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5016 if (mpfr_nan_p(lr))
5017 {
5018 mpfr_set_ui(lr, 0, GMP_RNDN);
5019 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5020 }
5021 if (mpfr_nan_p(li))
5022 {
5023 mpfr_set_ui(li, 0, GMP_RNDN);
5024 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5025 }
5026 is_infinity = true;
5027 }
5028
5029 // If we got an overflow in the intermediate computations,
5030 // then the result is infinity.
5031 if (!is_infinity
5032 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
5033 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
5034 {
5035 if (mpfr_nan_p(lr))
5036 {
5037 mpfr_set_ui(lr, 0, GMP_RNDN);
5038 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5039 }
5040 if (mpfr_nan_p(li))
5041 {
5042 mpfr_set_ui(li, 0, GMP_RNDN);
5043 mpfr_copysign(li, li, left_imag, GMP_RNDN);
5044 }
5045 if (mpfr_nan_p(rr))
5046 {
5047 mpfr_set_ui(rr, 0, GMP_RNDN);
5048 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5049 }
5050 if (mpfr_nan_p(ri))
5051 {
5052 mpfr_set_ui(ri, 0, GMP_RNDN);
5053 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5054 }
5055 is_infinity = true;
5056 }
5057
5058 if (is_infinity)
5059 {
5060 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
5061 mpfr_mul(lrri, lr, ri, GMP_RNDN);
5062 mpfr_mul(lirr, li, rr, GMP_RNDN);
5063 mpfr_mul(liri, li, ri, GMP_RNDN);
5064 mpfr_sub(real, lrrr, liri, GMP_RNDN);
5065 mpfr_add(imag, lrri, lirr, GMP_RNDN);
5066 mpfr_set_inf(real, mpfr_sgn(real));
5067 mpfr_set_inf(imag, mpfr_sgn(imag));
5068 }
5069
5070 mpfr_clear(lr);
5071 mpfr_clear(li);
5072 mpfr_clear(rr);
5073 mpfr_clear(ri);
5074 }
5075
5076 mpfr_clear(lrrr);
5077 mpfr_clear(lrri);
5078 mpfr_clear(lirr);
5079 mpfr_clear(liri);
5080 }
5081 break;
5082 case OPERATOR_DIV:
5083 {
5084 // For complex division we want to avoid having an
5085 // intermediate overflow turn the whole result in a NaN. We
5086 // scale the values to try to avoid this.
5087
5088 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
5089 {
5090 error_at(location, "division by zero");
5091 mpfr_set_ui(real, 0, GMP_RNDN);
5092 mpfr_set_ui(imag, 0, GMP_RNDN);
5093 break;
5094 }
5095
5096 mpfr_t rra;
5097 mpfr_t ria;
5098 mpfr_init(rra);
5099 mpfr_init(ria);
5100 mpfr_abs(rra, right_real, GMP_RNDN);
5101 mpfr_abs(ria, right_imag, GMP_RNDN);
5102 mpfr_t t;
5103 mpfr_init(t);
5104 mpfr_max(t, rra, ria, GMP_RNDN);
5105
5106 mpfr_t rr;
5107 mpfr_t ri;
5108 mpfr_init_set(rr, right_real, GMP_RNDN);
5109 mpfr_init_set(ri, right_imag, GMP_RNDN);
5110 long ilogbw = 0;
5111 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5112 {
5113 ilogbw = mpfr_get_exp(t);
5114 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5115 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5116 }
5117
5118 mpfr_t denom;
5119 mpfr_init(denom);
5120 mpfr_mul(denom, rr, rr, GMP_RNDN);
5121 mpfr_mul(t, ri, ri, GMP_RNDN);
5122 mpfr_add(denom, denom, t, GMP_RNDN);
5123
5124 mpfr_mul(real, left_real, rr, GMP_RNDN);
5125 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5126 mpfr_add(real, real, t, GMP_RNDN);
5127 mpfr_div(real, real, denom, GMP_RNDN);
5128 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5129
5130 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5131 mpfr_mul(t, left_real, ri, GMP_RNDN);
5132 mpfr_sub(imag, imag, t, GMP_RNDN);
5133 mpfr_div(imag, imag, denom, GMP_RNDN);
5134 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5135
5136 // If we wind up with NaN on both sides, check whether we
5137 // should really have infinity. The rule is that if either
5138 // side of the complex number is infinity, then the whole
5139 // value is infinity, even if the other side is NaN. So the
5140 // only case we have to fix is the one in which both sides are
5141 // NaN.
5142 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5143 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5144 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5145 {
5146 if (mpfr_zero_p(denom))
5147 {
5148 mpfr_set_inf(real, mpfr_sgn(rr));
5149 mpfr_mul(real, real, left_real, GMP_RNDN);
5150 mpfr_set_inf(imag, mpfr_sgn(rr));
5151 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5152 }
5153 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5154 && mpfr_number_p(rr) && mpfr_number_p(ri))
5155 {
5156 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5157 mpfr_copysign(t, t, left_real, GMP_RNDN);
5158
5159 mpfr_t t2;
5160 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5161 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5162
5163 mpfr_t t3;
5164 mpfr_init(t3);
5165 mpfr_mul(t3, t, rr, GMP_RNDN);
5166
5167 mpfr_t t4;
5168 mpfr_init(t4);
5169 mpfr_mul(t4, t2, ri, GMP_RNDN);
5170
5171 mpfr_add(t3, t3, t4, GMP_RNDN);
5172 mpfr_set_inf(real, mpfr_sgn(t3));
5173
5174 mpfr_mul(t3, t2, rr, GMP_RNDN);
5175 mpfr_mul(t4, t, ri, GMP_RNDN);
5176 mpfr_sub(t3, t3, t4, GMP_RNDN);
5177 mpfr_set_inf(imag, mpfr_sgn(t3));
5178
5179 mpfr_clear(t2);
5180 mpfr_clear(t3);
5181 mpfr_clear(t4);
5182 }
5183 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5184 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5185 {
5186 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5187 mpfr_copysign(t, t, rr, GMP_RNDN);
5188
5189 mpfr_t t2;
5190 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5191 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5192
5193 mpfr_t t3;
5194 mpfr_init(t3);
5195 mpfr_mul(t3, left_real, t, GMP_RNDN);
5196
5197 mpfr_t t4;
5198 mpfr_init(t4);
5199 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5200
5201 mpfr_add(t3, t3, t4, GMP_RNDN);
5202 mpfr_set_ui(real, 0, GMP_RNDN);
5203 mpfr_mul(real, real, t3, GMP_RNDN);
5204
5205 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5206 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5207 mpfr_sub(t3, t3, t4, GMP_RNDN);
5208 mpfr_set_ui(imag, 0, GMP_RNDN);
5209 mpfr_mul(imag, imag, t3, GMP_RNDN);
5210
5211 mpfr_clear(t2);
5212 mpfr_clear(t3);
5213 mpfr_clear(t4);
5214 }
5215 }
5216
5217 mpfr_clear(denom);
5218 mpfr_clear(rr);
5219 mpfr_clear(ri);
5220 mpfr_clear(t);
5221 mpfr_clear(rra);
5222 mpfr_clear(ria);
5223 }
5224 break;
5225 default:
5226 go_unreachable();
5227 }
5228
5229 mpfr_clear(left_real);
5230 mpfr_clear(left_imag);
5231 mpfr_clear(right_real);
5232 mpfr_clear(right_imag);
5233
5234 nc->set_complex(NULL, real, imag);
5235 mpfr_clear(real);
5236 mpfr_clear(imag);
5237
5238 return ret;
5239 }
5240
5241 // Lower a binary expression. We have to evaluate constant
5242 // expressions now, in order to implement Go's unlimited precision
5243 // constants.
5244
5245 Expression*
5246 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5247 Statement_inserter* inserter, int)
5248 {
5249 Location location = this->location();
5250 Operator op = this->op_;
5251 Expression* left = this->left_;
5252 Expression* right = this->right_;
5253
5254 const bool is_comparison = (op == OPERATOR_EQEQ
5255 || op == OPERATOR_NOTEQ
5256 || op == OPERATOR_LT
5257 || op == OPERATOR_LE
5258 || op == OPERATOR_GT
5259 || op == OPERATOR_GE);
5260
5261 // Numeric constant expressions.
5262 {
5263 Numeric_constant left_nc;
5264 Numeric_constant right_nc;
5265 if (left->numeric_constant_value(&left_nc)
5266 && right->numeric_constant_value(&right_nc))
5267 {
5268 if (is_comparison)
5269 {
5270 bool result;
5271 if (!Binary_expression::compare_constant(op, &left_nc,
5272 &right_nc, location,
5273 &result))
5274 return this;
5275 return Expression::make_cast(Type::make_boolean_type(),
5276 Expression::make_boolean(result,
5277 location),
5278 location);
5279 }
5280 else
5281 {
5282 Numeric_constant nc;
5283 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5284 location, &nc))
5285 return this;
5286 return nc.expression(location);
5287 }
5288 }
5289 }
5290
5291 // String constant expressions.
5292 if (left->type()->is_string_type() && right->type()->is_string_type())
5293 {
5294 std::string left_string;
5295 std::string right_string;
5296 if (left->string_constant_value(&left_string)
5297 && right->string_constant_value(&right_string))
5298 {
5299 if (op == OPERATOR_PLUS)
5300 return Expression::make_string(left_string + right_string,
5301 location);
5302 else if (is_comparison)
5303 {
5304 int cmp = left_string.compare(right_string);
5305 bool r = Binary_expression::cmp_to_bool(op, cmp);
5306 return Expression::make_boolean(r, location);
5307 }
5308 }
5309 }
5310
5311 // Lower struct and array comparisons.
5312 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5313 {
5314 if (left->type()->struct_type() != NULL)
5315 return this->lower_struct_comparison(gogo, inserter);
5316 else if (left->type()->array_type() != NULL
5317 && !left->type()->is_slice_type())
5318 return this->lower_array_comparison(gogo, inserter);
5319 }
5320
5321 return this;
5322 }
5323
5324 // Lower a struct comparison.
5325
5326 Expression*
5327 Binary_expression::lower_struct_comparison(Gogo* gogo,
5328 Statement_inserter* inserter)
5329 {
5330 Struct_type* st = this->left_->type()->struct_type();
5331 Struct_type* st2 = this->right_->type()->struct_type();
5332 if (st2 == NULL)
5333 return this;
5334 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5335 return this;
5336 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5337 this->right_->type(), NULL))
5338 return this;
5339
5340 // See if we can compare using memcmp. As a heuristic, we use
5341 // memcmp rather than field references and comparisons if there are
5342 // more than two fields.
5343 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5344 return this->lower_compare_to_memcmp(gogo, inserter);
5345
5346 Location loc = this->location();
5347
5348 Expression* left = this->left_;
5349 Temporary_statement* left_temp = NULL;
5350 if (left->var_expression() == NULL
5351 && left->temporary_reference_expression() == NULL)
5352 {
5353 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5354 inserter->insert(left_temp);
5355 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5356 }
5357
5358 Expression* right = this->right_;
5359 Temporary_statement* right_temp = NULL;
5360 if (right->var_expression() == NULL
5361 && right->temporary_reference_expression() == NULL)
5362 {
5363 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5364 inserter->insert(right_temp);
5365 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5366 }
5367
5368 Expression* ret = Expression::make_boolean(true, loc);
5369 const Struct_field_list* fields = st->fields();
5370 unsigned int field_index = 0;
5371 for (Struct_field_list::const_iterator pf = fields->begin();
5372 pf != fields->end();
5373 ++pf, ++field_index)
5374 {
5375 if (Gogo::is_sink_name(pf->field_name()))
5376 continue;
5377
5378 if (field_index > 0)
5379 {
5380 if (left_temp == NULL)
5381 left = left->copy();
5382 else
5383 left = Expression::make_temporary_reference(left_temp, loc);
5384 if (right_temp == NULL)
5385 right = right->copy();
5386 else
5387 right = Expression::make_temporary_reference(right_temp, loc);
5388 }
5389 Expression* f1 = Expression::make_field_reference(left, field_index,
5390 loc);
5391 Expression* f2 = Expression::make_field_reference(right, field_index,
5392 loc);
5393 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5394 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5395 }
5396
5397 if (this->op_ == OPERATOR_NOTEQ)
5398 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5399
5400 return ret;
5401 }
5402
5403 // Lower an array comparison.
5404
5405 Expression*
5406 Binary_expression::lower_array_comparison(Gogo* gogo,
5407 Statement_inserter* inserter)
5408 {
5409 Array_type* at = this->left_->type()->array_type();
5410 Array_type* at2 = this->right_->type()->array_type();
5411 if (at2 == NULL)
5412 return this;
5413 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5414 return this;
5415 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5416 this->right_->type(), NULL))
5417 return this;
5418
5419 // Call memcmp directly if possible. This may let the middle-end
5420 // optimize the call.
5421 if (at->compare_is_identity(gogo))
5422 return this->lower_compare_to_memcmp(gogo, inserter);
5423
5424 // Call the array comparison function.
5425 Named_object* hash_fn;
5426 Named_object* equal_fn;
5427 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5428 &hash_fn, &equal_fn);
5429
5430 Location loc = this->location();
5431
5432 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5433
5434 Expression_list* args = new Expression_list();
5435 args->push_back(this->operand_address(inserter, this->left_));
5436 args->push_back(this->operand_address(inserter, this->right_));
5437 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5438
5439 Expression* ret = Expression::make_call(func, args, false, loc);
5440
5441 if (this->op_ == OPERATOR_NOTEQ)
5442 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5443
5444 return ret;
5445 }
5446
5447 // Lower a struct or array comparison to a call to memcmp.
5448
5449 Expression*
5450 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5451 {
5452 Location loc = this->location();
5453
5454 Expression* a1 = this->operand_address(inserter, this->left_);
5455 Expression* a2 = this->operand_address(inserter, this->right_);
5456 Expression* len = Expression::make_type_info(this->left_->type(),
5457 TYPE_INFO_SIZE);
5458
5459 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5460
5461 mpz_t zval;
5462 mpz_init_set_ui(zval, 0);
5463 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5464 mpz_clear(zval);
5465
5466 return Expression::make_binary(this->op_, call, zero, loc);
5467 }
5468
5469 // Return the address of EXPR, cast to unsafe.Pointer.
5470
5471 Expression*
5472 Binary_expression::operand_address(Statement_inserter* inserter,
5473 Expression* expr)
5474 {
5475 Location loc = this->location();
5476
5477 if (!expr->is_addressable())
5478 {
5479 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5480 loc);
5481 inserter->insert(temp);
5482 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5483 }
5484 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5485 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5486 Type* void_type = Type::make_void_type();
5487 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5488 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5489 }
5490
5491 // Return the numeric constant value, if it has one.
5492
5493 bool
5494 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5495 {
5496 Numeric_constant left_nc;
5497 if (!this->left_->numeric_constant_value(&left_nc))
5498 return false;
5499 Numeric_constant right_nc;
5500 if (!this->right_->numeric_constant_value(&right_nc))
5501 return false;
5502 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5503 this->location(), nc);
5504 }
5505
5506 // Note that the value is being discarded.
5507
5508 bool
5509 Binary_expression::do_discarding_value()
5510 {
5511 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5512 return this->right_->discarding_value();
5513 else
5514 {
5515 this->unused_value_error();
5516 return false;
5517 }
5518 }
5519
5520 // Get type.
5521
5522 Type*
5523 Binary_expression::do_type()
5524 {
5525 if (this->classification() == EXPRESSION_ERROR)
5526 return Type::make_error_type();
5527
5528 switch (this->op_)
5529 {
5530 case OPERATOR_EQEQ:
5531 case OPERATOR_NOTEQ:
5532 case OPERATOR_LT:
5533 case OPERATOR_LE:
5534 case OPERATOR_GT:
5535 case OPERATOR_GE:
5536 if (this->type_ == NULL)
5537 this->type_ = Type::make_boolean_type();
5538 return this->type_;
5539
5540 case OPERATOR_PLUS:
5541 case OPERATOR_MINUS:
5542 case OPERATOR_OR:
5543 case OPERATOR_XOR:
5544 case OPERATOR_MULT:
5545 case OPERATOR_DIV:
5546 case OPERATOR_MOD:
5547 case OPERATOR_AND:
5548 case OPERATOR_BITCLEAR:
5549 case OPERATOR_OROR:
5550 case OPERATOR_ANDAND:
5551 {
5552 Type* type;
5553 if (!Binary_expression::operation_type(this->op_,
5554 this->left_->type(),
5555 this->right_->type(),
5556 &type))
5557 return Type::make_error_type();
5558 return type;
5559 }
5560
5561 case OPERATOR_LSHIFT:
5562 case OPERATOR_RSHIFT:
5563 return this->left_->type();
5564
5565 default:
5566 go_unreachable();
5567 }
5568 }
5569
5570 // Set type for a binary expression.
5571
5572 void
5573 Binary_expression::do_determine_type(const Type_context* context)
5574 {
5575 Type* tleft = this->left_->type();
5576 Type* tright = this->right_->type();
5577
5578 // Both sides should have the same type, except for the shift
5579 // operations. For a comparison, we should ignore the incoming
5580 // type.
5581
5582 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5583 || this->op_ == OPERATOR_RSHIFT);
5584
5585 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5586 || this->op_ == OPERATOR_NOTEQ
5587 || this->op_ == OPERATOR_LT
5588 || this->op_ == OPERATOR_LE
5589 || this->op_ == OPERATOR_GT
5590 || this->op_ == OPERATOR_GE);
5591
5592 Type_context subcontext(*context);
5593
5594 if (is_comparison)
5595 {
5596 // In a comparison, the context does not determine the types of
5597 // the operands.
5598 subcontext.type = NULL;
5599 }
5600
5601 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5602 {
5603 // For a logical operation, the context does not determine the
5604 // types of the operands. The operands must be some boolean
5605 // type but if the context has a boolean type they do not
5606 // inherit it. See http://golang.org/issue/3924.
5607 subcontext.type = NULL;
5608 }
5609
5610 // Set the context for the left hand operand.
5611 if (is_shift_op)
5612 {
5613 // The right hand operand of a shift plays no role in
5614 // determining the type of the left hand operand.
5615 }
5616 else if (!tleft->is_abstract())
5617 subcontext.type = tleft;
5618 else if (!tright->is_abstract())
5619 subcontext.type = tright;
5620 else if (subcontext.type == NULL)
5621 {
5622 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5623 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5624 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5625 {
5626 // Both sides have an abstract integer, abstract float, or
5627 // abstract complex type. Just let CONTEXT determine
5628 // whether they may remain abstract or not.
5629 }
5630 else if (tleft->complex_type() != NULL)
5631 subcontext.type = tleft;
5632 else if (tright->complex_type() != NULL)
5633 subcontext.type = tright;
5634 else if (tleft->float_type() != NULL)
5635 subcontext.type = tleft;
5636 else if (tright->float_type() != NULL)
5637 subcontext.type = tright;
5638 else
5639 subcontext.type = tleft;
5640
5641 if (subcontext.type != NULL && !context->may_be_abstract)
5642 subcontext.type = subcontext.type->make_non_abstract_type();
5643 }
5644
5645 this->left_->determine_type(&subcontext);
5646
5647 if (is_shift_op)
5648 {
5649 // We may have inherited an unusable type for the shift operand.
5650 // Give a useful error if that happened.
5651 if (tleft->is_abstract()
5652 && subcontext.type != NULL
5653 && !subcontext.may_be_abstract
5654 && subcontext.type->interface_type() == NULL
5655 && subcontext.type->integer_type() == NULL)
5656 this->report_error(("invalid context-determined non-integer type "
5657 "for left operand of shift"));
5658
5659 // The context for the right hand operand is the same as for the
5660 // left hand operand, except for a shift operator.
5661 subcontext.type = Type::lookup_integer_type("uint");
5662 subcontext.may_be_abstract = false;
5663 }
5664
5665 this->right_->determine_type(&subcontext);
5666
5667 if (is_comparison)
5668 {
5669 if (this->type_ != NULL && !this->type_->is_abstract())
5670 ;
5671 else if (context->type != NULL && context->type->is_boolean_type())
5672 this->type_ = context->type;
5673 else if (!context->may_be_abstract)
5674 this->type_ = Type::lookup_bool_type();
5675 }
5676 }
5677
5678 // Report an error if the binary operator OP does not support TYPE.
5679 // OTYPE is the type of the other operand. Return whether the
5680 // operation is OK. This should not be used for shift.
5681
5682 bool
5683 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5684 Location location)
5685 {
5686 switch (op)
5687 {
5688 case OPERATOR_OROR:
5689 case OPERATOR_ANDAND:
5690 if (!type->is_boolean_type())
5691 {
5692 error_at(location, "expected boolean type");
5693 return false;
5694 }
5695 break;
5696
5697 case OPERATOR_EQEQ:
5698 case OPERATOR_NOTEQ:
5699 {
5700 std::string reason;
5701 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5702 {
5703 error_at(location, "%s", reason.c_str());
5704 return false;
5705 }
5706 }
5707 break;
5708
5709 case OPERATOR_LT:
5710 case OPERATOR_LE:
5711 case OPERATOR_GT:
5712 case OPERATOR_GE:
5713 {
5714 std::string reason;
5715 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5716 {
5717 error_at(location, "%s", reason.c_str());
5718 return false;
5719 }
5720 }
5721 break;
5722
5723 case OPERATOR_PLUS:
5724 case OPERATOR_PLUSEQ:
5725 if (type->integer_type() == NULL
5726 && type->float_type() == NULL
5727 && type->complex_type() == NULL
5728 && !type->is_string_type())
5729 {
5730 error_at(location,
5731 "expected integer, floating, complex, or string type");
5732 return false;
5733 }
5734 break;
5735
5736 case OPERATOR_MINUS:
5737 case OPERATOR_MINUSEQ:
5738 case OPERATOR_MULT:
5739 case OPERATOR_MULTEQ:
5740 case OPERATOR_DIV:
5741 case OPERATOR_DIVEQ:
5742 if (type->integer_type() == NULL
5743 && type->float_type() == NULL
5744 && type->complex_type() == NULL)
5745 {
5746 error_at(location, "expected integer, floating, or complex type");
5747 return false;
5748 }
5749 break;
5750
5751 case OPERATOR_MOD:
5752 case OPERATOR_MODEQ:
5753 case OPERATOR_OR:
5754 case OPERATOR_OREQ:
5755 case OPERATOR_AND:
5756 case OPERATOR_ANDEQ:
5757 case OPERATOR_XOR:
5758 case OPERATOR_XOREQ:
5759 case OPERATOR_BITCLEAR:
5760 case OPERATOR_BITCLEAREQ:
5761 if (type->integer_type() == NULL)
5762 {
5763 error_at(location, "expected integer type");
5764 return false;
5765 }
5766 break;
5767
5768 default:
5769 go_unreachable();
5770 }
5771
5772 return true;
5773 }
5774
5775 // Check types.
5776
5777 void
5778 Binary_expression::do_check_types(Gogo*)
5779 {
5780 if (this->classification() == EXPRESSION_ERROR)
5781 return;
5782
5783 Type* left_type = this->left_->type();
5784 Type* right_type = this->right_->type();
5785 if (left_type->is_error() || right_type->is_error())
5786 {
5787 this->set_is_error();
5788 return;
5789 }
5790
5791 if (this->op_ == OPERATOR_EQEQ
5792 || this->op_ == OPERATOR_NOTEQ
5793 || this->op_ == OPERATOR_LT
5794 || this->op_ == OPERATOR_LE
5795 || this->op_ == OPERATOR_GT
5796 || this->op_ == OPERATOR_GE)
5797 {
5798 if (left_type->is_nil_type() && right_type->is_nil_type())
5799 {
5800 this->report_error(_("invalid comparison of nil with nil"));
5801 return;
5802 }
5803 if (!Type::are_assignable(left_type, right_type, NULL)
5804 && !Type::are_assignable(right_type, left_type, NULL))
5805 {
5806 this->report_error(_("incompatible types in binary expression"));
5807 return;
5808 }
5809 if (!Binary_expression::check_operator_type(this->op_, left_type,
5810 right_type,
5811 this->location())
5812 || !Binary_expression::check_operator_type(this->op_, right_type,
5813 left_type,
5814 this->location()))
5815 {
5816 this->set_is_error();
5817 return;
5818 }
5819 }
5820 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5821 {
5822 if (!Type::are_compatible_for_binop(left_type, right_type))
5823 {
5824 this->report_error(_("incompatible types in binary expression"));
5825 return;
5826 }
5827 if (!Binary_expression::check_operator_type(this->op_, left_type,
5828 right_type,
5829 this->location()))
5830 {
5831 this->set_is_error();
5832 return;
5833 }
5834 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5835 {
5836 // Division by a zero integer constant is an error.
5837 Numeric_constant rconst;
5838 unsigned long rval;
5839 if (left_type->integer_type() != NULL
5840 && this->right_->numeric_constant_value(&rconst)
5841 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5842 && rval == 0)
5843 {
5844 this->report_error(_("integer division by zero"));
5845 return;
5846 }
5847 }
5848 }
5849 else
5850 {
5851 if (left_type->integer_type() == NULL)
5852 this->report_error(_("shift of non-integer operand"));
5853
5854 if (!right_type->is_abstract()
5855 && (right_type->integer_type() == NULL
5856 || !right_type->integer_type()->is_unsigned()))
5857 this->report_error(_("shift count not unsigned integer"));
5858 else
5859 {
5860 Numeric_constant nc;
5861 if (this->right_->numeric_constant_value(&nc))
5862 {
5863 mpz_t val;
5864 if (!nc.to_int(&val))
5865 this->report_error(_("shift count not unsigned integer"));
5866 else
5867 {
5868 if (mpz_sgn(val) < 0)
5869 {
5870 this->report_error(_("negative shift count"));
5871 mpz_set_ui(val, 0);
5872 Location rloc = this->right_->location();
5873 this->right_ = Expression::make_integer(&val, right_type,
5874 rloc);
5875 }
5876 mpz_clear(val);
5877 }
5878 }
5879 }
5880 }
5881 }
5882
5883 // Get a tree for a binary expression.
5884
5885 tree
5886 Binary_expression::do_get_tree(Translate_context* context)
5887 {
5888 Gogo* gogo = context->gogo();
5889
5890 tree left = this->left_->get_tree(context);
5891 tree right = this->right_->get_tree(context);
5892
5893 if (left == error_mark_node || right == error_mark_node)
5894 return error_mark_node;
5895
5896 enum tree_code code;
5897 bool use_left_type = true;
5898 bool is_shift_op = false;
5899 bool is_idiv_op = false;
5900 switch (this->op_)
5901 {
5902 case OPERATOR_EQEQ:
5903 case OPERATOR_NOTEQ:
5904 case OPERATOR_LT:
5905 case OPERATOR_LE:
5906 case OPERATOR_GT:
5907 case OPERATOR_GE:
5908 return Expression::comparison_tree(context, this->type_, this->op_,
5909 this->left_->type(), left,
5910 this->right_->type(), right,
5911 this->location());
5912
5913 case OPERATOR_OROR:
5914 code = TRUTH_ORIF_EXPR;
5915 use_left_type = false;
5916 break;
5917 case OPERATOR_ANDAND:
5918 code = TRUTH_ANDIF_EXPR;
5919 use_left_type = false;
5920 break;
5921 case OPERATOR_PLUS:
5922 code = PLUS_EXPR;
5923 break;
5924 case OPERATOR_MINUS:
5925 code = MINUS_EXPR;
5926 break;
5927 case OPERATOR_OR:
5928 code = BIT_IOR_EXPR;
5929 break;
5930 case OPERATOR_XOR:
5931 code = BIT_XOR_EXPR;
5932 break;
5933 case OPERATOR_MULT:
5934 code = MULT_EXPR;
5935 break;
5936 case OPERATOR_DIV:
5937 {
5938 Type *t = this->left_->type();
5939 if (t->float_type() != NULL || t->complex_type() != NULL)
5940 code = RDIV_EXPR;
5941 else
5942 {
5943 code = TRUNC_DIV_EXPR;
5944 is_idiv_op = true;
5945 }
5946 }
5947 break;
5948 case OPERATOR_MOD:
5949 code = TRUNC_MOD_EXPR;
5950 is_idiv_op = true;
5951 break;
5952 case OPERATOR_LSHIFT:
5953 code = LSHIFT_EXPR;
5954 is_shift_op = true;
5955 break;
5956 case OPERATOR_RSHIFT:
5957 code = RSHIFT_EXPR;
5958 is_shift_op = true;
5959 break;
5960 case OPERATOR_AND:
5961 code = BIT_AND_EXPR;
5962 break;
5963 case OPERATOR_BITCLEAR:
5964 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5965 code = BIT_AND_EXPR;
5966 break;
5967 default:
5968 go_unreachable();
5969 }
5970
5971 location_t gccloc = this->location().gcc_location();
5972 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5973
5974 if (this->left_->type()->is_string_type())
5975 {
5976 go_assert(this->op_ == OPERATOR_PLUS);
5977 Type* st = Type::make_string_type();
5978 tree string_type = type_to_tree(st->get_backend(gogo));
5979 static tree string_plus_decl;
5980 return Gogo::call_builtin(&string_plus_decl,
5981 this->location(),
5982 "__go_string_plus",
5983 2,
5984 string_type,
5985 string_type,
5986 left,
5987 string_type,
5988 right);
5989 }
5990
5991 // For complex division Go wants slightly different results than the
5992 // GCC library provides, so we have our own runtime routine.
5993 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5994 {
5995 const char *name;
5996 tree *pdecl;
5997 Type* ctype;
5998 static tree complex64_div_decl;
5999 static tree complex128_div_decl;
6000 switch (this->left_->type()->complex_type()->bits())
6001 {
6002 case 64:
6003 name = "__go_complex64_div";
6004 pdecl = &complex64_div_decl;
6005 ctype = Type::lookup_complex_type("complex64");
6006 break;
6007 case 128:
6008 name = "__go_complex128_div";
6009 pdecl = &complex128_div_decl;
6010 ctype = Type::lookup_complex_type("complex128");
6011 break;
6012 default:
6013 go_unreachable();
6014 }
6015 Btype* cbtype = ctype->get_backend(gogo);
6016 tree ctype_tree = type_to_tree(cbtype);
6017 return Gogo::call_builtin(pdecl,
6018 this->location(),
6019 name,
6020 2,
6021 ctype_tree,
6022 ctype_tree,
6023 fold_convert_loc(gccloc, ctype_tree, left),
6024 type,
6025 fold_convert_loc(gccloc, ctype_tree, right));
6026 }
6027
6028 tree compute_type = excess_precision_type(type);
6029 if (compute_type != NULL_TREE)
6030 {
6031 left = ::convert(compute_type, left);
6032 right = ::convert(compute_type, right);
6033 }
6034
6035 tree eval_saved = NULL_TREE;
6036 if (is_shift_op
6037 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
6038 {
6039 // Make sure the values are evaluated.
6040 if (!DECL_P(left))
6041 {
6042 left = save_expr(left);
6043 eval_saved = left;
6044 }
6045 if (!DECL_P(right))
6046 {
6047 right = save_expr(right);
6048 if (eval_saved == NULL_TREE)
6049 eval_saved = right;
6050 else
6051 eval_saved = fold_build2_loc(gccloc, COMPOUND_EXPR,
6052 void_type_node, eval_saved, right);
6053 }
6054 }
6055
6056 tree ret = fold_build2_loc(gccloc, code,
6057 compute_type != NULL_TREE ? compute_type : type,
6058 left, right);
6059
6060 if (compute_type != NULL_TREE)
6061 ret = ::convert(type, ret);
6062
6063 // In Go, a shift larger than the size of the type is well-defined.
6064 // This is not true in GENERIC, so we need to insert a conditional.
6065 if (is_shift_op)
6066 {
6067 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
6068 go_assert(this->left_->type()->integer_type() != NULL);
6069 int bits = TYPE_PRECISION(TREE_TYPE(left));
6070
6071 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
6072 build_int_cst_type(TREE_TYPE(right), bits));
6073
6074 tree overflow_result = fold_convert_loc(gccloc, TREE_TYPE(left),
6075 integer_zero_node);
6076 if (this->op_ == OPERATOR_RSHIFT
6077 && !this->left_->type()->integer_type()->is_unsigned())
6078 {
6079 tree neg =
6080 fold_build2_loc(gccloc, LT_EXPR, boolean_type_node,
6081 left,
6082 fold_convert_loc(gccloc, TREE_TYPE(left),
6083 integer_zero_node));
6084 tree neg_one =
6085 fold_build2_loc(gccloc, MINUS_EXPR, TREE_TYPE(left),
6086 fold_convert_loc(gccloc, TREE_TYPE(left),
6087 integer_zero_node),
6088 fold_convert_loc(gccloc, TREE_TYPE(left),
6089 integer_one_node));
6090 overflow_result =
6091 fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
6092 neg, neg_one, overflow_result);
6093 }
6094
6095 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
6096 compare, ret, overflow_result);
6097
6098 if (eval_saved != NULL_TREE)
6099 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
6100 eval_saved, ret);
6101 }
6102
6103 // Add checks for division by zero and division overflow as needed.
6104 if (is_idiv_op)
6105 {
6106 if (go_check_divide_zero)
6107 {
6108 // right == 0
6109 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
6110 right,
6111 fold_convert_loc(gccloc,
6112 TREE_TYPE(right),
6113 integer_zero_node));
6114
6115 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO), 0
6116 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6117 tree panic = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
6118 gogo->runtime_error(errcode,
6119 this->location()),
6120 fold_convert_loc(gccloc, TREE_TYPE(ret),
6121 integer_zero_node));
6122
6123 // right == 0 ? (__go_runtime_error(...), 0) : ret
6124 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
6125 check, panic, ret);
6126 }
6127
6128 if (go_check_divide_overflow)
6129 {
6130 // right == -1
6131 // FIXME: It would be nice to say that this test is expected
6132 // to return false.
6133 tree m1 = integer_minus_one_node;
6134 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
6135 right,
6136 fold_convert_loc(gccloc,
6137 TREE_TYPE(right),
6138 m1));
6139
6140 tree overflow;
6141 if (TYPE_UNSIGNED(TREE_TYPE(ret)))
6142 {
6143 // An unsigned -1 is the largest possible number, so
6144 // dividing is always 1 or 0.
6145 tree cmp = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
6146 left, right);
6147 if (this->op_ == OPERATOR_DIV)
6148 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
6149 cmp,
6150 fold_convert_loc(gccloc,
6151 TREE_TYPE(ret),
6152 integer_one_node),
6153 fold_convert_loc(gccloc,
6154 TREE_TYPE(ret),
6155 integer_zero_node));
6156 else
6157 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
6158 cmp,
6159 fold_convert_loc(gccloc,
6160 TREE_TYPE(ret),
6161 integer_zero_node),
6162 left);
6163 }
6164 else
6165 {
6166 // Computing left / -1 is the same as computing - left,
6167 // which does not overflow since Go sets -fwrapv.
6168 if (this->op_ == OPERATOR_DIV)
6169 overflow = fold_build1_loc(gccloc, NEGATE_EXPR, TREE_TYPE(left),
6170 left);
6171 else
6172 overflow = integer_zero_node;
6173 }
6174 overflow = fold_convert_loc(gccloc, TREE_TYPE(ret), overflow);
6175
6176 // right == -1 ? - left : ret
6177 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
6178 check, overflow, ret);
6179 }
6180
6181 if (eval_saved != NULL_TREE)
6182 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
6183 eval_saved, ret);
6184 }
6185
6186 return ret;
6187 }
6188
6189 // Export a binary expression.
6190
6191 void
6192 Binary_expression::do_export(Export* exp) const
6193 {
6194 exp->write_c_string("(");
6195 this->left_->export_expression(exp);
6196 switch (this->op_)
6197 {
6198 case OPERATOR_OROR:
6199 exp->write_c_string(" || ");
6200 break;
6201 case OPERATOR_ANDAND:
6202 exp->write_c_string(" && ");
6203 break;
6204 case OPERATOR_EQEQ:
6205 exp->write_c_string(" == ");
6206 break;
6207 case OPERATOR_NOTEQ:
6208 exp->write_c_string(" != ");
6209 break;
6210 case OPERATOR_LT:
6211 exp->write_c_string(" < ");
6212 break;
6213 case OPERATOR_LE:
6214 exp->write_c_string(" <= ");
6215 break;
6216 case OPERATOR_GT:
6217 exp->write_c_string(" > ");
6218 break;
6219 case OPERATOR_GE:
6220 exp->write_c_string(" >= ");
6221 break;
6222 case OPERATOR_PLUS:
6223 exp->write_c_string(" + ");
6224 break;
6225 case OPERATOR_MINUS:
6226 exp->write_c_string(" - ");
6227 break;
6228 case OPERATOR_OR:
6229 exp->write_c_string(" | ");
6230 break;
6231 case OPERATOR_XOR:
6232 exp->write_c_string(" ^ ");
6233 break;
6234 case OPERATOR_MULT:
6235 exp->write_c_string(" * ");
6236 break;
6237 case OPERATOR_DIV:
6238 exp->write_c_string(" / ");
6239 break;
6240 case OPERATOR_MOD:
6241 exp->write_c_string(" % ");
6242 break;
6243 case OPERATOR_LSHIFT:
6244 exp->write_c_string(" << ");
6245 break;
6246 case OPERATOR_RSHIFT:
6247 exp->write_c_string(" >> ");
6248 break;
6249 case OPERATOR_AND:
6250 exp->write_c_string(" & ");
6251 break;
6252 case OPERATOR_BITCLEAR:
6253 exp->write_c_string(" &^ ");
6254 break;
6255 default:
6256 go_unreachable();
6257 }
6258 this->right_->export_expression(exp);
6259 exp->write_c_string(")");
6260 }
6261
6262 // Import a binary expression.
6263
6264 Expression*
6265 Binary_expression::do_import(Import* imp)
6266 {
6267 imp->require_c_string("(");
6268
6269 Expression* left = Expression::import_expression(imp);
6270
6271 Operator op;
6272 if (imp->match_c_string(" || "))
6273 {
6274 op = OPERATOR_OROR;
6275 imp->advance(4);
6276 }
6277 else if (imp->match_c_string(" && "))
6278 {
6279 op = OPERATOR_ANDAND;
6280 imp->advance(4);
6281 }
6282 else if (imp->match_c_string(" == "))
6283 {
6284 op = OPERATOR_EQEQ;
6285 imp->advance(4);
6286 }
6287 else if (imp->match_c_string(" != "))
6288 {
6289 op = OPERATOR_NOTEQ;
6290 imp->advance(4);
6291 }
6292 else if (imp->match_c_string(" < "))
6293 {
6294 op = OPERATOR_LT;
6295 imp->advance(3);
6296 }
6297 else if (imp->match_c_string(" <= "))
6298 {
6299 op = OPERATOR_LE;
6300 imp->advance(4);
6301 }
6302 else if (imp->match_c_string(" > "))
6303 {
6304 op = OPERATOR_GT;
6305 imp->advance(3);
6306 }
6307 else if (imp->match_c_string(" >= "))
6308 {
6309 op = OPERATOR_GE;
6310 imp->advance(4);
6311 }
6312 else if (imp->match_c_string(" + "))
6313 {
6314 op = OPERATOR_PLUS;
6315 imp->advance(3);
6316 }
6317 else if (imp->match_c_string(" - "))
6318 {
6319 op = OPERATOR_MINUS;
6320 imp->advance(3);
6321 }
6322 else if (imp->match_c_string(" | "))
6323 {
6324 op = OPERATOR_OR;
6325 imp->advance(3);
6326 }
6327 else if (imp->match_c_string(" ^ "))
6328 {
6329 op = OPERATOR_XOR;
6330 imp->advance(3);
6331 }
6332 else if (imp->match_c_string(" * "))
6333 {
6334 op = OPERATOR_MULT;
6335 imp->advance(3);
6336 }
6337 else if (imp->match_c_string(" / "))
6338 {
6339 op = OPERATOR_DIV;
6340 imp->advance(3);
6341 }
6342 else if (imp->match_c_string(" % "))
6343 {
6344 op = OPERATOR_MOD;
6345 imp->advance(3);
6346 }
6347 else if (imp->match_c_string(" << "))
6348 {
6349 op = OPERATOR_LSHIFT;
6350 imp->advance(4);
6351 }
6352 else if (imp->match_c_string(" >> "))
6353 {
6354 op = OPERATOR_RSHIFT;
6355 imp->advance(4);
6356 }
6357 else if (imp->match_c_string(" & "))
6358 {
6359 op = OPERATOR_AND;
6360 imp->advance(3);
6361 }
6362 else if (imp->match_c_string(" &^ "))
6363 {
6364 op = OPERATOR_BITCLEAR;
6365 imp->advance(4);
6366 }
6367 else
6368 {
6369 error_at(imp->location(), "unrecognized binary operator");
6370 return Expression::make_error(imp->location());
6371 }
6372
6373 Expression* right = Expression::import_expression(imp);
6374
6375 imp->require_c_string(")");
6376
6377 return Expression::make_binary(op, left, right, imp->location());
6378 }
6379
6380 // Dump ast representation of a binary expression.
6381
6382 void
6383 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6384 {
6385 ast_dump_context->ostream() << "(";
6386 ast_dump_context->dump_expression(this->left_);
6387 ast_dump_context->ostream() << " ";
6388 ast_dump_context->dump_operator(this->op_);
6389 ast_dump_context->ostream() << " ";
6390 ast_dump_context->dump_expression(this->right_);
6391 ast_dump_context->ostream() << ") ";
6392 }
6393
6394 // Make a binary expression.
6395
6396 Expression*
6397 Expression::make_binary(Operator op, Expression* left, Expression* right,
6398 Location location)
6399 {
6400 return new Binary_expression(op, left, right, location);
6401 }
6402
6403 // Implement a comparison.
6404
6405 tree
6406 Expression::comparison_tree(Translate_context* context, Type* result_type,
6407 Operator op, Type* left_type, tree left_tree,
6408 Type* right_type, tree right_tree,
6409 Location location)
6410 {
6411 Type* int_type = Type::lookup_integer_type("int");
6412 tree int_type_tree = type_to_tree(int_type->get_backend(context->gogo()));
6413
6414 enum tree_code code;
6415 switch (op)
6416 {
6417 case OPERATOR_EQEQ:
6418 code = EQ_EXPR;
6419 break;
6420 case OPERATOR_NOTEQ:
6421 code = NE_EXPR;
6422 break;
6423 case OPERATOR_LT:
6424 code = LT_EXPR;
6425 break;
6426 case OPERATOR_LE:
6427 code = LE_EXPR;
6428 break;
6429 case OPERATOR_GT:
6430 code = GT_EXPR;
6431 break;
6432 case OPERATOR_GE:
6433 code = GE_EXPR;
6434 break;
6435 default:
6436 go_unreachable();
6437 }
6438
6439 if (left_type->is_string_type() && right_type->is_string_type())
6440 {
6441 Type* st = Type::make_string_type();
6442 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6443 static tree string_compare_decl;
6444 left_tree = Gogo::call_builtin(&string_compare_decl,
6445 location,
6446 "__go_strcmp",
6447 2,
6448 int_type_tree,
6449 string_type,
6450 left_tree,
6451 string_type,
6452 right_tree);
6453 right_tree = build_int_cst_type(int_type_tree, 0);
6454 }
6455 else if ((left_type->interface_type() != NULL
6456 && right_type->interface_type() == NULL
6457 && !right_type->is_nil_type())
6458 || (left_type->interface_type() == NULL
6459 && !left_type->is_nil_type()
6460 && right_type->interface_type() != NULL))
6461 {
6462 // Comparing an interface value to a non-interface value.
6463 if (left_type->interface_type() == NULL)
6464 {
6465 std::swap(left_type, right_type);
6466 std::swap(left_tree, right_tree);
6467 }
6468
6469 // The right operand is not an interface. We need to take its
6470 // address if it is not a pointer.
6471 tree make_tmp;
6472 tree arg;
6473 if (right_type->points_to() != NULL)
6474 {
6475 make_tmp = NULL_TREE;
6476 arg = right_tree;
6477 }
6478 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree))
6479 || (TREE_CODE(right_tree) != CONST_DECL
6480 && DECL_P(right_tree)))
6481 {
6482 make_tmp = NULL_TREE;
6483 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6484 if (DECL_P(right_tree))
6485 TREE_ADDRESSABLE(right_tree) = 1;
6486 }
6487 else
6488 {
6489 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6490 get_name(right_tree));
6491 DECL_IGNORED_P(tmp) = 0;
6492 DECL_INITIAL(tmp) = right_tree;
6493 TREE_ADDRESSABLE(tmp) = 1;
6494 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6495 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6496 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6497 }
6498 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6499
6500 Bexpression* descriptor_bexpr =
6501 right_type->type_descriptor_pointer(context->gogo(), location);
6502 tree descriptor = expr_to_tree(descriptor_bexpr);
6503
6504 if (left_type->interface_type()->is_empty())
6505 {
6506 static tree empty_interface_value_compare_decl;
6507 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6508 location,
6509 "__go_empty_interface_value_compare",
6510 3,
6511 int_type_tree,
6512 TREE_TYPE(left_tree),
6513 left_tree,
6514 TREE_TYPE(descriptor),
6515 descriptor,
6516 ptr_type_node,
6517 arg);
6518 if (left_tree == error_mark_node)
6519 return error_mark_node;
6520 // This can panic if the type is not comparable.
6521 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6522 }
6523 else
6524 {
6525 static tree interface_value_compare_decl;
6526 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6527 location,
6528 "__go_interface_value_compare",
6529 3,
6530 int_type_tree,
6531 TREE_TYPE(left_tree),
6532 left_tree,
6533 TREE_TYPE(descriptor),
6534 descriptor,
6535 ptr_type_node,
6536 arg);
6537 if (left_tree == error_mark_node)
6538 return error_mark_node;
6539 // This can panic if the type is not comparable.
6540 TREE_NOTHROW(interface_value_compare_decl) = 0;
6541 }
6542 right_tree = build_int_cst_type(int_type_tree, 0);
6543
6544 if (make_tmp != NULL_TREE)
6545 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6546 left_tree);
6547 }
6548 else if (left_type->interface_type() != NULL
6549 && right_type->interface_type() != NULL)
6550 {
6551 if (left_type->interface_type()->is_empty()
6552 && right_type->interface_type()->is_empty())
6553 {
6554 static tree empty_interface_compare_decl;
6555 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6556 location,
6557 "__go_empty_interface_compare",
6558 2,
6559 int_type_tree,
6560 TREE_TYPE(left_tree),
6561 left_tree,
6562 TREE_TYPE(right_tree),
6563 right_tree);
6564 if (left_tree == error_mark_node)
6565 return error_mark_node;
6566 // This can panic if the type is uncomparable.
6567 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6568 }
6569 else if (!left_type->interface_type()->is_empty()
6570 && !right_type->interface_type()->is_empty())
6571 {
6572 static tree interface_compare_decl;
6573 left_tree = Gogo::call_builtin(&interface_compare_decl,
6574 location,
6575 "__go_interface_compare",
6576 2,
6577 int_type_tree,
6578 TREE_TYPE(left_tree),
6579 left_tree,
6580 TREE_TYPE(right_tree),
6581 right_tree);
6582 if (left_tree == error_mark_node)
6583 return error_mark_node;
6584 // This can panic if the type is uncomparable.
6585 TREE_NOTHROW(interface_compare_decl) = 0;
6586 }
6587 else
6588 {
6589 if (left_type->interface_type()->is_empty())
6590 {
6591 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6592 std::swap(left_type, right_type);
6593 std::swap(left_tree, right_tree);
6594 }
6595 go_assert(!left_type->interface_type()->is_empty());
6596 go_assert(right_type->interface_type()->is_empty());
6597 static tree interface_empty_compare_decl;
6598 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6599 location,
6600 "__go_interface_empty_compare",
6601 2,
6602 int_type_tree,
6603 TREE_TYPE(left_tree),
6604 left_tree,
6605 TREE_TYPE(right_tree),
6606 right_tree);
6607 if (left_tree == error_mark_node)
6608 return error_mark_node;
6609 // This can panic if the type is uncomparable.
6610 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6611 }
6612
6613 right_tree = build_int_cst_type(int_type_tree, 0);
6614 }
6615
6616 if (left_type->is_nil_type()
6617 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6618 {
6619 std::swap(left_type, right_type);
6620 std::swap(left_tree, right_tree);
6621 }
6622
6623 if (right_type->is_nil_type())
6624 {
6625 if (left_type->array_type() != NULL
6626 && left_type->array_type()->length() == NULL)
6627 {
6628 Array_type* at = left_type->array_type();
6629 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6630 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6631 }
6632 else if (left_type->interface_type() != NULL)
6633 {
6634 // An interface is nil if the first field is nil.
6635 tree left_type_tree = TREE_TYPE(left_tree);
6636 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6637 tree field = TYPE_FIELDS(left_type_tree);
6638 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6639 field, NULL_TREE);
6640 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6641 }
6642 else
6643 {
6644 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6645 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6646 }
6647 }
6648
6649 if (left_tree == error_mark_node || right_tree == error_mark_node)
6650 return error_mark_node;
6651
6652 tree result_type_tree;
6653 if (result_type == NULL)
6654 result_type_tree = boolean_type_node;
6655 else
6656 result_type_tree = type_to_tree(result_type->get_backend(context->gogo()));
6657
6658 tree ret = fold_build2(code, result_type_tree, left_tree, right_tree);
6659 if (CAN_HAVE_LOCATION_P(ret))
6660 SET_EXPR_LOCATION(ret, location.gcc_location());
6661 return ret;
6662 }
6663
6664 // Class Bound_method_expression.
6665
6666 // Traversal.
6667
6668 int
6669 Bound_method_expression::do_traverse(Traverse* traverse)
6670 {
6671 return Expression::traverse(&this->expr_, traverse);
6672 }
6673
6674 // Lower the expression. If this is a method value rather than being
6675 // called, and the method is accessed via a pointer, we may need to
6676 // add nil checks. Introduce a temporary variable so that those nil
6677 // checks do not cause multiple evaluation.
6678
6679 Expression*
6680 Bound_method_expression::do_lower(Gogo*, Named_object*,
6681 Statement_inserter* inserter, int)
6682 {
6683 // For simplicity we use a temporary for every call to an embedded
6684 // method, even though some of them might be pure value methods and
6685 // not require a temporary.
6686 if (this->expr_->var_expression() == NULL
6687 && this->expr_->temporary_reference_expression() == NULL
6688 && this->expr_->set_and_use_temporary_expression() == NULL
6689 && (this->method_->field_indexes() != NULL
6690 || (this->method_->is_value_method()
6691 && this->expr_->type()->points_to() != NULL)))
6692 {
6693 Temporary_statement* temp =
6694 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6695 inserter->insert(temp);
6696 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6697 this->location());
6698 }
6699 return this;
6700 }
6701
6702 // Return the type of a bound method expression. The type of this
6703 // object is simply the type of the method with no receiver.
6704
6705 Type*
6706 Bound_method_expression::do_type()
6707 {
6708 Named_object* fn = this->method_->named_object();
6709 Function_type* fntype;
6710 if (fn->is_function())
6711 fntype = fn->func_value()->type();
6712 else if (fn->is_function_declaration())
6713 fntype = fn->func_declaration_value()->type();
6714 else
6715 return Type::make_error_type();
6716 return fntype->copy_without_receiver();
6717 }
6718
6719 // Determine the types of a method expression.
6720
6721 void
6722 Bound_method_expression::do_determine_type(const Type_context*)
6723 {
6724 Named_object* fn = this->method_->named_object();
6725 Function_type* fntype;
6726 if (fn->is_function())
6727 fntype = fn->func_value()->type();
6728 else if (fn->is_function_declaration())
6729 fntype = fn->func_declaration_value()->type();
6730 else
6731 fntype = NULL;
6732 if (fntype == NULL || !fntype->is_method())
6733 this->expr_->determine_type_no_context();
6734 else
6735 {
6736 Type_context subcontext(fntype->receiver()->type(), false);
6737 this->expr_->determine_type(&subcontext);
6738 }
6739 }
6740
6741 // Check the types of a method expression.
6742
6743 void
6744 Bound_method_expression::do_check_types(Gogo*)
6745 {
6746 Named_object* fn = this->method_->named_object();
6747 if (!fn->is_function() && !fn->is_function_declaration())
6748 {
6749 this->report_error(_("object is not a method"));
6750 return;
6751 }
6752
6753 Function_type* fntype;
6754 if (fn->is_function())
6755 fntype = fn->func_value()->type();
6756 else if (fn->is_function_declaration())
6757 fntype = fn->func_declaration_value()->type();
6758 else
6759 go_unreachable();
6760 Type* rtype = fntype->receiver()->type()->deref();
6761 Type* etype = (this->expr_type_ != NULL
6762 ? this->expr_type_
6763 : this->expr_->type());
6764 etype = etype->deref();
6765 if (!Type::are_identical(rtype, etype, true, NULL))
6766 this->report_error(_("method type does not match object type"));
6767 }
6768
6769 // If a bound method expression is not simply called, then it is
6770 // represented as a closure. The closure will hold a single variable,
6771 // the receiver to pass to the method. The function will be a simple
6772 // thunk that pulls that value from the closure and calls the method
6773 // with the remaining arguments.
6774 //
6775 // Because method values are not common, we don't build all thunks for
6776 // every methods, but instead only build them as we need them. In
6777 // particular, we even build them on demand for methods defined in
6778 // other packages.
6779
6780 Bound_method_expression::Method_value_thunks
6781 Bound_method_expression::method_value_thunks;
6782
6783 // Find or create the thunk for METHOD.
6784
6785 Named_object*
6786 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6787 Named_object* fn)
6788 {
6789 std::pair<Named_object*, Named_object*> val(fn, NULL);
6790 std::pair<Method_value_thunks::iterator, bool> ins =
6791 Bound_method_expression::method_value_thunks.insert(val);
6792 if (!ins.second)
6793 {
6794 // We have seen this method before.
6795 go_assert(ins.first->second != NULL);
6796 return ins.first->second;
6797 }
6798
6799 Location loc = fn->location();
6800
6801 Function_type* orig_fntype;
6802 if (fn->is_function())
6803 orig_fntype = fn->func_value()->type();
6804 else if (fn->is_function_declaration())
6805 orig_fntype = fn->func_declaration_value()->type();
6806 else
6807 orig_fntype = NULL;
6808
6809 if (orig_fntype == NULL || !orig_fntype->is_method())
6810 {
6811 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6812 return ins.first->second;
6813 }
6814
6815 Struct_field_list* sfl = new Struct_field_list();
6816 // The type here is wrong--it should be the C function type. But it
6817 // doesn't really matter.
6818 Type* vt = Type::make_pointer_type(Type::make_void_type());
6819 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6820 sfl->push_back(Struct_field(Typed_identifier("val.1",
6821 orig_fntype->receiver()->type(),
6822 loc)));
6823 Type* closure_type = Type::make_struct_type(sfl, loc);
6824 closure_type = Type::make_pointer_type(closure_type);
6825
6826 Function_type* new_fntype = orig_fntype->copy_with_names();
6827
6828 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6829 false, loc);
6830
6831 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6832 cvar->set_is_used();
6833 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6834 new_no->func_value()->set_closure_var(cp);
6835
6836 gogo->start_block(loc);
6837
6838 // Field 0 of the closure is the function code pointer, field 1 is
6839 // the value on which to invoke the method.
6840 Expression* arg = Expression::make_var_reference(cp, loc);
6841 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6842 arg = Expression::make_field_reference(arg, 1, loc);
6843
6844 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6845
6846 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6847 Expression_list* args;
6848 if (orig_params == NULL || orig_params->empty())
6849 args = NULL;
6850 else
6851 {
6852 const Typed_identifier_list* new_params = new_fntype->parameters();
6853 args = new Expression_list();
6854 for (Typed_identifier_list::const_iterator p = new_params->begin();
6855 p != new_params->end();
6856 ++p)
6857 {
6858 Named_object* p_no = gogo->lookup(p->name(), NULL);
6859 go_assert(p_no != NULL
6860 && p_no->is_variable()
6861 && p_no->var_value()->is_parameter());
6862 args->push_back(Expression::make_var_reference(p_no, loc));
6863 }
6864 }
6865
6866 Call_expression* call = Expression::make_call(bme, args,
6867 orig_fntype->is_varargs(),
6868 loc);
6869 call->set_varargs_are_lowered();
6870
6871 Statement* s = Statement::make_return_from_call(call, loc);
6872 gogo->add_statement(s);
6873 Block* b = gogo->finish_block(loc);
6874 gogo->add_block(b, loc);
6875 gogo->lower_block(new_no, b);
6876 gogo->finish_function(loc);
6877
6878 ins.first->second = new_no;
6879 return new_no;
6880 }
6881
6882 // Return an expression to check *REF for nil while dereferencing
6883 // according to FIELD_INDEXES. Update *REF to build up the field
6884 // reference. This is a static function so that we don't have to
6885 // worry about declaring Field_indexes in expressions.h.
6886
6887 static Expression*
6888 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6889 Expression** ref)
6890 {
6891 if (field_indexes == NULL)
6892 return Expression::make_boolean(false, loc);
6893 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6894 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6895 go_assert(stype != NULL
6896 && field_indexes->field_index < stype->field_count());
6897 if ((*ref)->type()->struct_type() == NULL)
6898 {
6899 go_assert((*ref)->type()->points_to() != NULL);
6900 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6901 Expression::make_nil(loc),
6902 loc);
6903 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6904 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6905 go_assert((*ref)->type()->struct_type() == stype);
6906 }
6907 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6908 loc);
6909 return cond;
6910 }
6911
6912 // Get the tree for a method value.
6913
6914 tree
6915 Bound_method_expression::do_get_tree(Translate_context* context)
6916 {
6917 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6918 this->method_,
6919 this->function_);
6920 if (thunk->is_erroneous())
6921 {
6922 go_assert(saw_errors());
6923 return error_mark_node;
6924 }
6925
6926 // FIXME: We should lower this earlier, but we can't lower it in the
6927 // lowering pass because at that point we don't know whether we need
6928 // to create the thunk or not. If the expression is called, we
6929 // don't need the thunk.
6930
6931 Location loc = this->location();
6932
6933 // If the method expects a value, and we have a pointer, we need to
6934 // dereference the pointer.
6935
6936 Named_object* fn = this->method_->named_object();
6937 Function_type* fntype;
6938 if (fn->is_function())
6939 fntype = fn->func_value()->type();
6940 else if (fn->is_function_declaration())
6941 fntype = fn->func_declaration_value()->type();
6942 else
6943 go_unreachable();
6944
6945 Expression* val = this->expr_;
6946 if (fntype->receiver()->type()->points_to() == NULL
6947 && val->type()->points_to() != NULL)
6948 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6949
6950 // Note that we are ignoring this->expr_type_ here. The thunk will
6951 // expect a closure whose second field has type this->expr_type_ (if
6952 // that is not NULL). We are going to pass it a closure whose
6953 // second field has type this->expr_->type(). Since
6954 // this->expr_type_ is only not-NULL for pointer types, we can get
6955 // away with this.
6956
6957 Struct_field_list* fields = new Struct_field_list();
6958 fields->push_back(Struct_field(Typed_identifier("fn.0",
6959 thunk->func_value()->type(),
6960 loc)));
6961 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6962 Struct_type* st = Type::make_struct_type(fields, loc);
6963
6964 Expression_list* vals = new Expression_list();
6965 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6966 vals->push_back(val);
6967
6968 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6969 ret = Expression::make_heap_composite(ret, loc);
6970
6971 tree ret_tree = ret->get_tree(context);
6972
6973 Expression* nil_check = NULL;
6974
6975 // See whether the expression or any embedded pointers are nil.
6976
6977 Expression* expr = this->expr_;
6978 if (this->method_->field_indexes() != NULL)
6979 {
6980 // Note that we are evaluating this->expr_ twice, but that is OK
6981 // because in the lowering pass we forced it into a temporary
6982 // variable.
6983 Expression* ref = expr;
6984 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6985 expr = ref;
6986 }
6987
6988 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6989 {
6990 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6991 Expression::make_nil(loc),
6992 loc);
6993 if (nil_check == NULL)
6994 nil_check = n;
6995 else
6996 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6997 }
6998
6999 if (nil_check != NULL)
7000 {
7001 tree nil_check_tree = nil_check->get_tree(context);
7002 tree crash =
7003 context->gogo()->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
7004 if (ret_tree == error_mark_node
7005 || nil_check_tree == error_mark_node
7006 || crash == error_mark_node)
7007 return error_mark_node;
7008
7009 ret_tree = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
7010 TREE_TYPE(ret_tree),
7011 build3_loc(loc.gcc_location(), COND_EXPR,
7012 void_type_node, nil_check_tree,
7013 crash, NULL_TREE),
7014 ret_tree);
7015 }
7016
7017 return ret_tree;
7018 }
7019
7020 // Dump ast representation of a bound method expression.
7021
7022 void
7023 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7024 const
7025 {
7026 if (this->expr_type_ != NULL)
7027 ast_dump_context->ostream() << "(";
7028 ast_dump_context->dump_expression(this->expr_);
7029 if (this->expr_type_ != NULL)
7030 {
7031 ast_dump_context->ostream() << ":";
7032 ast_dump_context->dump_type(this->expr_type_);
7033 ast_dump_context->ostream() << ")";
7034 }
7035
7036 ast_dump_context->ostream() << "." << this->function_->name();
7037 }
7038
7039 // Make a method expression.
7040
7041 Bound_method_expression*
7042 Expression::make_bound_method(Expression* expr, const Method* method,
7043 Named_object* function, Location location)
7044 {
7045 return new Bound_method_expression(expr, method, function, location);
7046 }
7047
7048 // Class Builtin_call_expression. This is used for a call to a
7049 // builtin function.
7050
7051 class Builtin_call_expression : public Call_expression
7052 {
7053 public:
7054 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
7055 bool is_varargs, Location location);
7056
7057 protected:
7058 // This overrides Call_expression::do_lower.
7059 Expression*
7060 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7061
7062 bool
7063 do_is_constant() const;
7064
7065 bool
7066 do_numeric_constant_value(Numeric_constant*) const;
7067
7068 bool
7069 do_discarding_value();
7070
7071 Type*
7072 do_type();
7073
7074 void
7075 do_determine_type(const Type_context*);
7076
7077 void
7078 do_check_types(Gogo*);
7079
7080 Expression*
7081 do_copy()
7082 {
7083 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
7084 this->args()->copy(),
7085 this->is_varargs(),
7086 this->location());
7087 }
7088
7089 tree
7090 do_get_tree(Translate_context*);
7091
7092 void
7093 do_export(Export*) const;
7094
7095 virtual bool
7096 do_is_recover_call() const;
7097
7098 virtual void
7099 do_set_recover_arg(Expression*);
7100
7101 private:
7102 // The builtin functions.
7103 enum Builtin_function_code
7104 {
7105 BUILTIN_INVALID,
7106
7107 // Predeclared builtin functions.
7108 BUILTIN_APPEND,
7109 BUILTIN_CAP,
7110 BUILTIN_CLOSE,
7111 BUILTIN_COMPLEX,
7112 BUILTIN_COPY,
7113 BUILTIN_DELETE,
7114 BUILTIN_IMAG,
7115 BUILTIN_LEN,
7116 BUILTIN_MAKE,
7117 BUILTIN_NEW,
7118 BUILTIN_PANIC,
7119 BUILTIN_PRINT,
7120 BUILTIN_PRINTLN,
7121 BUILTIN_REAL,
7122 BUILTIN_RECOVER,
7123
7124 // Builtin functions from the unsafe package.
7125 BUILTIN_ALIGNOF,
7126 BUILTIN_OFFSETOF,
7127 BUILTIN_SIZEOF
7128 };
7129
7130 Expression*
7131 one_arg() const;
7132
7133 bool
7134 check_one_arg();
7135
7136 static Type*
7137 real_imag_type(Type*);
7138
7139 static Type*
7140 complex_type(Type*);
7141
7142 Expression*
7143 lower_make();
7144
7145 bool
7146 check_int_value(Expression*, bool is_length);
7147
7148 // A pointer back to the general IR structure. This avoids a global
7149 // variable, or passing it around everywhere.
7150 Gogo* gogo_;
7151 // The builtin function being called.
7152 Builtin_function_code code_;
7153 // Used to stop endless loops when the length of an array uses len
7154 // or cap of the array itself.
7155 mutable bool seen_;
7156 };
7157
7158 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7159 Expression* fn,
7160 Expression_list* args,
7161 bool is_varargs,
7162 Location location)
7163 : Call_expression(fn, args, is_varargs, location),
7164 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
7165 {
7166 Func_expression* fnexp = this->fn()->func_expression();
7167 go_assert(fnexp != NULL);
7168 const std::string& name(fnexp->named_object()->name());
7169 if (name == "append")
7170 this->code_ = BUILTIN_APPEND;
7171 else if (name == "cap")
7172 this->code_ = BUILTIN_CAP;
7173 else if (name == "close")
7174 this->code_ = BUILTIN_CLOSE;
7175 else if (name == "complex")
7176 this->code_ = BUILTIN_COMPLEX;
7177 else if (name == "copy")
7178 this->code_ = BUILTIN_COPY;
7179 else if (name == "delete")
7180 this->code_ = BUILTIN_DELETE;
7181 else if (name == "imag")
7182 this->code_ = BUILTIN_IMAG;
7183 else if (name == "len")
7184 this->code_ = BUILTIN_LEN;
7185 else if (name == "make")
7186 this->code_ = BUILTIN_MAKE;
7187 else if (name == "new")
7188 this->code_ = BUILTIN_NEW;
7189 else if (name == "panic")
7190 this->code_ = BUILTIN_PANIC;
7191 else if (name == "print")
7192 this->code_ = BUILTIN_PRINT;
7193 else if (name == "println")
7194 this->code_ = BUILTIN_PRINTLN;
7195 else if (name == "real")
7196 this->code_ = BUILTIN_REAL;
7197 else if (name == "recover")
7198 this->code_ = BUILTIN_RECOVER;
7199 else if (name == "Alignof")
7200 this->code_ = BUILTIN_ALIGNOF;
7201 else if (name == "Offsetof")
7202 this->code_ = BUILTIN_OFFSETOF;
7203 else if (name == "Sizeof")
7204 this->code_ = BUILTIN_SIZEOF;
7205 else
7206 go_unreachable();
7207 }
7208
7209 // Return whether this is a call to recover. This is a virtual
7210 // function called from the parent class.
7211
7212 bool
7213 Builtin_call_expression::do_is_recover_call() const
7214 {
7215 if (this->classification() == EXPRESSION_ERROR)
7216 return false;
7217 return this->code_ == BUILTIN_RECOVER;
7218 }
7219
7220 // Set the argument for a call to recover.
7221
7222 void
7223 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7224 {
7225 const Expression_list* args = this->args();
7226 go_assert(args == NULL || args->empty());
7227 Expression_list* new_args = new Expression_list();
7228 new_args->push_back(arg);
7229 this->set_args(new_args);
7230 }
7231
7232 // Lower a builtin call expression. This turns new and make into
7233 // specific expressions. We also convert to a constant if we can.
7234
7235 Expression*
7236 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7237 Statement_inserter* inserter, int)
7238 {
7239 if (this->classification() == EXPRESSION_ERROR)
7240 return this;
7241
7242 Location loc = this->location();
7243
7244 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7245 {
7246 this->report_error(_("invalid use of %<...%> with builtin function"));
7247 return Expression::make_error(loc);
7248 }
7249
7250 if (this->code_ == BUILTIN_OFFSETOF)
7251 {
7252 Expression* arg = this->one_arg();
7253
7254 if (arg->bound_method_expression() != NULL
7255 || arg->interface_field_reference_expression() != NULL)
7256 {
7257 this->report_error(_("invalid use of method value as argument "
7258 "of Offsetof"));
7259 return this;
7260 }
7261
7262 Field_reference_expression* farg = arg->field_reference_expression();
7263 while (farg != NULL)
7264 {
7265 if (!farg->implicit())
7266 break;
7267 // When the selector refers to an embedded field,
7268 // it must not be reached through pointer indirections.
7269 if (farg->expr()->deref() != farg->expr())
7270 {
7271 this->report_error(_("argument of Offsetof implies "
7272 "indirection of an embedded field"));
7273 return this;
7274 }
7275 // Go up until we reach the original base.
7276 farg = farg->expr()->field_reference_expression();
7277 }
7278 }
7279
7280 if (this->is_constant())
7281 {
7282 Numeric_constant nc;
7283 if (this->numeric_constant_value(&nc))
7284 return nc.expression(loc);
7285 }
7286
7287 switch (this->code_)
7288 {
7289 default:
7290 break;
7291
7292 case BUILTIN_NEW:
7293 {
7294 const Expression_list* args = this->args();
7295 if (args == NULL || args->size() < 1)
7296 this->report_error(_("not enough arguments"));
7297 else if (args->size() > 1)
7298 this->report_error(_("too many arguments"));
7299 else
7300 {
7301 Expression* arg = args->front();
7302 if (!arg->is_type_expression())
7303 {
7304 error_at(arg->location(), "expected type");
7305 this->set_is_error();
7306 }
7307 else
7308 return Expression::make_allocation(arg->type(), loc);
7309 }
7310 }
7311 break;
7312
7313 case BUILTIN_MAKE:
7314 return this->lower_make();
7315
7316 case BUILTIN_RECOVER:
7317 if (function != NULL)
7318 function->func_value()->set_calls_recover();
7319 else
7320 {
7321 // Calling recover outside of a function always returns the
7322 // nil empty interface.
7323 Type* eface = Type::make_empty_interface_type(loc);
7324 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7325 }
7326 break;
7327
7328 case BUILTIN_APPEND:
7329 {
7330 // Lower the varargs.
7331 const Expression_list* args = this->args();
7332 if (args == NULL || args->empty())
7333 return this;
7334 Type* slice_type = args->front()->type();
7335 if (!slice_type->is_slice_type())
7336 {
7337 error_at(args->front()->location(), "argument 1 must be a slice");
7338 this->set_is_error();
7339 return this;
7340 }
7341 Type* element_type = slice_type->array_type()->element_type();
7342 this->lower_varargs(gogo, function, inserter,
7343 Type::make_array_type(element_type, NULL),
7344 2);
7345 }
7346 break;
7347
7348 case BUILTIN_DELETE:
7349 {
7350 // Lower to a runtime function call.
7351 const Expression_list* args = this->args();
7352 if (args == NULL || args->size() < 2)
7353 this->report_error(_("not enough arguments"));
7354 else if (args->size() > 2)
7355 this->report_error(_("too many arguments"));
7356 else if (args->front()->type()->map_type() == NULL)
7357 this->report_error(_("argument 1 must be a map"));
7358 else
7359 {
7360 // Since this function returns no value it must appear in
7361 // a statement by itself, so we don't have to worry about
7362 // order of evaluation of values around it. Evaluate the
7363 // map first to get order of evaluation right.
7364 Map_type* mt = args->front()->type()->map_type();
7365 Temporary_statement* map_temp =
7366 Statement::make_temporary(mt, args->front(), loc);
7367 inserter->insert(map_temp);
7368
7369 Temporary_statement* key_temp =
7370 Statement::make_temporary(mt->key_type(), args->back(), loc);
7371 inserter->insert(key_temp);
7372
7373 Expression* e1 = Expression::make_temporary_reference(map_temp,
7374 loc);
7375 Expression* e2 = Expression::make_temporary_reference(key_temp,
7376 loc);
7377 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7378 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7379 2, e1, e2);
7380 }
7381 }
7382 break;
7383 }
7384
7385 return this;
7386 }
7387
7388 // Lower a make expression.
7389
7390 Expression*
7391 Builtin_call_expression::lower_make()
7392 {
7393 Location loc = this->location();
7394
7395 const Expression_list* args = this->args();
7396 if (args == NULL || args->size() < 1)
7397 {
7398 this->report_error(_("not enough arguments"));
7399 return Expression::make_error(this->location());
7400 }
7401
7402 Expression_list::const_iterator parg = args->begin();
7403
7404 Expression* first_arg = *parg;
7405 if (!first_arg->is_type_expression())
7406 {
7407 error_at(first_arg->location(), "expected type");
7408 this->set_is_error();
7409 return Expression::make_error(this->location());
7410 }
7411 Type* type = first_arg->type();
7412
7413 bool is_slice = false;
7414 bool is_map = false;
7415 bool is_chan = false;
7416 if (type->is_slice_type())
7417 is_slice = true;
7418 else if (type->map_type() != NULL)
7419 is_map = true;
7420 else if (type->channel_type() != NULL)
7421 is_chan = true;
7422 else
7423 {
7424 this->report_error(_("invalid type for make function"));
7425 return Expression::make_error(this->location());
7426 }
7427
7428 bool have_big_args = false;
7429 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7430 int uintptr_bits = uintptr_type->integer_type()->bits();
7431
7432 Type_context int_context(Type::lookup_integer_type("int"), false);
7433
7434 ++parg;
7435 Expression* len_arg;
7436 if (parg == args->end())
7437 {
7438 if (is_slice)
7439 {
7440 this->report_error(_("length required when allocating a slice"));
7441 return Expression::make_error(this->location());
7442 }
7443
7444 mpz_t zval;
7445 mpz_init_set_ui(zval, 0);
7446 len_arg = Expression::make_integer(&zval, NULL, loc);
7447 mpz_clear(zval);
7448 }
7449 else
7450 {
7451 len_arg = *parg;
7452 len_arg->determine_type(&int_context);
7453 if (!this->check_int_value(len_arg, true))
7454 return Expression::make_error(this->location());
7455 if (len_arg->type()->integer_type() != NULL
7456 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7457 have_big_args = true;
7458 ++parg;
7459 }
7460
7461 Expression* cap_arg = NULL;
7462 if (is_slice && parg != args->end())
7463 {
7464 cap_arg = *parg;
7465 cap_arg->determine_type(&int_context);
7466 if (!this->check_int_value(cap_arg, false))
7467 return Expression::make_error(this->location());
7468
7469 Numeric_constant nclen;
7470 Numeric_constant nccap;
7471 unsigned long vlen;
7472 unsigned long vcap;
7473 if (len_arg->numeric_constant_value(&nclen)
7474 && cap_arg->numeric_constant_value(&nccap)
7475 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7476 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7477 && vlen > vcap)
7478 {
7479 this->report_error(_("len larger than cap"));
7480 return Expression::make_error(this->location());
7481 }
7482
7483 if (cap_arg->type()->integer_type() != NULL
7484 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7485 have_big_args = true;
7486 ++parg;
7487 }
7488
7489 if (parg != args->end())
7490 {
7491 this->report_error(_("too many arguments to make"));
7492 return Expression::make_error(this->location());
7493 }
7494
7495 Location type_loc = first_arg->location();
7496 Expression* type_arg;
7497 if (is_slice || is_chan)
7498 type_arg = Expression::make_type_descriptor(type, type_loc);
7499 else if (is_map)
7500 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7501 else
7502 go_unreachable();
7503
7504 Expression* call;
7505 if (is_slice)
7506 {
7507 if (cap_arg == NULL)
7508 call = Runtime::make_call((have_big_args
7509 ? Runtime::MAKESLICE1BIG
7510 : Runtime::MAKESLICE1),
7511 loc, 2, type_arg, len_arg);
7512 else
7513 call = Runtime::make_call((have_big_args
7514 ? Runtime::MAKESLICE2BIG
7515 : Runtime::MAKESLICE2),
7516 loc, 3, type_arg, len_arg, cap_arg);
7517 }
7518 else if (is_map)
7519 call = Runtime::make_call((have_big_args
7520 ? Runtime::MAKEMAPBIG
7521 : Runtime::MAKEMAP),
7522 loc, 2, type_arg, len_arg);
7523 else if (is_chan)
7524 call = Runtime::make_call((have_big_args
7525 ? Runtime::MAKECHANBIG
7526 : Runtime::MAKECHAN),
7527 loc, 2, type_arg, len_arg);
7528 else
7529 go_unreachable();
7530
7531 return Expression::make_unsafe_cast(type, call, loc);
7532 }
7533
7534 // Return whether an expression has an integer value. Report an error
7535 // if not. This is used when handling calls to the predeclared make
7536 // function.
7537
7538 bool
7539 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7540 {
7541 Numeric_constant nc;
7542 if (e->numeric_constant_value(&nc))
7543 {
7544 unsigned long v;
7545 switch (nc.to_unsigned_long(&v))
7546 {
7547 case Numeric_constant::NC_UL_VALID:
7548 break;
7549 case Numeric_constant::NC_UL_NOTINT:
7550 error_at(e->location(), "non-integer %s argument to make",
7551 is_length ? "len" : "cap");
7552 return false;
7553 case Numeric_constant::NC_UL_NEGATIVE:
7554 error_at(e->location(), "negative %s argument to make",
7555 is_length ? "len" : "cap");
7556 return false;
7557 case Numeric_constant::NC_UL_BIG:
7558 // We don't want to give a compile-time error for a 64-bit
7559 // value on a 32-bit target.
7560 break;
7561 }
7562
7563 mpz_t val;
7564 if (!nc.to_int(&val))
7565 go_unreachable();
7566 int bits = mpz_sizeinbase(val, 2);
7567 mpz_clear(val);
7568 Type* int_type = Type::lookup_integer_type("int");
7569 if (bits >= int_type->integer_type()->bits())
7570 {
7571 error_at(e->location(), "%s argument too large for make",
7572 is_length ? "len" : "cap");
7573 return false;
7574 }
7575
7576 return true;
7577 }
7578
7579 if (e->type()->integer_type() != NULL)
7580 return true;
7581
7582 error_at(e->location(), "non-integer %s argument to make",
7583 is_length ? "len" : "cap");
7584 return false;
7585 }
7586
7587 // Return the type of the real or imag functions, given the type of
7588 // the argument. We need to map complex to float, complex64 to
7589 // float32, and complex128 to float64, so it has to be done by name.
7590 // This returns NULL if it can't figure out the type.
7591
7592 Type*
7593 Builtin_call_expression::real_imag_type(Type* arg_type)
7594 {
7595 if (arg_type == NULL || arg_type->is_abstract())
7596 return NULL;
7597 Named_type* nt = arg_type->named_type();
7598 if (nt == NULL)
7599 return NULL;
7600 while (nt->real_type()->named_type() != NULL)
7601 nt = nt->real_type()->named_type();
7602 if (nt->name() == "complex64")
7603 return Type::lookup_float_type("float32");
7604 else if (nt->name() == "complex128")
7605 return Type::lookup_float_type("float64");
7606 else
7607 return NULL;
7608 }
7609
7610 // Return the type of the complex function, given the type of one of the
7611 // argments. Like real_imag_type, we have to map by name.
7612
7613 Type*
7614 Builtin_call_expression::complex_type(Type* arg_type)
7615 {
7616 if (arg_type == NULL || arg_type->is_abstract())
7617 return NULL;
7618 Named_type* nt = arg_type->named_type();
7619 if (nt == NULL)
7620 return NULL;
7621 while (nt->real_type()->named_type() != NULL)
7622 nt = nt->real_type()->named_type();
7623 if (nt->name() == "float32")
7624 return Type::lookup_complex_type("complex64");
7625 else if (nt->name() == "float64")
7626 return Type::lookup_complex_type("complex128");
7627 else
7628 return NULL;
7629 }
7630
7631 // Return a single argument, or NULL if there isn't one.
7632
7633 Expression*
7634 Builtin_call_expression::one_arg() const
7635 {
7636 const Expression_list* args = this->args();
7637 if (args == NULL || args->size() != 1)
7638 return NULL;
7639 return args->front();
7640 }
7641
7642 // A traversal class which looks for a call or receive expression.
7643
7644 class Find_call_expression : public Traverse
7645 {
7646 public:
7647 Find_call_expression()
7648 : Traverse(traverse_expressions),
7649 found_(false)
7650 { }
7651
7652 int
7653 expression(Expression**);
7654
7655 bool
7656 found()
7657 { return this->found_; }
7658
7659 private:
7660 bool found_;
7661 };
7662
7663 int
7664 Find_call_expression::expression(Expression** pexpr)
7665 {
7666 if ((*pexpr)->call_expression() != NULL
7667 || (*pexpr)->receive_expression() != NULL)
7668 {
7669 this->found_ = true;
7670 return TRAVERSE_EXIT;
7671 }
7672 return TRAVERSE_CONTINUE;
7673 }
7674
7675 // Return whether this is constant: len of a string constant, or len
7676 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7677 // unsafe.Alignof.
7678
7679 bool
7680 Builtin_call_expression::do_is_constant() const
7681 {
7682 if (this->is_error_expression())
7683 return true;
7684 switch (this->code_)
7685 {
7686 case BUILTIN_LEN:
7687 case BUILTIN_CAP:
7688 {
7689 if (this->seen_)
7690 return false;
7691
7692 Expression* arg = this->one_arg();
7693 if (arg == NULL)
7694 return false;
7695 Type* arg_type = arg->type();
7696
7697 if (arg_type->points_to() != NULL
7698 && arg_type->points_to()->array_type() != NULL
7699 && !arg_type->points_to()->is_slice_type())
7700 arg_type = arg_type->points_to();
7701
7702 // The len and cap functions are only constant if there are no
7703 // function calls or channel operations in the arguments.
7704 // Otherwise we have to make the call.
7705 if (!arg->is_constant())
7706 {
7707 Find_call_expression find_call;
7708 Expression::traverse(&arg, &find_call);
7709 if (find_call.found())
7710 return false;
7711 }
7712
7713 if (arg_type->array_type() != NULL
7714 && arg_type->array_type()->length() != NULL)
7715 return true;
7716
7717 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7718 {
7719 this->seen_ = true;
7720 bool ret = arg->is_constant();
7721 this->seen_ = false;
7722 return ret;
7723 }
7724 }
7725 break;
7726
7727 case BUILTIN_SIZEOF:
7728 case BUILTIN_ALIGNOF:
7729 return this->one_arg() != NULL;
7730
7731 case BUILTIN_OFFSETOF:
7732 {
7733 Expression* arg = this->one_arg();
7734 if (arg == NULL)
7735 return false;
7736 return arg->field_reference_expression() != NULL;
7737 }
7738
7739 case BUILTIN_COMPLEX:
7740 {
7741 const Expression_list* args = this->args();
7742 if (args != NULL && args->size() == 2)
7743 return args->front()->is_constant() && args->back()->is_constant();
7744 }
7745 break;
7746
7747 case BUILTIN_REAL:
7748 case BUILTIN_IMAG:
7749 {
7750 Expression* arg = this->one_arg();
7751 return arg != NULL && arg->is_constant();
7752 }
7753
7754 default:
7755 break;
7756 }
7757
7758 return false;
7759 }
7760
7761 // Return a numeric constant if possible.
7762
7763 bool
7764 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7765 {
7766 if (this->code_ == BUILTIN_LEN
7767 || this->code_ == BUILTIN_CAP)
7768 {
7769 Expression* arg = this->one_arg();
7770 if (arg == NULL)
7771 return false;
7772 Type* arg_type = arg->type();
7773
7774 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7775 {
7776 std::string sval;
7777 if (arg->string_constant_value(&sval))
7778 {
7779 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7780 sval.length());
7781 return true;
7782 }
7783 }
7784
7785 if (arg_type->points_to() != NULL
7786 && arg_type->points_to()->array_type() != NULL
7787 && !arg_type->points_to()->is_slice_type())
7788 arg_type = arg_type->points_to();
7789
7790 if (arg_type->array_type() != NULL
7791 && arg_type->array_type()->length() != NULL)
7792 {
7793 if (this->seen_)
7794 return false;
7795 Expression* e = arg_type->array_type()->length();
7796 this->seen_ = true;
7797 bool r = e->numeric_constant_value(nc);
7798 this->seen_ = false;
7799 if (r)
7800 {
7801 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7802 this->location()))
7803 r = false;
7804 }
7805 return r;
7806 }
7807 }
7808 else if (this->code_ == BUILTIN_SIZEOF
7809 || this->code_ == BUILTIN_ALIGNOF)
7810 {
7811 Expression* arg = this->one_arg();
7812 if (arg == NULL)
7813 return false;
7814 Type* arg_type = arg->type();
7815 if (arg_type->is_error())
7816 return false;
7817 if (arg_type->is_abstract())
7818 return false;
7819
7820 unsigned int ret;
7821 if (this->code_ == BUILTIN_SIZEOF)
7822 {
7823 if (!arg_type->backend_type_size(this->gogo_, &ret))
7824 return false;
7825 }
7826 else if (this->code_ == BUILTIN_ALIGNOF)
7827 {
7828 if (arg->field_reference_expression() == NULL)
7829 {
7830 if (!arg_type->backend_type_align(this->gogo_, &ret))
7831 return false;
7832 }
7833 else
7834 {
7835 // Calling unsafe.Alignof(s.f) returns the alignment of
7836 // the type of f when it is used as a field in a struct.
7837 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7838 return false;
7839 }
7840 }
7841 else
7842 go_unreachable();
7843
7844 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7845 static_cast<unsigned long>(ret));
7846 return true;
7847 }
7848 else if (this->code_ == BUILTIN_OFFSETOF)
7849 {
7850 Expression* arg = this->one_arg();
7851 if (arg == NULL)
7852 return false;
7853 Field_reference_expression* farg = arg->field_reference_expression();
7854 if (farg == NULL)
7855 return false;
7856 unsigned int total_offset = 0;
7857 while (true)
7858 {
7859 Expression* struct_expr = farg->expr();
7860 Type* st = struct_expr->type();
7861 if (st->struct_type() == NULL)
7862 return false;
7863 if (st->named_type() != NULL)
7864 st->named_type()->convert(this->gogo_);
7865 unsigned int offset;
7866 if (!st->struct_type()->backend_field_offset(this->gogo_,
7867 farg->field_index(),
7868 &offset))
7869 return false;
7870 total_offset += offset;
7871 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7872 {
7873 // Go up until we reach the original base.
7874 farg = struct_expr->field_reference_expression();
7875 continue;
7876 }
7877 break;
7878 }
7879 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7880 static_cast<unsigned long>(total_offset));
7881 return true;
7882 }
7883 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7884 {
7885 Expression* arg = this->one_arg();
7886 if (arg == NULL)
7887 return false;
7888
7889 Numeric_constant argnc;
7890 if (!arg->numeric_constant_value(&argnc))
7891 return false;
7892
7893 mpfr_t real;
7894 mpfr_t imag;
7895 if (!argnc.to_complex(&real, &imag))
7896 return false;
7897
7898 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7899 if (this->code_ == BUILTIN_REAL)
7900 nc->set_float(type, real);
7901 else
7902 nc->set_float(type, imag);
7903 return true;
7904 }
7905 else if (this->code_ == BUILTIN_COMPLEX)
7906 {
7907 const Expression_list* args = this->args();
7908 if (args == NULL || args->size() != 2)
7909 return false;
7910
7911 Numeric_constant rnc;
7912 if (!args->front()->numeric_constant_value(&rnc))
7913 return false;
7914 Numeric_constant inc;
7915 if (!args->back()->numeric_constant_value(&inc))
7916 return false;
7917
7918 if (rnc.type() != NULL
7919 && !rnc.type()->is_abstract()
7920 && inc.type() != NULL
7921 && !inc.type()->is_abstract()
7922 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7923 return false;
7924
7925 mpfr_t r;
7926 if (!rnc.to_float(&r))
7927 return false;
7928 mpfr_t i;
7929 if (!inc.to_float(&i))
7930 {
7931 mpfr_clear(r);
7932 return false;
7933 }
7934
7935 Type* arg_type = rnc.type();
7936 if (arg_type == NULL || arg_type->is_abstract())
7937 arg_type = inc.type();
7938
7939 Type* type = Builtin_call_expression::complex_type(arg_type);
7940 nc->set_complex(type, r, i);
7941
7942 mpfr_clear(r);
7943 mpfr_clear(i);
7944
7945 return true;
7946 }
7947
7948 return false;
7949 }
7950
7951 // Give an error if we are discarding the value of an expression which
7952 // should not normally be discarded. We don't give an error for
7953 // discarding the value of an ordinary function call, but we do for
7954 // builtin functions, purely for consistency with the gc compiler.
7955
7956 bool
7957 Builtin_call_expression::do_discarding_value()
7958 {
7959 switch (this->code_)
7960 {
7961 case BUILTIN_INVALID:
7962 default:
7963 go_unreachable();
7964
7965 case BUILTIN_APPEND:
7966 case BUILTIN_CAP:
7967 case BUILTIN_COMPLEX:
7968 case BUILTIN_IMAG:
7969 case BUILTIN_LEN:
7970 case BUILTIN_MAKE:
7971 case BUILTIN_NEW:
7972 case BUILTIN_REAL:
7973 case BUILTIN_ALIGNOF:
7974 case BUILTIN_OFFSETOF:
7975 case BUILTIN_SIZEOF:
7976 this->unused_value_error();
7977 return false;
7978
7979 case BUILTIN_CLOSE:
7980 case BUILTIN_COPY:
7981 case BUILTIN_DELETE:
7982 case BUILTIN_PANIC:
7983 case BUILTIN_PRINT:
7984 case BUILTIN_PRINTLN:
7985 case BUILTIN_RECOVER:
7986 return true;
7987 }
7988 }
7989
7990 // Return the type.
7991
7992 Type*
7993 Builtin_call_expression::do_type()
7994 {
7995 switch (this->code_)
7996 {
7997 case BUILTIN_INVALID:
7998 default:
7999 go_unreachable();
8000
8001 case BUILTIN_NEW:
8002 case BUILTIN_MAKE:
8003 {
8004 const Expression_list* args = this->args();
8005 if (args == NULL || args->empty())
8006 return Type::make_error_type();
8007 return Type::make_pointer_type(args->front()->type());
8008 }
8009
8010 case BUILTIN_CAP:
8011 case BUILTIN_COPY:
8012 case BUILTIN_LEN:
8013 return Type::lookup_integer_type("int");
8014
8015 case BUILTIN_ALIGNOF:
8016 case BUILTIN_OFFSETOF:
8017 case BUILTIN_SIZEOF:
8018 return Type::lookup_integer_type("uintptr");
8019
8020 case BUILTIN_CLOSE:
8021 case BUILTIN_DELETE:
8022 case BUILTIN_PANIC:
8023 case BUILTIN_PRINT:
8024 case BUILTIN_PRINTLN:
8025 return Type::make_void_type();
8026
8027 case BUILTIN_RECOVER:
8028 return Type::make_empty_interface_type(Linemap::predeclared_location());
8029
8030 case BUILTIN_APPEND:
8031 {
8032 const Expression_list* args = this->args();
8033 if (args == NULL || args->empty())
8034 return Type::make_error_type();
8035 return args->front()->type();
8036 }
8037
8038 case BUILTIN_REAL:
8039 case BUILTIN_IMAG:
8040 {
8041 Expression* arg = this->one_arg();
8042 if (arg == NULL)
8043 return Type::make_error_type();
8044 Type* t = arg->type();
8045 if (t->is_abstract())
8046 t = t->make_non_abstract_type();
8047 t = Builtin_call_expression::real_imag_type(t);
8048 if (t == NULL)
8049 t = Type::make_error_type();
8050 return t;
8051 }
8052
8053 case BUILTIN_COMPLEX:
8054 {
8055 const Expression_list* args = this->args();
8056 if (args == NULL || args->size() != 2)
8057 return Type::make_error_type();
8058 Type* t = args->front()->type();
8059 if (t->is_abstract())
8060 {
8061 t = args->back()->type();
8062 if (t->is_abstract())
8063 t = t->make_non_abstract_type();
8064 }
8065 t = Builtin_call_expression::complex_type(t);
8066 if (t == NULL)
8067 t = Type::make_error_type();
8068 return t;
8069 }
8070 }
8071 }
8072
8073 // Determine the type.
8074
8075 void
8076 Builtin_call_expression::do_determine_type(const Type_context* context)
8077 {
8078 if (!this->determining_types())
8079 return;
8080
8081 this->fn()->determine_type_no_context();
8082
8083 const Expression_list* args = this->args();
8084
8085 bool is_print;
8086 Type* arg_type = NULL;
8087 switch (this->code_)
8088 {
8089 case BUILTIN_PRINT:
8090 case BUILTIN_PRINTLN:
8091 // Do not force a large integer constant to "int".
8092 is_print = true;
8093 break;
8094
8095 case BUILTIN_REAL:
8096 case BUILTIN_IMAG:
8097 arg_type = Builtin_call_expression::complex_type(context->type);
8098 if (arg_type == NULL)
8099 arg_type = Type::lookup_complex_type("complex128");
8100 is_print = false;
8101 break;
8102
8103 case BUILTIN_COMPLEX:
8104 {
8105 // For the complex function the type of one operand can
8106 // determine the type of the other, as in a binary expression.
8107 arg_type = Builtin_call_expression::real_imag_type(context->type);
8108 if (arg_type == NULL)
8109 arg_type = Type::lookup_float_type("float64");
8110 if (args != NULL && args->size() == 2)
8111 {
8112 Type* t1 = args->front()->type();
8113 Type* t2 = args->back()->type();
8114 if (!t1->is_abstract())
8115 arg_type = t1;
8116 else if (!t2->is_abstract())
8117 arg_type = t2;
8118 }
8119 is_print = false;
8120 }
8121 break;
8122
8123 default:
8124 is_print = false;
8125 break;
8126 }
8127
8128 if (args != NULL)
8129 {
8130 for (Expression_list::const_iterator pa = args->begin();
8131 pa != args->end();
8132 ++pa)
8133 {
8134 Type_context subcontext;
8135 subcontext.type = arg_type;
8136
8137 if (is_print)
8138 {
8139 // We want to print large constants, we so can't just
8140 // use the appropriate nonabstract type. Use uint64 for
8141 // an integer if we know it is nonnegative, otherwise
8142 // use int64 for a integer, otherwise use float64 for a
8143 // float or complex128 for a complex.
8144 Type* want_type = NULL;
8145 Type* atype = (*pa)->type();
8146 if (atype->is_abstract())
8147 {
8148 if (atype->integer_type() != NULL)
8149 {
8150 Numeric_constant nc;
8151 if (this->numeric_constant_value(&nc))
8152 {
8153 mpz_t val;
8154 if (nc.to_int(&val))
8155 {
8156 if (mpz_sgn(val) >= 0)
8157 want_type = Type::lookup_integer_type("uint64");
8158 mpz_clear(val);
8159 }
8160 }
8161 if (want_type == NULL)
8162 want_type = Type::lookup_integer_type("int64");
8163 }
8164 else if (atype->float_type() != NULL)
8165 want_type = Type::lookup_float_type("float64");
8166 else if (atype->complex_type() != NULL)
8167 want_type = Type::lookup_complex_type("complex128");
8168 else if (atype->is_abstract_string_type())
8169 want_type = Type::lookup_string_type();
8170 else if (atype->is_abstract_boolean_type())
8171 want_type = Type::lookup_bool_type();
8172 else
8173 go_unreachable();
8174 subcontext.type = want_type;
8175 }
8176 }
8177
8178 (*pa)->determine_type(&subcontext);
8179 }
8180 }
8181 }
8182
8183 // If there is exactly one argument, return true. Otherwise give an
8184 // error message and return false.
8185
8186 bool
8187 Builtin_call_expression::check_one_arg()
8188 {
8189 const Expression_list* args = this->args();
8190 if (args == NULL || args->size() < 1)
8191 {
8192 this->report_error(_("not enough arguments"));
8193 return false;
8194 }
8195 else if (args->size() > 1)
8196 {
8197 this->report_error(_("too many arguments"));
8198 return false;
8199 }
8200 if (args->front()->is_error_expression()
8201 || args->front()->type()->is_error())
8202 {
8203 this->set_is_error();
8204 return false;
8205 }
8206 return true;
8207 }
8208
8209 // Check argument types for a builtin function.
8210
8211 void
8212 Builtin_call_expression::do_check_types(Gogo*)
8213 {
8214 if (this->is_error_expression())
8215 return;
8216 switch (this->code_)
8217 {
8218 case BUILTIN_INVALID:
8219 case BUILTIN_NEW:
8220 case BUILTIN_MAKE:
8221 case BUILTIN_DELETE:
8222 return;
8223
8224 case BUILTIN_LEN:
8225 case BUILTIN_CAP:
8226 {
8227 // The single argument may be either a string or an array or a
8228 // map or a channel, or a pointer to a closed array.
8229 if (this->check_one_arg())
8230 {
8231 Type* arg_type = this->one_arg()->type();
8232 if (arg_type->points_to() != NULL
8233 && arg_type->points_to()->array_type() != NULL
8234 && !arg_type->points_to()->is_slice_type())
8235 arg_type = arg_type->points_to();
8236 if (this->code_ == BUILTIN_CAP)
8237 {
8238 if (!arg_type->is_error()
8239 && arg_type->array_type() == NULL
8240 && arg_type->channel_type() == NULL)
8241 this->report_error(_("argument must be array or slice "
8242 "or channel"));
8243 }
8244 else
8245 {
8246 if (!arg_type->is_error()
8247 && !arg_type->is_string_type()
8248 && arg_type->array_type() == NULL
8249 && arg_type->map_type() == NULL
8250 && arg_type->channel_type() == NULL)
8251 this->report_error(_("argument must be string or "
8252 "array or slice or map or channel"));
8253 }
8254 }
8255 }
8256 break;
8257
8258 case BUILTIN_PRINT:
8259 case BUILTIN_PRINTLN:
8260 {
8261 const Expression_list* args = this->args();
8262 if (args == NULL)
8263 {
8264 if (this->code_ == BUILTIN_PRINT)
8265 warning_at(this->location(), 0,
8266 "no arguments for builtin function %<%s%>",
8267 (this->code_ == BUILTIN_PRINT
8268 ? "print"
8269 : "println"));
8270 }
8271 else
8272 {
8273 for (Expression_list::const_iterator p = args->begin();
8274 p != args->end();
8275 ++p)
8276 {
8277 Type* type = (*p)->type();
8278 if (type->is_error()
8279 || type->is_string_type()
8280 || type->integer_type() != NULL
8281 || type->float_type() != NULL
8282 || type->complex_type() != NULL
8283 || type->is_boolean_type()
8284 || type->points_to() != NULL
8285 || type->interface_type() != NULL
8286 || type->channel_type() != NULL
8287 || type->map_type() != NULL
8288 || type->function_type() != NULL
8289 || type->is_slice_type())
8290 ;
8291 else if ((*p)->is_type_expression())
8292 {
8293 // If this is a type expression it's going to give
8294 // an error anyhow, so we don't need one here.
8295 }
8296 else
8297 this->report_error(_("unsupported argument type to "
8298 "builtin function"));
8299 }
8300 }
8301 }
8302 break;
8303
8304 case BUILTIN_CLOSE:
8305 if (this->check_one_arg())
8306 {
8307 if (this->one_arg()->type()->channel_type() == NULL)
8308 this->report_error(_("argument must be channel"));
8309 else if (!this->one_arg()->type()->channel_type()->may_send())
8310 this->report_error(_("cannot close receive-only channel"));
8311 }
8312 break;
8313
8314 case BUILTIN_PANIC:
8315 case BUILTIN_SIZEOF:
8316 case BUILTIN_ALIGNOF:
8317 this->check_one_arg();
8318 break;
8319
8320 case BUILTIN_RECOVER:
8321 if (this->args() != NULL && !this->args()->empty())
8322 this->report_error(_("too many arguments"));
8323 break;
8324
8325 case BUILTIN_OFFSETOF:
8326 if (this->check_one_arg())
8327 {
8328 Expression* arg = this->one_arg();
8329 if (arg->field_reference_expression() == NULL)
8330 this->report_error(_("argument must be a field reference"));
8331 }
8332 break;
8333
8334 case BUILTIN_COPY:
8335 {
8336 const Expression_list* args = this->args();
8337 if (args == NULL || args->size() < 2)
8338 {
8339 this->report_error(_("not enough arguments"));
8340 break;
8341 }
8342 else if (args->size() > 2)
8343 {
8344 this->report_error(_("too many arguments"));
8345 break;
8346 }
8347 Type* arg1_type = args->front()->type();
8348 Type* arg2_type = args->back()->type();
8349 if (arg1_type->is_error() || arg2_type->is_error())
8350 break;
8351
8352 Type* e1;
8353 if (arg1_type->is_slice_type())
8354 e1 = arg1_type->array_type()->element_type();
8355 else
8356 {
8357 this->report_error(_("left argument must be a slice"));
8358 break;
8359 }
8360
8361 if (arg2_type->is_slice_type())
8362 {
8363 Type* e2 = arg2_type->array_type()->element_type();
8364 if (!Type::are_identical(e1, e2, true, NULL))
8365 this->report_error(_("element types must be the same"));
8366 }
8367 else if (arg2_type->is_string_type())
8368 {
8369 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8370 this->report_error(_("first argument must be []byte"));
8371 }
8372 else
8373 this->report_error(_("second argument must be slice or string"));
8374 }
8375 break;
8376
8377 case BUILTIN_APPEND:
8378 {
8379 const Expression_list* args = this->args();
8380 if (args == NULL || args->size() < 2)
8381 {
8382 this->report_error(_("not enough arguments"));
8383 break;
8384 }
8385 if (args->size() > 2)
8386 {
8387 this->report_error(_("too many arguments"));
8388 break;
8389 }
8390 if (args->front()->type()->is_error()
8391 || args->back()->type()->is_error())
8392 break;
8393
8394 Array_type* at = args->front()->type()->array_type();
8395 Type* e = at->element_type();
8396
8397 // The language permits appending a string to a []byte, as a
8398 // special case.
8399 if (args->back()->type()->is_string_type())
8400 {
8401 if (e->integer_type() != NULL && e->integer_type()->is_byte())
8402 break;
8403 }
8404
8405 // The language says that the second argument must be
8406 // assignable to a slice of the element type of the first
8407 // argument. We already know the first argument is a slice
8408 // type.
8409 Type* arg2_type = Type::make_array_type(e, NULL);
8410 std::string reason;
8411 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8412 {
8413 if (reason.empty())
8414 this->report_error(_("argument 2 has invalid type"));
8415 else
8416 {
8417 error_at(this->location(), "argument 2 has invalid type (%s)",
8418 reason.c_str());
8419 this->set_is_error();
8420 }
8421 }
8422 break;
8423 }
8424
8425 case BUILTIN_REAL:
8426 case BUILTIN_IMAG:
8427 if (this->check_one_arg())
8428 {
8429 if (this->one_arg()->type()->complex_type() == NULL)
8430 this->report_error(_("argument must have complex type"));
8431 }
8432 break;
8433
8434 case BUILTIN_COMPLEX:
8435 {
8436 const Expression_list* args = this->args();
8437 if (args == NULL || args->size() < 2)
8438 this->report_error(_("not enough arguments"));
8439 else if (args->size() > 2)
8440 this->report_error(_("too many arguments"));
8441 else if (args->front()->is_error_expression()
8442 || args->front()->type()->is_error()
8443 || args->back()->is_error_expression()
8444 || args->back()->type()->is_error())
8445 this->set_is_error();
8446 else if (!Type::are_identical(args->front()->type(),
8447 args->back()->type(), true, NULL))
8448 this->report_error(_("complex arguments must have identical types"));
8449 else if (args->front()->type()->float_type() == NULL)
8450 this->report_error(_("complex arguments must have "
8451 "floating-point type"));
8452 }
8453 break;
8454
8455 default:
8456 go_unreachable();
8457 }
8458 }
8459
8460 // Return the tree for a builtin function.
8461
8462 tree
8463 Builtin_call_expression::do_get_tree(Translate_context* context)
8464 {
8465 Gogo* gogo = context->gogo();
8466 Location location = this->location();
8467 switch (this->code_)
8468 {
8469 case BUILTIN_INVALID:
8470 case BUILTIN_NEW:
8471 case BUILTIN_MAKE:
8472 go_unreachable();
8473
8474 case BUILTIN_LEN:
8475 case BUILTIN_CAP:
8476 {
8477 const Expression_list* args = this->args();
8478 go_assert(args != NULL && args->size() == 1);
8479 Expression* arg = *args->begin();
8480 Type* arg_type = arg->type();
8481
8482 if (this->seen_)
8483 {
8484 go_assert(saw_errors());
8485 return error_mark_node;
8486 }
8487 this->seen_ = true;
8488
8489 tree arg_tree = arg->get_tree(context);
8490
8491 this->seen_ = false;
8492
8493 if (arg_tree == error_mark_node)
8494 return error_mark_node;
8495
8496 if (arg_type->points_to() != NULL)
8497 {
8498 arg_type = arg_type->points_to();
8499 go_assert(arg_type->array_type() != NULL
8500 && !arg_type->is_slice_type());
8501 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
8502 arg_tree = build_fold_indirect_ref(arg_tree);
8503 }
8504
8505 Type* int_type = Type::lookup_integer_type("int");
8506 tree int_type_tree = type_to_tree(int_type->get_backend(gogo));
8507
8508 tree val_tree;
8509 if (this->code_ == BUILTIN_LEN)
8510 {
8511 if (arg_type->is_string_type())
8512 val_tree = String_type::length_tree(gogo, arg_tree);
8513 else if (arg_type->array_type() != NULL)
8514 {
8515 if (this->seen_)
8516 {
8517 go_assert(saw_errors());
8518 return error_mark_node;
8519 }
8520 this->seen_ = true;
8521 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
8522 this->seen_ = false;
8523 }
8524 else if (arg_type->map_type() != NULL)
8525 {
8526 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8527 static tree map_len_fndecl;
8528 val_tree = Gogo::call_builtin(&map_len_fndecl,
8529 location,
8530 "__go_map_len",
8531 1,
8532 int_type_tree,
8533 arg_type_tree,
8534 arg_tree);
8535 }
8536 else if (arg_type->channel_type() != NULL)
8537 {
8538 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8539 static tree chan_len_fndecl;
8540 val_tree = Gogo::call_builtin(&chan_len_fndecl,
8541 location,
8542 "__go_chan_len",
8543 1,
8544 int_type_tree,
8545 arg_type_tree,
8546 arg_tree);
8547 }
8548 else
8549 go_unreachable();
8550 }
8551 else
8552 {
8553 if (arg_type->array_type() != NULL)
8554 {
8555 if (this->seen_)
8556 {
8557 go_assert(saw_errors());
8558 return error_mark_node;
8559 }
8560 this->seen_ = true;
8561 val_tree = arg_type->array_type()->capacity_tree(gogo,
8562 arg_tree);
8563 this->seen_ = false;
8564 }
8565 else if (arg_type->channel_type() != NULL)
8566 {
8567 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8568 static tree chan_cap_fndecl;
8569 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
8570 location,
8571 "__go_chan_cap",
8572 1,
8573 int_type_tree,
8574 arg_type_tree,
8575 arg_tree);
8576 }
8577 else
8578 go_unreachable();
8579 }
8580
8581 return fold_convert_loc(location.gcc_location(), int_type_tree,
8582 val_tree);
8583 }
8584
8585 case BUILTIN_PRINT:
8586 case BUILTIN_PRINTLN:
8587 {
8588 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8589 tree stmt_list = NULL_TREE;
8590
8591 const Expression_list* call_args = this->args();
8592 if (call_args != NULL)
8593 {
8594 for (Expression_list::const_iterator p = call_args->begin();
8595 p != call_args->end();
8596 ++p)
8597 {
8598 if (is_ln && p != call_args->begin())
8599 {
8600 static tree print_space_fndecl;
8601 tree call = Gogo::call_builtin(&print_space_fndecl,
8602 location,
8603 "__go_print_space",
8604 0,
8605 void_type_node);
8606 if (call == error_mark_node)
8607 return error_mark_node;
8608 append_to_statement_list(call, &stmt_list);
8609 }
8610
8611 Type* type = (*p)->type();
8612
8613 tree arg = (*p)->get_tree(context);
8614 if (arg == error_mark_node)
8615 return error_mark_node;
8616
8617 tree* pfndecl;
8618 const char* fnname;
8619 if (type->is_string_type())
8620 {
8621 static tree print_string_fndecl;
8622 pfndecl = &print_string_fndecl;
8623 fnname = "__go_print_string";
8624 }
8625 else if (type->integer_type() != NULL
8626 && type->integer_type()->is_unsigned())
8627 {
8628 static tree print_uint64_fndecl;
8629 pfndecl = &print_uint64_fndecl;
8630 fnname = "__go_print_uint64";
8631 Type* itype = Type::lookup_integer_type("uint64");
8632 Btype* bitype = itype->get_backend(gogo);
8633 arg = fold_convert_loc(location.gcc_location(),
8634 type_to_tree(bitype), arg);
8635 }
8636 else if (type->integer_type() != NULL)
8637 {
8638 static tree print_int64_fndecl;
8639 pfndecl = &print_int64_fndecl;
8640 fnname = "__go_print_int64";
8641 Type* itype = Type::lookup_integer_type("int64");
8642 Btype* bitype = itype->get_backend(gogo);
8643 arg = fold_convert_loc(location.gcc_location(),
8644 type_to_tree(bitype), arg);
8645 }
8646 else if (type->float_type() != NULL)
8647 {
8648 static tree print_double_fndecl;
8649 pfndecl = &print_double_fndecl;
8650 fnname = "__go_print_double";
8651 arg = fold_convert_loc(location.gcc_location(),
8652 double_type_node, arg);
8653 }
8654 else if (type->complex_type() != NULL)
8655 {
8656 static tree print_complex_fndecl;
8657 pfndecl = &print_complex_fndecl;
8658 fnname = "__go_print_complex";
8659 arg = fold_convert_loc(location.gcc_location(),
8660 complex_double_type_node, arg);
8661 }
8662 else if (type->is_boolean_type())
8663 {
8664 static tree print_bool_fndecl;
8665 pfndecl = &print_bool_fndecl;
8666 fnname = "__go_print_bool";
8667 }
8668 else if (type->points_to() != NULL
8669 || type->channel_type() != NULL
8670 || type->map_type() != NULL
8671 || type->function_type() != NULL)
8672 {
8673 static tree print_pointer_fndecl;
8674 pfndecl = &print_pointer_fndecl;
8675 fnname = "__go_print_pointer";
8676 arg = fold_convert_loc(location.gcc_location(),
8677 ptr_type_node, arg);
8678 }
8679 else if (type->interface_type() != NULL)
8680 {
8681 if (type->interface_type()->is_empty())
8682 {
8683 static tree print_empty_interface_fndecl;
8684 pfndecl = &print_empty_interface_fndecl;
8685 fnname = "__go_print_empty_interface";
8686 }
8687 else
8688 {
8689 static tree print_interface_fndecl;
8690 pfndecl = &print_interface_fndecl;
8691 fnname = "__go_print_interface";
8692 }
8693 }
8694 else if (type->is_slice_type())
8695 {
8696 static tree print_slice_fndecl;
8697 pfndecl = &print_slice_fndecl;
8698 fnname = "__go_print_slice";
8699 }
8700 else
8701 {
8702 go_assert(saw_errors());
8703 return error_mark_node;
8704 }
8705
8706 tree call = Gogo::call_builtin(pfndecl,
8707 location,
8708 fnname,
8709 1,
8710 void_type_node,
8711 TREE_TYPE(arg),
8712 arg);
8713 if (call == error_mark_node)
8714 return error_mark_node;
8715 append_to_statement_list(call, &stmt_list);
8716 }
8717 }
8718
8719 if (is_ln)
8720 {
8721 static tree print_nl_fndecl;
8722 tree call = Gogo::call_builtin(&print_nl_fndecl,
8723 location,
8724 "__go_print_nl",
8725 0,
8726 void_type_node);
8727 if (call == error_mark_node)
8728 return error_mark_node;
8729 append_to_statement_list(call, &stmt_list);
8730 }
8731
8732 return stmt_list;
8733 }
8734
8735 case BUILTIN_PANIC:
8736 {
8737 const Expression_list* args = this->args();
8738 go_assert(args != NULL && args->size() == 1);
8739 Expression* arg = args->front();
8740 tree arg_tree = arg->get_tree(context);
8741 if (arg_tree == error_mark_node)
8742 return error_mark_node;
8743 Type *empty =
8744 Type::make_empty_interface_type(Linemap::predeclared_location());
8745 arg_tree = Expression::convert_for_assignment(context, empty,
8746 arg->type(),
8747 arg_tree, location);
8748 static tree panic_fndecl;
8749 tree call = Gogo::call_builtin(&panic_fndecl,
8750 location,
8751 "__go_panic",
8752 1,
8753 void_type_node,
8754 TREE_TYPE(arg_tree),
8755 arg_tree);
8756 if (call == error_mark_node)
8757 return error_mark_node;
8758 // This function will throw an exception.
8759 TREE_NOTHROW(panic_fndecl) = 0;
8760 // This function will not return.
8761 TREE_THIS_VOLATILE(panic_fndecl) = 1;
8762 return call;
8763 }
8764
8765 case BUILTIN_RECOVER:
8766 {
8767 // The argument is set when building recover thunks. It's a
8768 // boolean value which is true if we can recover a value now.
8769 const Expression_list* args = this->args();
8770 go_assert(args != NULL && args->size() == 1);
8771 Expression* arg = args->front();
8772 tree arg_tree = arg->get_tree(context);
8773 if (arg_tree == error_mark_node)
8774 return error_mark_node;
8775
8776 Type *empty =
8777 Type::make_empty_interface_type(Linemap::predeclared_location());
8778 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8779
8780 Type* nil_type = Type::make_nil_type();
8781 Expression* nil = Expression::make_nil(location);
8782 tree nil_tree = nil->get_tree(context);
8783 tree empty_nil_tree = Expression::convert_for_assignment(context,
8784 empty,
8785 nil_type,
8786 nil_tree,
8787 location);
8788
8789 // We need to handle a deferred call to recover specially,
8790 // because it changes whether it can recover a panic or not.
8791 // See test7 in test/recover1.go.
8792 tree call;
8793 if (this->is_deferred())
8794 {
8795 static tree deferred_recover_fndecl;
8796 call = Gogo::call_builtin(&deferred_recover_fndecl,
8797 location,
8798 "__go_deferred_recover",
8799 0,
8800 empty_tree);
8801 }
8802 else
8803 {
8804 static tree recover_fndecl;
8805 call = Gogo::call_builtin(&recover_fndecl,
8806 location,
8807 "__go_recover",
8808 0,
8809 empty_tree);
8810 }
8811 if (call == error_mark_node)
8812 return error_mark_node;
8813 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8814 arg_tree, call, empty_nil_tree);
8815 }
8816
8817 case BUILTIN_CLOSE:
8818 {
8819 const Expression_list* args = this->args();
8820 go_assert(args != NULL && args->size() == 1);
8821 Expression* arg = args->front();
8822 tree arg_tree = arg->get_tree(context);
8823 if (arg_tree == error_mark_node)
8824 return error_mark_node;
8825 static tree close_fndecl;
8826 return Gogo::call_builtin(&close_fndecl,
8827 location,
8828 "__go_builtin_close",
8829 1,
8830 void_type_node,
8831 TREE_TYPE(arg_tree),
8832 arg_tree);
8833 }
8834
8835 case BUILTIN_SIZEOF:
8836 case BUILTIN_OFFSETOF:
8837 case BUILTIN_ALIGNOF:
8838 {
8839 Numeric_constant nc;
8840 unsigned long val;
8841 if (!this->numeric_constant_value(&nc)
8842 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8843 {
8844 go_assert(saw_errors());
8845 return error_mark_node;
8846 }
8847 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8848 tree type = type_to_tree(uintptr_type->get_backend(gogo));
8849 return build_int_cst(type, val);
8850 }
8851
8852 case BUILTIN_COPY:
8853 {
8854 const Expression_list* args = this->args();
8855 go_assert(args != NULL && args->size() == 2);
8856 Expression* arg1 = args->front();
8857 Expression* arg2 = args->back();
8858
8859 tree arg1_tree = arg1->get_tree(context);
8860 tree arg2_tree = arg2->get_tree(context);
8861 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8862 return error_mark_node;
8863
8864 Type* arg1_type = arg1->type();
8865 Array_type* at = arg1_type->array_type();
8866 arg1_tree = save_expr(arg1_tree);
8867 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8868 tree arg1_len = at->length_tree(gogo, arg1_tree);
8869 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8870 return error_mark_node;
8871
8872 Type* arg2_type = arg2->type();
8873 tree arg2_val;
8874 tree arg2_len;
8875 if (arg2_type->is_slice_type())
8876 {
8877 at = arg2_type->array_type();
8878 arg2_tree = save_expr(arg2_tree);
8879 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8880 arg2_len = at->length_tree(gogo, arg2_tree);
8881 }
8882 else
8883 {
8884 arg2_tree = save_expr(arg2_tree);
8885 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8886 arg2_len = String_type::length_tree(gogo, arg2_tree);
8887 }
8888 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8889 return error_mark_node;
8890
8891 arg1_len = save_expr(arg1_len);
8892 arg2_len = save_expr(arg2_len);
8893 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8894 TREE_TYPE(arg1_len),
8895 fold_build2_loc(location.gcc_location(),
8896 LT_EXPR, boolean_type_node,
8897 arg1_len, arg2_len),
8898 arg1_len, arg2_len);
8899 len = save_expr(len);
8900
8901 Type* element_type = at->element_type();
8902 Btype* element_btype = element_type->get_backend(gogo);
8903 tree element_type_tree = type_to_tree(element_btype);
8904 if (element_type_tree == error_mark_node)
8905 return error_mark_node;
8906 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8907 tree bytecount = fold_convert_loc(location.gcc_location(),
8908 TREE_TYPE(element_size), len);
8909 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8910 TREE_TYPE(element_size),
8911 bytecount, element_size);
8912 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8913 bytecount);
8914
8915 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8916 arg1_val);
8917 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8918 arg2_val);
8919
8920 static tree copy_fndecl;
8921 tree call = Gogo::call_builtin(&copy_fndecl,
8922 location,
8923 "__go_copy",
8924 3,
8925 void_type_node,
8926 ptr_type_node,
8927 arg1_val,
8928 ptr_type_node,
8929 arg2_val,
8930 size_type_node,
8931 bytecount);
8932 if (call == error_mark_node)
8933 return error_mark_node;
8934
8935 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8936 TREE_TYPE(len), call, len);
8937 }
8938
8939 case BUILTIN_APPEND:
8940 {
8941 const Expression_list* args = this->args();
8942 go_assert(args != NULL && args->size() == 2);
8943 Expression* arg1 = args->front();
8944 Expression* arg2 = args->back();
8945
8946 tree arg1_tree = arg1->get_tree(context);
8947 tree arg2_tree = arg2->get_tree(context);
8948 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8949 return error_mark_node;
8950
8951 Array_type* at = arg1->type()->array_type();
8952 Type* element_type = at->element_type()->forwarded();
8953
8954 tree arg2_val;
8955 tree arg2_len;
8956 tree element_size;
8957 if (arg2->type()->is_string_type()
8958 && element_type->integer_type() != NULL
8959 && element_type->integer_type()->is_byte())
8960 {
8961 arg2_tree = save_expr(arg2_tree);
8962 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8963 arg2_len = String_type::length_tree(gogo, arg2_tree);
8964 element_size = size_int(1);
8965 }
8966 else
8967 {
8968 arg2_tree = Expression::convert_for_assignment(context, at,
8969 arg2->type(),
8970 arg2_tree,
8971 location);
8972 if (arg2_tree == error_mark_node)
8973 return error_mark_node;
8974
8975 arg2_tree = save_expr(arg2_tree);
8976
8977 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8978 arg2_len = at->length_tree(gogo, arg2_tree);
8979
8980 Btype* element_btype = element_type->get_backend(gogo);
8981 tree element_type_tree = type_to_tree(element_btype);
8982 if (element_type_tree == error_mark_node)
8983 return error_mark_node;
8984 element_size = TYPE_SIZE_UNIT(element_type_tree);
8985 }
8986
8987 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8988 arg2_val);
8989 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8990 arg2_len);
8991 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8992 element_size);
8993
8994 if (arg2_val == error_mark_node
8995 || arg2_len == error_mark_node
8996 || element_size == error_mark_node)
8997 return error_mark_node;
8998
8999 // We rebuild the decl each time since the slice types may
9000 // change.
9001 tree append_fndecl = NULL_TREE;
9002 return Gogo::call_builtin(&append_fndecl,
9003 location,
9004 "__go_append",
9005 4,
9006 TREE_TYPE(arg1_tree),
9007 TREE_TYPE(arg1_tree),
9008 arg1_tree,
9009 ptr_type_node,
9010 arg2_val,
9011 size_type_node,
9012 arg2_len,
9013 size_type_node,
9014 element_size);
9015 }
9016
9017 case BUILTIN_REAL:
9018 case BUILTIN_IMAG:
9019 {
9020 const Expression_list* args = this->args();
9021 go_assert(args != NULL && args->size() == 1);
9022 Expression* arg = args->front();
9023 tree arg_tree = arg->get_tree(context);
9024 if (arg_tree == error_mark_node)
9025 return error_mark_node;
9026 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
9027 if (this->code_ == BUILTIN_REAL)
9028 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
9029 TREE_TYPE(TREE_TYPE(arg_tree)),
9030 arg_tree);
9031 else
9032 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
9033 TREE_TYPE(TREE_TYPE(arg_tree)),
9034 arg_tree);
9035 }
9036
9037 case BUILTIN_COMPLEX:
9038 {
9039 const Expression_list* args = this->args();
9040 go_assert(args != NULL && args->size() == 2);
9041 tree r = args->front()->get_tree(context);
9042 tree i = args->back()->get_tree(context);
9043 if (r == error_mark_node || i == error_mark_node)
9044 return error_mark_node;
9045 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
9046 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
9047 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
9048 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
9049 build_complex_type(TREE_TYPE(r)),
9050 r, i);
9051 }
9052
9053 default:
9054 go_unreachable();
9055 }
9056 }
9057
9058 // We have to support exporting a builtin call expression, because
9059 // code can set a constant to the result of a builtin expression.
9060
9061 void
9062 Builtin_call_expression::do_export(Export* exp) const
9063 {
9064 Numeric_constant nc;
9065 if (!this->numeric_constant_value(&nc))
9066 {
9067 error_at(this->location(), "value is not constant");
9068 return;
9069 }
9070
9071 if (nc.is_int())
9072 {
9073 mpz_t val;
9074 nc.get_int(&val);
9075 Integer_expression::export_integer(exp, val);
9076 mpz_clear(val);
9077 }
9078 else if (nc.is_float())
9079 {
9080 mpfr_t fval;
9081 nc.get_float(&fval);
9082 Float_expression::export_float(exp, fval);
9083 mpfr_clear(fval);
9084 }
9085 else if (nc.is_complex())
9086 {
9087 mpfr_t real;
9088 mpfr_t imag;
9089 Complex_expression::export_complex(exp, real, imag);
9090 mpfr_clear(real);
9091 mpfr_clear(imag);
9092 }
9093 else
9094 go_unreachable();
9095
9096 // A trailing space lets us reliably identify the end of the number.
9097 exp->write_c_string(" ");
9098 }
9099
9100 // Class Call_expression.
9101
9102 // A Go function can be viewed in a couple of different ways. The
9103 // code of a Go function becomes a backend function with parameters
9104 // whose types are simply the backend representation of the Go types.
9105 // If there are multiple results, they are returned as a backend
9106 // struct.
9107
9108 // However, when Go code refers to a function other than simply
9109 // calling it, the backend type of that function is actually a struct.
9110 // The first field of the struct points to the Go function code
9111 // (sometimes a wrapper as described below). The remaining fields
9112 // hold addresses of closed-over variables. This struct is called a
9113 // closure.
9114
9115 // There are a few cases to consider.
9116
9117 // A direct function call of a known function in package scope. In
9118 // this case there are no closed-over variables, and we know the name
9119 // of the function code. We can simply produce a backend call to the
9120 // function directly, and not worry about the closure.
9121
9122 // A direct function call of a known function literal. In this case
9123 // we know the function code and we know the closure. We generate the
9124 // function code such that it expects an additional final argument of
9125 // the closure type. We pass the closure as the last argument, after
9126 // the other arguments.
9127
9128 // An indirect function call. In this case we have a closure. We
9129 // load the pointer to the function code from the first field of the
9130 // closure. We pass the address of the closure as the last argument.
9131
9132 // A call to a method of an interface. Type methods are always at
9133 // package scope, so we call the function directly, and don't worry
9134 // about the closure.
9135
9136 // This means that for a function at package scope we have two cases.
9137 // One is the direct call, which has no closure. The other is the
9138 // indirect call, which does have a closure. We can't simply ignore
9139 // the closure, even though it is the last argument, because that will
9140 // fail on targets where the function pops its arguments. So when
9141 // generating a closure for a package-scope function we set the
9142 // function code pointer in the closure to point to a wrapper
9143 // function. This wrapper function accepts a final argument that
9144 // points to the closure, ignores it, and calls the real function as a
9145 // direct function call. This wrapper will normally be efficient, and
9146 // can often simply be a tail call to the real function.
9147
9148 // We don't use GCC's static chain pointer because 1) we don't need
9149 // it; 2) GCC only permits using a static chain to call a known
9150 // function, so we can't use it for an indirect call anyhow. Since we
9151 // can't use it for an indirect call, we may as well not worry about
9152 // using it for a direct call either.
9153
9154 // We pass the closure last rather than first because it means that
9155 // the function wrapper we put into a closure for a package-scope
9156 // function can normally just be a tail call to the real function.
9157
9158 // For method expressions we generate a wrapper that loads the
9159 // receiver from the closure and then calls the method. This
9160 // unfortunately forces reshuffling the arguments, since there is a
9161 // new first argument, but we can't avoid reshuffling either for
9162 // method expressions or for indirect calls of package-scope
9163 // functions, and since the latter are more common we reshuffle for
9164 // method expressions.
9165
9166 // Note that the Go code retains the Go types. The extra final
9167 // argument only appears when we convert to the backend
9168 // representation.
9169
9170 // Traversal.
9171
9172 int
9173 Call_expression::do_traverse(Traverse* traverse)
9174 {
9175 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9176 return TRAVERSE_EXIT;
9177 if (this->args_ != NULL)
9178 {
9179 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9180 return TRAVERSE_EXIT;
9181 }
9182 return TRAVERSE_CONTINUE;
9183 }
9184
9185 // Lower a call statement.
9186
9187 Expression*
9188 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9189 Statement_inserter* inserter, int)
9190 {
9191 Location loc = this->location();
9192
9193 // A type cast can look like a function call.
9194 if (this->fn_->is_type_expression()
9195 && this->args_ != NULL
9196 && this->args_->size() == 1)
9197 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9198 loc);
9199
9200 // Because do_type will return an error type and thus prevent future
9201 // errors, check for that case now to ensure that the error gets
9202 // reported.
9203 Function_type* fntype = this->get_function_type();
9204 if (fntype == NULL)
9205 {
9206 if (!this->fn_->type()->is_error())
9207 this->report_error(_("expected function"));
9208 return Expression::make_error(loc);
9209 }
9210
9211 // Handle an argument which is a call to a function which returns
9212 // multiple results.
9213 if (this->args_ != NULL
9214 && this->args_->size() == 1
9215 && this->args_->front()->call_expression() != NULL)
9216 {
9217 size_t rc = this->args_->front()->call_expression()->result_count();
9218 if (rc > 1
9219 && ((fntype->parameters() != NULL
9220 && (fntype->parameters()->size() == rc
9221 || (fntype->is_varargs()
9222 && fntype->parameters()->size() - 1 <= rc)))
9223 || fntype->is_builtin()))
9224 {
9225 Call_expression* call = this->args_->front()->call_expression();
9226 Expression_list* args = new Expression_list;
9227 for (size_t i = 0; i < rc; ++i)
9228 args->push_back(Expression::make_call_result(call, i));
9229 // We can't return a new call expression here, because this
9230 // one may be referenced by Call_result expressions. We
9231 // also can't delete the old arguments, because we may still
9232 // traverse them somewhere up the call stack. FIXME.
9233 this->args_ = args;
9234 }
9235 }
9236
9237 // Recognize a call to a builtin function.
9238 if (fntype->is_builtin())
9239 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9240 this->is_varargs_, loc);
9241
9242 // If this call returns multiple results, create a temporary
9243 // variable for each result.
9244 size_t rc = this->result_count();
9245 if (rc > 1 && this->results_ == NULL)
9246 {
9247 std::vector<Temporary_statement*>* temps =
9248 new std::vector<Temporary_statement*>;
9249 temps->reserve(rc);
9250 const Typed_identifier_list* results = fntype->results();
9251 for (Typed_identifier_list::const_iterator p = results->begin();
9252 p != results->end();
9253 ++p)
9254 {
9255 Temporary_statement* temp = Statement::make_temporary(p->type(),
9256 NULL, loc);
9257 inserter->insert(temp);
9258 temps->push_back(temp);
9259 }
9260 this->results_ = temps;
9261 }
9262
9263 // Handle a call to a varargs function by packaging up the extra
9264 // parameters.
9265 if (fntype->is_varargs())
9266 {
9267 const Typed_identifier_list* parameters = fntype->parameters();
9268 go_assert(parameters != NULL && !parameters->empty());
9269 Type* varargs_type = parameters->back().type();
9270 this->lower_varargs(gogo, function, inserter, varargs_type,
9271 parameters->size());
9272 }
9273
9274 // If this is call to a method, call the method directly passing the
9275 // object as the first parameter.
9276 Bound_method_expression* bme = this->fn_->bound_method_expression();
9277 if (bme != NULL)
9278 {
9279 Named_object* methodfn = bme->function();
9280 Expression* first_arg = bme->first_argument();
9281
9282 // We always pass a pointer when calling a method.
9283 if (first_arg->type()->points_to() == NULL
9284 && !first_arg->type()->is_error())
9285 {
9286 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9287 // We may need to create a temporary variable so that we can
9288 // take the address. We can't do that here because it will
9289 // mess up the order of evaluation.
9290 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9291 ue->set_create_temp();
9292 }
9293
9294 // If we are calling a method which was inherited from an
9295 // embedded struct, and the method did not get a stub, then the
9296 // first type may be wrong.
9297 Type* fatype = bme->first_argument_type();
9298 if (fatype != NULL)
9299 {
9300 if (fatype->points_to() == NULL)
9301 fatype = Type::make_pointer_type(fatype);
9302 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9303 }
9304
9305 Expression_list* new_args = new Expression_list();
9306 new_args->push_back(first_arg);
9307 if (this->args_ != NULL)
9308 {
9309 for (Expression_list::const_iterator p = this->args_->begin();
9310 p != this->args_->end();
9311 ++p)
9312 new_args->push_back(*p);
9313 }
9314
9315 // We have to change in place because this structure may be
9316 // referenced by Call_result_expressions. We can't delete the
9317 // old arguments, because we may be traversing them up in some
9318 // caller. FIXME.
9319 this->args_ = new_args;
9320 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9321 bme->location());
9322 }
9323
9324 return this;
9325 }
9326
9327 // Lower a call to a varargs function. FUNCTION is the function in
9328 // which the call occurs--it's not the function we are calling.
9329 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9330 // PARAM_COUNT is the number of parameters of the function we are
9331 // calling; the last of these parameters will be the varargs
9332 // parameter.
9333
9334 void
9335 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9336 Statement_inserter* inserter,
9337 Type* varargs_type, size_t param_count)
9338 {
9339 if (this->varargs_are_lowered_)
9340 return;
9341
9342 Location loc = this->location();
9343
9344 go_assert(param_count > 0);
9345 go_assert(varargs_type->is_slice_type());
9346
9347 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9348 if (arg_count < param_count - 1)
9349 {
9350 // Not enough arguments; will be caught in check_types.
9351 return;
9352 }
9353
9354 Expression_list* old_args = this->args_;
9355 Expression_list* new_args = new Expression_list();
9356 bool push_empty_arg = false;
9357 if (old_args == NULL || old_args->empty())
9358 {
9359 go_assert(param_count == 1);
9360 push_empty_arg = true;
9361 }
9362 else
9363 {
9364 Expression_list::const_iterator pa;
9365 int i = 1;
9366 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9367 {
9368 if (static_cast<size_t>(i) == param_count)
9369 break;
9370 new_args->push_back(*pa);
9371 }
9372
9373 // We have reached the varargs parameter.
9374
9375 bool issued_error = false;
9376 if (pa == old_args->end())
9377 push_empty_arg = true;
9378 else if (pa + 1 == old_args->end() && this->is_varargs_)
9379 new_args->push_back(*pa);
9380 else if (this->is_varargs_)
9381 {
9382 if ((*pa)->type()->is_slice_type())
9383 this->report_error(_("too many arguments"));
9384 else
9385 {
9386 error_at(this->location(),
9387 _("invalid use of %<...%> with non-slice"));
9388 this->set_is_error();
9389 }
9390 return;
9391 }
9392 else
9393 {
9394 Type* element_type = varargs_type->array_type()->element_type();
9395 Expression_list* vals = new Expression_list;
9396 for (; pa != old_args->end(); ++pa, ++i)
9397 {
9398 // Check types here so that we get a better message.
9399 Type* patype = (*pa)->type();
9400 Location paloc = (*pa)->location();
9401 if (!this->check_argument_type(i, element_type, patype,
9402 paloc, issued_error))
9403 continue;
9404 vals->push_back(*pa);
9405 }
9406 Expression* val =
9407 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9408 gogo->lower_expression(function, inserter, &val);
9409 new_args->push_back(val);
9410 }
9411 }
9412
9413 if (push_empty_arg)
9414 new_args->push_back(Expression::make_nil(loc));
9415
9416 // We can't return a new call expression here, because this one may
9417 // be referenced by Call_result expressions. FIXME. We can't
9418 // delete OLD_ARGS because we may have both a Call_expression and a
9419 // Builtin_call_expression which refer to them. FIXME.
9420 this->args_ = new_args;
9421 this->varargs_are_lowered_ = true;
9422 }
9423
9424 // Get the function type. This can return NULL in error cases.
9425
9426 Function_type*
9427 Call_expression::get_function_type() const
9428 {
9429 return this->fn_->type()->function_type();
9430 }
9431
9432 // Return the number of values which this call will return.
9433
9434 size_t
9435 Call_expression::result_count() const
9436 {
9437 const Function_type* fntype = this->get_function_type();
9438 if (fntype == NULL)
9439 return 0;
9440 if (fntype->results() == NULL)
9441 return 0;
9442 return fntype->results()->size();
9443 }
9444
9445 // Return the temporary which holds a result.
9446
9447 Temporary_statement*
9448 Call_expression::result(size_t i) const
9449 {
9450 if (this->results_ == NULL || this->results_->size() <= i)
9451 {
9452 go_assert(saw_errors());
9453 return NULL;
9454 }
9455 return (*this->results_)[i];
9456 }
9457
9458 // Return whether this is a call to the predeclared function recover.
9459
9460 bool
9461 Call_expression::is_recover_call() const
9462 {
9463 return this->do_is_recover_call();
9464 }
9465
9466 // Set the argument to the recover function.
9467
9468 void
9469 Call_expression::set_recover_arg(Expression* arg)
9470 {
9471 this->do_set_recover_arg(arg);
9472 }
9473
9474 // Virtual functions also implemented by Builtin_call_expression.
9475
9476 bool
9477 Call_expression::do_is_recover_call() const
9478 {
9479 return false;
9480 }
9481
9482 void
9483 Call_expression::do_set_recover_arg(Expression*)
9484 {
9485 go_unreachable();
9486 }
9487
9488 // We have found an error with this call expression; return true if
9489 // we should report it.
9490
9491 bool
9492 Call_expression::issue_error()
9493 {
9494 if (this->issued_error_)
9495 return false;
9496 else
9497 {
9498 this->issued_error_ = true;
9499 return true;
9500 }
9501 }
9502
9503 // Get the type.
9504
9505 Type*
9506 Call_expression::do_type()
9507 {
9508 if (this->type_ != NULL)
9509 return this->type_;
9510
9511 Type* ret;
9512 Function_type* fntype = this->get_function_type();
9513 if (fntype == NULL)
9514 return Type::make_error_type();
9515
9516 const Typed_identifier_list* results = fntype->results();
9517 if (results == NULL)
9518 ret = Type::make_void_type();
9519 else if (results->size() == 1)
9520 ret = results->begin()->type();
9521 else
9522 ret = Type::make_call_multiple_result_type(this);
9523
9524 this->type_ = ret;
9525
9526 return this->type_;
9527 }
9528
9529 // Determine types for a call expression. We can use the function
9530 // parameter types to set the types of the arguments.
9531
9532 void
9533 Call_expression::do_determine_type(const Type_context*)
9534 {
9535 if (!this->determining_types())
9536 return;
9537
9538 this->fn_->determine_type_no_context();
9539 Function_type* fntype = this->get_function_type();
9540 const Typed_identifier_list* parameters = NULL;
9541 if (fntype != NULL)
9542 parameters = fntype->parameters();
9543 if (this->args_ != NULL)
9544 {
9545 Typed_identifier_list::const_iterator pt;
9546 if (parameters != NULL)
9547 pt = parameters->begin();
9548 bool first = true;
9549 for (Expression_list::const_iterator pa = this->args_->begin();
9550 pa != this->args_->end();
9551 ++pa)
9552 {
9553 if (first)
9554 {
9555 first = false;
9556 // If this is a method, the first argument is the
9557 // receiver.
9558 if (fntype != NULL && fntype->is_method())
9559 {
9560 Type* rtype = fntype->receiver()->type();
9561 // The receiver is always passed as a pointer.
9562 if (rtype->points_to() == NULL)
9563 rtype = Type::make_pointer_type(rtype);
9564 Type_context subcontext(rtype, false);
9565 (*pa)->determine_type(&subcontext);
9566 continue;
9567 }
9568 }
9569
9570 if (parameters != NULL && pt != parameters->end())
9571 {
9572 Type_context subcontext(pt->type(), false);
9573 (*pa)->determine_type(&subcontext);
9574 ++pt;
9575 }
9576 else
9577 (*pa)->determine_type_no_context();
9578 }
9579 }
9580 }
9581
9582 // Called when determining types for a Call_expression. Return true
9583 // if we should go ahead, false if they have already been determined.
9584
9585 bool
9586 Call_expression::determining_types()
9587 {
9588 if (this->types_are_determined_)
9589 return false;
9590 else
9591 {
9592 this->types_are_determined_ = true;
9593 return true;
9594 }
9595 }
9596
9597 // Check types for parameter I.
9598
9599 bool
9600 Call_expression::check_argument_type(int i, const Type* parameter_type,
9601 const Type* argument_type,
9602 Location argument_location,
9603 bool issued_error)
9604 {
9605 std::string reason;
9606 bool ok;
9607 if (this->are_hidden_fields_ok_)
9608 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9609 &reason);
9610 else
9611 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9612 if (!ok)
9613 {
9614 if (!issued_error)
9615 {
9616 if (reason.empty())
9617 error_at(argument_location, "argument %d has incompatible type", i);
9618 else
9619 error_at(argument_location,
9620 "argument %d has incompatible type (%s)",
9621 i, reason.c_str());
9622 }
9623 this->set_is_error();
9624 return false;
9625 }
9626 return true;
9627 }
9628
9629 // Check types.
9630
9631 void
9632 Call_expression::do_check_types(Gogo*)
9633 {
9634 if (this->classification() == EXPRESSION_ERROR)
9635 return;
9636
9637 Function_type* fntype = this->get_function_type();
9638 if (fntype == NULL)
9639 {
9640 if (!this->fn_->type()->is_error())
9641 this->report_error(_("expected function"));
9642 return;
9643 }
9644
9645 bool is_method = fntype->is_method();
9646 if (is_method)
9647 {
9648 go_assert(this->args_ != NULL && !this->args_->empty());
9649 Type* rtype = fntype->receiver()->type();
9650 Expression* first_arg = this->args_->front();
9651 // The language permits copying hidden fields for a method
9652 // receiver. We dereference the values since receivers are
9653 // always passed as pointers.
9654 std::string reason;
9655 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9656 first_arg->type()->deref(),
9657 &reason))
9658 {
9659 if (reason.empty())
9660 this->report_error(_("incompatible type for receiver"));
9661 else
9662 {
9663 error_at(this->location(),
9664 "incompatible type for receiver (%s)",
9665 reason.c_str());
9666 this->set_is_error();
9667 }
9668 }
9669 }
9670
9671 // Note that varargs was handled by the lower_varargs() method, so
9672 // we don't have to worry about it here unless something is wrong.
9673 if (this->is_varargs_ && !this->varargs_are_lowered_)
9674 {
9675 if (!fntype->is_varargs())
9676 {
9677 error_at(this->location(),
9678 _("invalid use of %<...%> calling non-variadic function"));
9679 this->set_is_error();
9680 return;
9681 }
9682 }
9683
9684 const Typed_identifier_list* parameters = fntype->parameters();
9685 if (this->args_ == NULL)
9686 {
9687 if (parameters != NULL && !parameters->empty())
9688 this->report_error(_("not enough arguments"));
9689 }
9690 else if (parameters == NULL)
9691 {
9692 if (!is_method || this->args_->size() > 1)
9693 this->report_error(_("too many arguments"));
9694 }
9695 else
9696 {
9697 int i = 0;
9698 Expression_list::const_iterator pa = this->args_->begin();
9699 if (is_method)
9700 ++pa;
9701 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9702 pt != parameters->end();
9703 ++pt, ++pa, ++i)
9704 {
9705 if (pa == this->args_->end())
9706 {
9707 this->report_error(_("not enough arguments"));
9708 return;
9709 }
9710 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9711 (*pa)->location(), false);
9712 }
9713 if (pa != this->args_->end())
9714 this->report_error(_("too many arguments"));
9715 }
9716 }
9717
9718 // Return whether we have to use a temporary variable to ensure that
9719 // we evaluate this call expression in order. If the call returns no
9720 // results then it will inevitably be executed last.
9721
9722 bool
9723 Call_expression::do_must_eval_in_order() const
9724 {
9725 return this->result_count() > 0;
9726 }
9727
9728 // Get the function and the first argument to use when calling an
9729 // interface method.
9730
9731 tree
9732 Call_expression::interface_method_function(
9733 Translate_context* context,
9734 Interface_field_reference_expression* interface_method,
9735 tree* first_arg_ptr)
9736 {
9737 tree expr = interface_method->expr()->get_tree(context);
9738 if (expr == error_mark_node)
9739 return error_mark_node;
9740 expr = save_expr(expr);
9741 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9742 if (first_arg == error_mark_node)
9743 return error_mark_node;
9744 *first_arg_ptr = first_arg;
9745 return interface_method->get_function_tree(context, expr);
9746 }
9747
9748 // Build the call expression.
9749
9750 tree
9751 Call_expression::do_get_tree(Translate_context* context)
9752 {
9753 if (this->tree_ != NULL_TREE)
9754 return this->tree_;
9755
9756 Function_type* fntype = this->get_function_type();
9757 if (fntype == NULL)
9758 return error_mark_node;
9759
9760 if (this->fn_->is_error_expression())
9761 return error_mark_node;
9762
9763 Gogo* gogo = context->gogo();
9764 Location location = this->location();
9765
9766 Func_expression* func = this->fn_->func_expression();
9767 Interface_field_reference_expression* interface_method =
9768 this->fn_->interface_field_reference_expression();
9769 const bool has_closure = func != NULL && func->closure() != NULL;
9770 const bool is_interface_method = interface_method != NULL;
9771
9772 bool has_closure_arg;
9773 if (has_closure)
9774 has_closure_arg = true;
9775 else if (func != NULL)
9776 has_closure_arg = false;
9777 else if (is_interface_method)
9778 has_closure_arg = false;
9779 else
9780 has_closure_arg = true;
9781
9782 int nargs;
9783 tree* args;
9784 if (this->args_ == NULL || this->args_->empty())
9785 {
9786 nargs = is_interface_method ? 1 : 0;
9787 args = nargs == 0 ? NULL : new tree[nargs];
9788 }
9789 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9790 {
9791 // Passing a receiver parameter.
9792 go_assert(!is_interface_method
9793 && fntype->is_method()
9794 && this->args_->size() == 1);
9795 nargs = 1;
9796 args = new tree[nargs];
9797 args[0] = this->args_->front()->get_tree(context);
9798 }
9799 else
9800 {
9801 const Typed_identifier_list* params = fntype->parameters();
9802
9803 nargs = this->args_->size();
9804 int i = is_interface_method ? 1 : 0;
9805 nargs += i;
9806 args = new tree[nargs];
9807
9808 Typed_identifier_list::const_iterator pp = params->begin();
9809 Expression_list::const_iterator pe = this->args_->begin();
9810 if (!is_interface_method && fntype->is_method())
9811 {
9812 args[i] = (*pe)->get_tree(context);
9813 ++pe;
9814 ++i;
9815 }
9816 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9817 {
9818 go_assert(pp != params->end());
9819 tree arg_val = (*pe)->get_tree(context);
9820 args[i] = Expression::convert_for_assignment(context,
9821 pp->type(),
9822 (*pe)->type(),
9823 arg_val,
9824 location);
9825 if (args[i] == error_mark_node)
9826 return error_mark_node;
9827 }
9828 go_assert(pp == params->end());
9829 go_assert(i == nargs);
9830 }
9831
9832 tree fntype_tree = type_to_tree(fntype->get_backend(gogo));
9833 tree fnfield_type = type_to_tree(fntype->get_backend_fntype(gogo));
9834 if (fntype_tree == error_mark_node || fnfield_type == error_mark_node)
9835 return error_mark_node;
9836 go_assert(FUNCTION_POINTER_TYPE_P(fnfield_type));
9837 tree rettype = TREE_TYPE(TREE_TYPE(fnfield_type));
9838 if (rettype == error_mark_node)
9839 return error_mark_node;
9840
9841 tree fn;
9842 tree closure_tree;
9843 if (func != NULL)
9844 {
9845 Named_object* no = func->named_object();
9846 fn = expr_to_tree(Func_expression::get_code_pointer(gogo, no, location));
9847 if (!has_closure)
9848 closure_tree = NULL_TREE;
9849 else
9850 {
9851 closure_tree = func->closure()->get_tree(context);
9852 if (closure_tree == error_mark_node)
9853 return error_mark_node;
9854 }
9855 }
9856 else if (!is_interface_method)
9857 {
9858 closure_tree = this->fn_->get_tree(context);
9859 if (closure_tree == error_mark_node)
9860 return error_mark_node;
9861 tree fnc = fold_convert_loc(location.gcc_location(), fntype_tree,
9862 closure_tree);
9863 go_assert(POINTER_TYPE_P(TREE_TYPE(fnc))
9864 && (TREE_CODE(TREE_TYPE(TREE_TYPE(fnc)))
9865 == RECORD_TYPE));
9866 tree field = TYPE_FIELDS(TREE_TYPE(TREE_TYPE(fnc)));
9867 fn = fold_build3_loc(location.gcc_location(), COMPONENT_REF,
9868 TREE_TYPE(field),
9869 build_fold_indirect_ref_loc(location.gcc_location(),
9870 fnc),
9871 field, NULL_TREE);
9872 }
9873 else
9874 {
9875 fn = this->interface_method_function(context, interface_method,
9876 &args[0]);
9877 if (fn == error_mark_node)
9878 return error_mark_node;
9879 closure_tree = NULL_TREE;
9880 }
9881
9882 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9883 return error_mark_node;
9884
9885 tree fndecl = fn;
9886 if (TREE_CODE(fndecl) == ADDR_EXPR)
9887 fndecl = TREE_OPERAND(fndecl, 0);
9888
9889 // Add a type cast in case the type of the function is a recursive
9890 // type which refers to itself.
9891 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
9892 fn = fold_convert_loc(location.gcc_location(), fnfield_type, fn);
9893
9894 // This is to support builtin math functions when using 80387 math.
9895 tree excess_type = NULL_TREE;
9896 if (optimize
9897 && TREE_CODE(fndecl) == FUNCTION_DECL
9898 && DECL_IS_BUILTIN(fndecl)
9899 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9900 && nargs > 0
9901 && ((SCALAR_FLOAT_TYPE_P(rettype)
9902 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9903 || (COMPLEX_FLOAT_TYPE_P(rettype)
9904 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9905 {
9906 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9907 if (excess_type != NULL_TREE)
9908 {
9909 tree excess_fndecl = mathfn_built_in(excess_type,
9910 DECL_FUNCTION_CODE(fndecl));
9911 if (excess_fndecl == NULL_TREE)
9912 excess_type = NULL_TREE;
9913 else
9914 {
9915 fn = build_fold_addr_expr_loc(location.gcc_location(),
9916 excess_fndecl);
9917 for (int i = 0; i < nargs; ++i)
9918 {
9919 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9920 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9921 args[i] = ::convert(excess_type, args[i]);
9922 }
9923 }
9924 }
9925 }
9926
9927 if (func == NULL)
9928 fn = save_expr(fn);
9929
9930 if (!has_closure_arg)
9931 go_assert(closure_tree == NULL_TREE);
9932 else
9933 {
9934 // Pass the closure argument by calling the function function
9935 // __go_set_closure. In the order_evaluations pass we have
9936 // ensured that if any parameters contain call expressions, they
9937 // will have been moved out to temporary variables.
9938
9939 go_assert(closure_tree != NULL_TREE);
9940 closure_tree = fold_convert_loc(location.gcc_location(), ptr_type_node,
9941 closure_tree);
9942 static tree set_closure_fndecl;
9943 tree set_closure = Gogo::call_builtin(&set_closure_fndecl,
9944 location,
9945 "__go_set_closure",
9946 1,
9947 void_type_node,
9948 ptr_type_node,
9949 closure_tree);
9950 if (set_closure == error_mark_node)
9951 return error_mark_node;
9952 fn = build2_loc(location.gcc_location(), COMPOUND_EXPR,
9953 TREE_TYPE(fn), set_closure, fn);
9954 }
9955
9956 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9957 fn, nargs, args);
9958 delete[] args;
9959
9960 SET_EXPR_LOCATION(ret, location.gcc_location());
9961
9962 // If this is a recursive function type which returns itself, as in
9963 // type F func() F
9964 // we have used ptr_type_node for the return type. Add a cast here
9965 // to the correct type.
9966 if (TREE_TYPE(ret) == ptr_type_node)
9967 {
9968 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9969 ret = fold_convert_loc(location.gcc_location(), t, ret);
9970 }
9971
9972 if (excess_type != NULL_TREE)
9973 {
9974 // Calling convert here can undo our excess precision change.
9975 // That may or may not be a bug in convert_to_real.
9976 ret = build1(NOP_EXPR, rettype, ret);
9977 }
9978
9979 if (this->results_ != NULL)
9980 ret = this->set_results(context, ret);
9981
9982 this->tree_ = ret;
9983
9984 return ret;
9985 }
9986
9987 // Set the result variables if this call returns multiple results.
9988
9989 tree
9990 Call_expression::set_results(Translate_context* context, tree call_tree)
9991 {
9992 tree stmt_list = NULL_TREE;
9993
9994 call_tree = save_expr(call_tree);
9995
9996 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9997 {
9998 go_assert(saw_errors());
9999 return call_tree;
10000 }
10001
10002 Location loc = this->location();
10003 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
10004 size_t rc = this->result_count();
10005 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
10006 {
10007 go_assert(field != NULL_TREE);
10008
10009 Temporary_statement* temp = this->result(i);
10010 if (temp == NULL)
10011 {
10012 go_assert(saw_errors());
10013 return error_mark_node;
10014 }
10015 Temporary_reference_expression* ref =
10016 Expression::make_temporary_reference(temp, loc);
10017 ref->set_is_lvalue();
10018 tree temp_tree = ref->get_tree(context);
10019 if (temp_tree == error_mark_node)
10020 return error_mark_node;
10021
10022 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
10023 TREE_TYPE(field), call_tree, field, NULL_TREE);
10024 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
10025 void_type_node, temp_tree, val_tree);
10026
10027 append_to_statement_list(set_tree, &stmt_list);
10028 }
10029 go_assert(field == NULL_TREE);
10030
10031 return save_expr(stmt_list);
10032 }
10033
10034 // Dump ast representation for a call expressin.
10035
10036 void
10037 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10038 {
10039 this->fn_->dump_expression(ast_dump_context);
10040 ast_dump_context->ostream() << "(";
10041 if (args_ != NULL)
10042 ast_dump_context->dump_expression_list(this->args_);
10043
10044 ast_dump_context->ostream() << ") ";
10045 }
10046
10047 // Make a call expression.
10048
10049 Call_expression*
10050 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10051 Location location)
10052 {
10053 return new Call_expression(fn, args, is_varargs, location);
10054 }
10055
10056 // A single result from a call which returns multiple results.
10057
10058 class Call_result_expression : public Expression
10059 {
10060 public:
10061 Call_result_expression(Call_expression* call, unsigned int index)
10062 : Expression(EXPRESSION_CALL_RESULT, call->location()),
10063 call_(call), index_(index)
10064 { }
10065
10066 protected:
10067 int
10068 do_traverse(Traverse*);
10069
10070 Type*
10071 do_type();
10072
10073 void
10074 do_determine_type(const Type_context*);
10075
10076 void
10077 do_check_types(Gogo*);
10078
10079 Expression*
10080 do_copy()
10081 {
10082 return new Call_result_expression(this->call_->call_expression(),
10083 this->index_);
10084 }
10085
10086 bool
10087 do_must_eval_in_order() const
10088 { return true; }
10089
10090 tree
10091 do_get_tree(Translate_context*);
10092
10093 void
10094 do_dump_expression(Ast_dump_context*) const;
10095
10096 private:
10097 // The underlying call expression.
10098 Expression* call_;
10099 // Which result we want.
10100 unsigned int index_;
10101 };
10102
10103 // Traverse a call result.
10104
10105 int
10106 Call_result_expression::do_traverse(Traverse* traverse)
10107 {
10108 if (traverse->remember_expression(this->call_))
10109 {
10110 // We have already traversed the call expression.
10111 return TRAVERSE_CONTINUE;
10112 }
10113 return Expression::traverse(&this->call_, traverse);
10114 }
10115
10116 // Get the type.
10117
10118 Type*
10119 Call_result_expression::do_type()
10120 {
10121 if (this->classification() == EXPRESSION_ERROR)
10122 return Type::make_error_type();
10123
10124 // THIS->CALL_ can be replaced with a temporary reference due to
10125 // Call_expression::do_must_eval_in_order when there is an error.
10126 Call_expression* ce = this->call_->call_expression();
10127 if (ce == NULL)
10128 {
10129 this->set_is_error();
10130 return Type::make_error_type();
10131 }
10132 Function_type* fntype = ce->get_function_type();
10133 if (fntype == NULL)
10134 {
10135 if (ce->issue_error())
10136 {
10137 if (!ce->fn()->type()->is_error())
10138 this->report_error(_("expected function"));
10139 }
10140 this->set_is_error();
10141 return Type::make_error_type();
10142 }
10143 const Typed_identifier_list* results = fntype->results();
10144 if (results == NULL || results->size() < 2)
10145 {
10146 if (ce->issue_error())
10147 this->report_error(_("number of results does not match "
10148 "number of values"));
10149 return Type::make_error_type();
10150 }
10151 Typed_identifier_list::const_iterator pr = results->begin();
10152 for (unsigned int i = 0; i < this->index_; ++i)
10153 {
10154 if (pr == results->end())
10155 break;
10156 ++pr;
10157 }
10158 if (pr == results->end())
10159 {
10160 if (ce->issue_error())
10161 this->report_error(_("number of results does not match "
10162 "number of values"));
10163 return Type::make_error_type();
10164 }
10165 return pr->type();
10166 }
10167
10168 // Check the type. Just make sure that we trigger the warning in
10169 // do_type.
10170
10171 void
10172 Call_result_expression::do_check_types(Gogo*)
10173 {
10174 this->type();
10175 }
10176
10177 // Determine the type. We have nothing to do here, but the 0 result
10178 // needs to pass down to the caller.
10179
10180 void
10181 Call_result_expression::do_determine_type(const Type_context*)
10182 {
10183 this->call_->determine_type_no_context();
10184 }
10185
10186 // Return the tree. We just refer to the temporary set by the call
10187 // expression. We don't do this at lowering time because it makes it
10188 // hard to evaluate the call at the right time.
10189
10190 tree
10191 Call_result_expression::do_get_tree(Translate_context* context)
10192 {
10193 Call_expression* ce = this->call_->call_expression();
10194 if (ce == NULL)
10195 {
10196 go_assert(this->call_->is_error_expression());
10197 return error_mark_node;
10198 }
10199 Temporary_statement* ts = ce->result(this->index_);
10200 if (ts == NULL)
10201 {
10202 go_assert(saw_errors());
10203 return error_mark_node;
10204 }
10205 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10206 return ref->get_tree(context);
10207 }
10208
10209 // Dump ast representation for a call result expression.
10210
10211 void
10212 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10213 const
10214 {
10215 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10216 // (struct) and the fields are referenced instead.
10217 ast_dump_context->ostream() << this->index_ << "@(";
10218 ast_dump_context->dump_expression(this->call_);
10219 ast_dump_context->ostream() << ")";
10220 }
10221
10222 // Make a reference to a single result of a call which returns
10223 // multiple results.
10224
10225 Expression*
10226 Expression::make_call_result(Call_expression* call, unsigned int index)
10227 {
10228 return new Call_result_expression(call, index);
10229 }
10230
10231 // Class Index_expression.
10232
10233 // Traversal.
10234
10235 int
10236 Index_expression::do_traverse(Traverse* traverse)
10237 {
10238 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10239 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10240 || (this->end_ != NULL
10241 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10242 || (this->cap_ != NULL
10243 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10244 return TRAVERSE_EXIT;
10245 return TRAVERSE_CONTINUE;
10246 }
10247
10248 // Lower an index expression. This converts the generic index
10249 // expression into an array index, a string index, or a map index.
10250
10251 Expression*
10252 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10253 {
10254 Location location = this->location();
10255 Expression* left = this->left_;
10256 Expression* start = this->start_;
10257 Expression* end = this->end_;
10258 Expression* cap = this->cap_;
10259
10260 Type* type = left->type();
10261 if (type->is_error())
10262 return Expression::make_error(location);
10263 else if (left->is_type_expression())
10264 {
10265 error_at(location, "attempt to index type expression");
10266 return Expression::make_error(location);
10267 }
10268 else if (type->array_type() != NULL)
10269 return Expression::make_array_index(left, start, end, cap, location);
10270 else if (type->points_to() != NULL
10271 && type->points_to()->array_type() != NULL
10272 && !type->points_to()->is_slice_type())
10273 {
10274 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10275 location);
10276 return Expression::make_array_index(deref, start, end, cap, location);
10277 }
10278 else if (type->is_string_type())
10279 {
10280 if (cap != NULL)
10281 {
10282 error_at(location, "invalid 3-index slice of string");
10283 return Expression::make_error(location);
10284 }
10285 return Expression::make_string_index(left, start, end, location);
10286 }
10287 else if (type->map_type() != NULL)
10288 {
10289 if (end != NULL || cap != NULL)
10290 {
10291 error_at(location, "invalid slice of map");
10292 return Expression::make_error(location);
10293 }
10294 Map_index_expression* ret = Expression::make_map_index(left, start,
10295 location);
10296 if (this->is_lvalue_)
10297 ret->set_is_lvalue();
10298 return ret;
10299 }
10300 else
10301 {
10302 error_at(location,
10303 "attempt to index object which is not array, string, or map");
10304 return Expression::make_error(location);
10305 }
10306 }
10307
10308 // Write an indexed expression
10309 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10310
10311 void
10312 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10313 const Expression* expr,
10314 const Expression* start,
10315 const Expression* end,
10316 const Expression* cap)
10317 {
10318 expr->dump_expression(ast_dump_context);
10319 ast_dump_context->ostream() << "[";
10320 start->dump_expression(ast_dump_context);
10321 if (end != NULL)
10322 {
10323 ast_dump_context->ostream() << ":";
10324 end->dump_expression(ast_dump_context);
10325 }
10326 if (cap != NULL)
10327 {
10328 ast_dump_context->ostream() << ":";
10329 cap->dump_expression(ast_dump_context);
10330 }
10331 ast_dump_context->ostream() << "]";
10332 }
10333
10334 // Dump ast representation for an index expression.
10335
10336 void
10337 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10338 const
10339 {
10340 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10341 this->start_, this->end_, this->cap_);
10342 }
10343
10344 // Make an index expression.
10345
10346 Expression*
10347 Expression::make_index(Expression* left, Expression* start, Expression* end,
10348 Expression* cap, Location location)
10349 {
10350 return new Index_expression(left, start, end, cap, location);
10351 }
10352
10353 // An array index. This is used for both indexing and slicing.
10354
10355 class Array_index_expression : public Expression
10356 {
10357 public:
10358 Array_index_expression(Expression* array, Expression* start,
10359 Expression* end, Expression* cap, Location location)
10360 : Expression(EXPRESSION_ARRAY_INDEX, location),
10361 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
10362 { }
10363
10364 protected:
10365 int
10366 do_traverse(Traverse*);
10367
10368 Type*
10369 do_type();
10370
10371 void
10372 do_determine_type(const Type_context*);
10373
10374 void
10375 do_check_types(Gogo*);
10376
10377 Expression*
10378 do_copy()
10379 {
10380 return Expression::make_array_index(this->array_->copy(),
10381 this->start_->copy(),
10382 (this->end_ == NULL
10383 ? NULL
10384 : this->end_->copy()),
10385 (this->cap_ == NULL
10386 ? NULL
10387 : this->cap_->copy()),
10388 this->location());
10389 }
10390
10391 bool
10392 do_must_eval_subexpressions_in_order(int* skip) const
10393 {
10394 *skip = 1;
10395 return true;
10396 }
10397
10398 bool
10399 do_is_addressable() const;
10400
10401 void
10402 do_address_taken(bool escapes)
10403 { this->array_->address_taken(escapes); }
10404
10405 tree
10406 do_get_tree(Translate_context*);
10407
10408 void
10409 do_dump_expression(Ast_dump_context*) const;
10410
10411 private:
10412 // The array we are getting a value from.
10413 Expression* array_;
10414 // The start or only index.
10415 Expression* start_;
10416 // The end index of a slice. This may be NULL for a simple array
10417 // index, or it may be a nil expression for the length of the array.
10418 Expression* end_;
10419 // The capacity argument of a slice. This may be NULL for an array index or
10420 // slice.
10421 Expression* cap_;
10422 // The type of the expression.
10423 Type* type_;
10424 };
10425
10426 // Array index traversal.
10427
10428 int
10429 Array_index_expression::do_traverse(Traverse* traverse)
10430 {
10431 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10432 return TRAVERSE_EXIT;
10433 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10434 return TRAVERSE_EXIT;
10435 if (this->end_ != NULL)
10436 {
10437 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10438 return TRAVERSE_EXIT;
10439 }
10440 if (this->cap_ != NULL)
10441 {
10442 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10443 return TRAVERSE_EXIT;
10444 }
10445 return TRAVERSE_CONTINUE;
10446 }
10447
10448 // Return the type of an array index.
10449
10450 Type*
10451 Array_index_expression::do_type()
10452 {
10453 if (this->type_ == NULL)
10454 {
10455 Array_type* type = this->array_->type()->array_type();
10456 if (type == NULL)
10457 this->type_ = Type::make_error_type();
10458 else if (this->end_ == NULL)
10459 this->type_ = type->element_type();
10460 else if (type->is_slice_type())
10461 {
10462 // A slice of a slice has the same type as the original
10463 // slice.
10464 this->type_ = this->array_->type()->deref();
10465 }
10466 else
10467 {
10468 // A slice of an array is a slice.
10469 this->type_ = Type::make_array_type(type->element_type(), NULL);
10470 }
10471 }
10472 return this->type_;
10473 }
10474
10475 // Set the type of an array index.
10476
10477 void
10478 Array_index_expression::do_determine_type(const Type_context*)
10479 {
10480 this->array_->determine_type_no_context();
10481 this->start_->determine_type_no_context();
10482 if (this->end_ != NULL)
10483 this->end_->determine_type_no_context();
10484 if (this->cap_ != NULL)
10485 this->cap_->determine_type_no_context();
10486 }
10487
10488 // Check types of an array index.
10489
10490 void
10491 Array_index_expression::do_check_types(Gogo*)
10492 {
10493 Numeric_constant nc;
10494 unsigned long v;
10495 if (this->start_->type()->integer_type() == NULL
10496 && !this->start_->type()->is_error()
10497 && (!this->start_->numeric_constant_value(&nc)
10498 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10499 this->report_error(_("index must be integer"));
10500 if (this->end_ != NULL
10501 && this->end_->type()->integer_type() == NULL
10502 && !this->end_->type()->is_error()
10503 && !this->end_->is_nil_expression()
10504 && !this->end_->is_error_expression()
10505 && (!this->end_->numeric_constant_value(&nc)
10506 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10507 this->report_error(_("slice end must be integer"));
10508 if (this->cap_ != NULL
10509 && this->cap_->type()->integer_type() == NULL
10510 && !this->cap_->type()->is_error()
10511 && !this->cap_->is_nil_expression()
10512 && !this->cap_->is_error_expression()
10513 && (!this->cap_->numeric_constant_value(&nc)
10514 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10515 this->report_error(_("slice capacity must be integer"));
10516
10517 Array_type* array_type = this->array_->type()->array_type();
10518 if (array_type == NULL)
10519 {
10520 go_assert(this->array_->type()->is_error());
10521 return;
10522 }
10523
10524 unsigned int int_bits =
10525 Type::lookup_integer_type("int")->integer_type()->bits();
10526
10527 Numeric_constant lvalnc;
10528 mpz_t lval;
10529 bool lval_valid = (array_type->length() != NULL
10530 && array_type->length()->numeric_constant_value(&lvalnc)
10531 && lvalnc.to_int(&lval));
10532 Numeric_constant inc;
10533 mpz_t ival;
10534 bool ival_valid = false;
10535 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10536 {
10537 ival_valid = true;
10538 if (mpz_sgn(ival) < 0
10539 || mpz_sizeinbase(ival, 2) >= int_bits
10540 || (lval_valid
10541 && (this->end_ == NULL
10542 ? mpz_cmp(ival, lval) >= 0
10543 : mpz_cmp(ival, lval) > 0)))
10544 {
10545 error_at(this->start_->location(), "array index out of bounds");
10546 this->set_is_error();
10547 }
10548 }
10549 if (this->end_ != NULL && !this->end_->is_nil_expression())
10550 {
10551 Numeric_constant enc;
10552 mpz_t eval;
10553 bool eval_valid = false;
10554 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10555 {
10556 eval_valid = true;
10557 if (mpz_sgn(eval) < 0
10558 || mpz_sizeinbase(eval, 2) >= int_bits
10559 || (lval_valid && mpz_cmp(eval, lval) > 0))
10560 {
10561 error_at(this->end_->location(), "array index out of bounds");
10562 this->set_is_error();
10563 }
10564 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10565 this->report_error(_("inverted slice range"));
10566 }
10567
10568 Numeric_constant cnc;
10569 mpz_t cval;
10570 if (this->cap_ != NULL
10571 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10572 {
10573 if (mpz_sgn(cval) < 0
10574 || mpz_sizeinbase(cval, 2) >= int_bits
10575 || (lval_valid && mpz_cmp(cval, lval) > 0))
10576 {
10577 error_at(this->cap_->location(), "array index out of bounds");
10578 this->set_is_error();
10579 }
10580 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10581 {
10582 error_at(this->cap_->location(),
10583 "invalid slice index: capacity less than start");
10584 this->set_is_error();
10585 }
10586 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10587 {
10588 error_at(this->cap_->location(),
10589 "invalid slice index: capacity less than length");
10590 this->set_is_error();
10591 }
10592 mpz_clear(cval);
10593 }
10594
10595 if (eval_valid)
10596 mpz_clear(eval);
10597 }
10598 if (ival_valid)
10599 mpz_clear(ival);
10600 if (lval_valid)
10601 mpz_clear(lval);
10602
10603 // A slice of an array requires an addressable array. A slice of a
10604 // slice is always possible.
10605 if (this->end_ != NULL && !array_type->is_slice_type())
10606 {
10607 if (!this->array_->is_addressable())
10608 this->report_error(_("slice of unaddressable value"));
10609 else
10610 this->array_->address_taken(true);
10611 }
10612 }
10613
10614 // Return whether this expression is addressable.
10615
10616 bool
10617 Array_index_expression::do_is_addressable() const
10618 {
10619 // A slice expression is not addressable.
10620 if (this->end_ != NULL)
10621 return false;
10622
10623 // An index into a slice is addressable.
10624 if (this->array_->type()->is_slice_type())
10625 return true;
10626
10627 // An index into an array is addressable if the array is
10628 // addressable.
10629 return this->array_->is_addressable();
10630 }
10631
10632 // Get a tree for an array index.
10633
10634 tree
10635 Array_index_expression::do_get_tree(Translate_context* context)
10636 {
10637 Gogo* gogo = context->gogo();
10638 Location loc = this->location();
10639
10640 Array_type* array_type = this->array_->type()->array_type();
10641 if (array_type == NULL)
10642 {
10643 go_assert(this->array_->type()->is_error());
10644 return error_mark_node;
10645 }
10646
10647 tree type_tree = type_to_tree(array_type->get_backend(gogo));
10648 if (type_tree == error_mark_node)
10649 return error_mark_node;
10650
10651 tree array_tree = this->array_->get_tree(context);
10652 if (array_tree == error_mark_node)
10653 return error_mark_node;
10654
10655 if (array_type->length() == NULL && !DECL_P(array_tree))
10656 array_tree = save_expr(array_tree);
10657
10658 tree length_tree = NULL_TREE;
10659 if (this->end_ == NULL || this->end_->is_nil_expression())
10660 {
10661 length_tree = array_type->length_tree(gogo, array_tree);
10662 if (length_tree == error_mark_node)
10663 return error_mark_node;
10664 length_tree = save_expr(length_tree);
10665 }
10666
10667 tree capacity_tree = NULL_TREE;
10668 if (this->end_ != NULL)
10669 {
10670 capacity_tree = array_type->capacity_tree(gogo, array_tree);
10671 if (capacity_tree == error_mark_node)
10672 return error_mark_node;
10673 capacity_tree = save_expr(capacity_tree);
10674 }
10675
10676 tree cap_arg = capacity_tree;
10677 if (this->cap_ != NULL)
10678 {
10679 cap_arg = this->cap_->get_tree(context);
10680 if (cap_arg == error_mark_node)
10681 return error_mark_node;
10682 }
10683
10684 tree length_type = (length_tree != NULL_TREE
10685 ? TREE_TYPE(length_tree)
10686 : TREE_TYPE(cap_arg));
10687
10688 tree bad_index = boolean_false_node;
10689
10690 tree start_tree = this->start_->get_tree(context);
10691 if (start_tree == error_mark_node)
10692 return error_mark_node;
10693 if (!DECL_P(start_tree))
10694 start_tree = save_expr(start_tree);
10695 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10696 start_tree = convert_to_integer(length_type, start_tree);
10697
10698 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10699 loc);
10700
10701 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10702 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10703 boolean_type_node, bad_index,
10704 fold_build2_loc(loc.gcc_location(),
10705 (this->end_ == NULL
10706 ? GE_EXPR
10707 : GT_EXPR),
10708 boolean_type_node, start_tree,
10709 (this->end_ == NULL
10710 ? length_tree
10711 : capacity_tree)));
10712
10713 int code = (array_type->length() != NULL
10714 ? (this->end_ == NULL
10715 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10716 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10717 : (this->end_ == NULL
10718 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10719 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10720 tree crash = gogo->runtime_error(code, loc);
10721
10722 if (this->end_ == NULL)
10723 {
10724 // Simple array indexing. This has to return an l-value, so
10725 // wrap the index check into START_TREE.
10726 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
10727 build3(COND_EXPR, void_type_node,
10728 bad_index, crash, NULL_TREE),
10729 start_tree);
10730 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
10731
10732 if (array_type->length() != NULL)
10733 {
10734 // Fixed array.
10735 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
10736 start_tree, NULL_TREE, NULL_TREE);
10737 }
10738 else
10739 {
10740 // Open array.
10741 tree values = array_type->value_pointer_tree(gogo, array_tree);
10742 Type* element_type = array_type->element_type();
10743 Btype* belement_type = element_type->get_backend(gogo);
10744 tree element_type_tree = type_to_tree(belement_type);
10745 if (element_type_tree == error_mark_node)
10746 return error_mark_node;
10747 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10748 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10749 start_tree, element_size);
10750 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10751 TREE_TYPE(values), values, offset);
10752 return build_fold_indirect_ref(ptr);
10753 }
10754 }
10755
10756 // Array slice.
10757
10758 if (this->cap_ != NULL)
10759 {
10760 if (!DECL_P(cap_arg))
10761 cap_arg = save_expr(cap_arg);
10762 if (!INTEGRAL_TYPE_P(TREE_TYPE(cap_arg)))
10763 cap_arg = convert_to_integer(length_type, cap_arg);
10764
10765 bad_index = Expression::check_bounds(cap_arg, length_type, bad_index,
10766 loc);
10767 cap_arg = fold_convert_loc(loc.gcc_location(), length_type, cap_arg);
10768
10769 tree bad_cap = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10770 boolean_type_node,
10771 fold_build2_loc(loc.gcc_location(),
10772 LT_EXPR, boolean_type_node,
10773 cap_arg, start_tree),
10774 fold_build2_loc(loc.gcc_location(),
10775 GT_EXPR, boolean_type_node,
10776 cap_arg, capacity_tree));
10777 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10778 boolean_type_node, bad_index, bad_cap);
10779 }
10780
10781 tree end_tree;
10782 if (this->end_->is_nil_expression())
10783 end_tree = length_tree;
10784 else
10785 {
10786 end_tree = this->end_->get_tree(context);
10787 if (end_tree == error_mark_node)
10788 return error_mark_node;
10789 if (!DECL_P(end_tree))
10790 end_tree = save_expr(end_tree);
10791 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10792 end_tree = convert_to_integer(length_type, end_tree);
10793
10794 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
10795 loc);
10796
10797 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
10798
10799 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10800 boolean_type_node,
10801 fold_build2_loc(loc.gcc_location(),
10802 LT_EXPR, boolean_type_node,
10803 end_tree, start_tree),
10804 fold_build2_loc(loc.gcc_location(),
10805 GT_EXPR, boolean_type_node,
10806 end_tree, cap_arg));
10807 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10808 boolean_type_node, bad_index, bad_end);
10809 }
10810
10811
10812 Type* element_type = array_type->element_type();
10813 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
10814 if (element_type_tree == error_mark_node)
10815 return error_mark_node;
10816 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10817
10818 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10819 fold_convert_loc(loc.gcc_location(), sizetype,
10820 start_tree),
10821 element_size);
10822
10823 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
10824 if (value_pointer == error_mark_node)
10825 return error_mark_node;
10826
10827 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10828 TREE_TYPE(value_pointer),
10829 value_pointer, offset);
10830
10831 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10832 length_type, end_tree, start_tree);
10833
10834 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10835 length_type, cap_arg, start_tree);
10836
10837 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
10838 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
10839
10840 vec<constructor_elt, va_gc> *init;
10841 vec_alloc (init, 3);
10842
10843 constructor_elt empty = {NULL, NULL};
10844 constructor_elt* elt = init->quick_push(empty);
10845 tree field = TYPE_FIELDS(struct_tree);
10846 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
10847 elt->index = field;
10848 elt->value = value_pointer;
10849
10850 elt = init->quick_push(empty);
10851 field = DECL_CHAIN(field);
10852 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
10853 elt->index = field;
10854 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10855 result_length_tree);
10856
10857 elt = init->quick_push(empty);
10858 field = DECL_CHAIN(field);
10859 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
10860 elt->index = field;
10861 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10862 result_capacity_tree);
10863
10864 tree constructor = build_constructor(struct_tree, init);
10865
10866 if (TREE_CONSTANT(value_pointer)
10867 && TREE_CONSTANT(result_length_tree)
10868 && TREE_CONSTANT(result_capacity_tree))
10869 TREE_CONSTANT(constructor) = 1;
10870
10871 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
10872 TREE_TYPE(constructor),
10873 build3(COND_EXPR, void_type_node,
10874 bad_index, crash, NULL_TREE),
10875 constructor);
10876 }
10877
10878 // Dump ast representation for an array index expression.
10879
10880 void
10881 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10882 const
10883 {
10884 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10885 this->start_, this->end_, this->cap_);
10886 }
10887
10888 // Make an array index expression. END and CAP may be NULL.
10889
10890 Expression*
10891 Expression::make_array_index(Expression* array, Expression* start,
10892 Expression* end, Expression* cap,
10893 Location location)
10894 {
10895 return new Array_index_expression(array, start, end, cap, location);
10896 }
10897
10898 // A string index. This is used for both indexing and slicing.
10899
10900 class String_index_expression : public Expression
10901 {
10902 public:
10903 String_index_expression(Expression* string, Expression* start,
10904 Expression* end, Location location)
10905 : Expression(EXPRESSION_STRING_INDEX, location),
10906 string_(string), start_(start), end_(end)
10907 { }
10908
10909 protected:
10910 int
10911 do_traverse(Traverse*);
10912
10913 Type*
10914 do_type();
10915
10916 void
10917 do_determine_type(const Type_context*);
10918
10919 void
10920 do_check_types(Gogo*);
10921
10922 Expression*
10923 do_copy()
10924 {
10925 return Expression::make_string_index(this->string_->copy(),
10926 this->start_->copy(),
10927 (this->end_ == NULL
10928 ? NULL
10929 : this->end_->copy()),
10930 this->location());
10931 }
10932
10933 bool
10934 do_must_eval_subexpressions_in_order(int* skip) const
10935 {
10936 *skip = 1;
10937 return true;
10938 }
10939
10940 tree
10941 do_get_tree(Translate_context*);
10942
10943 void
10944 do_dump_expression(Ast_dump_context*) const;
10945
10946 private:
10947 // The string we are getting a value from.
10948 Expression* string_;
10949 // The start or only index.
10950 Expression* start_;
10951 // The end index of a slice. This may be NULL for a single index,
10952 // or it may be a nil expression for the length of the string.
10953 Expression* end_;
10954 };
10955
10956 // String index traversal.
10957
10958 int
10959 String_index_expression::do_traverse(Traverse* traverse)
10960 {
10961 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10962 return TRAVERSE_EXIT;
10963 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10964 return TRAVERSE_EXIT;
10965 if (this->end_ != NULL)
10966 {
10967 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10968 return TRAVERSE_EXIT;
10969 }
10970 return TRAVERSE_CONTINUE;
10971 }
10972
10973 // Return the type of a string index.
10974
10975 Type*
10976 String_index_expression::do_type()
10977 {
10978 if (this->end_ == NULL)
10979 return Type::lookup_integer_type("uint8");
10980 else
10981 return this->string_->type();
10982 }
10983
10984 // Determine the type of a string index.
10985
10986 void
10987 String_index_expression::do_determine_type(const Type_context*)
10988 {
10989 this->string_->determine_type_no_context();
10990 this->start_->determine_type_no_context();
10991 if (this->end_ != NULL)
10992 this->end_->determine_type_no_context();
10993 }
10994
10995 // Check types of a string index.
10996
10997 void
10998 String_index_expression::do_check_types(Gogo*)
10999 {
11000 Numeric_constant nc;
11001 unsigned long v;
11002 if (this->start_->type()->integer_type() == NULL
11003 && !this->start_->type()->is_error()
11004 && (!this->start_->numeric_constant_value(&nc)
11005 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11006 this->report_error(_("index must be integer"));
11007 if (this->end_ != NULL
11008 && this->end_->type()->integer_type() == NULL
11009 && !this->end_->type()->is_error()
11010 && !this->end_->is_nil_expression()
11011 && !this->end_->is_error_expression()
11012 && (!this->end_->numeric_constant_value(&nc)
11013 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11014 this->report_error(_("slice end must be integer"));
11015
11016 std::string sval;
11017 bool sval_valid = this->string_->string_constant_value(&sval);
11018
11019 Numeric_constant inc;
11020 mpz_t ival;
11021 bool ival_valid = false;
11022 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11023 {
11024 ival_valid = true;
11025 if (mpz_sgn(ival) < 0
11026 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
11027 {
11028 error_at(this->start_->location(), "string index out of bounds");
11029 this->set_is_error();
11030 }
11031 }
11032 if (this->end_ != NULL && !this->end_->is_nil_expression())
11033 {
11034 Numeric_constant enc;
11035 mpz_t eval;
11036 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11037 {
11038 if (mpz_sgn(eval) < 0
11039 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11040 {
11041 error_at(this->end_->location(), "string index out of bounds");
11042 this->set_is_error();
11043 }
11044 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11045 this->report_error(_("inverted slice range"));
11046 mpz_clear(eval);
11047 }
11048 }
11049 if (ival_valid)
11050 mpz_clear(ival);
11051 }
11052
11053 // Get a tree for a string index.
11054
11055 tree
11056 String_index_expression::do_get_tree(Translate_context* context)
11057 {
11058 Location loc = this->location();
11059
11060 tree string_tree = this->string_->get_tree(context);
11061 if (string_tree == error_mark_node)
11062 return error_mark_node;
11063
11064 if (this->string_->type()->points_to() != NULL)
11065 string_tree = build_fold_indirect_ref(string_tree);
11066 if (!DECL_P(string_tree))
11067 string_tree = save_expr(string_tree);
11068 tree string_type = TREE_TYPE(string_tree);
11069
11070 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
11071 length_tree = save_expr(length_tree);
11072
11073 Type* int_type = Type::lookup_integer_type("int");
11074 tree length_type = type_to_tree(int_type->get_backend(context->gogo()));
11075
11076 tree bad_index = boolean_false_node;
11077
11078 tree start_tree = this->start_->get_tree(context);
11079 if (start_tree == error_mark_node)
11080 return error_mark_node;
11081 if (!DECL_P(start_tree))
11082 start_tree = save_expr(start_tree);
11083 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
11084 start_tree = convert_to_integer(length_type, start_tree);
11085
11086 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
11087 loc);
11088
11089 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
11090
11091 int code = (this->end_ == NULL
11092 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11093 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11094 tree crash = context->gogo()->runtime_error(code, loc);
11095
11096 if (this->end_ == NULL)
11097 {
11098 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
11099 boolean_type_node, bad_index,
11100 fold_build2_loc(loc.gcc_location(), GE_EXPR,
11101 boolean_type_node,
11102 start_tree, length_tree));
11103
11104 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
11105 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
11106 TREE_TYPE(bytes_tree),
11107 bytes_tree,
11108 fold_convert_loc(loc.gcc_location(), sizetype,
11109 start_tree));
11110 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
11111
11112 return build2(COMPOUND_EXPR, TREE_TYPE(index),
11113 build3(COND_EXPR, void_type_node,
11114 bad_index, crash, NULL_TREE),
11115 index);
11116 }
11117 else
11118 {
11119 tree end_tree;
11120 if (this->end_->is_nil_expression())
11121 end_tree = build_int_cst(length_type, -1);
11122 else
11123 {
11124 end_tree = this->end_->get_tree(context);
11125 if (end_tree == error_mark_node)
11126 return error_mark_node;
11127 if (!DECL_P(end_tree))
11128 end_tree = save_expr(end_tree);
11129 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
11130 end_tree = convert_to_integer(length_type, end_tree);
11131
11132 bad_index = Expression::check_bounds(end_tree, length_type,
11133 bad_index, loc);
11134
11135 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
11136 end_tree);
11137 }
11138
11139 static tree strslice_fndecl;
11140 tree ret = Gogo::call_builtin(&strslice_fndecl,
11141 loc,
11142 "__go_string_slice",
11143 3,
11144 string_type,
11145 string_type,
11146 string_tree,
11147 length_type,
11148 start_tree,
11149 length_type,
11150 end_tree);
11151 if (ret == error_mark_node)
11152 return error_mark_node;
11153 // This will panic if the bounds are out of range for the
11154 // string.
11155 TREE_NOTHROW(strslice_fndecl) = 0;
11156
11157 if (bad_index == boolean_false_node)
11158 return ret;
11159 else
11160 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
11161 build3(COND_EXPR, void_type_node,
11162 bad_index, crash, NULL_TREE),
11163 ret);
11164 }
11165 }
11166
11167 // Dump ast representation for a string index expression.
11168
11169 void
11170 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11171 const
11172 {
11173 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11174 this->start_, this->end_, NULL);
11175 }
11176
11177 // Make a string index expression. END may be NULL.
11178
11179 Expression*
11180 Expression::make_string_index(Expression* string, Expression* start,
11181 Expression* end, Location location)
11182 {
11183 return new String_index_expression(string, start, end, location);
11184 }
11185
11186 // Class Map_index.
11187
11188 // Get the type of the map.
11189
11190 Map_type*
11191 Map_index_expression::get_map_type() const
11192 {
11193 Map_type* mt = this->map_->type()->deref()->map_type();
11194 if (mt == NULL)
11195 go_assert(saw_errors());
11196 return mt;
11197 }
11198
11199 // Map index traversal.
11200
11201 int
11202 Map_index_expression::do_traverse(Traverse* traverse)
11203 {
11204 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11205 return TRAVERSE_EXIT;
11206 return Expression::traverse(&this->index_, traverse);
11207 }
11208
11209 // Return the type of a map index.
11210
11211 Type*
11212 Map_index_expression::do_type()
11213 {
11214 Map_type* mt = this->get_map_type();
11215 if (mt == NULL)
11216 return Type::make_error_type();
11217 Type* type = mt->val_type();
11218 // If this map index is in a tuple assignment, we actually return a
11219 // pointer to the value type. Tuple_map_assignment_statement is
11220 // responsible for handling this correctly. We need to get the type
11221 // right in case this gets assigned to a temporary variable.
11222 if (this->is_in_tuple_assignment_)
11223 type = Type::make_pointer_type(type);
11224 return type;
11225 }
11226
11227 // Fix the type of a map index.
11228
11229 void
11230 Map_index_expression::do_determine_type(const Type_context*)
11231 {
11232 this->map_->determine_type_no_context();
11233 Map_type* mt = this->get_map_type();
11234 Type* key_type = mt == NULL ? NULL : mt->key_type();
11235 Type_context subcontext(key_type, false);
11236 this->index_->determine_type(&subcontext);
11237 }
11238
11239 // Check types of a map index.
11240
11241 void
11242 Map_index_expression::do_check_types(Gogo*)
11243 {
11244 std::string reason;
11245 Map_type* mt = this->get_map_type();
11246 if (mt == NULL)
11247 return;
11248 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11249 {
11250 if (reason.empty())
11251 this->report_error(_("incompatible type for map index"));
11252 else
11253 {
11254 error_at(this->location(), "incompatible type for map index (%s)",
11255 reason.c_str());
11256 this->set_is_error();
11257 }
11258 }
11259 }
11260
11261 // Get a tree for a map index.
11262
11263 tree
11264 Map_index_expression::do_get_tree(Translate_context* context)
11265 {
11266 Map_type* type = this->get_map_type();
11267 if (type == NULL)
11268 return error_mark_node;
11269
11270 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
11271 if (valptr == error_mark_node)
11272 return error_mark_node;
11273 valptr = save_expr(valptr);
11274
11275 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
11276
11277 if (this->is_lvalue_)
11278 return build_fold_indirect_ref(valptr);
11279 else if (this->is_in_tuple_assignment_)
11280 {
11281 // Tuple_map_assignment_statement is responsible for using this
11282 // appropriately.
11283 return valptr;
11284 }
11285 else
11286 {
11287 Gogo* gogo = context->gogo();
11288 Btype* val_btype = type->val_type()->get_backend(gogo);
11289 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
11290 return fold_build3(COND_EXPR, val_type_tree,
11291 fold_build2(EQ_EXPR, boolean_type_node, valptr,
11292 fold_convert(TREE_TYPE(valptr),
11293 null_pointer_node)),
11294 expr_to_tree(val_zero),
11295 build_fold_indirect_ref(valptr));
11296 }
11297 }
11298
11299 // Get a tree for the map index. This returns a tree which evaluates
11300 // to a pointer to a value. The pointer will be NULL if the key is
11301 // not in the map.
11302
11303 tree
11304 Map_index_expression::get_value_pointer(Translate_context* context,
11305 bool insert)
11306 {
11307 Map_type* type = this->get_map_type();
11308 if (type == NULL)
11309 return error_mark_node;
11310
11311 tree map_tree = this->map_->get_tree(context);
11312 tree index_tree = this->index_->get_tree(context);
11313 index_tree = Expression::convert_for_assignment(context, type->key_type(),
11314 this->index_->type(),
11315 index_tree,
11316 this->location());
11317 if (map_tree == error_mark_node || index_tree == error_mark_node)
11318 return error_mark_node;
11319
11320 if (this->map_->type()->points_to() != NULL)
11321 map_tree = build_fold_indirect_ref(map_tree);
11322
11323 // We need to pass in a pointer to the key, so stuff it into a
11324 // variable.
11325 tree tmp;
11326 tree make_tmp;
11327 if (current_function_decl != NULL)
11328 {
11329 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
11330 DECL_IGNORED_P(tmp) = 0;
11331 DECL_INITIAL(tmp) = index_tree;
11332 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
11333 TREE_ADDRESSABLE(tmp) = 1;
11334 }
11335 else
11336 {
11337 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11338 create_tmp_var_name("M"),
11339 TREE_TYPE(index_tree));
11340 DECL_EXTERNAL(tmp) = 0;
11341 TREE_PUBLIC(tmp) = 0;
11342 TREE_STATIC(tmp) = 1;
11343 DECL_ARTIFICIAL(tmp) = 1;
11344 if (!TREE_CONSTANT(index_tree))
11345 make_tmp = fold_build2_loc(this->location().gcc_location(),
11346 INIT_EXPR, void_type_node,
11347 tmp, index_tree);
11348 else
11349 {
11350 TREE_READONLY(tmp) = 1;
11351 TREE_CONSTANT(tmp) = 1;
11352 DECL_INITIAL(tmp) = index_tree;
11353 make_tmp = NULL_TREE;
11354 }
11355 rest_of_decl_compilation(tmp, 1, 0);
11356 }
11357 tree tmpref =
11358 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
11359 build_fold_addr_expr_loc(this->location().gcc_location(),
11360 tmp));
11361
11362 static tree map_index_fndecl;
11363 tree call = Gogo::call_builtin(&map_index_fndecl,
11364 this->location(),
11365 "__go_map_index",
11366 3,
11367 const_ptr_type_node,
11368 TREE_TYPE(map_tree),
11369 map_tree,
11370 const_ptr_type_node,
11371 tmpref,
11372 boolean_type_node,
11373 (insert
11374 ? boolean_true_node
11375 : boolean_false_node));
11376 if (call == error_mark_node)
11377 return error_mark_node;
11378 // This can panic on a map of interface type if the interface holds
11379 // an uncomparable or unhashable type.
11380 TREE_NOTHROW(map_index_fndecl) = 0;
11381
11382 Type* val_type = type->val_type();
11383 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
11384 if (val_type_tree == error_mark_node)
11385 return error_mark_node;
11386 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
11387
11388 tree ret = fold_convert_loc(this->location().gcc_location(),
11389 ptr_val_type_tree, call);
11390 if (make_tmp != NULL_TREE)
11391 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
11392 return ret;
11393 }
11394
11395 // Dump ast representation for a map index expression
11396
11397 void
11398 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11399 const
11400 {
11401 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11402 this->index_, NULL, NULL);
11403 }
11404
11405 // Make a map index expression.
11406
11407 Map_index_expression*
11408 Expression::make_map_index(Expression* map, Expression* index,
11409 Location location)
11410 {
11411 return new Map_index_expression(map, index, location);
11412 }
11413
11414 // Class Field_reference_expression.
11415
11416 // Lower a field reference expression. There is nothing to lower, but
11417 // this is where we generate the tracking information for fields with
11418 // the magic go:"track" tag.
11419
11420 Expression*
11421 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11422 Statement_inserter* inserter, int)
11423 {
11424 Struct_type* struct_type = this->expr_->type()->struct_type();
11425 if (struct_type == NULL)
11426 {
11427 // Error will be reported elsewhere.
11428 return this;
11429 }
11430 const Struct_field* field = struct_type->field(this->field_index_);
11431 if (field == NULL)
11432 return this;
11433 if (!field->has_tag())
11434 return this;
11435 if (field->tag().find("go:\"track\"") == std::string::npos)
11436 return this;
11437
11438 // We have found a reference to a tracked field. Build a call to
11439 // the runtime function __go_fieldtrack with a string that describes
11440 // the field. FIXME: We should only call this once per referenced
11441 // field per function, not once for each reference to the field.
11442
11443 if (this->called_fieldtrack_)
11444 return this;
11445 this->called_fieldtrack_ = true;
11446
11447 Location loc = this->location();
11448
11449 std::string s = "fieldtrack \"";
11450 Named_type* nt = this->expr_->type()->named_type();
11451 if (nt == NULL || nt->named_object()->package() == NULL)
11452 s.append(gogo->pkgpath());
11453 else
11454 s.append(nt->named_object()->package()->pkgpath());
11455 s.push_back('.');
11456 if (nt != NULL)
11457 s.append(Gogo::unpack_hidden_name(nt->name()));
11458 s.push_back('.');
11459 s.append(field->field_name());
11460 s.push_back('"');
11461
11462 // We can't use a string here, because internally a string holds a
11463 // pointer to the actual bytes; when the linker garbage collects the
11464 // string, it won't garbage collect the bytes. So we use a
11465 // [...]byte.
11466
11467 mpz_t val;
11468 mpz_init_set_ui(val, s.length());
11469 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11470 mpz_clear(val);
11471
11472 Type* byte_type = gogo->lookup_global("byte")->type_value();
11473 Type* array_type = Type::make_array_type(byte_type, length_expr);
11474
11475 Expression_list* bytes = new Expression_list();
11476 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11477 {
11478 mpz_init_set_ui(val, *p);
11479 Expression* byte = Expression::make_integer(&val, NULL, loc);
11480 mpz_clear(val);
11481 bytes->push_back(byte);
11482 }
11483
11484 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11485 bytes, false, loc);
11486
11487 Variable* var = new Variable(array_type, e, true, false, false, loc);
11488
11489 static int count;
11490 char buf[50];
11491 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11492 ++count;
11493
11494 Named_object* no = gogo->add_variable(buf, var);
11495 e = Expression::make_var_reference(no, loc);
11496 e = Expression::make_unary(OPERATOR_AND, e, loc);
11497
11498 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11499 inserter->insert(Statement::make_statement(call, false));
11500
11501 // Put this function, and the global variable we just created, into
11502 // unique sections. This will permit the linker to garbage collect
11503 // them if they are not referenced. The effect is that the only
11504 // strings, indicating field references, that will wind up in the
11505 // executable will be those for functions that are actually needed.
11506 if (function != NULL)
11507 function->func_value()->set_in_unique_section();
11508 var->set_in_unique_section();
11509
11510 return this;
11511 }
11512
11513 // Return the type of a field reference.
11514
11515 Type*
11516 Field_reference_expression::do_type()
11517 {
11518 Type* type = this->expr_->type();
11519 if (type->is_error())
11520 return type;
11521 Struct_type* struct_type = type->struct_type();
11522 go_assert(struct_type != NULL);
11523 return struct_type->field(this->field_index_)->type();
11524 }
11525
11526 // Check the types for a field reference.
11527
11528 void
11529 Field_reference_expression::do_check_types(Gogo*)
11530 {
11531 Type* type = this->expr_->type();
11532 if (type->is_error())
11533 return;
11534 Struct_type* struct_type = type->struct_type();
11535 go_assert(struct_type != NULL);
11536 go_assert(struct_type->field(this->field_index_) != NULL);
11537 }
11538
11539 // Get a tree for a field reference.
11540
11541 tree
11542 Field_reference_expression::do_get_tree(Translate_context* context)
11543 {
11544 tree struct_tree = this->expr_->get_tree(context);
11545 if (struct_tree == error_mark_node
11546 || TREE_TYPE(struct_tree) == error_mark_node)
11547 return error_mark_node;
11548 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
11549 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
11550 if (field == NULL_TREE)
11551 {
11552 // This can happen for a type which refers to itself indirectly
11553 // and then turns out to be erroneous.
11554 go_assert(saw_errors());
11555 return error_mark_node;
11556 }
11557 for (unsigned int i = this->field_index_; i > 0; --i)
11558 {
11559 field = DECL_CHAIN(field);
11560 go_assert(field != NULL_TREE);
11561 }
11562 if (TREE_TYPE(field) == error_mark_node)
11563 return error_mark_node;
11564 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
11565 NULL_TREE);
11566 }
11567
11568 // Dump ast representation for a field reference expression.
11569
11570 void
11571 Field_reference_expression::do_dump_expression(
11572 Ast_dump_context* ast_dump_context) const
11573 {
11574 this->expr_->dump_expression(ast_dump_context);
11575 ast_dump_context->ostream() << "." << this->field_index_;
11576 }
11577
11578 // Make a reference to a qualified identifier in an expression.
11579
11580 Field_reference_expression*
11581 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11582 Location location)
11583 {
11584 return new Field_reference_expression(expr, field_index, location);
11585 }
11586
11587 // Class Interface_field_reference_expression.
11588
11589 // Return a tree for the pointer to the function to call.
11590
11591 tree
11592 Interface_field_reference_expression::get_function_tree(Translate_context*,
11593 tree expr)
11594 {
11595 if (this->expr_->type()->points_to() != NULL)
11596 expr = build_fold_indirect_ref(expr);
11597
11598 tree expr_type = TREE_TYPE(expr);
11599 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
11600
11601 tree field = TYPE_FIELDS(expr_type);
11602 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
11603
11604 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
11605 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
11606
11607 table = build_fold_indirect_ref(table);
11608 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
11609
11610 std::string name = Gogo::unpack_hidden_name(this->name_);
11611 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
11612 field != NULL_TREE;
11613 field = DECL_CHAIN(field))
11614 {
11615 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
11616 break;
11617 }
11618 go_assert(field != NULL_TREE);
11619
11620 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
11621 }
11622
11623 // Return a tree for the first argument to pass to the interface
11624 // function.
11625
11626 tree
11627 Interface_field_reference_expression::get_underlying_object_tree(
11628 Translate_context*,
11629 tree expr)
11630 {
11631 if (this->expr_->type()->points_to() != NULL)
11632 expr = build_fold_indirect_ref(expr);
11633
11634 tree expr_type = TREE_TYPE(expr);
11635 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
11636
11637 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
11638 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
11639
11640 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
11641 }
11642
11643 // Traversal.
11644
11645 int
11646 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11647 {
11648 return Expression::traverse(&this->expr_, traverse);
11649 }
11650
11651 // Lower the expression. If this expression is not called, we need to
11652 // evaluate the expression twice when converting to the backend
11653 // interface. So introduce a temporary variable if necessary.
11654
11655 Expression*
11656 Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11657 Statement_inserter* inserter,
11658 int)
11659 {
11660 if (this->expr_->var_expression() == NULL
11661 && this->expr_->temporary_reference_expression() == NULL
11662 && this->expr_->set_and_use_temporary_expression() == NULL)
11663 {
11664 Temporary_statement* temp =
11665 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11666 inserter->insert(temp);
11667 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11668 this->location());
11669 }
11670 return this;
11671 }
11672
11673 // Return the type of an interface field reference.
11674
11675 Type*
11676 Interface_field_reference_expression::do_type()
11677 {
11678 Type* expr_type = this->expr_->type();
11679
11680 Type* points_to = expr_type->points_to();
11681 if (points_to != NULL)
11682 expr_type = points_to;
11683
11684 Interface_type* interface_type = expr_type->interface_type();
11685 if (interface_type == NULL)
11686 return Type::make_error_type();
11687
11688 const Typed_identifier* method = interface_type->find_method(this->name_);
11689 if (method == NULL)
11690 return Type::make_error_type();
11691
11692 return method->type();
11693 }
11694
11695 // Determine types.
11696
11697 void
11698 Interface_field_reference_expression::do_determine_type(const Type_context*)
11699 {
11700 this->expr_->determine_type_no_context();
11701 }
11702
11703 // Check the types for an interface field reference.
11704
11705 void
11706 Interface_field_reference_expression::do_check_types(Gogo*)
11707 {
11708 Type* type = this->expr_->type();
11709
11710 Type* points_to = type->points_to();
11711 if (points_to != NULL)
11712 type = points_to;
11713
11714 Interface_type* interface_type = type->interface_type();
11715 if (interface_type == NULL)
11716 {
11717 if (!type->is_error_type())
11718 this->report_error(_("expected interface or pointer to interface"));
11719 }
11720 else
11721 {
11722 const Typed_identifier* method =
11723 interface_type->find_method(this->name_);
11724 if (method == NULL)
11725 {
11726 error_at(this->location(), "method %qs not in interface",
11727 Gogo::message_name(this->name_).c_str());
11728 this->set_is_error();
11729 }
11730 }
11731 }
11732
11733 // If an interface field reference is not simply called, then it is
11734 // represented as a closure. The closure will hold a single variable,
11735 // the value of the interface on which the method should be called.
11736 // The function will be a simple thunk that pulls the value from the
11737 // closure and calls the method with the remaining arguments.
11738
11739 // Because method values are not common, we don't build all thunks for
11740 // all possible interface methods, but instead only build them as we
11741 // need them. In particular, we even build them on demand for
11742 // interface methods defined in other packages.
11743
11744 Interface_field_reference_expression::Interface_method_thunks
11745 Interface_field_reference_expression::interface_method_thunks;
11746
11747 // Find or create the thunk to call method NAME on TYPE.
11748
11749 Named_object*
11750 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11751 Interface_type* type,
11752 const std::string& name)
11753 {
11754 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11755 std::pair<Interface_method_thunks::iterator, bool> ins =
11756 Interface_field_reference_expression::interface_method_thunks.insert(val);
11757 if (ins.second)
11758 {
11759 // This is the first time we have seen this interface.
11760 ins.first->second = new Method_thunks();
11761 }
11762
11763 for (Method_thunks::const_iterator p = ins.first->second->begin();
11764 p != ins.first->second->end();
11765 p++)
11766 if (p->first == name)
11767 return p->second;
11768
11769 Location loc = type->location();
11770
11771 const Typed_identifier* method_id = type->find_method(name);
11772 if (method_id == NULL)
11773 return Named_object::make_erroneous_name(Gogo::thunk_name());
11774
11775 Function_type* orig_fntype = method_id->type()->function_type();
11776 if (orig_fntype == NULL)
11777 return Named_object::make_erroneous_name(Gogo::thunk_name());
11778
11779 Struct_field_list* sfl = new Struct_field_list();
11780 // The type here is wrong--it should be the C function type. But it
11781 // doesn't really matter.
11782 Type* vt = Type::make_pointer_type(Type::make_void_type());
11783 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11784 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11785 Type* closure_type = Type::make_struct_type(sfl, loc);
11786 closure_type = Type::make_pointer_type(closure_type);
11787
11788 Function_type* new_fntype = orig_fntype->copy_with_names();
11789
11790 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11791 false, loc);
11792
11793 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11794 cvar->set_is_used();
11795 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11796 new_no->func_value()->set_closure_var(cp);
11797
11798 gogo->start_block(loc);
11799
11800 // Field 0 of the closure is the function code pointer, field 1 is
11801 // the value on which to invoke the method.
11802 Expression* arg = Expression::make_var_reference(cp, loc);
11803 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11804 arg = Expression::make_field_reference(arg, 1, loc);
11805
11806 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11807 loc);
11808
11809 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11810 Expression_list* args;
11811 if (orig_params == NULL || orig_params->empty())
11812 args = NULL;
11813 else
11814 {
11815 const Typed_identifier_list* new_params = new_fntype->parameters();
11816 args = new Expression_list();
11817 for (Typed_identifier_list::const_iterator p = new_params->begin();
11818 p != new_params->end();
11819 ++p)
11820 {
11821 Named_object* p_no = gogo->lookup(p->name(), NULL);
11822 go_assert(p_no != NULL
11823 && p_no->is_variable()
11824 && p_no->var_value()->is_parameter());
11825 args->push_back(Expression::make_var_reference(p_no, loc));
11826 }
11827 }
11828
11829 Call_expression* call = Expression::make_call(ifre, args,
11830 orig_fntype->is_varargs(),
11831 loc);
11832 call->set_varargs_are_lowered();
11833
11834 Statement* s = Statement::make_return_from_call(call, loc);
11835 gogo->add_statement(s);
11836 Block* b = gogo->finish_block(loc);
11837 gogo->add_block(b, loc);
11838 gogo->lower_block(new_no, b);
11839 gogo->finish_function(loc);
11840
11841 ins.first->second->push_back(std::make_pair(name, new_no));
11842 return new_no;
11843 }
11844
11845 // Get a tree for a method value.
11846
11847 tree
11848 Interface_field_reference_expression::do_get_tree(Translate_context* context)
11849 {
11850 Interface_type* type = this->expr_->type()->interface_type();
11851 if (type == NULL)
11852 {
11853 go_assert(saw_errors());
11854 return error_mark_node;
11855 }
11856
11857 Named_object* thunk =
11858 Interface_field_reference_expression::create_thunk(context->gogo(),
11859 type, this->name_);
11860 if (thunk->is_erroneous())
11861 {
11862 go_assert(saw_errors());
11863 return error_mark_node;
11864 }
11865
11866 // FIXME: We should lower this earlier, but we can't it lower it in
11867 // the lowering pass because at that point we don't know whether we
11868 // need to create the thunk or not. If the expression is called, we
11869 // don't need the thunk.
11870
11871 Location loc = this->location();
11872
11873 Struct_field_list* fields = new Struct_field_list();
11874 fields->push_back(Struct_field(Typed_identifier("fn.0",
11875 thunk->func_value()->type(),
11876 loc)));
11877 fields->push_back(Struct_field(Typed_identifier("val.1",
11878 this->expr_->type(),
11879 loc)));
11880 Struct_type* st = Type::make_struct_type(fields, loc);
11881
11882 Expression_list* vals = new Expression_list();
11883 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11884 vals->push_back(this->expr_);
11885
11886 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11887 expr = Expression::make_heap_composite(expr, loc);
11888
11889 tree closure_tree = expr->get_tree(context);
11890
11891 // Note that we are evaluating this->expr_ twice, but that is OK
11892 // because in the lowering pass we forced it into a temporary
11893 // variable.
11894 tree expr_tree = this->expr_->get_tree(context);
11895 tree nil_check_tree = Expression::comparison_tree(context,
11896 Type::lookup_bool_type(),
11897 OPERATOR_EQEQ,
11898 this->expr_->type(),
11899 expr_tree,
11900 Type::make_nil_type(),
11901 null_pointer_node,
11902 loc);
11903 tree crash = context->gogo()->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11904 loc);
11905 if (closure_tree == error_mark_node
11906 || nil_check_tree == error_mark_node
11907 || crash == error_mark_node)
11908 return error_mark_node;
11909 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
11910 TREE_TYPE(closure_tree),
11911 build3_loc(loc.gcc_location(), COND_EXPR,
11912 void_type_node, nil_check_tree, crash,
11913 NULL_TREE),
11914 closure_tree);
11915 }
11916
11917 // Dump ast representation for an interface field reference.
11918
11919 void
11920 Interface_field_reference_expression::do_dump_expression(
11921 Ast_dump_context* ast_dump_context) const
11922 {
11923 this->expr_->dump_expression(ast_dump_context);
11924 ast_dump_context->ostream() << "." << this->name_;
11925 }
11926
11927 // Make a reference to a field in an interface.
11928
11929 Expression*
11930 Expression::make_interface_field_reference(Expression* expr,
11931 const std::string& field,
11932 Location location)
11933 {
11934 return new Interface_field_reference_expression(expr, field, location);
11935 }
11936
11937 // A general selector. This is a Parser_expression for LEFT.NAME. It
11938 // is lowered after we know the type of the left hand side.
11939
11940 class Selector_expression : public Parser_expression
11941 {
11942 public:
11943 Selector_expression(Expression* left, const std::string& name,
11944 Location location)
11945 : Parser_expression(EXPRESSION_SELECTOR, location),
11946 left_(left), name_(name)
11947 { }
11948
11949 protected:
11950 int
11951 do_traverse(Traverse* traverse)
11952 { return Expression::traverse(&this->left_, traverse); }
11953
11954 Expression*
11955 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11956
11957 Expression*
11958 do_copy()
11959 {
11960 return new Selector_expression(this->left_->copy(), this->name_,
11961 this->location());
11962 }
11963
11964 void
11965 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11966
11967 private:
11968 Expression*
11969 lower_method_expression(Gogo*);
11970
11971 // The expression on the left hand side.
11972 Expression* left_;
11973 // The name on the right hand side.
11974 std::string name_;
11975 };
11976
11977 // Lower a selector expression once we know the real type of the left
11978 // hand side.
11979
11980 Expression*
11981 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11982 int)
11983 {
11984 Expression* left = this->left_;
11985 if (left->is_type_expression())
11986 return this->lower_method_expression(gogo);
11987 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11988 this->location());
11989 }
11990
11991 // Lower a method expression T.M or (*T).M. We turn this into a
11992 // function literal.
11993
11994 Expression*
11995 Selector_expression::lower_method_expression(Gogo* gogo)
11996 {
11997 Location location = this->location();
11998 Type* type = this->left_->type();
11999 const std::string& name(this->name_);
12000
12001 bool is_pointer;
12002 if (type->points_to() == NULL)
12003 is_pointer = false;
12004 else
12005 {
12006 is_pointer = true;
12007 type = type->points_to();
12008 }
12009 Named_type* nt = type->named_type();
12010 if (nt == NULL)
12011 {
12012 error_at(location,
12013 ("method expression requires named type or "
12014 "pointer to named type"));
12015 return Expression::make_error(location);
12016 }
12017
12018 bool is_ambiguous;
12019 Method* method = nt->method_function(name, &is_ambiguous);
12020 const Typed_identifier* imethod = NULL;
12021 if (method == NULL && !is_pointer)
12022 {
12023 Interface_type* it = nt->interface_type();
12024 if (it != NULL)
12025 imethod = it->find_method(name);
12026 }
12027
12028 if (method == NULL && imethod == NULL)
12029 {
12030 if (!is_ambiguous)
12031 error_at(location, "type %<%s%s%> has no method %<%s%>",
12032 is_pointer ? "*" : "",
12033 nt->message_name().c_str(),
12034 Gogo::message_name(name).c_str());
12035 else
12036 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12037 Gogo::message_name(name).c_str(),
12038 is_pointer ? "*" : "",
12039 nt->message_name().c_str());
12040 return Expression::make_error(location);
12041 }
12042
12043 if (method != NULL && !is_pointer && !method->is_value_method())
12044 {
12045 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
12046 nt->message_name().c_str(),
12047 Gogo::message_name(name).c_str());
12048 return Expression::make_error(location);
12049 }
12050
12051 // Build a new function type in which the receiver becomes the first
12052 // argument.
12053 Function_type* method_type;
12054 if (method != NULL)
12055 {
12056 method_type = method->type();
12057 go_assert(method_type->is_method());
12058 }
12059 else
12060 {
12061 method_type = imethod->type()->function_type();
12062 go_assert(method_type != NULL && !method_type->is_method());
12063 }
12064
12065 const char* const receiver_name = "$this";
12066 Typed_identifier_list* parameters = new Typed_identifier_list();
12067 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12068 location));
12069
12070 const Typed_identifier_list* method_parameters = method_type->parameters();
12071 if (method_parameters != NULL)
12072 {
12073 int i = 0;
12074 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12075 p != method_parameters->end();
12076 ++p, ++i)
12077 {
12078 if (!p->name().empty())
12079 parameters->push_back(*p);
12080 else
12081 {
12082 char buf[20];
12083 snprintf(buf, sizeof buf, "$param%d", i);
12084 parameters->push_back(Typed_identifier(buf, p->type(),
12085 p->location()));
12086 }
12087 }
12088 }
12089
12090 const Typed_identifier_list* method_results = method_type->results();
12091 Typed_identifier_list* results;
12092 if (method_results == NULL)
12093 results = NULL;
12094 else
12095 {
12096 results = new Typed_identifier_list();
12097 for (Typed_identifier_list::const_iterator p = method_results->begin();
12098 p != method_results->end();
12099 ++p)
12100 results->push_back(*p);
12101 }
12102
12103 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12104 location);
12105 if (method_type->is_varargs())
12106 fntype->set_is_varargs();
12107
12108 // We generate methods which always takes a pointer to the receiver
12109 // as their first argument. If this is for a pointer type, we can
12110 // simply reuse the existing function. We use an internal hack to
12111 // get the right type.
12112 // FIXME: This optimization is disabled because it doesn't yet work
12113 // with function descriptors when the method expression is not
12114 // directly called.
12115 if (method != NULL && is_pointer && false)
12116 {
12117 Named_object* mno = (method->needs_stub_method()
12118 ? method->stub_object()
12119 : method->named_object());
12120 Expression* f = Expression::make_func_reference(mno, NULL, location);
12121 f = Expression::make_cast(fntype, f, location);
12122 Type_conversion_expression* tce =
12123 static_cast<Type_conversion_expression*>(f);
12124 tce->set_may_convert_function_types();
12125 return f;
12126 }
12127
12128 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12129 location);
12130
12131 Named_object* vno = gogo->lookup(receiver_name, NULL);
12132 go_assert(vno != NULL);
12133 Expression* ve = Expression::make_var_reference(vno, location);
12134 Expression* bm;
12135 if (method != NULL)
12136 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12137 else
12138 bm = Expression::make_interface_field_reference(ve, name, location);
12139
12140 // Even though we found the method above, if it has an error type we
12141 // may see an error here.
12142 if (bm->is_error_expression())
12143 {
12144 gogo->finish_function(location);
12145 return bm;
12146 }
12147
12148 Expression_list* args;
12149 if (parameters->size() <= 1)
12150 args = NULL;
12151 else
12152 {
12153 args = new Expression_list();
12154 Typed_identifier_list::const_iterator p = parameters->begin();
12155 ++p;
12156 for (; p != parameters->end(); ++p)
12157 {
12158 vno = gogo->lookup(p->name(), NULL);
12159 go_assert(vno != NULL);
12160 args->push_back(Expression::make_var_reference(vno, location));
12161 }
12162 }
12163
12164 gogo->start_block(location);
12165
12166 Call_expression* call = Expression::make_call(bm, args,
12167 method_type->is_varargs(),
12168 location);
12169
12170 Statement* s = Statement::make_return_from_call(call, location);
12171 gogo->add_statement(s);
12172
12173 Block* b = gogo->finish_block(location);
12174
12175 gogo->add_block(b, location);
12176
12177 // Lower the call in case there are multiple results.
12178 gogo->lower_block(no, b);
12179
12180 gogo->finish_function(location);
12181
12182 return Expression::make_func_reference(no, NULL, location);
12183 }
12184
12185 // Dump the ast for a selector expression.
12186
12187 void
12188 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12189 const
12190 {
12191 ast_dump_context->dump_expression(this->left_);
12192 ast_dump_context->ostream() << ".";
12193 ast_dump_context->ostream() << this->name_;
12194 }
12195
12196 // Make a selector expression.
12197
12198 Expression*
12199 Expression::make_selector(Expression* left, const std::string& name,
12200 Location location)
12201 {
12202 return new Selector_expression(left, name, location);
12203 }
12204
12205 // Implement the builtin function new.
12206
12207 class Allocation_expression : public Expression
12208 {
12209 public:
12210 Allocation_expression(Type* type, Location location)
12211 : Expression(EXPRESSION_ALLOCATION, location),
12212 type_(type)
12213 { }
12214
12215 protected:
12216 int
12217 do_traverse(Traverse* traverse)
12218 { return Type::traverse(this->type_, traverse); }
12219
12220 Type*
12221 do_type()
12222 { return Type::make_pointer_type(this->type_); }
12223
12224 void
12225 do_determine_type(const Type_context*)
12226 { }
12227
12228 Expression*
12229 do_copy()
12230 { return new Allocation_expression(this->type_, this->location()); }
12231
12232 tree
12233 do_get_tree(Translate_context*);
12234
12235 void
12236 do_dump_expression(Ast_dump_context*) const;
12237
12238 private:
12239 // The type we are allocating.
12240 Type* type_;
12241 };
12242
12243 // Return a tree for an allocation expression.
12244
12245 tree
12246 Allocation_expression::do_get_tree(Translate_context* context)
12247 {
12248 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
12249 if (type_tree == error_mark_node)
12250 return error_mark_node;
12251 tree size_tree = TYPE_SIZE_UNIT(type_tree);
12252 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
12253 this->location());
12254 if (space == error_mark_node)
12255 return error_mark_node;
12256 return fold_convert(build_pointer_type(type_tree), space);
12257 }
12258
12259 // Dump ast representation for an allocation expression.
12260
12261 void
12262 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12263 const
12264 {
12265 ast_dump_context->ostream() << "new(";
12266 ast_dump_context->dump_type(this->type_);
12267 ast_dump_context->ostream() << ")";
12268 }
12269
12270 // Make an allocation expression.
12271
12272 Expression*
12273 Expression::make_allocation(Type* type, Location location)
12274 {
12275 return new Allocation_expression(type, location);
12276 }
12277
12278 // Construct a struct.
12279
12280 class Struct_construction_expression : public Expression
12281 {
12282 public:
12283 Struct_construction_expression(Type* type, Expression_list* vals,
12284 Location location)
12285 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
12286 type_(type), vals_(vals), traverse_order_(NULL)
12287 { }
12288
12289 // Set the traversal order, used to ensure that we implement the
12290 // order of evaluation rules. Takes ownership of the argument.
12291 void
12292 set_traverse_order(std::vector<int>* traverse_order)
12293 { this->traverse_order_ = traverse_order; }
12294
12295 // Return whether this is a constant initializer.
12296 bool
12297 is_constant_struct() const;
12298
12299 protected:
12300 int
12301 do_traverse(Traverse* traverse);
12302
12303 Type*
12304 do_type()
12305 { return this->type_; }
12306
12307 void
12308 do_determine_type(const Type_context*);
12309
12310 void
12311 do_check_types(Gogo*);
12312
12313 Expression*
12314 do_copy()
12315 {
12316 Struct_construction_expression* ret =
12317 new Struct_construction_expression(this->type_, this->vals_->copy(),
12318 this->location());
12319 if (this->traverse_order_ != NULL)
12320 ret->set_traverse_order(this->traverse_order_);
12321 return ret;
12322 }
12323
12324 tree
12325 do_get_tree(Translate_context*);
12326
12327 void
12328 do_export(Export*) const;
12329
12330 void
12331 do_dump_expression(Ast_dump_context*) const;
12332
12333 private:
12334 // The type of the struct to construct.
12335 Type* type_;
12336 // The list of values, in order of the fields in the struct. A NULL
12337 // entry means that the field should be zero-initialized.
12338 Expression_list* vals_;
12339 // If not NULL, the order in which to traverse vals_. This is used
12340 // so that we implement the order of evaluation rules correctly.
12341 std::vector<int>* traverse_order_;
12342 };
12343
12344 // Traversal.
12345
12346 int
12347 Struct_construction_expression::do_traverse(Traverse* traverse)
12348 {
12349 if (this->vals_ != NULL)
12350 {
12351 if (this->traverse_order_ == NULL)
12352 {
12353 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12354 return TRAVERSE_EXIT;
12355 }
12356 else
12357 {
12358 for (std::vector<int>::const_iterator p =
12359 this->traverse_order_->begin();
12360 p != this->traverse_order_->end();
12361 ++p)
12362 {
12363 if (Expression::traverse(&this->vals_->at(*p), traverse)
12364 == TRAVERSE_EXIT)
12365 return TRAVERSE_EXIT;
12366 }
12367 }
12368 }
12369 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12370 return TRAVERSE_EXIT;
12371 return TRAVERSE_CONTINUE;
12372 }
12373
12374 // Return whether this is a constant initializer.
12375
12376 bool
12377 Struct_construction_expression::is_constant_struct() const
12378 {
12379 if (this->vals_ == NULL)
12380 return true;
12381 for (Expression_list::const_iterator pv = this->vals_->begin();
12382 pv != this->vals_->end();
12383 ++pv)
12384 {
12385 if (*pv != NULL
12386 && !(*pv)->is_constant()
12387 && (!(*pv)->is_composite_literal()
12388 || (*pv)->is_nonconstant_composite_literal()))
12389 return false;
12390 }
12391
12392 const Struct_field_list* fields = this->type_->struct_type()->fields();
12393 for (Struct_field_list::const_iterator pf = fields->begin();
12394 pf != fields->end();
12395 ++pf)
12396 {
12397 // There are no constant constructors for interfaces.
12398 if (pf->type()->interface_type() != NULL)
12399 return false;
12400 }
12401
12402 return true;
12403 }
12404
12405 // Final type determination.
12406
12407 void
12408 Struct_construction_expression::do_determine_type(const Type_context*)
12409 {
12410 if (this->vals_ == NULL)
12411 return;
12412 const Struct_field_list* fields = this->type_->struct_type()->fields();
12413 Expression_list::const_iterator pv = this->vals_->begin();
12414 for (Struct_field_list::const_iterator pf = fields->begin();
12415 pf != fields->end();
12416 ++pf, ++pv)
12417 {
12418 if (pv == this->vals_->end())
12419 return;
12420 if (*pv != NULL)
12421 {
12422 Type_context subcontext(pf->type(), false);
12423 (*pv)->determine_type(&subcontext);
12424 }
12425 }
12426 // Extra values are an error we will report elsewhere; we still want
12427 // to determine the type to avoid knockon errors.
12428 for (; pv != this->vals_->end(); ++pv)
12429 (*pv)->determine_type_no_context();
12430 }
12431
12432 // Check types.
12433
12434 void
12435 Struct_construction_expression::do_check_types(Gogo*)
12436 {
12437 if (this->vals_ == NULL)
12438 return;
12439
12440 Struct_type* st = this->type_->struct_type();
12441 if (this->vals_->size() > st->field_count())
12442 {
12443 this->report_error(_("too many expressions for struct"));
12444 return;
12445 }
12446
12447 const Struct_field_list* fields = st->fields();
12448 Expression_list::const_iterator pv = this->vals_->begin();
12449 int i = 0;
12450 for (Struct_field_list::const_iterator pf = fields->begin();
12451 pf != fields->end();
12452 ++pf, ++pv, ++i)
12453 {
12454 if (pv == this->vals_->end())
12455 {
12456 this->report_error(_("too few expressions for struct"));
12457 break;
12458 }
12459
12460 if (*pv == NULL)
12461 continue;
12462
12463 std::string reason;
12464 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12465 {
12466 if (reason.empty())
12467 error_at((*pv)->location(),
12468 "incompatible type for field %d in struct construction",
12469 i + 1);
12470 else
12471 error_at((*pv)->location(),
12472 ("incompatible type for field %d in "
12473 "struct construction (%s)"),
12474 i + 1, reason.c_str());
12475 this->set_is_error();
12476 }
12477 }
12478 go_assert(pv == this->vals_->end());
12479 }
12480
12481 // Return a tree for constructing a struct.
12482
12483 tree
12484 Struct_construction_expression::do_get_tree(Translate_context* context)
12485 {
12486 Gogo* gogo = context->gogo();
12487
12488 if (this->vals_ == NULL)
12489 {
12490 Btype* btype = this->type_->get_backend(gogo);
12491 return expr_to_tree(gogo->backend()->zero_expression(btype));
12492 }
12493
12494 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12495 if (type_tree == error_mark_node)
12496 return error_mark_node;
12497 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12498
12499 bool is_constant = true;
12500 const Struct_field_list* fields = this->type_->struct_type()->fields();
12501 vec<constructor_elt, va_gc> *elts;
12502 vec_alloc (elts, fields->size());
12503 Struct_field_list::const_iterator pf = fields->begin();
12504 Expression_list::const_iterator pv = this->vals_->begin();
12505 for (tree field = TYPE_FIELDS(type_tree);
12506 field != NULL_TREE;
12507 field = DECL_CHAIN(field), ++pf)
12508 {
12509 go_assert(pf != fields->end());
12510
12511 Btype* fbtype = pf->type()->get_backend(gogo);
12512
12513 tree val;
12514 if (pv == this->vals_->end())
12515 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
12516 else if (*pv == NULL)
12517 {
12518 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
12519 ++pv;
12520 }
12521 else
12522 {
12523 val = Expression::convert_for_assignment(context, pf->type(),
12524 (*pv)->type(),
12525 (*pv)->get_tree(context),
12526 this->location());
12527 ++pv;
12528 }
12529
12530 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
12531 return error_mark_node;
12532
12533 constructor_elt empty = {NULL, NULL};
12534 constructor_elt* elt = elts->quick_push(empty);
12535 elt->index = field;
12536 elt->value = val;
12537 if (!TREE_CONSTANT(val))
12538 is_constant = false;
12539 }
12540 go_assert(pf == fields->end());
12541
12542 tree ret = build_constructor(type_tree, elts);
12543 if (is_constant)
12544 TREE_CONSTANT(ret) = 1;
12545 return ret;
12546 }
12547
12548 // Export a struct construction.
12549
12550 void
12551 Struct_construction_expression::do_export(Export* exp) const
12552 {
12553 exp->write_c_string("convert(");
12554 exp->write_type(this->type_);
12555 for (Expression_list::const_iterator pv = this->vals_->begin();
12556 pv != this->vals_->end();
12557 ++pv)
12558 {
12559 exp->write_c_string(", ");
12560 if (*pv != NULL)
12561 (*pv)->export_expression(exp);
12562 }
12563 exp->write_c_string(")");
12564 }
12565
12566 // Dump ast representation of a struct construction expression.
12567
12568 void
12569 Struct_construction_expression::do_dump_expression(
12570 Ast_dump_context* ast_dump_context) const
12571 {
12572 ast_dump_context->dump_type(this->type_);
12573 ast_dump_context->ostream() << "{";
12574 ast_dump_context->dump_expression_list(this->vals_);
12575 ast_dump_context->ostream() << "}";
12576 }
12577
12578 // Make a struct composite literal. This used by the thunk code.
12579
12580 Expression*
12581 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12582 Location location)
12583 {
12584 go_assert(type->struct_type() != NULL);
12585 return new Struct_construction_expression(type, vals, location);
12586 }
12587
12588 // Construct an array. This class is not used directly; instead we
12589 // use the child classes, Fixed_array_construction_expression and
12590 // Open_array_construction_expression.
12591
12592 class Array_construction_expression : public Expression
12593 {
12594 protected:
12595 Array_construction_expression(Expression_classification classification,
12596 Type* type,
12597 const std::vector<unsigned long>* indexes,
12598 Expression_list* vals, Location location)
12599 : Expression(classification, location),
12600 type_(type), indexes_(indexes), vals_(vals)
12601 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
12602
12603 public:
12604 // Return whether this is a constant initializer.
12605 bool
12606 is_constant_array() const;
12607
12608 // Return the number of elements.
12609 size_t
12610 element_count() const
12611 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12612
12613 protected:
12614 int
12615 do_traverse(Traverse* traverse);
12616
12617 Type*
12618 do_type()
12619 { return this->type_; }
12620
12621 void
12622 do_determine_type(const Type_context*);
12623
12624 void
12625 do_check_types(Gogo*);
12626
12627 void
12628 do_export(Export*) const;
12629
12630 // The indexes.
12631 const std::vector<unsigned long>*
12632 indexes()
12633 { return this->indexes_; }
12634
12635 // The list of values.
12636 Expression_list*
12637 vals()
12638 { return this->vals_; }
12639
12640 // Get a constructor tree for the array values.
12641 tree
12642 get_constructor_tree(Translate_context* context, tree type_tree);
12643
12644 void
12645 do_dump_expression(Ast_dump_context*) const;
12646
12647 private:
12648 // The type of the array to construct.
12649 Type* type_;
12650 // The list of indexes into the array, one for each value. This may
12651 // be NULL, in which case the indexes start at zero and increment.
12652 const std::vector<unsigned long>* indexes_;
12653 // The list of values. This may be NULL if there are no values.
12654 Expression_list* vals_;
12655 };
12656
12657 // Traversal.
12658
12659 int
12660 Array_construction_expression::do_traverse(Traverse* traverse)
12661 {
12662 if (this->vals_ != NULL
12663 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12664 return TRAVERSE_EXIT;
12665 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12666 return TRAVERSE_EXIT;
12667 return TRAVERSE_CONTINUE;
12668 }
12669
12670 // Return whether this is a constant initializer.
12671
12672 bool
12673 Array_construction_expression::is_constant_array() const
12674 {
12675 if (this->vals_ == NULL)
12676 return true;
12677
12678 // There are no constant constructors for interfaces.
12679 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12680 return false;
12681
12682 for (Expression_list::const_iterator pv = this->vals_->begin();
12683 pv != this->vals_->end();
12684 ++pv)
12685 {
12686 if (*pv != NULL
12687 && !(*pv)->is_constant()
12688 && (!(*pv)->is_composite_literal()
12689 || (*pv)->is_nonconstant_composite_literal()))
12690 return false;
12691 }
12692 return true;
12693 }
12694
12695 // Final type determination.
12696
12697 void
12698 Array_construction_expression::do_determine_type(const Type_context*)
12699 {
12700 if (this->vals_ == NULL)
12701 return;
12702 Type_context subcontext(this->type_->array_type()->element_type(), false);
12703 for (Expression_list::const_iterator pv = this->vals_->begin();
12704 pv != this->vals_->end();
12705 ++pv)
12706 {
12707 if (*pv != NULL)
12708 (*pv)->determine_type(&subcontext);
12709 }
12710 }
12711
12712 // Check types.
12713
12714 void
12715 Array_construction_expression::do_check_types(Gogo*)
12716 {
12717 if (this->vals_ == NULL)
12718 return;
12719
12720 Array_type* at = this->type_->array_type();
12721 int i = 0;
12722 Type* element_type = at->element_type();
12723 for (Expression_list::const_iterator pv = this->vals_->begin();
12724 pv != this->vals_->end();
12725 ++pv, ++i)
12726 {
12727 if (*pv != NULL
12728 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12729 {
12730 error_at((*pv)->location(),
12731 "incompatible type for element %d in composite literal",
12732 i + 1);
12733 this->set_is_error();
12734 }
12735 }
12736 }
12737
12738 // Get a constructor tree for the array values.
12739
12740 tree
12741 Array_construction_expression::get_constructor_tree(Translate_context* context,
12742 tree type_tree)
12743 {
12744 vec<constructor_elt, va_gc> *values;
12745 vec_alloc (values, (this->vals_ == NULL ? 0 : this->vals_->size()));
12746 Type* element_type = this->type_->array_type()->element_type();
12747 bool is_constant = true;
12748 if (this->vals_ != NULL)
12749 {
12750 size_t i = 0;
12751 std::vector<unsigned long>::const_iterator pi;
12752 if (this->indexes_ != NULL)
12753 pi = this->indexes_->begin();
12754 for (Expression_list::const_iterator pv = this->vals_->begin();
12755 pv != this->vals_->end();
12756 ++pv, ++i)
12757 {
12758 if (this->indexes_ != NULL)
12759 go_assert(pi != this->indexes_->end());
12760 constructor_elt empty = {NULL, NULL};
12761 constructor_elt* elt = values->quick_push(empty);
12762
12763 if (this->indexes_ == NULL)
12764 elt->index = size_int(i);
12765 else
12766 elt->index = size_int(*pi);
12767
12768 if (*pv == NULL)
12769 {
12770 Gogo* gogo = context->gogo();
12771 Btype* ebtype = element_type->get_backend(gogo);
12772 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12773 elt->value = expr_to_tree(zv);
12774 }
12775 else
12776 {
12777 tree value_tree = (*pv)->get_tree(context);
12778 elt->value = Expression::convert_for_assignment(context,
12779 element_type,
12780 (*pv)->type(),
12781 value_tree,
12782 this->location());
12783 }
12784 if (elt->value == error_mark_node)
12785 return error_mark_node;
12786 if (!TREE_CONSTANT(elt->value))
12787 is_constant = false;
12788 if (this->indexes_ != NULL)
12789 ++pi;
12790 }
12791 if (this->indexes_ != NULL)
12792 go_assert(pi == this->indexes_->end());
12793 }
12794
12795 tree ret = build_constructor(type_tree, values);
12796 if (is_constant)
12797 TREE_CONSTANT(ret) = 1;
12798 return ret;
12799 }
12800
12801 // Export an array construction.
12802
12803 void
12804 Array_construction_expression::do_export(Export* exp) const
12805 {
12806 exp->write_c_string("convert(");
12807 exp->write_type(this->type_);
12808 if (this->vals_ != NULL)
12809 {
12810 std::vector<unsigned long>::const_iterator pi;
12811 if (this->indexes_ != NULL)
12812 pi = this->indexes_->begin();
12813 for (Expression_list::const_iterator pv = this->vals_->begin();
12814 pv != this->vals_->end();
12815 ++pv)
12816 {
12817 exp->write_c_string(", ");
12818
12819 if (this->indexes_ != NULL)
12820 {
12821 char buf[100];
12822 snprintf(buf, sizeof buf, "%lu", *pi);
12823 exp->write_c_string(buf);
12824 exp->write_c_string(":");
12825 }
12826
12827 if (*pv != NULL)
12828 (*pv)->export_expression(exp);
12829
12830 if (this->indexes_ != NULL)
12831 ++pi;
12832 }
12833 }
12834 exp->write_c_string(")");
12835 }
12836
12837 // Dump ast representation of an array construction expressin.
12838
12839 void
12840 Array_construction_expression::do_dump_expression(
12841 Ast_dump_context* ast_dump_context) const
12842 {
12843 Expression* length = this->type_->array_type()->length();
12844
12845 ast_dump_context->ostream() << "[" ;
12846 if (length != NULL)
12847 {
12848 ast_dump_context->dump_expression(length);
12849 }
12850 ast_dump_context->ostream() << "]" ;
12851 ast_dump_context->dump_type(this->type_);
12852 ast_dump_context->ostream() << "{" ;
12853 if (this->indexes_ == NULL)
12854 ast_dump_context->dump_expression_list(this->vals_);
12855 else
12856 {
12857 Expression_list::const_iterator pv = this->vals_->begin();
12858 for (std::vector<unsigned long>::const_iterator pi =
12859 this->indexes_->begin();
12860 pi != this->indexes_->end();
12861 ++pi, ++pv)
12862 {
12863 if (pi != this->indexes_->begin())
12864 ast_dump_context->ostream() << ", ";
12865 ast_dump_context->ostream() << *pi << ':';
12866 ast_dump_context->dump_expression(*pv);
12867 }
12868 }
12869 ast_dump_context->ostream() << "}" ;
12870
12871 }
12872
12873 // Construct a fixed array.
12874
12875 class Fixed_array_construction_expression :
12876 public Array_construction_expression
12877 {
12878 public:
12879 Fixed_array_construction_expression(Type* type,
12880 const std::vector<unsigned long>* indexes,
12881 Expression_list* vals, Location location)
12882 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12883 type, indexes, vals, location)
12884 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12885
12886 protected:
12887 Expression*
12888 do_copy()
12889 {
12890 return new Fixed_array_construction_expression(this->type(),
12891 this->indexes(),
12892 (this->vals() == NULL
12893 ? NULL
12894 : this->vals()->copy()),
12895 this->location());
12896 }
12897
12898 tree
12899 do_get_tree(Translate_context*);
12900 };
12901
12902 // Return a tree for constructing a fixed array.
12903
12904 tree
12905 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12906 {
12907 Type* type = this->type();
12908 Btype* btype = type->get_backend(context->gogo());
12909 return this->get_constructor_tree(context, type_to_tree(btype));
12910 }
12911
12912 // Construct an open array.
12913
12914 class Open_array_construction_expression : public Array_construction_expression
12915 {
12916 public:
12917 Open_array_construction_expression(Type* type,
12918 const std::vector<unsigned long>* indexes,
12919 Expression_list* vals, Location location)
12920 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
12921 type, indexes, vals, location)
12922 { go_assert(type->is_slice_type()); }
12923
12924 protected:
12925 // Note that taking the address of an open array literal is invalid.
12926
12927 Expression*
12928 do_copy()
12929 {
12930 return new Open_array_construction_expression(this->type(),
12931 this->indexes(),
12932 (this->vals() == NULL
12933 ? NULL
12934 : this->vals()->copy()),
12935 this->location());
12936 }
12937
12938 tree
12939 do_get_tree(Translate_context*);
12940 };
12941
12942 // Return a tree for constructing an open array.
12943
12944 tree
12945 Open_array_construction_expression::do_get_tree(Translate_context* context)
12946 {
12947 Array_type* array_type = this->type()->array_type();
12948 if (array_type == NULL)
12949 {
12950 go_assert(this->type()->is_error());
12951 return error_mark_node;
12952 }
12953
12954 Type* element_type = array_type->element_type();
12955 Btype* belement_type = element_type->get_backend(context->gogo());
12956 tree element_type_tree = type_to_tree(belement_type);
12957 if (element_type_tree == error_mark_node)
12958 return error_mark_node;
12959
12960 tree values;
12961 tree length_tree;
12962 if (this->vals() == NULL || this->vals()->empty())
12963 {
12964 // We need to create a unique value.
12965 tree max = size_int(0);
12966 tree constructor_type = build_array_type(element_type_tree,
12967 build_index_type(max));
12968 if (constructor_type == error_mark_node)
12969 return error_mark_node;
12970 vec<constructor_elt, va_gc> *vec;
12971 vec_alloc(vec, 1);
12972 constructor_elt empty = {NULL, NULL};
12973 constructor_elt* elt = vec->quick_push(empty);
12974 elt->index = size_int(0);
12975 Gogo* gogo = context->gogo();
12976 Btype* btype = element_type->get_backend(gogo);
12977 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
12978 values = build_constructor(constructor_type, vec);
12979 if (TREE_CONSTANT(elt->value))
12980 TREE_CONSTANT(values) = 1;
12981 length_tree = size_int(0);
12982 }
12983 else
12984 {
12985 unsigned long max_index;
12986 if (this->indexes() == NULL)
12987 max_index = this->vals()->size() - 1;
12988 else
12989 max_index = this->indexes()->back();
12990 tree max_tree = size_int(max_index);
12991 tree constructor_type = build_array_type(element_type_tree,
12992 build_index_type(max_tree));
12993 if (constructor_type == error_mark_node)
12994 return error_mark_node;
12995 values = this->get_constructor_tree(context, constructor_type);
12996 length_tree = size_int(max_index + 1);
12997 }
12998
12999 if (values == error_mark_node)
13000 return error_mark_node;
13001
13002 bool is_constant_initializer = TREE_CONSTANT(values);
13003
13004 // We have to copy the initial values into heap memory if we are in
13005 // a function or if the values are not constants. We also have to
13006 // copy them if they may contain pointers in a non-constant context,
13007 // as otherwise the garbage collector won't see them.
13008 bool copy_to_heap = (context->function() != NULL
13009 || !is_constant_initializer
13010 || (element_type->has_pointer()
13011 && !context->is_const()));
13012
13013 if (is_constant_initializer)
13014 {
13015 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
13016 create_tmp_var_name("C"), TREE_TYPE(values));
13017 DECL_EXTERNAL(tmp) = 0;
13018 TREE_PUBLIC(tmp) = 0;
13019 TREE_STATIC(tmp) = 1;
13020 DECL_ARTIFICIAL(tmp) = 1;
13021 if (copy_to_heap)
13022 {
13023 // If we are not copying the value to the heap, we will only
13024 // initialize the value once, so we can use this directly
13025 // rather than copying it. In that case we can't make it
13026 // read-only, because the program is permitted to change it.
13027 TREE_READONLY(tmp) = 1;
13028 TREE_CONSTANT(tmp) = 1;
13029 }
13030 DECL_INITIAL(tmp) = values;
13031 rest_of_decl_compilation(tmp, 1, 0);
13032 values = tmp;
13033 }
13034
13035 tree space;
13036 tree set;
13037 if (!copy_to_heap)
13038 {
13039 // the initializer will only run once.
13040 space = build_fold_addr_expr(values);
13041 set = NULL_TREE;
13042 }
13043 else
13044 {
13045 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
13046 space = context->gogo()->allocate_memory(element_type, memsize,
13047 this->location());
13048 space = save_expr(space);
13049
13050 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
13051 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13052 s);
13053 TREE_THIS_NOTRAP(ref) = 1;
13054 set = build2(MODIFY_EXPR, void_type_node, ref, values);
13055 }
13056
13057 // Build a constructor for the open array.
13058
13059 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13060 if (type_tree == error_mark_node)
13061 return error_mark_node;
13062 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
13063
13064 vec<constructor_elt, va_gc> *init;
13065 vec_alloc(init, 3);
13066
13067 constructor_elt empty = {NULL, NULL};
13068 constructor_elt* elt = init->quick_push(empty);
13069 tree field = TYPE_FIELDS(type_tree);
13070 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
13071 elt->index = field;
13072 elt->value = fold_convert(TREE_TYPE(field), space);
13073
13074 elt = init->quick_push(empty);
13075 field = DECL_CHAIN(field);
13076 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
13077 elt->index = field;
13078 elt->value = fold_convert(TREE_TYPE(field), length_tree);
13079
13080 elt = init->quick_push(empty);
13081 field = DECL_CHAIN(field);
13082 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
13083 elt->index = field;
13084 elt->value = fold_convert(TREE_TYPE(field), length_tree);
13085
13086 tree constructor = build_constructor(type_tree, init);
13087 if (constructor == error_mark_node)
13088 return error_mark_node;
13089 if (!copy_to_heap)
13090 TREE_CONSTANT(constructor) = 1;
13091
13092 if (set == NULL_TREE)
13093 return constructor;
13094 else
13095 return build2(COMPOUND_EXPR, type_tree, set, constructor);
13096 }
13097
13098 // Make a slice composite literal. This is used by the type
13099 // descriptor code.
13100
13101 Expression*
13102 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13103 Location location)
13104 {
13105 go_assert(type->is_slice_type());
13106 return new Open_array_construction_expression(type, NULL, vals, location);
13107 }
13108
13109 // Construct a map.
13110
13111 class Map_construction_expression : public Expression
13112 {
13113 public:
13114 Map_construction_expression(Type* type, Expression_list* vals,
13115 Location location)
13116 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
13117 type_(type), vals_(vals)
13118 { go_assert(vals == NULL || vals->size() % 2 == 0); }
13119
13120 protected:
13121 int
13122 do_traverse(Traverse* traverse);
13123
13124 Type*
13125 do_type()
13126 { return this->type_; }
13127
13128 void
13129 do_determine_type(const Type_context*);
13130
13131 void
13132 do_check_types(Gogo*);
13133
13134 Expression*
13135 do_copy()
13136 {
13137 return new Map_construction_expression(this->type_, this->vals_->copy(),
13138 this->location());
13139 }
13140
13141 tree
13142 do_get_tree(Translate_context*);
13143
13144 void
13145 do_export(Export*) const;
13146
13147 void
13148 do_dump_expression(Ast_dump_context*) const;
13149
13150 private:
13151 // The type of the map to construct.
13152 Type* type_;
13153 // The list of values.
13154 Expression_list* vals_;
13155 };
13156
13157 // Traversal.
13158
13159 int
13160 Map_construction_expression::do_traverse(Traverse* traverse)
13161 {
13162 if (this->vals_ != NULL
13163 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13164 return TRAVERSE_EXIT;
13165 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13166 return TRAVERSE_EXIT;
13167 return TRAVERSE_CONTINUE;
13168 }
13169
13170 // Final type determination.
13171
13172 void
13173 Map_construction_expression::do_determine_type(const Type_context*)
13174 {
13175 if (this->vals_ == NULL)
13176 return;
13177
13178 Map_type* mt = this->type_->map_type();
13179 Type_context key_context(mt->key_type(), false);
13180 Type_context val_context(mt->val_type(), false);
13181 for (Expression_list::const_iterator pv = this->vals_->begin();
13182 pv != this->vals_->end();
13183 ++pv)
13184 {
13185 (*pv)->determine_type(&key_context);
13186 ++pv;
13187 (*pv)->determine_type(&val_context);
13188 }
13189 }
13190
13191 // Check types.
13192
13193 void
13194 Map_construction_expression::do_check_types(Gogo*)
13195 {
13196 if (this->vals_ == NULL)
13197 return;
13198
13199 Map_type* mt = this->type_->map_type();
13200 int i = 0;
13201 Type* key_type = mt->key_type();
13202 Type* val_type = mt->val_type();
13203 for (Expression_list::const_iterator pv = this->vals_->begin();
13204 pv != this->vals_->end();
13205 ++pv, ++i)
13206 {
13207 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13208 {
13209 error_at((*pv)->location(),
13210 "incompatible type for element %d key in map construction",
13211 i + 1);
13212 this->set_is_error();
13213 }
13214 ++pv;
13215 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13216 {
13217 error_at((*pv)->location(),
13218 ("incompatible type for element %d value "
13219 "in map construction"),
13220 i + 1);
13221 this->set_is_error();
13222 }
13223 }
13224 }
13225
13226 // Return a tree for constructing a map.
13227
13228 tree
13229 Map_construction_expression::do_get_tree(Translate_context* context)
13230 {
13231 Gogo* gogo = context->gogo();
13232 Location loc = this->location();
13233
13234 Map_type* mt = this->type_->map_type();
13235
13236 // Build a struct to hold the key and value.
13237 tree struct_type = make_node(RECORD_TYPE);
13238
13239 Type* key_type = mt->key_type();
13240 tree id = get_identifier("__key");
13241 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
13242 if (key_type_tree == error_mark_node)
13243 return error_mark_node;
13244 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
13245 key_type_tree);
13246 DECL_CONTEXT(key_field) = struct_type;
13247 TYPE_FIELDS(struct_type) = key_field;
13248
13249 Type* val_type = mt->val_type();
13250 id = get_identifier("__val");
13251 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
13252 if (val_type_tree == error_mark_node)
13253 return error_mark_node;
13254 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
13255 val_type_tree);
13256 DECL_CONTEXT(val_field) = struct_type;
13257 DECL_CHAIN(key_field) = val_field;
13258
13259 layout_type(struct_type);
13260
13261 bool is_constant = true;
13262 size_t i = 0;
13263 tree valaddr;
13264 tree make_tmp;
13265
13266 if (this->vals_ == NULL || this->vals_->empty())
13267 {
13268 valaddr = null_pointer_node;
13269 make_tmp = NULL_TREE;
13270 }
13271 else
13272 {
13273 vec<constructor_elt, va_gc> *values;
13274 vec_alloc(values, this->vals_->size() / 2);
13275
13276 for (Expression_list::const_iterator pv = this->vals_->begin();
13277 pv != this->vals_->end();
13278 ++pv, ++i)
13279 {
13280 bool one_is_constant = true;
13281
13282 vec<constructor_elt, va_gc> *one;
13283 vec_alloc(one, 2);
13284
13285 constructor_elt empty = {NULL, NULL};
13286 constructor_elt* elt = one->quick_push(empty);
13287 elt->index = key_field;
13288 tree val_tree = (*pv)->get_tree(context);
13289 elt->value = Expression::convert_for_assignment(context, key_type,
13290 (*pv)->type(),
13291 val_tree, loc);
13292 if (elt->value == error_mark_node)
13293 return error_mark_node;
13294 if (!TREE_CONSTANT(elt->value))
13295 one_is_constant = false;
13296
13297 ++pv;
13298
13299 elt = one->quick_push(empty);
13300 elt->index = val_field;
13301 val_tree = (*pv)->get_tree(context);
13302 elt->value = Expression::convert_for_assignment(context, val_type,
13303 (*pv)->type(),
13304 val_tree, loc);
13305 if (elt->value == error_mark_node)
13306 return error_mark_node;
13307 if (!TREE_CONSTANT(elt->value))
13308 one_is_constant = false;
13309
13310 elt = values->quick_push(empty);
13311 elt->index = size_int(i);
13312 elt->value = build_constructor(struct_type, one);
13313 if (one_is_constant)
13314 TREE_CONSTANT(elt->value) = 1;
13315 else
13316 is_constant = false;
13317 }
13318
13319 tree index_type = build_index_type(size_int(i - 1));
13320 tree array_type = build_array_type(struct_type, index_type);
13321 tree init = build_constructor(array_type, values);
13322 if (is_constant)
13323 TREE_CONSTANT(init) = 1;
13324 tree tmp;
13325 if (current_function_decl != NULL)
13326 {
13327 tmp = create_tmp_var(array_type, get_name(array_type));
13328 DECL_INITIAL(tmp) = init;
13329 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
13330 void_type_node, tmp);
13331 TREE_ADDRESSABLE(tmp) = 1;
13332 }
13333 else
13334 {
13335 tmp = build_decl(loc.gcc_location(), VAR_DECL,
13336 create_tmp_var_name("M"), array_type);
13337 DECL_EXTERNAL(tmp) = 0;
13338 TREE_PUBLIC(tmp) = 0;
13339 TREE_STATIC(tmp) = 1;
13340 DECL_ARTIFICIAL(tmp) = 1;
13341 if (!TREE_CONSTANT(init))
13342 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
13343 void_type_node, tmp, init);
13344 else
13345 {
13346 TREE_READONLY(tmp) = 1;
13347 TREE_CONSTANT(tmp) = 1;
13348 DECL_INITIAL(tmp) = init;
13349 make_tmp = NULL_TREE;
13350 }
13351 rest_of_decl_compilation(tmp, 1, 0);
13352 }
13353
13354 valaddr = build_fold_addr_expr(tmp);
13355 }
13356
13357 Bexpression* bdescriptor = mt->map_descriptor_pointer(gogo, loc);
13358 tree descriptor = expr_to_tree(bdescriptor);
13359
13360 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
13361 if (type_tree == error_mark_node)
13362 return error_mark_node;
13363
13364 static tree construct_map_fndecl;
13365 tree call = Gogo::call_builtin(&construct_map_fndecl,
13366 loc,
13367 "__go_construct_map",
13368 6,
13369 type_tree,
13370 TREE_TYPE(descriptor),
13371 descriptor,
13372 sizetype,
13373 size_int(i),
13374 sizetype,
13375 TYPE_SIZE_UNIT(struct_type),
13376 sizetype,
13377 byte_position(val_field),
13378 sizetype,
13379 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
13380 const_ptr_type_node,
13381 fold_convert(const_ptr_type_node, valaddr));
13382 if (call == error_mark_node)
13383 return error_mark_node;
13384
13385 tree ret;
13386 if (make_tmp == NULL)
13387 ret = call;
13388 else
13389 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
13390 make_tmp, call);
13391 return ret;
13392 }
13393
13394 // Export an array construction.
13395
13396 void
13397 Map_construction_expression::do_export(Export* exp) const
13398 {
13399 exp->write_c_string("convert(");
13400 exp->write_type(this->type_);
13401 for (Expression_list::const_iterator pv = this->vals_->begin();
13402 pv != this->vals_->end();
13403 ++pv)
13404 {
13405 exp->write_c_string(", ");
13406 (*pv)->export_expression(exp);
13407 }
13408 exp->write_c_string(")");
13409 }
13410
13411 // Dump ast representation for a map construction expression.
13412
13413 void
13414 Map_construction_expression::do_dump_expression(
13415 Ast_dump_context* ast_dump_context) const
13416 {
13417 ast_dump_context->ostream() << "{" ;
13418 ast_dump_context->dump_expression_list(this->vals_, true);
13419 ast_dump_context->ostream() << "}";
13420 }
13421
13422 // A general composite literal. This is lowered to a type specific
13423 // version.
13424
13425 class Composite_literal_expression : public Parser_expression
13426 {
13427 public:
13428 Composite_literal_expression(Type* type, int depth, bool has_keys,
13429 Expression_list* vals, bool all_are_names,
13430 Location location)
13431 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
13432 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
13433 all_are_names_(all_are_names)
13434 { }
13435
13436 protected:
13437 int
13438 do_traverse(Traverse* traverse);
13439
13440 Expression*
13441 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
13442
13443 Expression*
13444 do_copy()
13445 {
13446 return new Composite_literal_expression(this->type_, this->depth_,
13447 this->has_keys_,
13448 (this->vals_ == NULL
13449 ? NULL
13450 : this->vals_->copy()),
13451 this->all_are_names_,
13452 this->location());
13453 }
13454
13455 void
13456 do_dump_expression(Ast_dump_context*) const;
13457
13458 private:
13459 Expression*
13460 lower_struct(Gogo*, Type*);
13461
13462 Expression*
13463 lower_array(Type*);
13464
13465 Expression*
13466 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
13467
13468 Expression*
13469 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
13470
13471 // The type of the composite literal.
13472 Type* type_;
13473 // The depth within a list of composite literals within a composite
13474 // literal, when the type is omitted.
13475 int depth_;
13476 // The values to put in the composite literal.
13477 Expression_list* vals_;
13478 // If this is true, then VALS_ is a list of pairs: a key and a
13479 // value. In an array initializer, a missing key will be NULL.
13480 bool has_keys_;
13481 // If this is true, then HAS_KEYS_ is true, and every key is a
13482 // simple identifier.
13483 bool all_are_names_;
13484 };
13485
13486 // Traversal.
13487
13488 int
13489 Composite_literal_expression::do_traverse(Traverse* traverse)
13490 {
13491 if (this->vals_ != NULL
13492 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13493 return TRAVERSE_EXIT;
13494 return Type::traverse(this->type_, traverse);
13495 }
13496
13497 // Lower a generic composite literal into a specific version based on
13498 // the type.
13499
13500 Expression*
13501 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13502 Statement_inserter* inserter, int)
13503 {
13504 Type* type = this->type_;
13505
13506 for (int depth = this->depth_; depth > 0; --depth)
13507 {
13508 if (type->array_type() != NULL)
13509 type = type->array_type()->element_type();
13510 else if (type->map_type() != NULL)
13511 type = type->map_type()->val_type();
13512 else
13513 {
13514 if (!type->is_error())
13515 error_at(this->location(),
13516 ("may only omit types within composite literals "
13517 "of slice, array, or map type"));
13518 return Expression::make_error(this->location());
13519 }
13520 }
13521
13522 Type *pt = type->points_to();
13523 bool is_pointer = false;
13524 if (pt != NULL)
13525 {
13526 is_pointer = true;
13527 type = pt;
13528 }
13529
13530 Expression* ret;
13531 if (type->is_error())
13532 return Expression::make_error(this->location());
13533 else if (type->struct_type() != NULL)
13534 ret = this->lower_struct(gogo, type);
13535 else if (type->array_type() != NULL)
13536 ret = this->lower_array(type);
13537 else if (type->map_type() != NULL)
13538 ret = this->lower_map(gogo, function, inserter, type);
13539 else
13540 {
13541 error_at(this->location(),
13542 ("expected struct, slice, array, or map type "
13543 "for composite literal"));
13544 return Expression::make_error(this->location());
13545 }
13546
13547 if (is_pointer)
13548 ret = Expression::make_heap_composite(ret, this->location());
13549
13550 return ret;
13551 }
13552
13553 // Lower a struct composite literal.
13554
13555 Expression*
13556 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13557 {
13558 Location location = this->location();
13559 Struct_type* st = type->struct_type();
13560 if (this->vals_ == NULL || !this->has_keys_)
13561 {
13562 if (this->vals_ != NULL
13563 && !this->vals_->empty()
13564 && type->named_type() != NULL
13565 && type->named_type()->named_object()->package() != NULL)
13566 {
13567 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13568 pf != st->fields()->end();
13569 ++pf)
13570 {
13571 if (Gogo::is_hidden_name(pf->field_name()))
13572 error_at(this->location(),
13573 "assignment of unexported field %qs in %qs literal",
13574 Gogo::message_name(pf->field_name()).c_str(),
13575 type->named_type()->message_name().c_str());
13576 }
13577 }
13578
13579 return new Struct_construction_expression(type, this->vals_, location);
13580 }
13581
13582 size_t field_count = st->field_count();
13583 std::vector<Expression*> vals(field_count);
13584 std::vector<int>* traverse_order = new(std::vector<int>);
13585 Expression_list::const_iterator p = this->vals_->begin();
13586 Expression* external_expr = NULL;
13587 const Named_object* external_no = NULL;
13588 while (p != this->vals_->end())
13589 {
13590 Expression* name_expr = *p;
13591
13592 ++p;
13593 go_assert(p != this->vals_->end());
13594 Expression* val = *p;
13595
13596 ++p;
13597
13598 if (name_expr == NULL)
13599 {
13600 error_at(val->location(), "mixture of field and value initializers");
13601 return Expression::make_error(location);
13602 }
13603
13604 bool bad_key = false;
13605 std::string name;
13606 const Named_object* no = NULL;
13607 switch (name_expr->classification())
13608 {
13609 case EXPRESSION_UNKNOWN_REFERENCE:
13610 name = name_expr->unknown_expression()->name();
13611 break;
13612
13613 case EXPRESSION_CONST_REFERENCE:
13614 no = static_cast<Const_expression*>(name_expr)->named_object();
13615 break;
13616
13617 case EXPRESSION_TYPE:
13618 {
13619 Type* t = name_expr->type();
13620 Named_type* nt = t->named_type();
13621 if (nt == NULL)
13622 bad_key = true;
13623 else
13624 no = nt->named_object();
13625 }
13626 break;
13627
13628 case EXPRESSION_VAR_REFERENCE:
13629 no = name_expr->var_expression()->named_object();
13630 break;
13631
13632 case EXPRESSION_FUNC_REFERENCE:
13633 no = name_expr->func_expression()->named_object();
13634 break;
13635
13636 case EXPRESSION_UNARY:
13637 // If there is a local variable around with the same name as
13638 // the field, and this occurs in the closure, then the
13639 // parser may turn the field reference into an indirection
13640 // through the closure. FIXME: This is a mess.
13641 {
13642 bad_key = true;
13643 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13644 if (ue->op() == OPERATOR_MULT)
13645 {
13646 Field_reference_expression* fre =
13647 ue->operand()->field_reference_expression();
13648 if (fre != NULL)
13649 {
13650 Struct_type* st =
13651 fre->expr()->type()->deref()->struct_type();
13652 if (st != NULL)
13653 {
13654 const Struct_field* sf = st->field(fre->field_index());
13655 name = sf->field_name();
13656
13657 // See below. FIXME.
13658 if (!Gogo::is_hidden_name(name)
13659 && name[0] >= 'a'
13660 && name[0] <= 'z')
13661 {
13662 if (gogo->lookup_global(name.c_str()) != NULL)
13663 name = gogo->pack_hidden_name(name, false);
13664 }
13665
13666 char buf[20];
13667 snprintf(buf, sizeof buf, "%u", fre->field_index());
13668 size_t buflen = strlen(buf);
13669 if (name.compare(name.length() - buflen, buflen, buf)
13670 == 0)
13671 {
13672 name = name.substr(0, name.length() - buflen);
13673 bad_key = false;
13674 }
13675 }
13676 }
13677 }
13678 }
13679 break;
13680
13681 default:
13682 bad_key = true;
13683 break;
13684 }
13685 if (bad_key)
13686 {
13687 error_at(name_expr->location(), "expected struct field name");
13688 return Expression::make_error(location);
13689 }
13690
13691 if (no != NULL)
13692 {
13693 if (no->package() != NULL && external_expr == NULL)
13694 {
13695 external_expr = name_expr;
13696 external_no = no;
13697 }
13698
13699 name = no->name();
13700
13701 // A predefined name won't be packed. If it starts with a
13702 // lower case letter we need to check for that case, because
13703 // the field name will be packed. FIXME.
13704 if (!Gogo::is_hidden_name(name)
13705 && name[0] >= 'a'
13706 && name[0] <= 'z')
13707 {
13708 Named_object* gno = gogo->lookup_global(name.c_str());
13709 if (gno == no)
13710 name = gogo->pack_hidden_name(name, false);
13711 }
13712 }
13713
13714 unsigned int index;
13715 const Struct_field* sf = st->find_local_field(name, &index);
13716 if (sf == NULL)
13717 {
13718 error_at(name_expr->location(), "unknown field %qs in %qs",
13719 Gogo::message_name(name).c_str(),
13720 (type->named_type() != NULL
13721 ? type->named_type()->message_name().c_str()
13722 : "unnamed struct"));
13723 return Expression::make_error(location);
13724 }
13725 if (vals[index] != NULL)
13726 {
13727 error_at(name_expr->location(),
13728 "duplicate value for field %qs in %qs",
13729 Gogo::message_name(name).c_str(),
13730 (type->named_type() != NULL
13731 ? type->named_type()->message_name().c_str()
13732 : "unnamed struct"));
13733 return Expression::make_error(location);
13734 }
13735
13736 if (type->named_type() != NULL
13737 && type->named_type()->named_object()->package() != NULL
13738 && Gogo::is_hidden_name(sf->field_name()))
13739 error_at(name_expr->location(),
13740 "assignment of unexported field %qs in %qs literal",
13741 Gogo::message_name(sf->field_name()).c_str(),
13742 type->named_type()->message_name().c_str());
13743
13744 vals[index] = val;
13745 traverse_order->push_back(index);
13746 }
13747
13748 if (!this->all_are_names_)
13749 {
13750 // This is a weird case like bug462 in the testsuite.
13751 if (external_expr == NULL)
13752 error_at(this->location(), "unknown field in %qs literal",
13753 (type->named_type() != NULL
13754 ? type->named_type()->message_name().c_str()
13755 : "unnamed struct"));
13756 else
13757 error_at(external_expr->location(), "unknown field %qs in %qs",
13758 external_no->message_name().c_str(),
13759 (type->named_type() != NULL
13760 ? type->named_type()->message_name().c_str()
13761 : "unnamed struct"));
13762 return Expression::make_error(location);
13763 }
13764
13765 Expression_list* list = new Expression_list;
13766 list->reserve(field_count);
13767 for (size_t i = 0; i < field_count; ++i)
13768 list->push_back(vals[i]);
13769
13770 Struct_construction_expression* ret =
13771 new Struct_construction_expression(type, list, location);
13772 ret->set_traverse_order(traverse_order);
13773 return ret;
13774 }
13775
13776 // Used to sort an index/value array.
13777
13778 class Index_value_compare
13779 {
13780 public:
13781 bool
13782 operator()(const std::pair<unsigned long, Expression*>& a,
13783 const std::pair<unsigned long, Expression*>& b)
13784 { return a.first < b.first; }
13785 };
13786
13787 // Lower an array composite literal.
13788
13789 Expression*
13790 Composite_literal_expression::lower_array(Type* type)
13791 {
13792 Location location = this->location();
13793 if (this->vals_ == NULL || !this->has_keys_)
13794 return this->make_array(type, NULL, this->vals_);
13795
13796 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13797 indexes->reserve(this->vals_->size());
13798 bool indexes_out_of_order = false;
13799 Expression_list* vals = new Expression_list();
13800 vals->reserve(this->vals_->size());
13801 unsigned long index = 0;
13802 Expression_list::const_iterator p = this->vals_->begin();
13803 while (p != this->vals_->end())
13804 {
13805 Expression* index_expr = *p;
13806
13807 ++p;
13808 go_assert(p != this->vals_->end());
13809 Expression* val = *p;
13810
13811 ++p;
13812
13813 if (index_expr == NULL)
13814 {
13815 if (!indexes->empty())
13816 indexes->push_back(index);
13817 }
13818 else
13819 {
13820 if (indexes->empty() && !vals->empty())
13821 {
13822 for (size_t i = 0; i < vals->size(); ++i)
13823 indexes->push_back(i);
13824 }
13825
13826 Numeric_constant nc;
13827 if (!index_expr->numeric_constant_value(&nc))
13828 {
13829 error_at(index_expr->location(),
13830 "index expression is not integer constant");
13831 return Expression::make_error(location);
13832 }
13833
13834 switch (nc.to_unsigned_long(&index))
13835 {
13836 case Numeric_constant::NC_UL_VALID:
13837 break;
13838 case Numeric_constant::NC_UL_NOTINT:
13839 error_at(index_expr->location(),
13840 "index expression is not integer constant");
13841 return Expression::make_error(location);
13842 case Numeric_constant::NC_UL_NEGATIVE:
13843 error_at(index_expr->location(), "index expression is negative");
13844 return Expression::make_error(location);
13845 case Numeric_constant::NC_UL_BIG:
13846 error_at(index_expr->location(), "index value overflow");
13847 return Expression::make_error(location);
13848 default:
13849 go_unreachable();
13850 }
13851
13852 Named_type* ntype = Type::lookup_integer_type("int");
13853 Integer_type* inttype = ntype->integer_type();
13854 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13855 && index >> (inttype->bits() - 1) != 0)
13856 {
13857 error_at(index_expr->location(), "index value overflow");
13858 return Expression::make_error(location);
13859 }
13860
13861 if (std::find(indexes->begin(), indexes->end(), index)
13862 != indexes->end())
13863 {
13864 error_at(index_expr->location(), "duplicate value for index %lu",
13865 index);
13866 return Expression::make_error(location);
13867 }
13868
13869 if (!indexes->empty() && index < indexes->back())
13870 indexes_out_of_order = true;
13871
13872 indexes->push_back(index);
13873 }
13874
13875 vals->push_back(val);
13876
13877 ++index;
13878 }
13879
13880 if (indexes->empty())
13881 {
13882 delete indexes;
13883 indexes = NULL;
13884 }
13885
13886 if (indexes_out_of_order)
13887 {
13888 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13889
13890 V v;
13891 v.reserve(indexes->size());
13892 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13893 for (Expression_list::const_iterator pe = vals->begin();
13894 pe != vals->end();
13895 ++pe, ++pi)
13896 v.push_back(std::make_pair(*pi, *pe));
13897
13898 std::sort(v.begin(), v.end(), Index_value_compare());
13899
13900 delete indexes;
13901 delete vals;
13902 indexes = new std::vector<unsigned long>();
13903 indexes->reserve(v.size());
13904 vals = new Expression_list();
13905 vals->reserve(v.size());
13906
13907 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13908 {
13909 indexes->push_back(p->first);
13910 vals->push_back(p->second);
13911 }
13912 }
13913
13914 return this->make_array(type, indexes, vals);
13915 }
13916
13917 // Actually build the array composite literal. This handles
13918 // [...]{...}.
13919
13920 Expression*
13921 Composite_literal_expression::make_array(
13922 Type* type,
13923 const std::vector<unsigned long>* indexes,
13924 Expression_list* vals)
13925 {
13926 Location location = this->location();
13927 Array_type* at = type->array_type();
13928
13929 if (at->length() != NULL && at->length()->is_nil_expression())
13930 {
13931 size_t size;
13932 if (vals == NULL)
13933 size = 0;
13934 else if (indexes != NULL)
13935 size = indexes->back() + 1;
13936 else
13937 {
13938 size = vals->size();
13939 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13940 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13941 && size >> (it->bits() - 1) != 0)
13942 {
13943 error_at(location, "too many elements in composite literal");
13944 return Expression::make_error(location);
13945 }
13946 }
13947
13948 mpz_t vlen;
13949 mpz_init_set_ui(vlen, size);
13950 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13951 mpz_clear(vlen);
13952 at = Type::make_array_type(at->element_type(), elen);
13953 type = at;
13954 }
13955 else if (at->length() != NULL
13956 && !at->length()->is_error_expression()
13957 && this->vals_ != NULL)
13958 {
13959 Numeric_constant nc;
13960 unsigned long val;
13961 if (at->length()->numeric_constant_value(&nc)
13962 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13963 {
13964 if (indexes == NULL)
13965 {
13966 if (this->vals_->size() > val)
13967 {
13968 error_at(location, "too many elements in composite literal");
13969 return Expression::make_error(location);
13970 }
13971 }
13972 else
13973 {
13974 unsigned long max = indexes->back();
13975 if (max >= val)
13976 {
13977 error_at(location,
13978 ("some element keys in composite literal "
13979 "are out of range"));
13980 return Expression::make_error(location);
13981 }
13982 }
13983 }
13984 }
13985
13986 if (at->length() != NULL)
13987 return new Fixed_array_construction_expression(type, indexes, vals,
13988 location);
13989 else
13990 return new Open_array_construction_expression(type, indexes, vals,
13991 location);
13992 }
13993
13994 // Lower a map composite literal.
13995
13996 Expression*
13997 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13998 Statement_inserter* inserter,
13999 Type* type)
14000 {
14001 Location location = this->location();
14002 if (this->vals_ != NULL)
14003 {
14004 if (!this->has_keys_)
14005 {
14006 error_at(location, "map composite literal must have keys");
14007 return Expression::make_error(location);
14008 }
14009
14010 for (Expression_list::iterator p = this->vals_->begin();
14011 p != this->vals_->end();
14012 p += 2)
14013 {
14014 if (*p == NULL)
14015 {
14016 ++p;
14017 error_at((*p)->location(),
14018 "map composite literal must have keys for every value");
14019 return Expression::make_error(location);
14020 }
14021 // Make sure we have lowered the key; it may not have been
14022 // lowered in order to handle keys for struct composite
14023 // literals. Lower it now to get the right error message.
14024 if ((*p)->unknown_expression() != NULL)
14025 {
14026 (*p)->unknown_expression()->clear_is_composite_literal_key();
14027 gogo->lower_expression(function, inserter, &*p);
14028 go_assert((*p)->is_error_expression());
14029 return Expression::make_error(location);
14030 }
14031 }
14032 }
14033
14034 return new Map_construction_expression(type, this->vals_, location);
14035 }
14036
14037 // Dump ast representation for a composite literal expression.
14038
14039 void
14040 Composite_literal_expression::do_dump_expression(
14041 Ast_dump_context* ast_dump_context) const
14042 {
14043 ast_dump_context->ostream() << "composite(";
14044 ast_dump_context->dump_type(this->type_);
14045 ast_dump_context->ostream() << ", {";
14046 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14047 ast_dump_context->ostream() << "})";
14048 }
14049
14050 // Make a composite literal expression.
14051
14052 Expression*
14053 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14054 Expression_list* vals, bool all_are_names,
14055 Location location)
14056 {
14057 return new Composite_literal_expression(type, depth, has_keys, vals,
14058 all_are_names, location);
14059 }
14060
14061 // Return whether this expression is a composite literal.
14062
14063 bool
14064 Expression::is_composite_literal() const
14065 {
14066 switch (this->classification_)
14067 {
14068 case EXPRESSION_COMPOSITE_LITERAL:
14069 case EXPRESSION_STRUCT_CONSTRUCTION:
14070 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14071 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
14072 case EXPRESSION_MAP_CONSTRUCTION:
14073 return true;
14074 default:
14075 return false;
14076 }
14077 }
14078
14079 // Return whether this expression is a composite literal which is not
14080 // constant.
14081
14082 bool
14083 Expression::is_nonconstant_composite_literal() const
14084 {
14085 switch (this->classification_)
14086 {
14087 case EXPRESSION_STRUCT_CONSTRUCTION:
14088 {
14089 const Struct_construction_expression *psce =
14090 static_cast<const Struct_construction_expression*>(this);
14091 return !psce->is_constant_struct();
14092 }
14093 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14094 {
14095 const Fixed_array_construction_expression *pace =
14096 static_cast<const Fixed_array_construction_expression*>(this);
14097 return !pace->is_constant_array();
14098 }
14099 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
14100 {
14101 const Open_array_construction_expression *pace =
14102 static_cast<const Open_array_construction_expression*>(this);
14103 return !pace->is_constant_array();
14104 }
14105 case EXPRESSION_MAP_CONSTRUCTION:
14106 return true;
14107 default:
14108 return false;
14109 }
14110 }
14111
14112 // Return true if this is a reference to a local variable.
14113
14114 bool
14115 Expression::is_local_variable() const
14116 {
14117 const Var_expression* ve = this->var_expression();
14118 if (ve == NULL)
14119 return false;
14120 const Named_object* no = ve->named_object();
14121 return (no->is_result_variable()
14122 || (no->is_variable() && !no->var_value()->is_global()));
14123 }
14124
14125 // Class Type_guard_expression.
14126
14127 // Traversal.
14128
14129 int
14130 Type_guard_expression::do_traverse(Traverse* traverse)
14131 {
14132 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14133 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14134 return TRAVERSE_EXIT;
14135 return TRAVERSE_CONTINUE;
14136 }
14137
14138 // Check types of a type guard expression. The expression must have
14139 // an interface type, but the actual type conversion is checked at run
14140 // time.
14141
14142 void
14143 Type_guard_expression::do_check_types(Gogo*)
14144 {
14145 Type* expr_type = this->expr_->type();
14146 if (expr_type->interface_type() == NULL)
14147 {
14148 if (!expr_type->is_error() && !this->type_->is_error())
14149 this->report_error(_("type assertion only valid for interface types"));
14150 this->set_is_error();
14151 }
14152 else if (this->type_->interface_type() == NULL)
14153 {
14154 std::string reason;
14155 if (!expr_type->interface_type()->implements_interface(this->type_,
14156 &reason))
14157 {
14158 if (!this->type_->is_error())
14159 {
14160 if (reason.empty())
14161 this->report_error(_("impossible type assertion: "
14162 "type does not implement interface"));
14163 else
14164 error_at(this->location(),
14165 ("impossible type assertion: "
14166 "type does not implement interface (%s)"),
14167 reason.c_str());
14168 }
14169 this->set_is_error();
14170 }
14171 }
14172 }
14173
14174 // Return a tree for a type guard expression.
14175
14176 tree
14177 Type_guard_expression::do_get_tree(Translate_context* context)
14178 {
14179 tree expr_tree = this->expr_->get_tree(context);
14180 if (expr_tree == error_mark_node)
14181 return error_mark_node;
14182 if (this->type_->interface_type() != NULL)
14183 return Expression::convert_interface_to_interface(context, this->type_,
14184 this->expr_->type(),
14185 expr_tree, true,
14186 this->location());
14187 else
14188 return Expression::convert_for_assignment(context, this->type_,
14189 this->expr_->type(), expr_tree,
14190 this->location());
14191 }
14192
14193 // Dump ast representation for a type guard expression.
14194
14195 void
14196 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14197 const
14198 {
14199 this->expr_->dump_expression(ast_dump_context);
14200 ast_dump_context->ostream() << ".";
14201 ast_dump_context->dump_type(this->type_);
14202 }
14203
14204 // Make a type guard expression.
14205
14206 Expression*
14207 Expression::make_type_guard(Expression* expr, Type* type,
14208 Location location)
14209 {
14210 return new Type_guard_expression(expr, type, location);
14211 }
14212
14213 // Class Heap_composite_expression.
14214
14215 // When you take the address of a composite literal, it is allocated
14216 // on the heap. This class implements that.
14217
14218 class Heap_composite_expression : public Expression
14219 {
14220 public:
14221 Heap_composite_expression(Expression* expr, Location location)
14222 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
14223 expr_(expr)
14224 { }
14225
14226 protected:
14227 int
14228 do_traverse(Traverse* traverse)
14229 { return Expression::traverse(&this->expr_, traverse); }
14230
14231 Type*
14232 do_type()
14233 { return Type::make_pointer_type(this->expr_->type()); }
14234
14235 void
14236 do_determine_type(const Type_context*)
14237 { this->expr_->determine_type_no_context(); }
14238
14239 Expression*
14240 do_copy()
14241 {
14242 return Expression::make_heap_composite(this->expr_->copy(),
14243 this->location());
14244 }
14245
14246 tree
14247 do_get_tree(Translate_context*);
14248
14249 // We only export global objects, and the parser does not generate
14250 // this in global scope.
14251 void
14252 do_export(Export*) const
14253 { go_unreachable(); }
14254
14255 void
14256 do_dump_expression(Ast_dump_context*) const;
14257
14258 private:
14259 // The composite literal which is being put on the heap.
14260 Expression* expr_;
14261 };
14262
14263 // Return a tree which allocates a composite literal on the heap.
14264
14265 tree
14266 Heap_composite_expression::do_get_tree(Translate_context* context)
14267 {
14268 tree expr_tree = this->expr_->get_tree(context);
14269 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
14270 return error_mark_node;
14271 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
14272 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
14273 tree space = context->gogo()->allocate_memory(this->expr_->type(),
14274 expr_size, this->location());
14275 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
14276 space = save_expr(space);
14277 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
14278 space);
14279 TREE_THIS_NOTRAP(ref) = 1;
14280 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
14281 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
14282 space);
14283 SET_EXPR_LOCATION(ret, this->location().gcc_location());
14284 return ret;
14285 }
14286
14287 // Dump ast representation for a heap composite expression.
14288
14289 void
14290 Heap_composite_expression::do_dump_expression(
14291 Ast_dump_context* ast_dump_context) const
14292 {
14293 ast_dump_context->ostream() << "&(";
14294 ast_dump_context->dump_expression(this->expr_);
14295 ast_dump_context->ostream() << ")";
14296 }
14297
14298 // Allocate a composite literal on the heap.
14299
14300 Expression*
14301 Expression::make_heap_composite(Expression* expr, Location location)
14302 {
14303 return new Heap_composite_expression(expr, location);
14304 }
14305
14306 // Class Receive_expression.
14307
14308 // Return the type of a receive expression.
14309
14310 Type*
14311 Receive_expression::do_type()
14312 {
14313 Channel_type* channel_type = this->channel_->type()->channel_type();
14314 if (channel_type == NULL)
14315 return Type::make_error_type();
14316 return channel_type->element_type();
14317 }
14318
14319 // Check types for a receive expression.
14320
14321 void
14322 Receive_expression::do_check_types(Gogo*)
14323 {
14324 Type* type = this->channel_->type();
14325 if (type->is_error())
14326 {
14327 this->set_is_error();
14328 return;
14329 }
14330 if (type->channel_type() == NULL)
14331 {
14332 this->report_error(_("expected channel"));
14333 return;
14334 }
14335 if (!type->channel_type()->may_receive())
14336 {
14337 this->report_error(_("invalid receive on send-only channel"));
14338 return;
14339 }
14340 }
14341
14342 // Get a tree for a receive expression.
14343
14344 tree
14345 Receive_expression::do_get_tree(Translate_context* context)
14346 {
14347 Location loc = this->location();
14348
14349 Channel_type* channel_type = this->channel_->type()->channel_type();
14350 if (channel_type == NULL)
14351 {
14352 go_assert(this->channel_->type()->is_error());
14353 return error_mark_node;
14354 }
14355
14356 Expression* td = Expression::make_type_descriptor(channel_type, loc);
14357 tree td_tree = td->get_tree(context);
14358
14359 Type* element_type = channel_type->element_type();
14360 Btype* element_type_btype = element_type->get_backend(context->gogo());
14361 tree element_type_tree = type_to_tree(element_type_btype);
14362
14363 tree channel = this->channel_->get_tree(context);
14364 if (element_type_tree == error_mark_node || channel == error_mark_node)
14365 return error_mark_node;
14366
14367 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
14368 }
14369
14370 // Dump ast representation for a receive expression.
14371
14372 void
14373 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14374 {
14375 ast_dump_context->ostream() << " <- " ;
14376 ast_dump_context->dump_expression(channel_);
14377 }
14378
14379 // Make a receive expression.
14380
14381 Receive_expression*
14382 Expression::make_receive(Expression* channel, Location location)
14383 {
14384 return new Receive_expression(channel, location);
14385 }
14386
14387 // An expression which evaluates to a pointer to the type descriptor
14388 // of a type.
14389
14390 class Type_descriptor_expression : public Expression
14391 {
14392 public:
14393 Type_descriptor_expression(Type* type, Location location)
14394 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14395 type_(type)
14396 { }
14397
14398 protected:
14399 Type*
14400 do_type()
14401 { return Type::make_type_descriptor_ptr_type(); }
14402
14403 void
14404 do_determine_type(const Type_context*)
14405 { }
14406
14407 Expression*
14408 do_copy()
14409 { return this; }
14410
14411 tree
14412 do_get_tree(Translate_context* context)
14413 {
14414 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
14415 this->location());
14416 return expr_to_tree(ret);
14417 }
14418
14419 void
14420 do_dump_expression(Ast_dump_context*) const;
14421
14422 private:
14423 // The type for which this is the descriptor.
14424 Type* type_;
14425 };
14426
14427 // Dump ast representation for a type descriptor expression.
14428
14429 void
14430 Type_descriptor_expression::do_dump_expression(
14431 Ast_dump_context* ast_dump_context) const
14432 {
14433 ast_dump_context->dump_type(this->type_);
14434 }
14435
14436 // Make a type descriptor expression.
14437
14438 Expression*
14439 Expression::make_type_descriptor(Type* type, Location location)
14440 {
14441 return new Type_descriptor_expression(type, location);
14442 }
14443
14444 // An expression which evaluates to some characteristic of a type.
14445 // This is only used to initialize fields of a type descriptor. Using
14446 // a new expression class is slightly inefficient but gives us a good
14447 // separation between the frontend and the middle-end with regard to
14448 // how types are laid out.
14449
14450 class Type_info_expression : public Expression
14451 {
14452 public:
14453 Type_info_expression(Type* type, Type_info type_info)
14454 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14455 type_(type), type_info_(type_info)
14456 { }
14457
14458 protected:
14459 Type*
14460 do_type();
14461
14462 void
14463 do_determine_type(const Type_context*)
14464 { }
14465
14466 Expression*
14467 do_copy()
14468 { return this; }
14469
14470 tree
14471 do_get_tree(Translate_context* context);
14472
14473 void
14474 do_dump_expression(Ast_dump_context*) const;
14475
14476 private:
14477 // The type for which we are getting information.
14478 Type* type_;
14479 // What information we want.
14480 Type_info type_info_;
14481 };
14482
14483 // The type is chosen to match what the type descriptor struct
14484 // expects.
14485
14486 Type*
14487 Type_info_expression::do_type()
14488 {
14489 switch (this->type_info_)
14490 {
14491 case TYPE_INFO_SIZE:
14492 return Type::lookup_integer_type("uintptr");
14493 case TYPE_INFO_ALIGNMENT:
14494 case TYPE_INFO_FIELD_ALIGNMENT:
14495 return Type::lookup_integer_type("uint8");
14496 default:
14497 go_unreachable();
14498 }
14499 }
14500
14501 // Return type information in GENERIC.
14502
14503 tree
14504 Type_info_expression::do_get_tree(Translate_context* context)
14505 {
14506 Btype* btype = this->type_->get_backend(context->gogo());
14507 Gogo* gogo = context->gogo();
14508 size_t val;
14509 switch (this->type_info_)
14510 {
14511 case TYPE_INFO_SIZE:
14512 val = gogo->backend()->type_size(btype);
14513 break;
14514 case TYPE_INFO_ALIGNMENT:
14515 val = gogo->backend()->type_alignment(btype);
14516 break;
14517 case TYPE_INFO_FIELD_ALIGNMENT:
14518 val = gogo->backend()->type_field_alignment(btype);
14519 break;
14520 default:
14521 go_unreachable();
14522 }
14523 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14524 go_assert(val_type_tree != error_mark_node);
14525 return build_int_cstu(val_type_tree, val);
14526 }
14527
14528 // Dump ast representation for a type info expression.
14529
14530 void
14531 Type_info_expression::do_dump_expression(
14532 Ast_dump_context* ast_dump_context) const
14533 {
14534 ast_dump_context->ostream() << "typeinfo(";
14535 ast_dump_context->dump_type(this->type_);
14536 ast_dump_context->ostream() << ",";
14537 ast_dump_context->ostream() <<
14538 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14539 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14540 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14541 : "unknown");
14542 ast_dump_context->ostream() << ")";
14543 }
14544
14545 // Make a type info expression.
14546
14547 Expression*
14548 Expression::make_type_info(Type* type, Type_info type_info)
14549 {
14550 return new Type_info_expression(type, type_info);
14551 }
14552
14553 // An expression which evaluates to the offset of a field within a
14554 // struct. This, like Type_info_expression, q.v., is only used to
14555 // initialize fields of a type descriptor.
14556
14557 class Struct_field_offset_expression : public Expression
14558 {
14559 public:
14560 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14561 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14562 Linemap::predeclared_location()),
14563 type_(type), field_(field)
14564 { }
14565
14566 protected:
14567 Type*
14568 do_type()
14569 { return Type::lookup_integer_type("uintptr"); }
14570
14571 void
14572 do_determine_type(const Type_context*)
14573 { }
14574
14575 Expression*
14576 do_copy()
14577 { return this; }
14578
14579 tree
14580 do_get_tree(Translate_context* context);
14581
14582 void
14583 do_dump_expression(Ast_dump_context*) const;
14584
14585 private:
14586 // The type of the struct.
14587 Struct_type* type_;
14588 // The field.
14589 const Struct_field* field_;
14590 };
14591
14592 // Return a struct field offset in GENERIC.
14593
14594 tree
14595 Struct_field_offset_expression::do_get_tree(Translate_context* context)
14596 {
14597 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
14598 if (type_tree == error_mark_node)
14599 return error_mark_node;
14600
14601 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
14602 go_assert(val_type_tree != error_mark_node);
14603
14604 const Struct_field_list* fields = this->type_->fields();
14605 tree struct_field_tree = TYPE_FIELDS(type_tree);
14606 Struct_field_list::const_iterator p;
14607 for (p = fields->begin();
14608 p != fields->end();
14609 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14610 {
14611 go_assert(struct_field_tree != NULL_TREE);
14612 if (&*p == this->field_)
14613 break;
14614 }
14615 go_assert(&*p == this->field_);
14616
14617 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14618 byte_position(struct_field_tree));
14619 }
14620
14621 // Dump ast representation for a struct field offset expression.
14622
14623 void
14624 Struct_field_offset_expression::do_dump_expression(
14625 Ast_dump_context* ast_dump_context) const
14626 {
14627 ast_dump_context->ostream() << "unsafe.Offsetof(";
14628 ast_dump_context->dump_type(this->type_);
14629 ast_dump_context->ostream() << '.';
14630 ast_dump_context->ostream() <<
14631 Gogo::message_name(this->field_->field_name());
14632 ast_dump_context->ostream() << ")";
14633 }
14634
14635 // Make an expression for a struct field offset.
14636
14637 Expression*
14638 Expression::make_struct_field_offset(Struct_type* type,
14639 const Struct_field* field)
14640 {
14641 return new Struct_field_offset_expression(type, field);
14642 }
14643
14644 // An expression which evaluates to a pointer to the map descriptor of
14645 // a map type.
14646
14647 class Map_descriptor_expression : public Expression
14648 {
14649 public:
14650 Map_descriptor_expression(Map_type* type, Location location)
14651 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14652 type_(type)
14653 { }
14654
14655 protected:
14656 Type*
14657 do_type()
14658 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14659
14660 void
14661 do_determine_type(const Type_context*)
14662 { }
14663
14664 Expression*
14665 do_copy()
14666 { return this; }
14667
14668 tree
14669 do_get_tree(Translate_context* context)
14670 {
14671 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14672 this->location());
14673 return expr_to_tree(ret);
14674 }
14675
14676 void
14677 do_dump_expression(Ast_dump_context*) const;
14678
14679 private:
14680 // The type for which this is the descriptor.
14681 Map_type* type_;
14682 };
14683
14684 // Dump ast representation for a map descriptor expression.
14685
14686 void
14687 Map_descriptor_expression::do_dump_expression(
14688 Ast_dump_context* ast_dump_context) const
14689 {
14690 ast_dump_context->ostream() << "map_descriptor(";
14691 ast_dump_context->dump_type(this->type_);
14692 ast_dump_context->ostream() << ")";
14693 }
14694
14695 // Make a map descriptor expression.
14696
14697 Expression*
14698 Expression::make_map_descriptor(Map_type* type, Location location)
14699 {
14700 return new Map_descriptor_expression(type, location);
14701 }
14702
14703 // An expression which evaluates to the address of an unnamed label.
14704
14705 class Label_addr_expression : public Expression
14706 {
14707 public:
14708 Label_addr_expression(Label* label, Location location)
14709 : Expression(EXPRESSION_LABEL_ADDR, location),
14710 label_(label)
14711 { }
14712
14713 protected:
14714 Type*
14715 do_type()
14716 { return Type::make_pointer_type(Type::make_void_type()); }
14717
14718 void
14719 do_determine_type(const Type_context*)
14720 { }
14721
14722 Expression*
14723 do_copy()
14724 { return new Label_addr_expression(this->label_, this->location()); }
14725
14726 tree
14727 do_get_tree(Translate_context* context)
14728 {
14729 return expr_to_tree(this->label_->get_addr(context, this->location()));
14730 }
14731
14732 void
14733 do_dump_expression(Ast_dump_context* ast_dump_context) const
14734 { ast_dump_context->ostream() << this->label_->name(); }
14735
14736 private:
14737 // The label whose address we are taking.
14738 Label* label_;
14739 };
14740
14741 // Make an expression for the address of an unnamed label.
14742
14743 Expression*
14744 Expression::make_label_addr(Label* label, Location location)
14745 {
14746 return new Label_addr_expression(label, location);
14747 }
14748
14749 // Import an expression. This comes at the end in order to see the
14750 // various class definitions.
14751
14752 Expression*
14753 Expression::import_expression(Import* imp)
14754 {
14755 int c = imp->peek_char();
14756 if (imp->match_c_string("- ")
14757 || imp->match_c_string("! ")
14758 || imp->match_c_string("^ "))
14759 return Unary_expression::do_import(imp);
14760 else if (c == '(')
14761 return Binary_expression::do_import(imp);
14762 else if (imp->match_c_string("true")
14763 || imp->match_c_string("false"))
14764 return Boolean_expression::do_import(imp);
14765 else if (c == '"')
14766 return String_expression::do_import(imp);
14767 else if (c == '-' || (c >= '0' && c <= '9'))
14768 {
14769 // This handles integers, floats and complex constants.
14770 return Integer_expression::do_import(imp);
14771 }
14772 else if (imp->match_c_string("nil"))
14773 return Nil_expression::do_import(imp);
14774 else if (imp->match_c_string("convert"))
14775 return Type_conversion_expression::do_import(imp);
14776 else
14777 {
14778 error_at(imp->location(), "import error: expected expression");
14779 return Expression::make_error(imp->location());
14780 }
14781 }
14782
14783 // Class Expression_list.
14784
14785 // Traverse the list.
14786
14787 int
14788 Expression_list::traverse(Traverse* traverse)
14789 {
14790 for (Expression_list::iterator p = this->begin();
14791 p != this->end();
14792 ++p)
14793 {
14794 if (*p != NULL)
14795 {
14796 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14797 return TRAVERSE_EXIT;
14798 }
14799 }
14800 return TRAVERSE_CONTINUE;
14801 }
14802
14803 // Copy the list.
14804
14805 Expression_list*
14806 Expression_list::copy()
14807 {
14808 Expression_list* ret = new Expression_list();
14809 for (Expression_list::iterator p = this->begin();
14810 p != this->end();
14811 ++p)
14812 {
14813 if (*p == NULL)
14814 ret->push_back(NULL);
14815 else
14816 ret->push_back((*p)->copy());
14817 }
14818 return ret;
14819 }
14820
14821 // Return whether an expression list has an error expression.
14822
14823 bool
14824 Expression_list::contains_error() const
14825 {
14826 for (Expression_list::const_iterator p = this->begin();
14827 p != this->end();
14828 ++p)
14829 if (*p != NULL && (*p)->is_error_expression())
14830 return true;
14831 return false;
14832 }
14833
14834 // Class Numeric_constant.
14835
14836 // Destructor.
14837
14838 Numeric_constant::~Numeric_constant()
14839 {
14840 this->clear();
14841 }
14842
14843 // Copy constructor.
14844
14845 Numeric_constant::Numeric_constant(const Numeric_constant& a)
14846 : classification_(a.classification_), type_(a.type_)
14847 {
14848 switch (a.classification_)
14849 {
14850 case NC_INVALID:
14851 break;
14852 case NC_INT:
14853 case NC_RUNE:
14854 mpz_init_set(this->u_.int_val, a.u_.int_val);
14855 break;
14856 case NC_FLOAT:
14857 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14858 break;
14859 case NC_COMPLEX:
14860 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
14861 GMP_RNDN);
14862 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
14863 GMP_RNDN);
14864 break;
14865 default:
14866 go_unreachable();
14867 }
14868 }
14869
14870 // Assignment operator.
14871
14872 Numeric_constant&
14873 Numeric_constant::operator=(const Numeric_constant& a)
14874 {
14875 this->clear();
14876 this->classification_ = a.classification_;
14877 this->type_ = a.type_;
14878 switch (a.classification_)
14879 {
14880 case NC_INVALID:
14881 break;
14882 case NC_INT:
14883 case NC_RUNE:
14884 mpz_init_set(this->u_.int_val, a.u_.int_val);
14885 break;
14886 case NC_FLOAT:
14887 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14888 break;
14889 case NC_COMPLEX:
14890 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
14891 GMP_RNDN);
14892 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
14893 GMP_RNDN);
14894 break;
14895 default:
14896 go_unreachable();
14897 }
14898 return *this;
14899 }
14900
14901 // Clear the contents.
14902
14903 void
14904 Numeric_constant::clear()
14905 {
14906 switch (this->classification_)
14907 {
14908 case NC_INVALID:
14909 break;
14910 case NC_INT:
14911 case NC_RUNE:
14912 mpz_clear(this->u_.int_val);
14913 break;
14914 case NC_FLOAT:
14915 mpfr_clear(this->u_.float_val);
14916 break;
14917 case NC_COMPLEX:
14918 mpfr_clear(this->u_.complex_val.real);
14919 mpfr_clear(this->u_.complex_val.imag);
14920 break;
14921 default:
14922 go_unreachable();
14923 }
14924 this->classification_ = NC_INVALID;
14925 }
14926
14927 // Set to an unsigned long value.
14928
14929 void
14930 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
14931 {
14932 this->clear();
14933 this->classification_ = NC_INT;
14934 this->type_ = type;
14935 mpz_init_set_ui(this->u_.int_val, val);
14936 }
14937
14938 // Set to an integer value.
14939
14940 void
14941 Numeric_constant::set_int(Type* type, const mpz_t val)
14942 {
14943 this->clear();
14944 this->classification_ = NC_INT;
14945 this->type_ = type;
14946 mpz_init_set(this->u_.int_val, val);
14947 }
14948
14949 // Set to a rune value.
14950
14951 void
14952 Numeric_constant::set_rune(Type* type, const mpz_t val)
14953 {
14954 this->clear();
14955 this->classification_ = NC_RUNE;
14956 this->type_ = type;
14957 mpz_init_set(this->u_.int_val, val);
14958 }
14959
14960 // Set to a floating point value.
14961
14962 void
14963 Numeric_constant::set_float(Type* type, const mpfr_t val)
14964 {
14965 this->clear();
14966 this->classification_ = NC_FLOAT;
14967 this->type_ = type;
14968 // Numeric constants do not have negative zero values, so remove
14969 // them here. They also don't have infinity or NaN values, but we
14970 // should never see them here.
14971 if (mpfr_zero_p(val))
14972 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
14973 else
14974 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
14975 }
14976
14977 // Set to a complex value.
14978
14979 void
14980 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
14981 {
14982 this->clear();
14983 this->classification_ = NC_COMPLEX;
14984 this->type_ = type;
14985 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
14986 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
14987 }
14988
14989 // Get an int value.
14990
14991 void
14992 Numeric_constant::get_int(mpz_t* val) const
14993 {
14994 go_assert(this->is_int());
14995 mpz_init_set(*val, this->u_.int_val);
14996 }
14997
14998 // Get a rune value.
14999
15000 void
15001 Numeric_constant::get_rune(mpz_t* val) const
15002 {
15003 go_assert(this->is_rune());
15004 mpz_init_set(*val, this->u_.int_val);
15005 }
15006
15007 // Get a floating point value.
15008
15009 void
15010 Numeric_constant::get_float(mpfr_t* val) const
15011 {
15012 go_assert(this->is_float());
15013 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15014 }
15015
15016 // Get a complex value.
15017
15018 void
15019 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15020 {
15021 go_assert(this->is_complex());
15022 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15023 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15024 }
15025
15026 // Express value as unsigned long if possible.
15027
15028 Numeric_constant::To_unsigned_long
15029 Numeric_constant::to_unsigned_long(unsigned long* val) const
15030 {
15031 switch (this->classification_)
15032 {
15033 case NC_INT:
15034 case NC_RUNE:
15035 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15036 case NC_FLOAT:
15037 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15038 case NC_COMPLEX:
15039 if (!mpfr_zero_p(this->u_.complex_val.imag))
15040 return NC_UL_NOTINT;
15041 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15042 default:
15043 go_unreachable();
15044 }
15045 }
15046
15047 // Express integer value as unsigned long if possible.
15048
15049 Numeric_constant::To_unsigned_long
15050 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15051 unsigned long *val) const
15052 {
15053 if (mpz_sgn(ival) < 0)
15054 return NC_UL_NEGATIVE;
15055 unsigned long ui = mpz_get_ui(ival);
15056 if (mpz_cmp_ui(ival, ui) != 0)
15057 return NC_UL_BIG;
15058 *val = ui;
15059 return NC_UL_VALID;
15060 }
15061
15062 // Express floating point value as unsigned long if possible.
15063
15064 Numeric_constant::To_unsigned_long
15065 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15066 unsigned long *val) const
15067 {
15068 if (!mpfr_integer_p(fval))
15069 return NC_UL_NOTINT;
15070 mpz_t ival;
15071 mpz_init(ival);
15072 mpfr_get_z(ival, fval, GMP_RNDN);
15073 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15074 mpz_clear(ival);
15075 return ret;
15076 }
15077
15078 // Convert value to integer if possible.
15079
15080 bool
15081 Numeric_constant::to_int(mpz_t* val) const
15082 {
15083 switch (this->classification_)
15084 {
15085 case NC_INT:
15086 case NC_RUNE:
15087 mpz_init_set(*val, this->u_.int_val);
15088 return true;
15089 case NC_FLOAT:
15090 if (!mpfr_integer_p(this->u_.float_val))
15091 return false;
15092 mpz_init(*val);
15093 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15094 return true;
15095 case NC_COMPLEX:
15096 if (!mpfr_zero_p(this->u_.complex_val.imag)
15097 || !mpfr_integer_p(this->u_.complex_val.real))
15098 return false;
15099 mpz_init(*val);
15100 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15101 return true;
15102 default:
15103 go_unreachable();
15104 }
15105 }
15106
15107 // Convert value to floating point if possible.
15108
15109 bool
15110 Numeric_constant::to_float(mpfr_t* val) const
15111 {
15112 switch (this->classification_)
15113 {
15114 case NC_INT:
15115 case NC_RUNE:
15116 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15117 return true;
15118 case NC_FLOAT:
15119 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15120 return true;
15121 case NC_COMPLEX:
15122 if (!mpfr_zero_p(this->u_.complex_val.imag))
15123 return false;
15124 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15125 return true;
15126 default:
15127 go_unreachable();
15128 }
15129 }
15130
15131 // Convert value to complex.
15132
15133 bool
15134 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15135 {
15136 switch (this->classification_)
15137 {
15138 case NC_INT:
15139 case NC_RUNE:
15140 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15141 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15142 return true;
15143 case NC_FLOAT:
15144 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15145 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15146 return true;
15147 case NC_COMPLEX:
15148 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15149 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15150 return true;
15151 default:
15152 go_unreachable();
15153 }
15154 }
15155
15156 // Get the type.
15157
15158 Type*
15159 Numeric_constant::type() const
15160 {
15161 if (this->type_ != NULL)
15162 return this->type_;
15163 switch (this->classification_)
15164 {
15165 case NC_INT:
15166 return Type::make_abstract_integer_type();
15167 case NC_RUNE:
15168 return Type::make_abstract_character_type();
15169 case NC_FLOAT:
15170 return Type::make_abstract_float_type();
15171 case NC_COMPLEX:
15172 return Type::make_abstract_complex_type();
15173 default:
15174 go_unreachable();
15175 }
15176 }
15177
15178 // If the constant can be expressed in TYPE, then set the type of the
15179 // constant to TYPE and return true. Otherwise return false, and, if
15180 // ISSUE_ERROR is true, report an appropriate error message.
15181
15182 bool
15183 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15184 {
15185 bool ret;
15186 if (type == NULL)
15187 ret = true;
15188 else if (type->integer_type() != NULL)
15189 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15190 else if (type->float_type() != NULL)
15191 ret = this->check_float_type(type->float_type(), issue_error, loc);
15192 else if (type->complex_type() != NULL)
15193 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15194 else
15195 go_unreachable();
15196 if (ret)
15197 this->type_ = type;
15198 return ret;
15199 }
15200
15201 // Check whether the constant can be expressed in an integer type.
15202
15203 bool
15204 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15205 Location location) const
15206 {
15207 mpz_t val;
15208 switch (this->classification_)
15209 {
15210 case NC_INT:
15211 case NC_RUNE:
15212 mpz_init_set(val, this->u_.int_val);
15213 break;
15214
15215 case NC_FLOAT:
15216 if (!mpfr_integer_p(this->u_.float_val))
15217 {
15218 if (issue_error)
15219 error_at(location, "floating point constant truncated to integer");
15220 return false;
15221 }
15222 mpz_init(val);
15223 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15224 break;
15225
15226 case NC_COMPLEX:
15227 if (!mpfr_integer_p(this->u_.complex_val.real)
15228 || !mpfr_zero_p(this->u_.complex_val.imag))
15229 {
15230 if (issue_error)
15231 error_at(location, "complex constant truncated to integer");
15232 return false;
15233 }
15234 mpz_init(val);
15235 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15236 break;
15237
15238 default:
15239 go_unreachable();
15240 }
15241
15242 bool ret;
15243 if (type->is_abstract())
15244 ret = true;
15245 else
15246 {
15247 int bits = mpz_sizeinbase(val, 2);
15248 if (type->is_unsigned())
15249 {
15250 // For an unsigned type we can only accept a nonnegative
15251 // number, and we must be able to represents at least BITS.
15252 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15253 }
15254 else
15255 {
15256 // For a signed type we need an extra bit to indicate the
15257 // sign. We have to handle the most negative integer
15258 // specially.
15259 ret = (bits + 1 <= type->bits()
15260 || (bits <= type->bits()
15261 && mpz_sgn(val) < 0
15262 && (mpz_scan1(val, 0)
15263 == static_cast<unsigned long>(type->bits() - 1))
15264 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15265 }
15266 }
15267
15268 if (!ret && issue_error)
15269 error_at(location, "integer constant overflow");
15270
15271 return ret;
15272 }
15273
15274 // Check whether the constant can be expressed in a floating point
15275 // type.
15276
15277 bool
15278 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15279 Location location)
15280 {
15281 mpfr_t val;
15282 switch (this->classification_)
15283 {
15284 case NC_INT:
15285 case NC_RUNE:
15286 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15287 break;
15288
15289 case NC_FLOAT:
15290 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15291 break;
15292
15293 case NC_COMPLEX:
15294 if (!mpfr_zero_p(this->u_.complex_val.imag))
15295 {
15296 if (issue_error)
15297 error_at(location, "complex constant truncated to float");
15298 return false;
15299 }
15300 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15301 break;
15302
15303 default:
15304 go_unreachable();
15305 }
15306
15307 bool ret;
15308 if (type->is_abstract())
15309 ret = true;
15310 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15311 {
15312 // A NaN or Infinity always fits in the range of the type.
15313 ret = true;
15314 }
15315 else
15316 {
15317 mp_exp_t exp = mpfr_get_exp(val);
15318 mp_exp_t max_exp;
15319 switch (type->bits())
15320 {
15321 case 32:
15322 max_exp = 128;
15323 break;
15324 case 64:
15325 max_exp = 1024;
15326 break;
15327 default:
15328 go_unreachable();
15329 }
15330
15331 ret = exp <= max_exp;
15332
15333 if (ret)
15334 {
15335 // Round the constant to the desired type.
15336 mpfr_t t;
15337 mpfr_init(t);
15338 switch (type->bits())
15339 {
15340 case 32:
15341 mpfr_set_prec(t, 24);
15342 break;
15343 case 64:
15344 mpfr_set_prec(t, 53);
15345 break;
15346 default:
15347 go_unreachable();
15348 }
15349 mpfr_set(t, val, GMP_RNDN);
15350 mpfr_set(val, t, GMP_RNDN);
15351 mpfr_clear(t);
15352
15353 this->set_float(type, val);
15354 }
15355 }
15356
15357 mpfr_clear(val);
15358
15359 if (!ret && issue_error)
15360 error_at(location, "floating point constant overflow");
15361
15362 return ret;
15363 }
15364
15365 // Check whether the constant can be expressed in a complex type.
15366
15367 bool
15368 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15369 Location location)
15370 {
15371 if (type->is_abstract())
15372 return true;
15373
15374 mp_exp_t max_exp;
15375 switch (type->bits())
15376 {
15377 case 64:
15378 max_exp = 128;
15379 break;
15380 case 128:
15381 max_exp = 1024;
15382 break;
15383 default:
15384 go_unreachable();
15385 }
15386
15387 mpfr_t real;
15388 mpfr_t imag;
15389 switch (this->classification_)
15390 {
15391 case NC_INT:
15392 case NC_RUNE:
15393 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
15394 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15395 break;
15396
15397 case NC_FLOAT:
15398 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
15399 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15400 break;
15401
15402 case NC_COMPLEX:
15403 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
15404 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
15405 break;
15406
15407 default:
15408 go_unreachable();
15409 }
15410
15411 bool ret = true;
15412 if (!mpfr_nan_p(real)
15413 && !mpfr_inf_p(real)
15414 && !mpfr_zero_p(real)
15415 && mpfr_get_exp(real) > max_exp)
15416 {
15417 if (issue_error)
15418 error_at(location, "complex real part overflow");
15419 ret = false;
15420 }
15421
15422 if (!mpfr_nan_p(imag)
15423 && !mpfr_inf_p(imag)
15424 && !mpfr_zero_p(imag)
15425 && mpfr_get_exp(imag) > max_exp)
15426 {
15427 if (issue_error)
15428 error_at(location, "complex imaginary part overflow");
15429 ret = false;
15430 }
15431
15432 if (ret)
15433 {
15434 // Round the constant to the desired type.
15435 mpfr_t t;
15436 mpfr_init(t);
15437 switch (type->bits())
15438 {
15439 case 64:
15440 mpfr_set_prec(t, 24);
15441 break;
15442 case 128:
15443 mpfr_set_prec(t, 53);
15444 break;
15445 default:
15446 go_unreachable();
15447 }
15448 mpfr_set(t, real, GMP_RNDN);
15449 mpfr_set(real, t, GMP_RNDN);
15450 mpfr_set(t, imag, GMP_RNDN);
15451 mpfr_set(imag, t, GMP_RNDN);
15452 mpfr_clear(t);
15453
15454 this->set_complex(type, real, imag);
15455 }
15456
15457 mpfr_clear(real);
15458 mpfr_clear(imag);
15459
15460 return ret;
15461 }
15462
15463 // Return an Expression for this value.
15464
15465 Expression*
15466 Numeric_constant::expression(Location loc) const
15467 {
15468 switch (this->classification_)
15469 {
15470 case NC_INT:
15471 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15472 case NC_RUNE:
15473 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15474 case NC_FLOAT:
15475 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15476 case NC_COMPLEX:
15477 return Expression::make_complex(&this->u_.complex_val.real,
15478 &this->u_.complex_val.imag,
15479 this->type_, loc);
15480 default:
15481 go_unreachable();
15482 }
15483 }