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 "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
24
25 // Class Expression.
26
Expression(Expression_classification classification,Location location)27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
30 {
31 }
32
~Expression()33 Expression::~Expression()
34 {
35 }
36
37 // Traverse the expressions.
38
39 int
traverse(Expression ** pexpr,Traverse * traverse)40 Expression::traverse(Expression** pexpr, Traverse* traverse)
41 {
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
44 {
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
50 }
51 return expr->do_traverse(traverse);
52 }
53
54 // Traverse subexpressions of this expression.
55
56 int
traverse_subexpressions(Traverse * traverse)57 Expression::traverse_subexpressions(Traverse* traverse)
58 {
59 return this->do_traverse(traverse);
60 }
61
62 // A traversal used to set the location of subexpressions.
63
64 class Set_location : public Traverse
65 {
66 public:
Set_location(Location loc)67 Set_location(Location loc)
68 : Traverse(traverse_expressions),
69 loc_(loc)
70 { }
71
72 int
73 expression(Expression** pexpr);
74
75 private:
76 Location loc_;
77 };
78
79 // Set the location of an expression.
80
81 int
expression(Expression ** pexpr)82 Set_location::expression(Expression** pexpr)
83 {
84 // Some expressions are shared or don't have an independent
85 // location, so we shouldn't change their location. This is the set
86 // of expressions for which do_copy is just "return this" or
87 // otherwise does not pass down the location.
88 switch ((*pexpr)->classification())
89 {
90 case Expression::EXPRESSION_ERROR:
91 case Expression::EXPRESSION_VAR_REFERENCE:
92 case Expression::EXPRESSION_ENCLOSED_VAR_REFERENCE:
93 case Expression::EXPRESSION_STRING:
94 case Expression::EXPRESSION_FUNC_DESCRIPTOR:
95 case Expression::EXPRESSION_TYPE:
96 case Expression::EXPRESSION_BOOLEAN:
97 case Expression::EXPRESSION_CONST_REFERENCE:
98 case Expression::EXPRESSION_NIL:
99 case Expression::EXPRESSION_TYPE_DESCRIPTOR:
100 case Expression::EXPRESSION_GC_SYMBOL:
101 case Expression::EXPRESSION_PTRMASK_SYMBOL:
102 case Expression::EXPRESSION_TYPE_INFO:
103 case Expression::EXPRESSION_STRUCT_FIELD_OFFSET:
104 return TRAVERSE_CONTINUE;
105 default:
106 break;
107 }
108
109 (*pexpr)->location_ = this->loc_;
110 return TRAVERSE_CONTINUE;
111 }
112
113 // Set the location of an expression and its subexpressions.
114
115 void
set_location(Location loc)116 Expression::set_location(Location loc)
117 {
118 this->location_ = loc;
119 Set_location sl(loc);
120 this->traverse_subexpressions(&sl);
121 }
122
123 // Default implementation for do_traverse for child classes.
124
125 int
do_traverse(Traverse *)126 Expression::do_traverse(Traverse*)
127 {
128 return TRAVERSE_CONTINUE;
129 }
130
131 // This virtual function is called by the parser if the value of this
132 // expression is being discarded. By default, we give an error.
133 // Expressions with side effects override.
134
135 bool
do_discarding_value()136 Expression::do_discarding_value()
137 {
138 this->unused_value_error();
139 return false;
140 }
141
142 // This virtual function is called to export expressions. This will
143 // only be used by expressions which may be constant.
144
145 void
do_export(Export_function_body *) const146 Expression::do_export(Export_function_body*) const
147 {
148 go_unreachable();
149 }
150
151 // Write a name to the export data.
152
153 void
export_name(Export_function_body * efb,const Named_object * no)154 Expression::export_name(Export_function_body* efb, const Named_object* no)
155 {
156 if (no->package() != NULL)
157 {
158 char buf[50];
159 snprintf(buf, sizeof buf, "<p%d>", efb->package_index(no->package()));
160 efb->write_c_string(buf);
161 }
162
163 if (!Gogo::is_hidden_name(no->name()))
164 efb->write_string(no->name());
165 else
166 {
167 efb->write_c_string(".");
168 efb->write_string(Gogo::unpack_hidden_name(no->name()));
169 }
170 }
171
172 // Give an error saying that the value of the expression is not used.
173
174 void
unused_value_error()175 Expression::unused_value_error()
176 {
177 if (this->type()->is_error())
178 {
179 go_assert(saw_errors());
180 this->set_is_error();
181 }
182 else
183 this->report_error(_("value computed is not used"));
184 }
185
186 // Note that this expression is an error. This is called by children
187 // when they discover an error.
188
189 void
set_is_error()190 Expression::set_is_error()
191 {
192 this->classification_ = EXPRESSION_ERROR;
193 }
194
195 // For children to call to report an error conveniently.
196
197 void
report_error(const char * msg)198 Expression::report_error(const char* msg)
199 {
200 go_error_at(this->location_, "%s", msg);
201 this->set_is_error();
202 }
203
204 // Set types of variables and constants. This is implemented by the
205 // child class.
206
207 void
determine_type(const Type_context * context)208 Expression::determine_type(const Type_context* context)
209 {
210 this->do_determine_type(context);
211 }
212
213 // Set types when there is no context.
214
215 void
determine_type_no_context()216 Expression::determine_type_no_context()
217 {
218 Type_context context;
219 this->do_determine_type(&context);
220 }
221
222 // Return true if two expressions refer to the same variable or struct
223 // field. This can only be true when there are no side effects.
224
225 bool
is_same_variable(Expression * a,Expression * b)226 Expression::is_same_variable(Expression* a, Expression* b)
227 {
228 if (a->classification() != b->classification())
229 return false;
230
231 Var_expression* av = a->var_expression();
232 if (av != NULL)
233 return av->named_object() == b->var_expression()->named_object();
234
235 Field_reference_expression* af = a->field_reference_expression();
236 if (af != NULL)
237 {
238 Field_reference_expression* bf = b->field_reference_expression();
239 return (af->field_index() == bf->field_index()
240 && Expression::is_same_variable(af->expr(), bf->expr()));
241 }
242
243 Unary_expression* au = a->unary_expression();
244 if (au != NULL)
245 {
246 Unary_expression* bu = b->unary_expression();
247 return (au->op() == OPERATOR_MULT
248 && bu->op() == OPERATOR_MULT
249 && Expression::is_same_variable(au->operand(),
250 bu->operand()));
251 }
252
253 Array_index_expression* aie = a->array_index_expression();
254 if (aie != NULL)
255 {
256 Array_index_expression* bie = b->array_index_expression();
257 return (aie->end() == NULL
258 && bie->end() == NULL
259 && Expression::is_same_variable(aie->array(), bie->array())
260 && Expression::is_same_variable(aie->start(), bie->start()));
261 }
262
263 Numeric_constant aval;
264 if (a->numeric_constant_value(&aval))
265 {
266 Numeric_constant bval;
267 if (b->numeric_constant_value(&bval))
268 return aval.equals(bval);
269 }
270
271 return false;
272 }
273
274 // Return an expression handling any conversions which must be done during
275 // assignment.
276
277 Expression*
convert_for_assignment(Gogo * gogo,Type * lhs_type,Expression * rhs,Location location)278 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
279 Expression* rhs, Location location)
280 {
281 Type* rhs_type = rhs->type();
282 if (lhs_type->is_error()
283 || rhs_type->is_error()
284 || rhs->is_error_expression())
285 return Expression::make_error(location);
286
287 bool are_identical = Type::are_identical(lhs_type, rhs_type,
288 (Type::COMPARE_ERRORS
289 | Type::COMPARE_TAGS),
290 NULL);
291 if (!are_identical && lhs_type->interface_type() != NULL)
292 {
293 // Type to interface conversions have been made explicit early.
294 go_assert(rhs_type->interface_type() != NULL);
295 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
296 location);
297 }
298 else if (!are_identical && rhs_type->interface_type() != NULL)
299 return Expression::convert_interface_to_type(gogo, lhs_type, rhs, location);
300 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
301 {
302 // Assigning nil to a slice.
303 Expression* nil = Expression::make_nil(location);
304 Expression* zero = Expression::make_integer_ul(0, NULL, location);
305 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
306 }
307 else if (rhs_type->is_nil_type())
308 return Expression::make_nil(location);
309 else if (are_identical)
310 {
311 if (lhs_type->forwarded() != rhs_type->forwarded())
312 {
313 // Different but identical types require an explicit
314 // conversion. This happens with type aliases.
315 return Expression::make_cast(lhs_type, rhs, location);
316 }
317
318 // No conversion is needed.
319 return rhs;
320 }
321 else if (lhs_type->points_to() != NULL)
322 return Expression::make_unsafe_cast(lhs_type, rhs, location);
323 else if (lhs_type->is_numeric_type())
324 return Expression::make_cast(lhs_type, rhs, location);
325 else if ((lhs_type->struct_type() != NULL
326 && rhs_type->struct_type() != NULL)
327 || (lhs_type->array_type() != NULL
328 && rhs_type->array_type() != NULL))
329 {
330 // This conversion must be permitted by Go, or we wouldn't have
331 // gotten here.
332 return Expression::make_unsafe_cast(lhs_type, rhs, location);
333 }
334 else
335 return rhs;
336 }
337
338 // Return an expression for a conversion from a non-interface type to an
339 // interface type. If ON_STACK is true, it can allocate the storage on
340 // stack.
341
342 Expression*
convert_type_to_interface(Type * lhs_type,Expression * rhs,bool on_stack,Location location)343 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
344 bool on_stack, Location location)
345 {
346 Interface_type* lhs_interface_type = lhs_type->interface_type();
347 bool lhs_is_empty = lhs_interface_type->is_empty();
348
349 // Since RHS_TYPE is a static type, we can create the interface
350 // method table at compile time.
351
352 // When setting an interface to nil, we just set both fields to
353 // NULL.
354 Type* rhs_type = rhs->type();
355 if (rhs_type->is_nil_type())
356 {
357 Expression* nil = Expression::make_nil(location);
358 return Expression::make_interface_value(lhs_type, nil, nil, location);
359 }
360
361 // This should have been checked already.
362 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
363 {
364 go_assert(saw_errors());
365 return Expression::make_error(location);
366 }
367
368 // An interface is a tuple. If LHS_TYPE is an empty interface type,
369 // then the first field is the type descriptor for RHS_TYPE.
370 // Otherwise it is the interface method table for RHS_TYPE.
371 Expression* first_field;
372 if (lhs_is_empty)
373 first_field = Expression::make_type_descriptor(rhs_type, location);
374 else
375 {
376 // Build the interface method table for this interface and this
377 // object type: a list of function pointers for each interface
378 // method.
379 Named_type* rhs_named_type = rhs_type->named_type();
380 Struct_type* rhs_struct_type = rhs_type->struct_type();
381 bool is_pointer = false;
382 if (rhs_named_type == NULL && rhs_struct_type == NULL)
383 {
384 rhs_named_type = rhs_type->deref()->named_type();
385 rhs_struct_type = rhs_type->deref()->struct_type();
386 is_pointer = true;
387 }
388 if (rhs_named_type != NULL)
389 first_field =
390 rhs_named_type->interface_method_table(lhs_interface_type,
391 is_pointer);
392 else if (rhs_struct_type != NULL)
393 first_field =
394 rhs_struct_type->interface_method_table(lhs_interface_type,
395 is_pointer);
396 else
397 first_field = Expression::make_nil(location);
398 }
399
400 Expression* obj;
401 if (rhs_type->is_direct_iface_type())
402 {
403 // We are assigning a pointer to the interface; the interface
404 // holds the pointer itself.
405 obj = unpack_direct_iface(rhs, location);
406 }
407 else
408 {
409 // We are assigning a non-pointer value to the interface; the
410 // interface gets a copy of the value in the heap if it escapes.
411 if (rhs->is_constant())
412 obj = Expression::make_unary(OPERATOR_AND, rhs, location);
413 else
414 {
415 obj = Expression::make_heap_expression(rhs, location);
416 if (on_stack)
417 obj->heap_expression()->set_allocate_on_stack();
418 }
419 }
420
421 return Expression::make_interface_value(lhs_type, first_field, obj, location);
422 }
423
424 // Return an expression for the pointer-typed value of a direct interface
425 // type. Specifically, for single field struct or array, get the single
426 // field, and do this recursively. The reason for this is that we don't
427 // want to assign a struct or an array to a pointer-typed field. The
428 // backend may not like that.
429
430 Expression*
unpack_direct_iface(Expression * rhs,Location loc)431 Expression::unpack_direct_iface(Expression* rhs, Location loc)
432 {
433 Struct_type* st = rhs->type()->struct_type();
434 if (st != NULL)
435 {
436 go_assert(st->field_count() == 1);
437 Expression* field = Expression::make_field_reference(rhs, 0, loc);
438 return unpack_direct_iface(field, loc);
439 }
440 Array_type* at = rhs->type()->array_type();
441 if (at != NULL)
442 {
443 int64_t len;
444 bool ok = at->int_length(&len);
445 go_assert(ok && len == 1);
446 Type* int_type = Type::lookup_integer_type("int");
447 Expression* index = Expression::make_integer_ul(0, int_type, loc);
448 Expression* elem = Expression::make_array_index(rhs, index, NULL, NULL, loc);
449 return unpack_direct_iface(elem, loc);
450 }
451 return rhs;
452 }
453
454 // The opposite of unpack_direct_iface.
455
456 Expression*
pack_direct_iface(Type * t,Expression * rhs,Location loc)457 Expression::pack_direct_iface(Type* t, Expression* rhs, Location loc)
458 {
459 if (rhs->type() == t)
460 return rhs;
461 Struct_type* st = t->struct_type();
462 if (st != NULL)
463 {
464 Expression_list* vals = new Expression_list();
465 vals->push_back(pack_direct_iface(st->field(0)->type(), rhs, loc));
466 return Expression::make_struct_composite_literal(t, vals, loc);
467 }
468 Array_type* at = t->array_type();
469 if (at != NULL)
470 {
471 Expression_list* vals = new Expression_list();
472 vals->push_back(pack_direct_iface(at->element_type(), rhs, loc));
473 return Expression::make_array_composite_literal(t, vals, loc);
474 }
475 return Expression::make_unsafe_cast(t, rhs, loc);
476 }
477
478 // Return an expression for the type descriptor of RHS.
479
480 Expression*
get_interface_type_descriptor(Expression * rhs)481 Expression::get_interface_type_descriptor(Expression* rhs)
482 {
483 go_assert(rhs->type()->interface_type() != NULL);
484 Location location = rhs->location();
485
486 // The type descriptor is the first field of an empty interface.
487 if (rhs->type()->interface_type()->is_empty())
488 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
489 location);
490
491 Expression* mtable =
492 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
493
494 Expression* descriptor =
495 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
496 descriptor = Expression::make_field_reference(descriptor, 0, location);
497 Expression* nil = Expression::make_nil(location);
498
499 Expression* eq =
500 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
501 return Expression::make_conditional(eq, nil, descriptor, location);
502 }
503
504 // Return an expression for the conversion of an interface type to an
505 // interface type.
506
507 Expression*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)508 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
509 bool for_type_guard,
510 Location location)
511 {
512 if (Type::are_identical(lhs_type, rhs->type(),
513 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
514 NULL))
515 return rhs;
516
517 Interface_type* lhs_interface_type = lhs_type->interface_type();
518 bool lhs_is_empty = lhs_interface_type->is_empty();
519
520 // In the general case this requires runtime examination of the type
521 // method table to match it up with the interface methods.
522
523 // FIXME: If all of the methods in the right hand side interface
524 // also appear in the left hand side interface, then we don't need
525 // to do a runtime check, although we still need to build a new
526 // method table.
527
528 // We are going to evaluate RHS multiple times.
529 go_assert(rhs->is_multi_eval_safe());
530
531 // Get the type descriptor for the right hand side. This will be
532 // NULL for a nil interface.
533 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
534 Expression* lhs_type_expr =
535 Expression::make_type_descriptor(lhs_type, location);
536
537 Expression* first_field;
538 if (for_type_guard)
539 {
540 // A type assertion fails when converting a nil interface.
541 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
542 lhs_type_expr, rhs_type_expr);
543 }
544 else if (lhs_is_empty)
545 {
546 // A conversion to an empty interface always succeeds, and the
547 // first field is just the type descriptor of the object.
548 first_field = rhs_type_expr;
549 }
550 else
551 {
552 // A conversion to a non-empty interface may fail, but unlike a
553 // type assertion converting nil will always succeed.
554 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
555 lhs_type_expr, rhs_type_expr);
556 }
557
558 // The second field is simply the object pointer.
559 Expression* obj =
560 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
561 return Expression::make_interface_value(lhs_type, first_field, obj, location);
562 }
563
564 // Return an expression for the conversion of an interface type to a
565 // non-interface type.
566
567 Expression*
convert_interface_to_type(Gogo * gogo,Type * lhs_type,Expression * rhs,Location location)568 Expression::convert_interface_to_type(Gogo* gogo, Type *lhs_type, Expression* rhs,
569 Location location)
570 {
571 // We are going to evaluate RHS multiple times.
572 go_assert(rhs->is_multi_eval_safe());
573
574 // Build an expression to check that the type is valid. It will
575 // panic with an appropriate runtime type error if the type is not
576 // valid.
577 // (lhs_type == rhs_type ? nil /*dummy*/ :
578 // panicdottype(lhs_type, rhs_type, inter_type))
579 // For some Oses, we need to call runtime.eqtype instead of
580 // lhs_type == rhs_type, as we may have unmerged type descriptors
581 // from shared libraries.
582 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
583 location);
584 Expression* rhs_descriptor =
585 Expression::get_interface_type_descriptor(rhs);
586
587 Type* rhs_type = rhs->type();
588 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
589 location);
590
591 Expression* cond;
592 if (gogo->need_eqtype()) {
593 cond = Runtime::make_call(Runtime::EQTYPE, location,
594 2, lhs_type_expr,
595 rhs_descriptor);
596 } else {
597 cond = Expression::make_binary(OPERATOR_EQEQ, lhs_type_expr,
598 rhs_descriptor, location);
599 }
600
601 rhs_descriptor = Expression::get_interface_type_descriptor(rhs);
602 Expression* panic = Runtime::make_call(Runtime::PANICDOTTYPE, location,
603 3, lhs_type_expr->copy(),
604 rhs_descriptor,
605 rhs_inter_expr);
606 Expression* nil = Expression::make_nil(location);
607 Expression* check = Expression::make_conditional(cond, nil, panic,
608 location);
609
610 // If the conversion succeeds, pull out the value.
611 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
612 location);
613
614 // If the value is a direct interface, then it is the value we want.
615 // Otherwise it points to the value.
616 if (lhs_type->is_direct_iface_type())
617 obj = Expression::pack_direct_iface(lhs_type, obj, location);
618 else
619 {
620 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
621 location);
622 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
623 location);
624 }
625 return Expression::make_compound(check, obj, location);
626 }
627
628 // Convert an expression to its backend representation. This is implemented by
629 // the child class. Not that it is not in general safe to call this multiple
630 // times for a single expression, but that we don't catch such errors.
631
632 Bexpression*
get_backend(Translate_context * context)633 Expression::get_backend(Translate_context* context)
634 {
635 // The child may have marked this expression as having an error.
636 if (this->classification_ == EXPRESSION_ERROR)
637 {
638 go_assert(saw_errors());
639 return context->backend()->error_expression();
640 }
641
642 return this->do_get_backend(context);
643 }
644
645 // Return a backend expression for VAL.
646 Bexpression*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)647 Expression::backend_numeric_constant_expression(Translate_context* context,
648 Numeric_constant* val)
649 {
650 Gogo* gogo = context->gogo();
651 Type* type = val->type();
652 if (type == NULL)
653 return gogo->backend()->error_expression();
654
655 Btype* btype = type->get_backend(gogo);
656 Bexpression* ret;
657 if (type->integer_type() != NULL)
658 {
659 mpz_t ival;
660 if (!val->to_int(&ival))
661 {
662 go_assert(saw_errors());
663 return gogo->backend()->error_expression();
664 }
665 ret = gogo->backend()->integer_constant_expression(btype, ival);
666 mpz_clear(ival);
667 }
668 else if (type->float_type() != NULL)
669 {
670 mpfr_t fval;
671 if (!val->to_float(&fval))
672 {
673 go_assert(saw_errors());
674 return gogo->backend()->error_expression();
675 }
676 ret = gogo->backend()->float_constant_expression(btype, fval);
677 mpfr_clear(fval);
678 }
679 else if (type->complex_type() != NULL)
680 {
681 mpc_t cval;
682 if (!val->to_complex(&cval))
683 {
684 go_assert(saw_errors());
685 return gogo->backend()->error_expression();
686 }
687 ret = gogo->backend()->complex_constant_expression(btype, cval);
688 mpc_clear(cval);
689 }
690 else
691 go_unreachable();
692
693 return ret;
694 }
695
696 // Insert bounds checks for an index expression. Check that that VAL
697 // >= 0 and that it fits in an int. Then check that VAL OP BOUND is
698 // true. If any condition is false, call one of the CODE runtime
699 // functions, which will panic.
700
701 void
check_bounds(Expression * val,Operator op,Expression * bound,Runtime::Function code,Runtime::Function code_u,Runtime::Function code_extend,Runtime::Function code_extend_u,Statement_inserter * inserter,Location loc)702 Expression::check_bounds(Expression* val, Operator op, Expression* bound,
703 Runtime::Function code,
704 Runtime::Function code_u,
705 Runtime::Function code_extend,
706 Runtime::Function code_extend_u,
707 Statement_inserter* inserter,
708 Location loc)
709 {
710 go_assert(val->is_multi_eval_safe());
711 go_assert(bound->is_multi_eval_safe());
712
713 Type* int_type = Type::lookup_integer_type("int");
714 int int_type_size = int_type->integer_type()->bits();
715
716 Type* val_type = val->type();
717 if (val_type->integer_type() == NULL)
718 {
719 go_assert(saw_errors());
720 return;
721 }
722 int val_type_size = val_type->integer_type()->bits();
723 bool val_is_unsigned = val_type->integer_type()->is_unsigned();
724
725 // Check that VAL >= 0.
726 Expression* check = NULL;
727 if (!val_is_unsigned)
728 {
729 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
730 check = Expression::make_binary(OPERATOR_GE, val->copy(), zero, loc);
731 }
732
733 // If VAL's type is larger than int, check that VAL fits in an int.
734 if (val_type_size > int_type_size
735 || (val_type_size == int_type_size
736 && val_is_unsigned))
737 {
738 mpz_t one;
739 mpz_init_set_ui(one, 1UL);
740
741 // maxval = 2^(int_type_size - 1) - 1
742 mpz_t maxval;
743 mpz_init(maxval);
744 mpz_mul_2exp(maxval, one, int_type_size - 1);
745 mpz_sub_ui(maxval, maxval, 1);
746 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
747 mpz_clear(one);
748 mpz_clear(maxval);
749
750 Expression* cmp = Expression::make_binary(OPERATOR_LE, val->copy(),
751 max, loc);
752 if (check == NULL)
753 check = cmp;
754 else
755 check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
756 }
757
758 // For the final check we can assume that VAL fits in an int.
759 Expression* ival;
760 if (val_type == int_type)
761 ival = val->copy();
762 else
763 ival = Expression::make_cast(int_type, val->copy(), loc);
764
765 // BOUND is assumed to fit in an int. Either it comes from len or
766 // cap, or it was checked by an earlier call.
767 Expression* ibound;
768 if (bound->type() == int_type)
769 ibound = bound->copy();
770 else
771 ibound = Expression::make_cast(int_type, bound->copy(), loc);
772
773 Expression* cmp = Expression::make_binary(op, ival, ibound, loc);
774 if (check == NULL)
775 check = cmp;
776 else
777 check = Expression::make_binary(OPERATOR_ANDAND, check, cmp, loc);
778
779 Runtime::Function c;
780 if (val_type_size > int_type_size)
781 {
782 if (val_is_unsigned)
783 c = code_extend_u;
784 else
785 c = code_extend;
786 }
787 else
788 {
789 if (val_is_unsigned)
790 c = code_u;
791 else
792 c = code;
793 }
794
795 Expression* ignore = Expression::make_boolean(true, loc);
796 Expression* crash = Runtime::make_call(c, loc, 2,
797 val->copy(), bound->copy());
798 Expression* cond = Expression::make_conditional(check, ignore, crash, loc);
799 inserter->insert(Statement::make_statement(cond, true));
800 }
801
802 void
dump_expression(Ast_dump_context * ast_dump_context) const803 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
804 {
805 this->do_dump_expression(ast_dump_context);
806 }
807
808 // Error expressions. This are used to avoid cascading errors.
809
810 class Error_expression : public Expression
811 {
812 public:
Error_expression(Location location)813 Error_expression(Location location)
814 : Expression(EXPRESSION_ERROR, location)
815 { }
816
817 protected:
818 bool
do_is_constant() const819 do_is_constant() const
820 { return true; }
821
822 bool
do_numeric_constant_value(Numeric_constant * nc) const823 do_numeric_constant_value(Numeric_constant* nc) const
824 {
825 nc->set_unsigned_long(NULL, 0);
826 return true;
827 }
828
829 bool
do_discarding_value()830 do_discarding_value()
831 { return true; }
832
833 Type*
do_type()834 do_type()
835 { return Type::make_error_type(); }
836
837 void
do_determine_type(const Type_context *)838 do_determine_type(const Type_context*)
839 { }
840
841 Expression*
do_copy()842 do_copy()
843 { return this; }
844
845 bool
do_is_addressable() const846 do_is_addressable() const
847 { return true; }
848
849 Bexpression*
do_get_backend(Translate_context * context)850 do_get_backend(Translate_context* context)
851 { return context->backend()->error_expression(); }
852
853 void
854 do_dump_expression(Ast_dump_context*) const;
855 };
856
857 // Dump the ast representation for an error expression to a dump context.
858
859 void
do_dump_expression(Ast_dump_context * ast_dump_context) const860 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
861 {
862 ast_dump_context->ostream() << "_Error_" ;
863 }
864
865 Expression*
make_error(Location location)866 Expression::make_error(Location location)
867 {
868 return new Error_expression(location);
869 }
870
871 // An expression which is really a type. This is used during parsing.
872 // It is an error if these survive after lowering.
873
874 class
875 Type_expression : public Expression
876 {
877 public:
Type_expression(Type * type,Location location)878 Type_expression(Type* type, Location location)
879 : Expression(EXPRESSION_TYPE, location),
880 type_(type)
881 { }
882
883 protected:
884 int
do_traverse(Traverse * traverse)885 do_traverse(Traverse* traverse)
886 { return Type::traverse(this->type_, traverse); }
887
888 Type*
do_type()889 do_type()
890 { return this->type_; }
891
892 void
do_determine_type(const Type_context *)893 do_determine_type(const Type_context*)
894 { }
895
896 void
897 do_check_types(Gogo*);
898
899 Expression*
do_copy()900 do_copy()
901 { return this; }
902
903 Bexpression*
do_get_backend(Translate_context *)904 do_get_backend(Translate_context*)
905 { go_unreachable(); }
906
907 void do_dump_expression(Ast_dump_context*) const;
908
909 private:
910 // The type which we are representing as an expression.
911 Type* type_;
912 };
913
914 void
do_check_types(Gogo *)915 Type_expression::do_check_types(Gogo*)
916 {
917 if (this->type_->is_error())
918 {
919 go_assert(saw_errors());
920 this->set_is_error();
921 }
922 else
923 this->report_error(_("invalid use of type"));
924 }
925
926 void
do_dump_expression(Ast_dump_context * ast_dump_context) const927 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
928 {
929 ast_dump_context->dump_type(this->type_);
930 }
931
932 Expression*
make_type(Type * type,Location location)933 Expression::make_type(Type* type, Location location)
934 {
935 return new Type_expression(type, location);
936 }
937
938 // Class Parser_expression.
939
940 Type*
do_type()941 Parser_expression::do_type()
942 {
943 // We should never really ask for the type of a Parser_expression.
944 // However, it can happen, at least when we have an invalid const
945 // whose initializer refers to the const itself. In that case we
946 // may ask for the type when lowering the const itself.
947 go_assert(saw_errors());
948 return Type::make_error_type();
949 }
950
951 // Class Var_expression.
952
953 // Lower a variable expression. Here we just make sure that the
954 // initialization expression of the variable has been lowered. This
955 // ensures that we will be able to determine the type of the variable
956 // if necessary.
957
958 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)959 Var_expression::do_lower(Gogo* gogo, Named_object* function,
960 Statement_inserter* inserter, int)
961 {
962 if (this->variable_->is_variable())
963 {
964 Variable* var = this->variable_->var_value();
965 // This is either a local variable or a global variable. A
966 // reference to a variable which is local to an enclosing
967 // function will be a reference to a field in a closure.
968 if (var->is_global())
969 {
970 function = NULL;
971 inserter = NULL;
972 }
973 var->lower_init_expression(gogo, function, inserter);
974 }
975 return this;
976 }
977
978 // Return the type of a reference to a variable.
979
980 Type*
do_type()981 Var_expression::do_type()
982 {
983 if (this->variable_->is_variable())
984 return this->variable_->var_value()->type();
985 else if (this->variable_->is_result_variable())
986 return this->variable_->result_var_value()->type();
987 else
988 go_unreachable();
989 }
990
991 // Determine the type of a reference to a variable.
992
993 void
do_determine_type(const Type_context *)994 Var_expression::do_determine_type(const Type_context*)
995 {
996 if (this->variable_->is_variable())
997 this->variable_->var_value()->determine_type();
998 }
999
1000 // Something takes the address of this variable. This means that we
1001 // may want to move the variable onto the heap.
1002
1003 void
do_address_taken(bool escapes)1004 Var_expression::do_address_taken(bool escapes)
1005 {
1006 if (!escapes)
1007 {
1008 if (this->variable_->is_variable())
1009 this->variable_->var_value()->set_non_escaping_address_taken();
1010 else if (this->variable_->is_result_variable())
1011 this->variable_->result_var_value()->set_non_escaping_address_taken();
1012 else
1013 go_unreachable();
1014 }
1015 else
1016 {
1017 if (this->variable_->is_variable())
1018 this->variable_->var_value()->set_address_taken();
1019 else if (this->variable_->is_result_variable())
1020 this->variable_->result_var_value()->set_address_taken();
1021 else
1022 go_unreachable();
1023 }
1024
1025 if (this->variable_->is_variable()
1026 && this->variable_->var_value()->is_in_heap())
1027 {
1028 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
1029 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1030 }
1031 }
1032
1033 // Export a reference to a variable.
1034
1035 void
do_export(Export_function_body * efb) const1036 Var_expression::do_export(Export_function_body* efb) const
1037 {
1038 Named_object* no = this->variable_;
1039 if (no->is_result_variable() || !no->var_value()->is_global())
1040 efb->write_string(Gogo::unpack_hidden_name(no->name()));
1041 else
1042 Expression::export_name(efb, no);
1043 }
1044
1045 // Get the backend representation for a reference to a variable.
1046
1047 Bexpression*
do_get_backend(Translate_context * context)1048 Var_expression::do_get_backend(Translate_context* context)
1049 {
1050 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
1051 context->function());
1052 bool is_in_heap;
1053 Location loc = this->location();
1054 Btype* btype;
1055 Gogo* gogo = context->gogo();
1056 if (this->variable_->is_variable())
1057 {
1058 is_in_heap = this->variable_->var_value()->is_in_heap();
1059 btype = this->variable_->var_value()->type()->get_backend(gogo);
1060 }
1061 else if (this->variable_->is_result_variable())
1062 {
1063 is_in_heap = this->variable_->result_var_value()->is_in_heap();
1064 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
1065 }
1066 else
1067 go_unreachable();
1068
1069 Bexpression* ret =
1070 context->backend()->var_expression(bvar, loc);
1071 if (is_in_heap)
1072 ret = context->backend()->indirect_expression(btype, ret, true, loc);
1073 return ret;
1074 }
1075
1076 // Ast dump for variable expression.
1077
1078 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1079 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1080 {
1081 ast_dump_context->ostream() << this->variable_->message_name() ;
1082 }
1083
1084 // Make a reference to a variable in an expression.
1085
1086 Expression*
make_var_reference(Named_object * var,Location location)1087 Expression::make_var_reference(Named_object* var, Location location)
1088 {
1089 if (var->is_sink())
1090 return Expression::make_sink(location);
1091
1092 // FIXME: Creating a new object for each reference to a variable is
1093 // wasteful.
1094 return new Var_expression(var, location);
1095 }
1096
1097 // Class Enclosed_var_expression.
1098
1099 int
do_traverse(Traverse *)1100 Enclosed_var_expression::do_traverse(Traverse*)
1101 {
1102 return TRAVERSE_CONTINUE;
1103 }
1104
1105 // Lower the reference to the enclosed variable.
1106
1107 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)1108 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
1109 Statement_inserter* inserter, int)
1110 {
1111 gogo->lower_expression(function, inserter, &this->reference_);
1112 return this;
1113 }
1114
1115 // Flatten the reference to the enclosed variable.
1116
1117 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)1118 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
1119 Statement_inserter* inserter)
1120 {
1121 gogo->flatten_expression(function, inserter, &this->reference_);
1122 return this;
1123 }
1124
1125 void
do_address_taken(bool escapes)1126 Enclosed_var_expression::do_address_taken(bool escapes)
1127 {
1128 if (!escapes)
1129 {
1130 if (this->variable_->is_variable())
1131 this->variable_->var_value()->set_non_escaping_address_taken();
1132 else if (this->variable_->is_result_variable())
1133 this->variable_->result_var_value()->set_non_escaping_address_taken();
1134 else
1135 go_unreachable();
1136 }
1137 else
1138 {
1139 if (this->variable_->is_variable())
1140 this->variable_->var_value()->set_address_taken();
1141 else if (this->variable_->is_result_variable())
1142 this->variable_->result_var_value()->set_address_taken();
1143 else
1144 go_unreachable();
1145 }
1146
1147 if (this->variable_->is_variable()
1148 && this->variable_->var_value()->is_in_heap())
1149 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
1150 }
1151
1152 // Ast dump for enclosed variable expression.
1153
1154 void
do_dump_expression(Ast_dump_context * adc) const1155 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
1156 {
1157 adc->ostream() << this->variable_->message_name();
1158 }
1159
1160 // Make a reference to a variable within an enclosing function.
1161
1162 Expression*
make_enclosing_var_reference(Expression * reference,Named_object * var,Location location)1163 Expression::make_enclosing_var_reference(Expression* reference,
1164 Named_object* var, Location location)
1165 {
1166 return new Enclosed_var_expression(reference, var, location);
1167 }
1168
1169 // Class Temporary_reference_expression.
1170
1171 // The type.
1172
1173 Type*
do_type()1174 Temporary_reference_expression::do_type()
1175 {
1176 return this->statement_->type();
1177 }
1178
1179 // Called if something takes the address of this temporary variable.
1180 // We never have to move temporary variables to the heap, but we do
1181 // need to know that they must live in the stack rather than in a
1182 // register.
1183
1184 void
do_address_taken(bool)1185 Temporary_reference_expression::do_address_taken(bool)
1186 {
1187 this->statement_->set_is_address_taken();
1188 }
1189
1190 // Export a reference to a temporary.
1191
1192 void
do_export(Export_function_body * efb) const1193 Temporary_reference_expression::do_export(Export_function_body* efb) const
1194 {
1195 unsigned int idx = efb->temporary_index(this->statement_);
1196 char buf[50];
1197 snprintf(buf, sizeof buf, "$t%u", idx);
1198 efb->write_c_string(buf);
1199 }
1200
1201 // Import a reference to a temporary.
1202
1203 Expression*
do_import(Import_function_body * ifb,Location loc)1204 Temporary_reference_expression::do_import(Import_function_body* ifb,
1205 Location loc)
1206 {
1207 std::string id = ifb->read_identifier();
1208 go_assert(id[0] == '$' && id[1] == 't');
1209 const char *p = id.c_str();
1210 char *end;
1211 long idx = strtol(p + 2, &end, 10);
1212 if (*end != '\0' || idx > 0x7fffffff)
1213 {
1214 if (!ifb->saw_error())
1215 go_error_at(loc,
1216 ("invalid export data for %qs: "
1217 "invalid temporary reference index at %lu"),
1218 ifb->name().c_str(),
1219 static_cast<unsigned long>(ifb->off()));
1220 ifb->set_saw_error();
1221 return Expression::make_error(loc);
1222 }
1223
1224 Temporary_statement* temp =
1225 ifb->temporary_statement(static_cast<unsigned int>(idx));
1226 if (temp == NULL)
1227 {
1228 if (!ifb->saw_error())
1229 go_error_at(loc,
1230 ("invalid export data for %qs: "
1231 "undefined temporary reference index at %lu"),
1232 ifb->name().c_str(),
1233 static_cast<unsigned long>(ifb->off()));
1234 ifb->set_saw_error();
1235 return Expression::make_error(loc);
1236 }
1237
1238 return Expression::make_temporary_reference(temp, loc);
1239 }
1240
1241 // Get a backend expression referring to the variable.
1242
1243 Bexpression*
do_get_backend(Translate_context * context)1244 Temporary_reference_expression::do_get_backend(Translate_context* context)
1245 {
1246 Gogo* gogo = context->gogo();
1247 Bvariable* bvar = this->statement_->get_backend_variable(context);
1248 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
1249
1250 // The backend can't always represent the same set of recursive types
1251 // that the Go frontend can. In some cases this means that a
1252 // temporary variable won't have the right backend type. Correct
1253 // that here by adding a type cast. We need to use base() to push
1254 // the circularity down one level.
1255 Type* stype = this->statement_->type();
1256 if (!this->is_lvalue_
1257 && stype->points_to() != NULL
1258 && stype->points_to()->is_void_type())
1259 {
1260 Btype* btype = this->type()->base()->get_backend(gogo);
1261 ret = gogo->backend()->convert_expression(btype, ret, this->location());
1262 }
1263 return ret;
1264 }
1265
1266 // Ast dump for temporary reference.
1267
1268 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1269 Temporary_reference_expression::do_dump_expression(
1270 Ast_dump_context* ast_dump_context) const
1271 {
1272 ast_dump_context->dump_temp_variable_name(this->statement_);
1273 }
1274
1275 // Make a reference to a temporary variable.
1276
1277 Temporary_reference_expression*
make_temporary_reference(Temporary_statement * statement,Location location)1278 Expression::make_temporary_reference(Temporary_statement* statement,
1279 Location location)
1280 {
1281 statement->add_use();
1282 return new Temporary_reference_expression(statement, location);
1283 }
1284
1285 // Class Set_and_use_temporary_expression.
1286
1287 // Return the type.
1288
1289 Type*
do_type()1290 Set_and_use_temporary_expression::do_type()
1291 {
1292 return this->statement_->type();
1293 }
1294
1295 // Determine the type of the expression.
1296
1297 void
do_determine_type(const Type_context * context)1298 Set_and_use_temporary_expression::do_determine_type(
1299 const Type_context* context)
1300 {
1301 this->expr_->determine_type(context);
1302 }
1303
1304 // Take the address.
1305
1306 void
do_address_taken(bool)1307 Set_and_use_temporary_expression::do_address_taken(bool)
1308 {
1309 this->statement_->set_is_address_taken();
1310 }
1311
1312 // Return the backend representation.
1313
1314 Bexpression*
do_get_backend(Translate_context * context)1315 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
1316 {
1317 Location loc = this->location();
1318 Gogo* gogo = context->gogo();
1319 Bvariable* bvar = this->statement_->get_backend_variable(context);
1320 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
1321
1322 Named_object* fn = context->function();
1323 go_assert(fn != NULL);
1324 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
1325 Bexpression* bexpr = this->expr_->get_backend(context);
1326 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
1327 bexpr, loc);
1328 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
1329 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
1330 return ret;
1331 }
1332
1333 // Dump.
1334
1335 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1336 Set_and_use_temporary_expression::do_dump_expression(
1337 Ast_dump_context* ast_dump_context) const
1338 {
1339 ast_dump_context->ostream() << '(';
1340 ast_dump_context->dump_temp_variable_name(this->statement_);
1341 ast_dump_context->ostream() << " = ";
1342 this->expr_->dump_expression(ast_dump_context);
1343 ast_dump_context->ostream() << ')';
1344 }
1345
1346 // Make a set-and-use temporary.
1347
1348 Set_and_use_temporary_expression*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)1349 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1350 Expression* expr, Location location)
1351 {
1352 return new Set_and_use_temporary_expression(statement, expr, location);
1353 }
1354
1355 // A sink expression--a use of the blank identifier _.
1356
1357 class Sink_expression : public Expression
1358 {
1359 public:
Sink_expression(Location location)1360 Sink_expression(Location location)
1361 : Expression(EXPRESSION_SINK, location),
1362 type_(NULL), bvar_(NULL)
1363 { }
1364
1365 protected:
1366 bool
do_discarding_value()1367 do_discarding_value()
1368 { return true; }
1369
1370 Type*
1371 do_type();
1372
1373 void
1374 do_determine_type(const Type_context*);
1375
1376 Expression*
do_copy()1377 do_copy()
1378 { return new Sink_expression(this->location()); }
1379
1380 Bexpression*
1381 do_get_backend(Translate_context*);
1382
1383 void
1384 do_dump_expression(Ast_dump_context*) const;
1385
1386 private:
1387 // The type of this sink variable.
1388 Type* type_;
1389 // The temporary variable we generate.
1390 Bvariable* bvar_;
1391 };
1392
1393 // Return the type of a sink expression.
1394
1395 Type*
do_type()1396 Sink_expression::do_type()
1397 {
1398 if (this->type_ == NULL)
1399 return Type::make_sink_type();
1400 return this->type_;
1401 }
1402
1403 // Determine the type of a sink expression.
1404
1405 void
do_determine_type(const Type_context * context)1406 Sink_expression::do_determine_type(const Type_context* context)
1407 {
1408 if (context->type != NULL)
1409 this->type_ = context->type;
1410 }
1411
1412 // Return a temporary variable for a sink expression. This will
1413 // presumably be a write-only variable which the middle-end will drop.
1414
1415 Bexpression*
do_get_backend(Translate_context * context)1416 Sink_expression::do_get_backend(Translate_context* context)
1417 {
1418 Location loc = this->location();
1419 Gogo* gogo = context->gogo();
1420 if (this->bvar_ == NULL)
1421 {
1422 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1423 Named_object* fn = context->function();
1424 go_assert(fn != NULL);
1425 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1426 Btype* bt = this->type_->get_backend(context->gogo());
1427 Bstatement* decl;
1428 this->bvar_ =
1429 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1430 false, loc, &decl);
1431 Bexpression* var_ref =
1432 gogo->backend()->var_expression(this->bvar_, loc);
1433 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1434 return var_ref;
1435 }
1436 return gogo->backend()->var_expression(this->bvar_, loc);
1437 }
1438
1439 // Ast dump for sink expression.
1440
1441 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1442 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1443 {
1444 ast_dump_context->ostream() << "_" ;
1445 }
1446
1447 // Make a sink expression.
1448
1449 Expression*
make_sink(Location location)1450 Expression::make_sink(Location location)
1451 {
1452 return new Sink_expression(location);
1453 }
1454
1455 // Class Func_expression.
1456
1457 // FIXME: Can a function expression appear in a constant expression?
1458 // The value is unchanging. Initializing a constant to the address of
1459 // a function seems like it could work, though there might be little
1460 // point to it.
1461
1462 // Traversal.
1463
1464 int
do_traverse(Traverse * traverse)1465 Func_expression::do_traverse(Traverse* traverse)
1466 {
1467 return (this->closure_ == NULL
1468 ? TRAVERSE_CONTINUE
1469 : Expression::traverse(&this->closure_, traverse));
1470 }
1471
1472 // Return the type of a function expression.
1473
1474 Type*
do_type()1475 Func_expression::do_type()
1476 {
1477 if (this->function_->is_function())
1478 return this->function_->func_value()->type();
1479 else if (this->function_->is_function_declaration())
1480 return this->function_->func_declaration_value()->type();
1481 else
1482 go_unreachable();
1483 }
1484
1485 // Get the backend representation for the code of a function expression.
1486
1487 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1488 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1489 {
1490 Function_type* fntype;
1491 if (no->is_function())
1492 fntype = no->func_value()->type();
1493 else if (no->is_function_declaration())
1494 fntype = no->func_declaration_value()->type();
1495 else
1496 go_unreachable();
1497
1498 // Builtin functions are handled specially by Call_expression. We
1499 // can't take their address.
1500 if (fntype->is_builtin())
1501 {
1502 go_error_at(loc,
1503 ("invalid use of special built-in function %qs; "
1504 "must be called"),
1505 no->message_name().c_str());
1506 return gogo->backend()->error_expression();
1507 }
1508
1509 Bfunction* fndecl;
1510 if (no->is_function())
1511 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1512 else if (no->is_function_declaration())
1513 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1514 else
1515 go_unreachable();
1516
1517 return gogo->backend()->function_code_expression(fndecl, loc);
1518 }
1519
1520 // Get the backend representation for a function expression. This is used when
1521 // we take the address of a function rather than simply calling it. A func
1522 // value is represented as a pointer to a block of memory. The first
1523 // word of that memory is a pointer to the function code. The
1524 // remaining parts of that memory are the addresses of variables that
1525 // the function closes over.
1526
1527 Bexpression*
do_get_backend(Translate_context * context)1528 Func_expression::do_get_backend(Translate_context* context)
1529 {
1530 // If there is no closure, just use the function descriptor.
1531 if (this->closure_ == NULL)
1532 {
1533 Gogo* gogo = context->gogo();
1534 Named_object* no = this->function_;
1535 Expression* descriptor;
1536 if (no->is_function())
1537 descriptor = no->func_value()->descriptor(gogo, no);
1538 else if (no->is_function_declaration())
1539 {
1540 if (no->func_declaration_value()->type()->is_builtin())
1541 {
1542 go_error_at(this->location(),
1543 ("invalid use of special built-in function %qs; "
1544 "must be called"),
1545 no->message_name().c_str());
1546 return gogo->backend()->error_expression();
1547 }
1548 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1549 }
1550 else
1551 go_unreachable();
1552
1553 Bexpression* bdesc = descriptor->get_backend(context);
1554 return gogo->backend()->address_expression(bdesc, this->location());
1555 }
1556
1557 go_assert(this->function_->func_value()->enclosing() != NULL);
1558
1559 // If there is a closure, then the closure is itself the function
1560 // expression. It is a pointer to a struct whose first field points
1561 // to the function code and whose remaining fields are the addresses
1562 // of the closed-over variables.
1563 Bexpression *bexpr = this->closure_->get_backend(context);
1564
1565 // Introduce a backend type conversion, to account for any differences
1566 // between the argument type (function descriptor, struct with a
1567 // single field) and the closure (struct with multiple fields).
1568 Gogo* gogo = context->gogo();
1569 Btype *btype = this->type()->get_backend(gogo);
1570 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1571 }
1572
1573 // The cost of inlining a function reference.
1574
1575 int
do_inlining_cost() const1576 Func_expression::do_inlining_cost() const
1577 {
1578 // FIXME: We don't inline references to nested functions.
1579 if (this->closure_ != NULL)
1580 return 0x100000;
1581 if (this->function_->is_function()
1582 && this->function_->func_value()->enclosing() != NULL)
1583 return 0x100000;
1584
1585 return 1;
1586 }
1587
1588 // Export a reference to a function.
1589
1590 void
do_export(Export_function_body * efb) const1591 Func_expression::do_export(Export_function_body* efb) const
1592 {
1593 Expression::export_name(efb, this->function_);
1594 }
1595
1596 // Ast dump for function.
1597
1598 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1599 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1600 {
1601 ast_dump_context->ostream() << this->function_->name();
1602 if (this->closure_ != NULL)
1603 {
1604 ast_dump_context->ostream() << " {closure = ";
1605 this->closure_->dump_expression(ast_dump_context);
1606 ast_dump_context->ostream() << "}";
1607 }
1608 }
1609
1610 // Make a reference to a function in an expression.
1611
1612 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1613 Expression::make_func_reference(Named_object* function, Expression* closure,
1614 Location location)
1615 {
1616 Func_expression* fe = new Func_expression(function, closure, location);
1617
1618 // Detect references to builtin functions and set the runtime code if
1619 // appropriate.
1620 if (function->is_function_declaration())
1621 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1622 return fe;
1623 }
1624
1625 // Class Func_descriptor_expression.
1626
1627 // Constructor.
1628
Func_descriptor_expression(Named_object * fn)1629 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1630 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1631 fn_(fn), dvar_(NULL)
1632 {
1633 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1634 }
1635
1636 // Traversal.
1637
1638 int
do_traverse(Traverse *)1639 Func_descriptor_expression::do_traverse(Traverse*)
1640 {
1641 return TRAVERSE_CONTINUE;
1642 }
1643
1644 // All function descriptors have the same type.
1645
1646 Type* Func_descriptor_expression::descriptor_type;
1647
1648 void
make_func_descriptor_type()1649 Func_descriptor_expression::make_func_descriptor_type()
1650 {
1651 if (Func_descriptor_expression::descriptor_type != NULL)
1652 return;
1653 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1654 Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1655 Func_descriptor_expression::descriptor_type =
1656 Type::make_builtin_named_type("functionDescriptor", struct_type);
1657 }
1658
1659 Type*
do_type()1660 Func_descriptor_expression::do_type()
1661 {
1662 Func_descriptor_expression::make_func_descriptor_type();
1663 return Func_descriptor_expression::descriptor_type;
1664 }
1665
1666 // The backend representation for a function descriptor.
1667
1668 Bexpression*
do_get_backend(Translate_context * context)1669 Func_descriptor_expression::do_get_backend(Translate_context* context)
1670 {
1671 Named_object* no = this->fn_;
1672 Location loc = no->location();
1673 if (this->dvar_ != NULL)
1674 return context->backend()->var_expression(this->dvar_, loc);
1675
1676 Gogo* gogo = context->gogo();
1677 Backend_name bname;
1678 gogo->function_descriptor_backend_name(no, &bname);
1679 bool is_descriptor = false;
1680 if (no->is_function_declaration()
1681 && !no->func_declaration_value()->asm_name().empty()
1682 && Linemap::is_predeclared_location(no->location()))
1683 is_descriptor = true;
1684
1685 // The runtime package implements some functions defined in the
1686 // syscall package. Let the syscall package define the descriptor
1687 // in this case.
1688 if (gogo->compiling_runtime()
1689 && gogo->package_name() == "runtime"
1690 && no->is_function()
1691 && !no->func_value()->asm_name().empty()
1692 && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1693 is_descriptor = true;
1694
1695 Btype* btype = this->type()->get_backend(gogo);
1696
1697 Bvariable* bvar;
1698 if (no->package() != NULL || is_descriptor)
1699 bvar =
1700 context->backend()->immutable_struct_reference(bname.name(),
1701 bname.optional_asm_name(),
1702 btype, loc);
1703 else
1704 {
1705 Location bloc = Linemap::predeclared_location();
1706
1707 // The runtime package has hash/equality functions that are
1708 // referenced by type descriptors outside of the runtime, so the
1709 // function descriptors must be visible even though they are not
1710 // exported.
1711 bool is_exported_runtime = false;
1712 if (gogo->compiling_runtime()
1713 && gogo->package_name() == "runtime"
1714 && (no->name().find("hash") != std::string::npos
1715 || no->name().find("equal") != std::string::npos))
1716 is_exported_runtime = true;
1717
1718 bool is_hidden = ((no->is_function()
1719 && no->func_value()->enclosing() != NULL)
1720 || (Gogo::is_hidden_name(no->name())
1721 && !is_exported_runtime)
1722 || Gogo::is_thunk(no));
1723
1724 if (no->is_function() && no->func_value()->is_referenced_by_inline())
1725 is_hidden = false;
1726
1727 bvar = context->backend()->immutable_struct(bname.name(),
1728 bname.optional_asm_name(),
1729 is_hidden, false,
1730 btype, bloc);
1731 Expression_list* vals = new Expression_list();
1732 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1733 Expression* init =
1734 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1735 Translate_context bcontext(gogo, NULL, NULL, NULL);
1736 bcontext.set_is_const();
1737 Bexpression* binit = init->get_backend(&bcontext);
1738 context->backend()->immutable_struct_set_init(bvar, bname.name(),
1739 is_hidden, false, btype,
1740 bloc, binit);
1741 }
1742
1743 this->dvar_ = bvar;
1744 return gogo->backend()->var_expression(bvar, loc);
1745 }
1746
1747 // Print a function descriptor expression.
1748
1749 void
do_dump_expression(Ast_dump_context * context) const1750 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1751 {
1752 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1753 }
1754
1755 // Make a function descriptor expression.
1756
1757 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1758 Expression::make_func_descriptor(Named_object* fn)
1759 {
1760 return new Func_descriptor_expression(fn);
1761 }
1762
1763 // Make the function descriptor type, so that it can be converted.
1764
1765 void
make_func_descriptor_type()1766 Expression::make_func_descriptor_type()
1767 {
1768 Func_descriptor_expression::make_func_descriptor_type();
1769 }
1770
1771 // A reference to just the code of a function.
1772
1773 class Func_code_reference_expression : public Expression
1774 {
1775 public:
Func_code_reference_expression(Named_object * function,Location location)1776 Func_code_reference_expression(Named_object* function, Location location)
1777 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1778 function_(function)
1779 { }
1780
1781 protected:
1782 int
do_traverse(Traverse *)1783 do_traverse(Traverse*)
1784 { return TRAVERSE_CONTINUE; }
1785
1786 bool
do_is_static_initializer() const1787 do_is_static_initializer() const
1788 { return true; }
1789
1790 Type*
do_type()1791 do_type()
1792 { return Type::make_pointer_type(Type::make_void_type()); }
1793
1794 void
do_determine_type(const Type_context *)1795 do_determine_type(const Type_context*)
1796 { }
1797
1798 Expression*
do_copy()1799 do_copy()
1800 {
1801 return Expression::make_func_code_reference(this->function_,
1802 this->location());
1803 }
1804
1805 Bexpression*
1806 do_get_backend(Translate_context*);
1807
1808 void
do_dump_expression(Ast_dump_context * context) const1809 do_dump_expression(Ast_dump_context* context) const
1810 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1811
1812 private:
1813 // The function.
1814 Named_object* function_;
1815 };
1816
1817 // Get the backend representation for a reference to function code.
1818
1819 Bexpression*
do_get_backend(Translate_context * context)1820 Func_code_reference_expression::do_get_backend(Translate_context* context)
1821 {
1822 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1823 this->location());
1824 }
1825
1826 // Make a reference to the code of a function.
1827
1828 Expression*
make_func_code_reference(Named_object * function,Location location)1829 Expression::make_func_code_reference(Named_object* function, Location location)
1830 {
1831 return new Func_code_reference_expression(function, location);
1832 }
1833
1834 // Class Unknown_expression.
1835
1836 // Return the name of an unknown expression.
1837
1838 const std::string&
name() const1839 Unknown_expression::name() const
1840 {
1841 return this->named_object_->name();
1842 }
1843
1844 // Lower a reference to an unknown name.
1845
1846 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1847 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1848 {
1849 Location location = this->location();
1850 Named_object* no = this->named_object_;
1851 Named_object* real;
1852 if (!no->is_unknown())
1853 real = no;
1854 else
1855 {
1856 real = no->unknown_value()->real_named_object();
1857 if (real == NULL)
1858 {
1859 if (!this->no_error_message_)
1860 go_error_at(location, "reference to undefined name %qs",
1861 this->named_object_->message_name().c_str());
1862 return Expression::make_error(location);
1863 }
1864 }
1865 switch (real->classification())
1866 {
1867 case Named_object::NAMED_OBJECT_CONST:
1868 return Expression::make_const_reference(real, location);
1869 case Named_object::NAMED_OBJECT_TYPE:
1870 return Expression::make_type(real->type_value(), location);
1871 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1872 if (!this->no_error_message_)
1873 go_error_at(location, "reference to undefined type %qs",
1874 real->message_name().c_str());
1875 return Expression::make_error(location);
1876 case Named_object::NAMED_OBJECT_VAR:
1877 real->var_value()->set_is_used();
1878 return Expression::make_var_reference(real, location);
1879 case Named_object::NAMED_OBJECT_FUNC:
1880 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1881 return Expression::make_func_reference(real, NULL, location);
1882 case Named_object::NAMED_OBJECT_PACKAGE:
1883 if (!this->no_error_message_)
1884 go_error_at(location, "unexpected reference to package");
1885 return Expression::make_error(location);
1886 default:
1887 go_unreachable();
1888 }
1889 }
1890
1891 // Dump the ast representation for an unknown expression to a dump context.
1892
1893 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1894 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1895 {
1896 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1897 << ")";
1898 }
1899
1900 // Make a reference to an unknown name.
1901
1902 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1903 Expression::make_unknown_reference(Named_object* no, Location location)
1904 {
1905 return new Unknown_expression(no, location);
1906 }
1907
1908 // Start exporting a type conversion for a constant, if needed. This
1909 // returns whether we need to export a closing parenthesis.
1910
1911 bool
export_constant_type(Export_function_body * efb,Type * type)1912 Expression::export_constant_type(Export_function_body* efb, Type* type)
1913 {
1914 if (type == NULL
1915 || type->is_abstract()
1916 || type == efb->type_context())
1917 return false;
1918 efb->write_c_string("$convert(");
1919 efb->write_type(type);
1920 efb->write_c_string(", ");
1921 return true;
1922 }
1923
1924 // Finish a type conversion for a constant.
1925
1926 void
finish_export_constant_type(Export_function_body * efb,bool needed)1927 Expression::finish_export_constant_type(Export_function_body* efb, bool needed)
1928 {
1929 if (needed)
1930 efb->write_c_string(")");
1931 }
1932
1933 // A boolean expression.
1934
1935 class Boolean_expression : public Expression
1936 {
1937 public:
Boolean_expression(bool val,Location location)1938 Boolean_expression(bool val, Location location)
1939 : Expression(EXPRESSION_BOOLEAN, location),
1940 val_(val), type_(NULL)
1941 { }
1942
1943 static Expression*
1944 do_import(Import_expression*, Location);
1945
1946 protected:
1947 int
1948 do_traverse(Traverse*);
1949
1950 bool
do_is_constant() const1951 do_is_constant() const
1952 { return true; }
1953
1954 bool
do_is_zero_value() const1955 do_is_zero_value() const
1956 { return this->val_ == false; }
1957
1958 bool
do_boolean_constant_value(bool * val) const1959 do_boolean_constant_value(bool* val) const
1960 {
1961 *val = this->val_;
1962 return true;
1963 }
1964
1965 bool
do_is_static_initializer() const1966 do_is_static_initializer() const
1967 { return true; }
1968
1969 Type*
1970 do_type();
1971
1972 void
1973 do_determine_type(const Type_context*);
1974
1975 Expression*
do_copy()1976 do_copy()
1977 { return this; }
1978
1979 Bexpression*
do_get_backend(Translate_context * context)1980 do_get_backend(Translate_context* context)
1981 { return context->backend()->boolean_constant_expression(this->val_); }
1982
1983 int
do_inlining_cost() const1984 do_inlining_cost() const
1985 { return 1; }
1986
1987 void
1988 do_export(Export_function_body* efb) const;
1989
1990 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1991 do_dump_expression(Ast_dump_context* ast_dump_context) const
1992 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1993
1994 private:
1995 // The constant.
1996 bool val_;
1997 // The type as determined by context.
1998 Type* type_;
1999 };
2000
2001 // Traverse a boolean expression. We just need to traverse the type
2002 // if there is one.
2003
2004 int
do_traverse(Traverse * traverse)2005 Boolean_expression::do_traverse(Traverse* traverse)
2006 {
2007 if (this->type_ != NULL)
2008 return Type::traverse(this->type_, traverse);
2009 return TRAVERSE_CONTINUE;
2010 }
2011
2012 // Get the type.
2013
2014 Type*
do_type()2015 Boolean_expression::do_type()
2016 {
2017 if (this->type_ == NULL)
2018 this->type_ = Type::make_boolean_type();
2019 return this->type_;
2020 }
2021
2022 // Set the type from the context.
2023
2024 void
do_determine_type(const Type_context * context)2025 Boolean_expression::do_determine_type(const Type_context* context)
2026 {
2027 if (this->type_ != NULL && !this->type_->is_abstract())
2028 ;
2029 else if (context->type != NULL && context->type->is_boolean_type())
2030 this->type_ = context->type;
2031 else if (!context->may_be_abstract)
2032 this->type_ = Type::lookup_bool_type();
2033 }
2034
2035 // Export a boolean constant.
2036
2037 void
do_export(Export_function_body * efb) const2038 Boolean_expression::do_export(Export_function_body* efb) const
2039 {
2040 bool exported_type = Expression::export_constant_type(efb, this->type_);
2041 efb->write_c_string(this->val_ ? "$true" : "$false");
2042 Expression::finish_export_constant_type(efb, exported_type);
2043 }
2044
2045 // Import a boolean constant.
2046
2047 Expression*
do_import(Import_expression * imp,Location loc)2048 Boolean_expression::do_import(Import_expression* imp, Location loc)
2049 {
2050 if (imp->version() >= EXPORT_FORMAT_V3)
2051 imp->require_c_string("$");
2052 if (imp->peek_char() == 't')
2053 {
2054 imp->require_c_string("true");
2055 return Expression::make_boolean(true, loc);
2056 }
2057 else
2058 {
2059 imp->require_c_string("false");
2060 return Expression::make_boolean(false, loc);
2061 }
2062 }
2063
2064 // Make a boolean expression.
2065
2066 Expression*
make_boolean(bool val,Location location)2067 Expression::make_boolean(bool val, Location location)
2068 {
2069 return new Boolean_expression(val, location);
2070 }
2071
2072 // Class String_expression.
2073
2074 // Traverse a string expression. We just need to traverse the type
2075 // if there is one.
2076
2077 int
do_traverse(Traverse * traverse)2078 String_expression::do_traverse(Traverse* traverse)
2079 {
2080 if (this->type_ != NULL)
2081 return Type::traverse(this->type_, traverse);
2082 return TRAVERSE_CONTINUE;
2083 }
2084
2085 // Get the type.
2086
2087 Type*
do_type()2088 String_expression::do_type()
2089 {
2090 if (this->type_ == NULL)
2091 this->type_ = Type::make_string_type();
2092 return this->type_;
2093 }
2094
2095 // Set the type from the context.
2096
2097 void
do_determine_type(const Type_context * context)2098 String_expression::do_determine_type(const Type_context* context)
2099 {
2100 if (this->type_ != NULL && !this->type_->is_abstract())
2101 ;
2102 else if (context->type != NULL && context->type->is_string_type())
2103 this->type_ = context->type;
2104 else if (!context->may_be_abstract)
2105 this->type_ = Type::lookup_string_type();
2106 }
2107
2108 // Build a string constant.
2109
2110 Bexpression*
do_get_backend(Translate_context * context)2111 String_expression::do_get_backend(Translate_context* context)
2112 {
2113 Gogo* gogo = context->gogo();
2114 Btype* btype = Type::make_string_type()->get_backend(gogo);
2115
2116 Location loc = this->location();
2117 std::vector<Bexpression*> init(2);
2118 Bexpression* str_cst =
2119 gogo->backend()->string_constant_expression(this->val_);
2120 init[0] = gogo->backend()->address_expression(str_cst, loc);
2121
2122 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
2123 mpz_t lenval;
2124 mpz_init_set_ui(lenval, this->val_.length());
2125 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
2126 mpz_clear(lenval);
2127
2128 return gogo->backend()->constructor_expression(btype, init, loc);
2129 }
2130
2131 // Write string literal to string dump.
2132
2133 void
export_string(String_dump * exp,const String_expression * str)2134 String_expression::export_string(String_dump* exp,
2135 const String_expression* str)
2136 {
2137 std::string s;
2138 s.reserve(str->val_.length() * 4 + 2);
2139 s += '"';
2140 for (std::string::const_iterator p = str->val_.begin();
2141 p != str->val_.end();
2142 ++p)
2143 {
2144 if (*p == '\\' || *p == '"')
2145 {
2146 s += '\\';
2147 s += *p;
2148 }
2149 else if (*p >= 0x20 && *p < 0x7f)
2150 s += *p;
2151 else if (*p == '\n')
2152 s += "\\n";
2153 else if (*p == '\t')
2154 s += "\\t";
2155 else
2156 {
2157 s += "\\x";
2158 unsigned char c = *p;
2159 unsigned int dig = c >> 4;
2160 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2161 dig = c & 0xf;
2162 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
2163 }
2164 }
2165 s += '"';
2166 exp->write_string(s);
2167 }
2168
2169 // Export a string expression.
2170
2171 void
do_export(Export_function_body * efb) const2172 String_expression::do_export(Export_function_body* efb) const
2173 {
2174 bool exported_type = Expression::export_constant_type(efb, this->type_);
2175 String_expression::export_string(efb, this);
2176 Expression::finish_export_constant_type(efb, exported_type);
2177 }
2178
2179 // Import a string expression.
2180
2181 Expression*
do_import(Import_expression * imp,Location loc)2182 String_expression::do_import(Import_expression* imp, Location loc)
2183 {
2184 imp->require_c_string("\"");
2185 std::string val;
2186 while (true)
2187 {
2188 int c = imp->get_char();
2189 if (c == '"' || c == -1)
2190 break;
2191 if (c != '\\')
2192 val += static_cast<char>(c);
2193 else
2194 {
2195 c = imp->get_char();
2196 if (c == '\\' || c == '"')
2197 val += static_cast<char>(c);
2198 else if (c == 'n')
2199 val += '\n';
2200 else if (c == 't')
2201 val += '\t';
2202 else if (c == 'x')
2203 {
2204 c = imp->get_char();
2205 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2206 c = imp->get_char();
2207 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
2208 char v = (vh << 4) | vl;
2209 val += v;
2210 }
2211 else
2212 {
2213 go_error_at(imp->location(), "bad string constant");
2214 return Expression::make_error(loc);
2215 }
2216 }
2217 }
2218 return Expression::make_string(val, loc);
2219 }
2220
2221 // Ast dump for string expression.
2222
2223 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2224 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2225 {
2226 String_expression::export_string(ast_dump_context, this);
2227 }
2228
2229 // Make a string expression with abstract string type (common case).
2230
2231 Expression*
make_string(const std::string & val,Location location)2232 Expression::make_string(const std::string& val, Location location)
2233 {
2234 return new String_expression(val, NULL, location);
2235 }
2236
2237 // Make a string expression with a specific string type.
2238
2239 Expression*
make_string_typed(const std::string & val,Type * type,Location location)2240 Expression::make_string_typed(const std::string& val, Type* type, Location location)
2241 {
2242 return new String_expression(val, type, location);
2243 }
2244
2245 // An expression that evaluates to some characteristic of a string.
2246 // This is used when indexing, bound-checking, or nil checking a string.
2247
2248 class String_info_expression : public Expression
2249 {
2250 public:
String_info_expression(Expression * string,String_info string_info,Location location)2251 String_info_expression(Expression* string, String_info string_info,
2252 Location location)
2253 : Expression(EXPRESSION_STRING_INFO, location),
2254 string_(string), string_info_(string_info)
2255 { }
2256
2257 protected:
2258 Type*
2259 do_type();
2260
2261 void
do_determine_type(const Type_context *)2262 do_determine_type(const Type_context*)
2263 { go_unreachable(); }
2264
2265 Expression*
do_copy()2266 do_copy()
2267 {
2268 return new String_info_expression(this->string_->copy(), this->string_info_,
2269 this->location());
2270 }
2271
2272 Bexpression*
2273 do_get_backend(Translate_context* context);
2274
2275 void
2276 do_dump_expression(Ast_dump_context*) const;
2277
2278 void
do_issue_nil_check()2279 do_issue_nil_check()
2280 { this->string_->issue_nil_check(); }
2281
2282 private:
2283 // The string for which we are getting information.
2284 Expression* string_;
2285 // What information we want.
2286 String_info string_info_;
2287 };
2288
2289 // Return the type of the string info.
2290
2291 Type*
do_type()2292 String_info_expression::do_type()
2293 {
2294 switch (this->string_info_)
2295 {
2296 case STRING_INFO_DATA:
2297 {
2298 Type* byte_type = Type::lookup_integer_type("uint8");
2299 return Type::make_pointer_type(byte_type);
2300 }
2301 case STRING_INFO_LENGTH:
2302 return Type::lookup_integer_type("int");
2303 default:
2304 go_unreachable();
2305 }
2306 }
2307
2308 // Return string information in GENERIC.
2309
2310 Bexpression*
do_get_backend(Translate_context * context)2311 String_info_expression::do_get_backend(Translate_context* context)
2312 {
2313 Gogo* gogo = context->gogo();
2314
2315 Bexpression* bstring = this->string_->get_backend(context);
2316 switch (this->string_info_)
2317 {
2318 case STRING_INFO_DATA:
2319 case STRING_INFO_LENGTH:
2320 return gogo->backend()->struct_field_expression(bstring,
2321 this->string_info_,
2322 this->location());
2323 break;
2324 default:
2325 go_unreachable();
2326 }
2327 }
2328
2329 // Dump ast representation for a type info expression.
2330
2331 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2332 String_info_expression::do_dump_expression(
2333 Ast_dump_context* ast_dump_context) const
2334 {
2335 ast_dump_context->ostream() << "stringinfo(";
2336 this->string_->dump_expression(ast_dump_context);
2337 ast_dump_context->ostream() << ",";
2338 ast_dump_context->ostream() <<
2339 (this->string_info_ == STRING_INFO_DATA ? "data"
2340 : this->string_info_ == STRING_INFO_LENGTH ? "length"
2341 : "unknown");
2342 ast_dump_context->ostream() << ")";
2343 }
2344
2345 // Make a string info expression.
2346
2347 Expression*
make_string_info(Expression * string,String_info string_info,Location location)2348 Expression::make_string_info(Expression* string, String_info string_info,
2349 Location location)
2350 {
2351 return new String_info_expression(string, string_info, location);
2352 }
2353
2354 // An expression that represents an string value: a struct with value pointer
2355 // and length fields.
2356
2357 class String_value_expression : public Expression
2358 {
2359 public:
String_value_expression(Expression * valptr,Expression * len,Location location)2360 String_value_expression(Expression* valptr, Expression* len, Location location)
2361 : Expression(EXPRESSION_STRING_VALUE, location),
2362 valptr_(valptr), len_(len)
2363 { }
2364
2365 protected:
2366 int
2367 do_traverse(Traverse*);
2368
2369 Type*
do_type()2370 do_type()
2371 { return Type::make_string_type(); }
2372
2373 void
do_determine_type(const Type_context *)2374 do_determine_type(const Type_context*)
2375 { go_unreachable(); }
2376
2377 Expression*
do_copy()2378 do_copy()
2379 {
2380 return new String_value_expression(this->valptr_->copy(),
2381 this->len_->copy(),
2382 this->location());
2383 }
2384
2385 Bexpression*
2386 do_get_backend(Translate_context* context);
2387
2388 void
2389 do_dump_expression(Ast_dump_context*) const;
2390
2391 private:
2392 // The value pointer.
2393 Expression* valptr_;
2394 // The length.
2395 Expression* len_;
2396 };
2397
2398 int
do_traverse(Traverse * traverse)2399 String_value_expression::do_traverse(Traverse* traverse)
2400 {
2401 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2402 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT)
2403 return TRAVERSE_EXIT;
2404 return TRAVERSE_CONTINUE;
2405 }
2406
2407 Bexpression*
do_get_backend(Translate_context * context)2408 String_value_expression::do_get_backend(Translate_context* context)
2409 {
2410 std::vector<Bexpression*> vals(2);
2411 vals[0] = this->valptr_->get_backend(context);
2412 vals[1] = this->len_->get_backend(context);
2413
2414 Gogo* gogo = context->gogo();
2415 Btype* btype = Type::make_string_type()->get_backend(gogo);
2416 return gogo->backend()->constructor_expression(btype, vals, this->location());
2417 }
2418
2419 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2420 String_value_expression::do_dump_expression(
2421 Ast_dump_context* ast_dump_context) const
2422 {
2423 ast_dump_context->ostream() << "stringvalue(";
2424 ast_dump_context->ostream() << "value: ";
2425 this->valptr_->dump_expression(ast_dump_context);
2426 ast_dump_context->ostream() << ", length: ";
2427 this->len_->dump_expression(ast_dump_context);
2428 ast_dump_context->ostream() << ")";
2429 }
2430
2431 Expression*
make_string_value(Expression * valptr,Expression * len,Location location)2432 Expression::make_string_value(Expression* valptr, Expression* len,
2433 Location location)
2434 {
2435 return new String_value_expression(valptr, len, location);
2436 }
2437
2438 // Make an integer expression.
2439
2440 class Integer_expression : public Expression
2441 {
2442 public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)2443 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
2444 Location location)
2445 : Expression(EXPRESSION_INTEGER, location),
2446 type_(type), is_character_constant_(is_character_constant)
2447 { mpz_init_set(this->val_, *val); }
2448
2449 static Expression*
2450 do_import(Import_expression*, Location);
2451
2452 // Write VAL to string dump.
2453 static void
2454 export_integer(String_dump* exp, const mpz_t val);
2455
2456 // Write VAL to dump context.
2457 static void
2458 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
2459
2460 protected:
2461 int
2462 do_traverse(Traverse*);
2463
2464 bool
do_is_constant() const2465 do_is_constant() const
2466 { return true; }
2467
2468 bool
do_is_zero_value() const2469 do_is_zero_value() const
2470 { return mpz_sgn(this->val_) == 0; }
2471
2472 bool
do_is_static_initializer() const2473 do_is_static_initializer() const
2474 { return true; }
2475
2476 bool
2477 do_numeric_constant_value(Numeric_constant* nc) const;
2478
2479 Type*
2480 do_type();
2481
2482 void
2483 do_determine_type(const Type_context* context);
2484
2485 void
2486 do_check_types(Gogo*);
2487
2488 Bexpression*
2489 do_get_backend(Translate_context*);
2490
2491 Expression*
do_copy()2492 do_copy()
2493 {
2494 if (this->is_character_constant_)
2495 return Expression::make_character(&this->val_,
2496 (this->type_ == NULL
2497 ? NULL
2498 : this->type_->copy_expressions()),
2499 this->location());
2500 else
2501 return Expression::make_integer_z(&this->val_,
2502 (this->type_ == NULL
2503 ? NULL
2504 : this->type_->copy_expressions()),
2505 this->location());
2506 }
2507
2508 int
do_inlining_cost() const2509 do_inlining_cost() const
2510 { return 1; }
2511
2512 void
2513 do_export(Export_function_body*) const;
2514
2515 void
2516 do_dump_expression(Ast_dump_context*) const;
2517
2518 private:
2519 // The integer value.
2520 mpz_t val_;
2521 // The type so far.
2522 Type* type_;
2523 // Whether this is a character constant.
2524 bool is_character_constant_;
2525 };
2526
2527 // Traverse an integer expression. We just need to traverse the type
2528 // if there is one.
2529
2530 int
do_traverse(Traverse * traverse)2531 Integer_expression::do_traverse(Traverse* traverse)
2532 {
2533 if (this->type_ != NULL)
2534 return Type::traverse(this->type_, traverse);
2535 return TRAVERSE_CONTINUE;
2536 }
2537
2538 // Return a numeric constant for this expression. We have to mark
2539 // this as a character when appropriate.
2540
2541 bool
do_numeric_constant_value(Numeric_constant * nc) const2542 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
2543 {
2544 if (this->is_character_constant_)
2545 nc->set_rune(this->type_, this->val_);
2546 else
2547 nc->set_int(this->type_, this->val_);
2548 return true;
2549 }
2550
2551 // Return the current type. If we haven't set the type yet, we return
2552 // an abstract integer type.
2553
2554 Type*
do_type()2555 Integer_expression::do_type()
2556 {
2557 if (this->type_ == NULL)
2558 {
2559 if (this->is_character_constant_)
2560 this->type_ = Type::make_abstract_character_type();
2561 else
2562 this->type_ = Type::make_abstract_integer_type();
2563 }
2564 return this->type_;
2565 }
2566
2567 // Set the type of the integer value. Here we may switch from an
2568 // abstract type to a real type.
2569
2570 void
do_determine_type(const Type_context * context)2571 Integer_expression::do_determine_type(const Type_context* context)
2572 {
2573 if (this->type_ != NULL && !this->type_->is_abstract())
2574 ;
2575 else if (context->type != NULL && context->type->is_numeric_type())
2576 this->type_ = context->type;
2577 else if (!context->may_be_abstract)
2578 {
2579 if (this->is_character_constant_)
2580 this->type_ = Type::lookup_integer_type("int32");
2581 else
2582 this->type_ = Type::lookup_integer_type("int");
2583 }
2584 }
2585
2586 // Check the type of an integer constant.
2587
2588 void
do_check_types(Gogo *)2589 Integer_expression::do_check_types(Gogo*)
2590 {
2591 Type* type = this->type_;
2592 if (type == NULL)
2593 return;
2594 Numeric_constant nc;
2595 if (this->is_character_constant_)
2596 nc.set_rune(NULL, this->val_);
2597 else
2598 nc.set_int(NULL, this->val_);
2599 if (!nc.set_type(type, true, this->location()))
2600 this->set_is_error();
2601 }
2602
2603 // Get the backend representation for an integer constant.
2604
2605 Bexpression*
do_get_backend(Translate_context * context)2606 Integer_expression::do_get_backend(Translate_context* context)
2607 {
2608 if (this->is_error_expression()
2609 || (this->type_ != NULL && this->type_->is_error_type()))
2610 {
2611 go_assert(saw_errors());
2612 return context->gogo()->backend()->error_expression();
2613 }
2614
2615 Type* resolved_type = NULL;
2616 if (this->type_ != NULL && !this->type_->is_abstract())
2617 resolved_type = this->type_;
2618 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2619 {
2620 // We are converting to an abstract floating point type.
2621 resolved_type = Type::lookup_float_type("float64");
2622 }
2623 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2624 {
2625 // We are converting to an abstract complex type.
2626 resolved_type = Type::lookup_complex_type("complex128");
2627 }
2628 else
2629 {
2630 // If we still have an abstract type here, then this is being
2631 // used in a constant expression which didn't get reduced for
2632 // some reason. Use a type which will fit the value. We use <,
2633 // not <=, because we need an extra bit for the sign bit.
2634 int bits = mpz_sizeinbase(this->val_, 2);
2635 Type* int_type = Type::lookup_integer_type("int");
2636 if (bits < int_type->integer_type()->bits())
2637 resolved_type = int_type;
2638 else if (bits < 64)
2639 resolved_type = Type::lookup_integer_type("int64");
2640 else
2641 {
2642 if (!saw_errors())
2643 go_error_at(this->location(),
2644 "unknown type for large integer constant");
2645 return context->gogo()->backend()->error_expression();
2646 }
2647 }
2648 Numeric_constant nc;
2649 nc.set_int(resolved_type, this->val_);
2650 return Expression::backend_numeric_constant_expression(context, &nc);
2651 }
2652
2653 // Write VAL to export data.
2654
2655 void
export_integer(String_dump * exp,const mpz_t val)2656 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2657 {
2658 char* s = mpz_get_str(NULL, 10, val);
2659 exp->write_c_string(s);
2660 free(s);
2661 }
2662
2663 // Export an integer in a constant expression.
2664
2665 void
do_export(Export_function_body * efb) const2666 Integer_expression::do_export(Export_function_body* efb) const
2667 {
2668 bool exported_type = Expression::export_constant_type(efb, this->type_);
2669
2670 Integer_expression::export_integer(efb, this->val_);
2671 if (this->is_character_constant_)
2672 efb->write_c_string("'");
2673 // A trailing space lets us reliably identify the end of the number.
2674 efb->write_c_string(" ");
2675
2676 Expression::finish_export_constant_type(efb, exported_type);
2677 }
2678
2679 // Import an integer, floating point, or complex value. This handles
2680 // all these types because they all start with digits.
2681
2682 Expression*
do_import(Import_expression * imp,Location loc)2683 Integer_expression::do_import(Import_expression* imp, Location loc)
2684 {
2685 std::string num = imp->read_identifier();
2686 imp->require_c_string(" ");
2687 if (!num.empty() && num[num.length() - 1] == 'i')
2688 {
2689 mpfr_t real;
2690 size_t plus_pos = num.find('+', 1);
2691 size_t minus_pos = num.find('-', 1);
2692 size_t pos;
2693 if (plus_pos == std::string::npos)
2694 pos = minus_pos;
2695 else if (minus_pos == std::string::npos)
2696 pos = plus_pos;
2697 else
2698 {
2699 go_error_at(imp->location(), "bad number in import data: %qs",
2700 num.c_str());
2701 return Expression::make_error(loc);
2702 }
2703 if (pos == std::string::npos)
2704 mpfr_set_ui(real, 0, MPFR_RNDN);
2705 else
2706 {
2707 std::string real_str = num.substr(0, pos);
2708 if (mpfr_init_set_str(real, real_str.c_str(), 10, MPFR_RNDN) != 0)
2709 {
2710 go_error_at(imp->location(), "bad number in import data: %qs",
2711 real_str.c_str());
2712 return Expression::make_error(loc);
2713 }
2714 }
2715
2716 std::string imag_str;
2717 if (pos == std::string::npos)
2718 imag_str = num;
2719 else
2720 imag_str = num.substr(pos);
2721 imag_str = imag_str.substr(0, imag_str.size() - 1);
2722 mpfr_t imag;
2723 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, MPFR_RNDN) != 0)
2724 {
2725 go_error_at(imp->location(), "bad number in import data: %qs",
2726 imag_str.c_str());
2727 return Expression::make_error(loc);
2728 }
2729 mpc_t cval;
2730 mpc_init2(cval, mpc_precision);
2731 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2732 mpfr_clear(real);
2733 mpfr_clear(imag);
2734 Expression* ret = Expression::make_complex(&cval, NULL, loc);
2735 mpc_clear(cval);
2736 return ret;
2737 }
2738 else if (num.find('.') == std::string::npos
2739 && num.find('E') == std::string::npos)
2740 {
2741 bool is_character_constant = (!num.empty()
2742 && num[num.length() - 1] == '\'');
2743 if (is_character_constant)
2744 num = num.substr(0, num.length() - 1);
2745 mpz_t val;
2746 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2747 {
2748 go_error_at(imp->location(), "bad number in import data: %qs",
2749 num.c_str());
2750 return Expression::make_error(loc);
2751 }
2752 Expression* ret;
2753 if (is_character_constant)
2754 ret = Expression::make_character(&val, NULL, loc);
2755 else
2756 ret = Expression::make_integer_z(&val, NULL, loc);
2757 mpz_clear(val);
2758 return ret;
2759 }
2760 else
2761 {
2762 mpfr_t val;
2763 if (mpfr_init_set_str(val, num.c_str(), 10, MPFR_RNDN) != 0)
2764 {
2765 go_error_at(imp->location(), "bad number in import data: %qs",
2766 num.c_str());
2767 return Expression::make_error(loc);
2768 }
2769 Expression* ret = Expression::make_float(&val, NULL, loc);
2770 mpfr_clear(val);
2771 return ret;
2772 }
2773 }
2774 // Ast dump for integer expression.
2775
2776 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2777 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2778 {
2779 if (this->is_character_constant_)
2780 ast_dump_context->ostream() << '\'';
2781 Integer_expression::export_integer(ast_dump_context, this->val_);
2782 if (this->is_character_constant_)
2783 ast_dump_context->ostream() << '\'';
2784 }
2785
2786 // Build a new integer value from a multi-precision integer.
2787
2788 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2789 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2790 {
2791 return new Integer_expression(val, type, false, location);
2792 }
2793
2794 // Build a new integer value from an unsigned long.
2795
2796 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2797 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2798 {
2799 mpz_t zval;
2800 mpz_init_set_ui(zval, val);
2801 Expression* ret = Expression::make_integer_z(&zval, type, location);
2802 mpz_clear(zval);
2803 return ret;
2804 }
2805
2806 // Build a new integer value from a signed long.
2807
2808 Expression*
make_integer_sl(long val,Type * type,Location location)2809 Expression::make_integer_sl(long val, Type *type, Location location)
2810 {
2811 mpz_t zval;
2812 mpz_init_set_si(zval, val);
2813 Expression* ret = Expression::make_integer_z(&zval, type, location);
2814 mpz_clear(zval);
2815 return ret;
2816 }
2817
2818 // Store an int64_t in an uninitialized mpz_t.
2819
2820 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2821 set_mpz_from_int64(mpz_t* zval, int64_t val)
2822 {
2823 if (val >= 0)
2824 {
2825 unsigned long ul = static_cast<unsigned long>(val);
2826 if (static_cast<int64_t>(ul) == val)
2827 {
2828 mpz_init_set_ui(*zval, ul);
2829 return;
2830 }
2831 }
2832 uint64_t uv;
2833 if (val >= 0)
2834 uv = static_cast<uint64_t>(val);
2835 else
2836 uv = static_cast<uint64_t>(- val);
2837 unsigned long ul = uv & 0xffffffffUL;
2838 mpz_init_set_ui(*zval, ul);
2839 mpz_t hval;
2840 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2841 mpz_mul_2exp(hval, hval, 32);
2842 mpz_add(*zval, *zval, hval);
2843 mpz_clear(hval);
2844 if (val < 0)
2845 mpz_neg(*zval, *zval);
2846 }
2847
2848 // Build a new integer value from an int64_t.
2849
2850 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2851 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2852 {
2853 mpz_t zval;
2854 set_mpz_from_int64(&zval, val);
2855 Expression* ret = Expression::make_integer_z(&zval, type, location);
2856 mpz_clear(zval);
2857 return ret;
2858 }
2859
2860 // Build a new character constant value.
2861
2862 Expression*
make_character(const mpz_t * val,Type * type,Location location)2863 Expression::make_character(const mpz_t* val, Type* type, Location location)
2864 {
2865 return new Integer_expression(val, type, true, location);
2866 }
2867
2868 // Floats.
2869
2870 class Float_expression : public Expression
2871 {
2872 public:
Float_expression(const mpfr_t * val,Type * type,Location location)2873 Float_expression(const mpfr_t* val, Type* type, Location location)
2874 : Expression(EXPRESSION_FLOAT, location),
2875 type_(type)
2876 {
2877 mpfr_init_set(this->val_, *val, MPFR_RNDN);
2878 }
2879
2880 // Write VAL to export data.
2881 static void
2882 export_float(String_dump* exp, const mpfr_t val);
2883
2884 // Write VAL to dump file.
2885 static void
2886 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2887
2888 protected:
2889 int
2890 do_traverse(Traverse*);
2891
2892 bool
do_is_constant() const2893 do_is_constant() const
2894 { return true; }
2895
2896 bool
do_is_zero_value() const2897 do_is_zero_value() const
2898 {
2899 return mpfr_zero_p(this->val_) != 0
2900 && mpfr_signbit(this->val_) == 0;
2901 }
2902
2903 bool
do_is_static_initializer() const2904 do_is_static_initializer() const
2905 { return true; }
2906
2907 bool
do_numeric_constant_value(Numeric_constant * nc) const2908 do_numeric_constant_value(Numeric_constant* nc) const
2909 {
2910 nc->set_float(this->type_, this->val_);
2911 return true;
2912 }
2913
2914 Type*
2915 do_type();
2916
2917 void
2918 do_determine_type(const Type_context*);
2919
2920 void
2921 do_check_types(Gogo*);
2922
2923 Expression*
do_copy()2924 do_copy()
2925 { return Expression::make_float(&this->val_,
2926 (this->type_ == NULL
2927 ? NULL
2928 : this->type_->copy_expressions()),
2929 this->location()); }
2930
2931 Bexpression*
2932 do_get_backend(Translate_context*);
2933
2934 int
do_inlining_cost() const2935 do_inlining_cost() const
2936 { return 1; }
2937
2938 void
2939 do_export(Export_function_body*) const;
2940
2941 void
2942 do_dump_expression(Ast_dump_context*) const;
2943
2944 private:
2945 // The floating point value.
2946 mpfr_t val_;
2947 // The type so far.
2948 Type* type_;
2949 };
2950
2951 // Traverse a float expression. We just need to traverse the type if
2952 // there is one.
2953
2954 int
do_traverse(Traverse * traverse)2955 Float_expression::do_traverse(Traverse* traverse)
2956 {
2957 if (this->type_ != NULL)
2958 return Type::traverse(this->type_, traverse);
2959 return TRAVERSE_CONTINUE;
2960 }
2961
2962 // Return the current type. If we haven't set the type yet, we return
2963 // an abstract float type.
2964
2965 Type*
do_type()2966 Float_expression::do_type()
2967 {
2968 if (this->type_ == NULL)
2969 this->type_ = Type::make_abstract_float_type();
2970 return this->type_;
2971 }
2972
2973 // Set the type of the float value. Here we may switch from an
2974 // abstract type to a real type.
2975
2976 void
do_determine_type(const Type_context * context)2977 Float_expression::do_determine_type(const Type_context* context)
2978 {
2979 if (this->type_ != NULL && !this->type_->is_abstract())
2980 ;
2981 else if (context->type != NULL
2982 && (context->type->integer_type() != NULL
2983 || context->type->float_type() != NULL
2984 || context->type->complex_type() != NULL))
2985 this->type_ = context->type;
2986 else if (!context->may_be_abstract)
2987 this->type_ = Type::lookup_float_type("float64");
2988 }
2989
2990 // Check the type of a float value.
2991
2992 void
do_check_types(Gogo *)2993 Float_expression::do_check_types(Gogo*)
2994 {
2995 Type* type = this->type_;
2996 if (type == NULL)
2997 return;
2998 Numeric_constant nc;
2999 nc.set_float(NULL, this->val_);
3000 if (!nc.set_type(this->type_, true, this->location()))
3001 this->set_is_error();
3002 }
3003
3004 // Get the backend representation for a float constant.
3005
3006 Bexpression*
do_get_backend(Translate_context * context)3007 Float_expression::do_get_backend(Translate_context* context)
3008 {
3009 if (this->is_error_expression()
3010 || (this->type_ != NULL && this->type_->is_error_type()))
3011 {
3012 go_assert(saw_errors());
3013 return context->gogo()->backend()->error_expression();
3014 }
3015
3016 Type* resolved_type;
3017 if (this->type_ != NULL && !this->type_->is_abstract())
3018 resolved_type = this->type_;
3019 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3020 {
3021 // We have an abstract integer type. We just hope for the best.
3022 resolved_type = Type::lookup_integer_type("int");
3023 }
3024 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
3025 {
3026 // We are converting to an abstract complex type.
3027 resolved_type = Type::lookup_complex_type("complex128");
3028 }
3029 else
3030 {
3031 // If we still have an abstract type here, then this is being
3032 // used in a constant expression which didn't get reduced. We
3033 // just use float64 and hope for the best.
3034 resolved_type = Type::lookup_float_type("float64");
3035 }
3036
3037 Numeric_constant nc;
3038 nc.set_float(resolved_type, this->val_);
3039 return Expression::backend_numeric_constant_expression(context, &nc);
3040 }
3041
3042 // Write a floating point number to a string dump.
3043
3044 void
export_float(String_dump * exp,const mpfr_t val)3045 Float_expression::export_float(String_dump *exp, const mpfr_t val)
3046 {
3047 mpfr_exp_t exponent;
3048 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, MPFR_RNDN);
3049 if (*s == '-')
3050 exp->write_c_string("-");
3051 exp->write_c_string("0.");
3052 exp->write_c_string(*s == '-' ? s + 1 : s);
3053 mpfr_free_str(s);
3054 char buf[30];
3055 snprintf(buf, sizeof buf, "E%ld", exponent);
3056 exp->write_c_string(buf);
3057 }
3058
3059 // Export a floating point number in a constant expression.
3060
3061 void
do_export(Export_function_body * efb) const3062 Float_expression::do_export(Export_function_body* efb) const
3063 {
3064 bool exported_type = Expression::export_constant_type(efb, this->type_);
3065
3066 Float_expression::export_float(efb, this->val_);
3067 // A trailing space lets us reliably identify the end of the number.
3068 efb->write_c_string(" ");
3069
3070 Expression::finish_export_constant_type(efb, exported_type);
3071 }
3072
3073 // Dump a floating point number to the dump file.
3074
3075 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3076 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3077 {
3078 Float_expression::export_float(ast_dump_context, this->val_);
3079 }
3080
3081 // Make a float expression.
3082
3083 Expression*
make_float(const mpfr_t * val,Type * type,Location location)3084 Expression::make_float(const mpfr_t* val, Type* type, Location location)
3085 {
3086 return new Float_expression(val, type, location);
3087 }
3088
3089 // Complex numbers.
3090
3091 class Complex_expression : public Expression
3092 {
3093 public:
Complex_expression(const mpc_t * val,Type * type,Location location)3094 Complex_expression(const mpc_t* val, Type* type, Location location)
3095 : Expression(EXPRESSION_COMPLEX, location),
3096 type_(type)
3097 {
3098 mpc_init2(this->val_, mpc_precision);
3099 mpc_set(this->val_, *val, MPC_RNDNN);
3100 }
3101
3102 // Write VAL to string dump.
3103 static void
3104 export_complex(String_dump* exp, const mpc_t val);
3105
3106 // Write REAL/IMAG to dump context.
3107 static void
3108 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
3109
3110 protected:
3111 int
3112 do_traverse(Traverse*);
3113
3114 bool
do_is_constant() const3115 do_is_constant() const
3116 { return true; }
3117
3118 bool
do_is_zero_value() const3119 do_is_zero_value() const
3120 {
3121 return mpfr_zero_p(mpc_realref(this->val_)) != 0
3122 && mpfr_signbit(mpc_realref(this->val_)) == 0
3123 && mpfr_zero_p(mpc_imagref(this->val_)) != 0
3124 && mpfr_signbit(mpc_imagref(this->val_)) == 0;
3125 }
3126
3127 bool
do_is_static_initializer() const3128 do_is_static_initializer() const
3129 { return true; }
3130
3131 bool
do_numeric_constant_value(Numeric_constant * nc) const3132 do_numeric_constant_value(Numeric_constant* nc) const
3133 {
3134 nc->set_complex(this->type_, this->val_);
3135 return true;
3136 }
3137
3138 Type*
3139 do_type();
3140
3141 void
3142 do_determine_type(const Type_context*);
3143
3144 void
3145 do_check_types(Gogo*);
3146
3147 Expression*
do_copy()3148 do_copy()
3149 {
3150 return Expression::make_complex(&this->val_,
3151 (this->type_ == NULL
3152 ? NULL
3153 : this->type_->copy_expressions()),
3154 this->location());
3155 }
3156
3157 Bexpression*
3158 do_get_backend(Translate_context*);
3159
3160 int
do_inlining_cost() const3161 do_inlining_cost() const
3162 { return 2; }
3163
3164 void
3165 do_export(Export_function_body*) const;
3166
3167 void
3168 do_dump_expression(Ast_dump_context*) const;
3169
3170 private:
3171 // The complex value.
3172 mpc_t val_;
3173 // The type if known.
3174 Type* type_;
3175 };
3176
3177 // Traverse a complex expression. We just need to traverse the type
3178 // if there is one.
3179
3180 int
do_traverse(Traverse * traverse)3181 Complex_expression::do_traverse(Traverse* traverse)
3182 {
3183 if (this->type_ != NULL)
3184 return Type::traverse(this->type_, traverse);
3185 return TRAVERSE_CONTINUE;
3186 }
3187
3188 // Return the current type. If we haven't set the type yet, we return
3189 // an abstract complex type.
3190
3191 Type*
do_type()3192 Complex_expression::do_type()
3193 {
3194 if (this->type_ == NULL)
3195 this->type_ = Type::make_abstract_complex_type();
3196 return this->type_;
3197 }
3198
3199 // Set the type of the complex value. Here we may switch from an
3200 // abstract type to a real type.
3201
3202 void
do_determine_type(const Type_context * context)3203 Complex_expression::do_determine_type(const Type_context* context)
3204 {
3205 if (this->type_ != NULL && !this->type_->is_abstract())
3206 ;
3207 else if (context->type != NULL && context->type->is_numeric_type())
3208 this->type_ = context->type;
3209 else if (!context->may_be_abstract)
3210 this->type_ = Type::lookup_complex_type("complex128");
3211 }
3212
3213 // Check the type of a complex value.
3214
3215 void
do_check_types(Gogo *)3216 Complex_expression::do_check_types(Gogo*)
3217 {
3218 Type* type = this->type_;
3219 if (type == NULL)
3220 return;
3221 Numeric_constant nc;
3222 nc.set_complex(NULL, this->val_);
3223 if (!nc.set_type(this->type_, true, this->location()))
3224 this->set_is_error();
3225 }
3226
3227 // Get the backend representation for a complex constant.
3228
3229 Bexpression*
do_get_backend(Translate_context * context)3230 Complex_expression::do_get_backend(Translate_context* context)
3231 {
3232 if (this->is_error_expression()
3233 || (this->type_ != NULL && this->type_->is_error_type()))
3234 {
3235 go_assert(saw_errors());
3236 return context->gogo()->backend()->error_expression();
3237 }
3238
3239 Type* resolved_type;
3240 if (this->type_ != NULL && !this->type_->is_abstract())
3241 resolved_type = this->type_;
3242 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
3243 {
3244 // We are converting to an abstract integer type.
3245 resolved_type = Type::lookup_integer_type("int");
3246 }
3247 else if (this->type_ != NULL && this->type_->float_type() != NULL)
3248 {
3249 // We are converting to an abstract float type.
3250 resolved_type = Type::lookup_float_type("float64");
3251 }
3252 else
3253 {
3254 // If we still have an abstract type here, this is being
3255 // used in a constant expression which didn't get reduced. We
3256 // just use complex128 and hope for the best.
3257 resolved_type = Type::lookup_complex_type("complex128");
3258 }
3259
3260 Numeric_constant nc;
3261 nc.set_complex(resolved_type, this->val_);
3262 return Expression::backend_numeric_constant_expression(context, &nc);
3263 }
3264
3265 // Write REAL/IMAG to export data.
3266
3267 void
export_complex(String_dump * exp,const mpc_t val)3268 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
3269 {
3270 if (!mpfr_zero_p(mpc_realref(val)))
3271 {
3272 Float_expression::export_float(exp, mpc_realref(val));
3273 if (mpfr_sgn(mpc_imagref(val)) >= 0)
3274 exp->write_c_string("+");
3275 }
3276 Float_expression::export_float(exp, mpc_imagref(val));
3277 exp->write_c_string("i");
3278 }
3279
3280 // Export a complex number in a constant expression.
3281
3282 void
do_export(Export_function_body * efb) const3283 Complex_expression::do_export(Export_function_body* efb) const
3284 {
3285 bool exported_type = Expression::export_constant_type(efb, this->type_);
3286
3287 Complex_expression::export_complex(efb, this->val_);
3288 // A trailing space lets us reliably identify the end of the number.
3289 efb->write_c_string(" ");
3290
3291 Expression::finish_export_constant_type(efb, exported_type);
3292 }
3293
3294 // Dump a complex expression to the dump file.
3295
3296 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3297 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3298 {
3299 Complex_expression::export_complex(ast_dump_context, this->val_);
3300 }
3301
3302 // Make a complex expression.
3303
3304 Expression*
make_complex(const mpc_t * val,Type * type,Location location)3305 Expression::make_complex(const mpc_t* val, Type* type, Location location)
3306 {
3307 return new Complex_expression(val, type, location);
3308 }
3309
3310 // Find a named object in an expression.
3311
3312 class Find_named_object : public Traverse
3313 {
3314 public:
Find_named_object(Named_object * no)3315 Find_named_object(Named_object* no)
3316 : Traverse(traverse_expressions),
3317 no_(no), found_(false)
3318 { }
3319
3320 // Whether we found the object.
3321 bool
found() const3322 found() const
3323 { return this->found_; }
3324
3325 protected:
3326 int
3327 expression(Expression**);
3328
3329 private:
3330 // The object we are looking for.
3331 Named_object* no_;
3332 // Whether we found it.
3333 bool found_;
3334 };
3335
3336 // A reference to a const in an expression.
3337
3338 class Const_expression : public Expression
3339 {
3340 public:
Const_expression(Named_object * constant,Location location)3341 Const_expression(Named_object* constant, Location location)
3342 : Expression(EXPRESSION_CONST_REFERENCE, location),
3343 constant_(constant), type_(NULL), seen_(false)
3344 { }
3345
3346 Named_object*
named_object()3347 named_object()
3348 { return this->constant_; }
3349
3350 const Named_object*
named_object() const3351 named_object() const
3352 { return this->constant_; }
3353
3354 // Check that the initializer does not refer to the constant itself.
3355 void
3356 check_for_init_loop();
3357
3358 protected:
3359 int
3360 do_traverse(Traverse*);
3361
3362 Expression*
3363 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3364
3365 bool
do_is_constant() const3366 do_is_constant() const
3367 { return true; }
3368
3369 bool
do_is_zero_value() const3370 do_is_zero_value() const
3371 { return this->constant_->const_value()->expr()->is_zero_value(); }
3372
3373 bool
do_is_static_initializer() const3374 do_is_static_initializer() const
3375 { return true; }
3376
3377 bool
3378 do_numeric_constant_value(Numeric_constant* nc) const;
3379
3380 bool
3381 do_string_constant_value(std::string* val) const;
3382
3383 bool
3384 do_boolean_constant_value(bool* val) const;
3385
3386 Type*
3387 do_type();
3388
3389 // The type of a const is set by the declaration, not the use.
3390 void
3391 do_determine_type(const Type_context*);
3392
3393 void
3394 do_check_types(Gogo*);
3395
3396 Expression*
do_copy()3397 do_copy()
3398 { return this; }
3399
3400 Bexpression*
3401 do_get_backend(Translate_context* context);
3402
3403 int
do_inlining_cost() const3404 do_inlining_cost() const
3405 { return 1; }
3406
3407 // When exporting a reference to a const as part of a const
3408 // expression, we export the value. We ignore the fact that it has
3409 // a name.
3410 void
do_export(Export_function_body * efb) const3411 do_export(Export_function_body* efb) const
3412 { this->constant_->const_value()->expr()->export_expression(efb); }
3413
3414 void
3415 do_dump_expression(Ast_dump_context*) const;
3416
3417 private:
3418 // The constant.
3419 Named_object* constant_;
3420 // The type of this reference. This is used if the constant has an
3421 // abstract type.
3422 Type* type_;
3423 // Used to prevent infinite recursion when a constant incorrectly
3424 // refers to itself.
3425 mutable bool seen_;
3426 };
3427
3428 // Traversal.
3429
3430 int
do_traverse(Traverse * traverse)3431 Const_expression::do_traverse(Traverse* traverse)
3432 {
3433 if (this->type_ != NULL)
3434 return Type::traverse(this->type_, traverse);
3435 return TRAVERSE_CONTINUE;
3436 }
3437
3438 // Lower a constant expression. This is where we convert the
3439 // predeclared constant iota into an integer value.
3440
3441 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)3442 Const_expression::do_lower(Gogo* gogo, Named_object*,
3443 Statement_inserter*, int iota_value)
3444 {
3445 if (this->constant_->const_value()->expr()->classification()
3446 == EXPRESSION_IOTA)
3447 {
3448 if (iota_value == -1)
3449 {
3450 go_error_at(this->location(),
3451 "iota is only defined in const declarations");
3452 iota_value = 0;
3453 }
3454 return Expression::make_integer_ul(iota_value, NULL, this->location());
3455 }
3456
3457 // Make sure that the constant itself has been lowered.
3458 gogo->lower_constant(this->constant_);
3459
3460 return this;
3461 }
3462
3463 // Return a numeric constant value.
3464
3465 bool
do_numeric_constant_value(Numeric_constant * nc) const3466 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
3467 {
3468 if (this->seen_)
3469 return false;
3470
3471 Expression* e = this->constant_->const_value()->expr();
3472
3473 this->seen_ = true;
3474
3475 bool r = e->numeric_constant_value(nc);
3476
3477 this->seen_ = false;
3478
3479 Type* ctype;
3480 if (this->type_ != NULL)
3481 ctype = this->type_;
3482 else
3483 ctype = this->constant_->const_value()->type();
3484 if (r && ctype != NULL)
3485 {
3486 if (!nc->set_type(ctype, false, this->location()))
3487 return false;
3488 }
3489
3490 return r;
3491 }
3492
3493 bool
do_string_constant_value(std::string * val) const3494 Const_expression::do_string_constant_value(std::string* val) const
3495 {
3496 if (this->seen_)
3497 return false;
3498
3499 Expression* e = this->constant_->const_value()->expr();
3500
3501 this->seen_ = true;
3502 bool ok = e->string_constant_value(val);
3503 this->seen_ = false;
3504
3505 return ok;
3506 }
3507
3508 bool
do_boolean_constant_value(bool * val) const3509 Const_expression::do_boolean_constant_value(bool* val) const
3510 {
3511 if (this->seen_)
3512 return false;
3513
3514 Expression* e = this->constant_->const_value()->expr();
3515
3516 this->seen_ = true;
3517 bool ok = e->boolean_constant_value(val);
3518 this->seen_ = false;
3519
3520 return ok;
3521 }
3522
3523 // Return the type of the const reference.
3524
3525 Type*
do_type()3526 Const_expression::do_type()
3527 {
3528 if (this->type_ != NULL)
3529 return this->type_;
3530
3531 Named_constant* nc = this->constant_->const_value();
3532
3533 if (this->seen_ || nc->lowering())
3534 {
3535 if (nc->type() == NULL || !nc->type()->is_error_type())
3536 {
3537 Location loc = this->location();
3538 if (!this->seen_)
3539 loc = nc->location();
3540 go_error_at(loc, "constant refers to itself");
3541 }
3542 this->set_is_error();
3543 this->type_ = Type::make_error_type();
3544 nc->set_type(this->type_);
3545 return this->type_;
3546 }
3547
3548 this->seen_ = true;
3549
3550 Type* ret = nc->type();
3551
3552 if (ret != NULL)
3553 {
3554 this->seen_ = false;
3555 return ret;
3556 }
3557
3558 // During parsing, a named constant may have a NULL type, but we
3559 // must not return a NULL type here.
3560 ret = nc->expr()->type();
3561
3562 this->seen_ = false;
3563
3564 if (ret->is_error_type())
3565 nc->set_type(ret);
3566
3567 return ret;
3568 }
3569
3570 // Set the type of the const reference.
3571
3572 void
do_determine_type(const Type_context * context)3573 Const_expression::do_determine_type(const Type_context* context)
3574 {
3575 Type* ctype = this->constant_->const_value()->type();
3576 Type* cetype = (ctype != NULL
3577 ? ctype
3578 : this->constant_->const_value()->expr()->type());
3579 if (ctype != NULL && !ctype->is_abstract())
3580 ;
3581 else if (context->type != NULL
3582 && context->type->is_numeric_type()
3583 && cetype->is_numeric_type())
3584 this->type_ = context->type;
3585 else if (context->type != NULL
3586 && context->type->is_string_type()
3587 && cetype->is_string_type())
3588 this->type_ = context->type;
3589 else if (context->type != NULL
3590 && context->type->is_boolean_type()
3591 && cetype->is_boolean_type())
3592 this->type_ = context->type;
3593 else if (!context->may_be_abstract)
3594 {
3595 if (cetype->is_abstract())
3596 cetype = cetype->make_non_abstract_type();
3597 this->type_ = cetype;
3598 }
3599 }
3600
3601 // Check for a loop in which the initializer of a constant refers to
3602 // the constant itself.
3603
3604 void
check_for_init_loop()3605 Const_expression::check_for_init_loop()
3606 {
3607 if (this->type_ != NULL && this->type_->is_error())
3608 return;
3609
3610 if (this->seen_)
3611 {
3612 this->report_error(_("constant refers to itself"));
3613 this->type_ = Type::make_error_type();
3614 return;
3615 }
3616
3617 Expression* init = this->constant_->const_value()->expr();
3618 Find_named_object find_named_object(this->constant_);
3619
3620 this->seen_ = true;
3621 Expression::traverse(&init, &find_named_object);
3622 this->seen_ = false;
3623
3624 if (find_named_object.found())
3625 {
3626 if (this->type_ == NULL || !this->type_->is_error())
3627 {
3628 this->report_error(_("constant refers to itself"));
3629 this->type_ = Type::make_error_type();
3630 }
3631 return;
3632 }
3633 }
3634
3635 // Check types of a const reference.
3636
3637 void
do_check_types(Gogo *)3638 Const_expression::do_check_types(Gogo*)
3639 {
3640 if (this->type_ != NULL && this->type_->is_error())
3641 return;
3642
3643 this->check_for_init_loop();
3644
3645 // Check that numeric constant fits in type.
3646 if (this->type_ != NULL && this->type_->is_numeric_type())
3647 {
3648 Numeric_constant nc;
3649 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
3650 {
3651 if (!nc.set_type(this->type_, true, this->location()))
3652 this->set_is_error();
3653 }
3654 }
3655 }
3656
3657 // Return the backend representation for a const reference.
3658
3659 Bexpression*
do_get_backend(Translate_context * context)3660 Const_expression::do_get_backend(Translate_context* context)
3661 {
3662 if (this->is_error_expression()
3663 || (this->type_ != NULL && this->type_->is_error()))
3664 {
3665 go_assert(saw_errors());
3666 return context->backend()->error_expression();
3667 }
3668
3669 // If the type has been set for this expression, but the underlying
3670 // object is an abstract int or float, we try to get the abstract
3671 // value. Otherwise we may lose something in the conversion.
3672 Expression* expr = this->constant_->const_value()->expr();
3673 if (this->type_ != NULL
3674 && this->type_->is_numeric_type()
3675 && (this->constant_->const_value()->type() == NULL
3676 || this->constant_->const_value()->type()->is_abstract()))
3677 {
3678 Numeric_constant nc;
3679 if (expr->numeric_constant_value(&nc)
3680 && nc.set_type(this->type_, false, this->location()))
3681 {
3682 Expression* e = nc.expression(this->location());
3683 return e->get_backend(context);
3684 }
3685 }
3686
3687 if (this->type_ != NULL)
3688 expr = Expression::make_cast(this->type_, expr, this->location());
3689 return expr->get_backend(context);
3690 }
3691
3692 // Dump ast representation for constant expression.
3693
3694 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3695 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3696 {
3697 ast_dump_context->ostream() << this->constant_->name();
3698 }
3699
3700 // Make a reference to a constant in an expression.
3701
3702 Expression*
make_const_reference(Named_object * constant,Location location)3703 Expression::make_const_reference(Named_object* constant,
3704 Location location)
3705 {
3706 return new Const_expression(constant, location);
3707 }
3708
3709 // Find a named object in an expression.
3710
3711 int
expression(Expression ** pexpr)3712 Find_named_object::expression(Expression** pexpr)
3713 {
3714 switch ((*pexpr)->classification())
3715 {
3716 case Expression::EXPRESSION_CONST_REFERENCE:
3717 {
3718 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3719 if (ce->named_object() == this->no_)
3720 break;
3721
3722 // We need to check a constant initializer explicitly, as
3723 // loops here will not be caught by the loop checking for
3724 // variable initializers.
3725 ce->check_for_init_loop();
3726
3727 return TRAVERSE_CONTINUE;
3728 }
3729
3730 case Expression::EXPRESSION_VAR_REFERENCE:
3731 if ((*pexpr)->var_expression()->named_object() == this->no_)
3732 break;
3733 return TRAVERSE_CONTINUE;
3734 case Expression::EXPRESSION_FUNC_REFERENCE:
3735 if ((*pexpr)->func_expression()->named_object() == this->no_)
3736 break;
3737 return TRAVERSE_CONTINUE;
3738 default:
3739 return TRAVERSE_CONTINUE;
3740 }
3741 this->found_ = true;
3742 return TRAVERSE_EXIT;
3743 }
3744
3745 // The nil value.
3746
3747 class Nil_expression : public Expression
3748 {
3749 public:
Nil_expression(Location location)3750 Nil_expression(Location location)
3751 : Expression(EXPRESSION_NIL, location)
3752 { }
3753
3754 static Expression*
3755 do_import(Import_expression*, Location);
3756
3757 protected:
3758 bool
do_is_constant() const3759 do_is_constant() const
3760 { return true; }
3761
3762 bool
do_is_zero_value() const3763 do_is_zero_value() const
3764 { return true; }
3765
3766 bool
do_is_static_initializer() const3767 do_is_static_initializer() const
3768 { return true; }
3769
3770 Type*
do_type()3771 do_type()
3772 { return Type::make_nil_type(); }
3773
3774 void
do_determine_type(const Type_context *)3775 do_determine_type(const Type_context*)
3776 { }
3777
3778 Expression*
do_copy()3779 do_copy()
3780 { return this; }
3781
3782 Bexpression*
do_get_backend(Translate_context * context)3783 do_get_backend(Translate_context* context)
3784 { return context->backend()->nil_pointer_expression(); }
3785
3786 int
do_inlining_cost() const3787 do_inlining_cost() const
3788 { return 1; }
3789
3790 void
do_export(Export_function_body * efb) const3791 do_export(Export_function_body* efb) const
3792 { efb->write_c_string("$nil"); }
3793
3794 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3795 do_dump_expression(Ast_dump_context* ast_dump_context) const
3796 { ast_dump_context->ostream() << "nil"; }
3797 };
3798
3799 // Import a nil expression.
3800
3801 Expression*
do_import(Import_expression * imp,Location loc)3802 Nil_expression::do_import(Import_expression* imp, Location loc)
3803 {
3804 if (imp->version() >= EXPORT_FORMAT_V3)
3805 imp->require_c_string("$");
3806 imp->require_c_string("nil");
3807 return Expression::make_nil(loc);
3808 }
3809
3810 // Make a nil expression.
3811
3812 Expression*
make_nil(Location location)3813 Expression::make_nil(Location location)
3814 {
3815 return new Nil_expression(location);
3816 }
3817
3818 // The value of the predeclared constant iota. This is little more
3819 // than a marker. This will be lowered to an integer in
3820 // Const_expression::do_lower, which is where we know the value that
3821 // it should have.
3822
3823 class Iota_expression : public Parser_expression
3824 {
3825 public:
Iota_expression(Location location)3826 Iota_expression(Location location)
3827 : Parser_expression(EXPRESSION_IOTA, location)
3828 { }
3829
3830 protected:
3831 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3832 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3833 { go_unreachable(); }
3834
3835 // There should only ever be one of these.
3836 Expression*
do_copy()3837 do_copy()
3838 { go_unreachable(); }
3839
3840 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3841 do_dump_expression(Ast_dump_context* ast_dump_context) const
3842 { ast_dump_context->ostream() << "iota"; }
3843 };
3844
3845 // Make an iota expression. This is only called for one case: the
3846 // value of the predeclared constant iota.
3847
3848 Expression*
make_iota()3849 Expression::make_iota()
3850 {
3851 static Iota_expression iota_expression(Linemap::unknown_location());
3852 return &iota_expression;
3853 }
3854
3855 // Class Type_conversion_expression.
3856
3857 // Traversal.
3858
3859 int
do_traverse(Traverse * traverse)3860 Type_conversion_expression::do_traverse(Traverse* traverse)
3861 {
3862 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3863 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3864 return TRAVERSE_EXIT;
3865 return TRAVERSE_CONTINUE;
3866 }
3867
3868 // Convert to a constant at lowering time.
3869
3870 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3871 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3872 Statement_inserter*, int)
3873 {
3874 Type* type = this->type_;
3875 Expression* val = this->expr_;
3876 Location location = this->location();
3877
3878 if (type->is_numeric_type())
3879 {
3880 Numeric_constant nc;
3881 if (val->numeric_constant_value(&nc))
3882 {
3883 if (!nc.set_type(type, true, location))
3884 return Expression::make_error(location);
3885 return nc.expression(location);
3886 }
3887 }
3888
3889 // According to the language specification on string conversions
3890 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3891 // When converting an integer into a string, the string will be a UTF-8
3892 // representation of the integer and integers "outside the range of valid
3893 // Unicode code points are converted to '\uFFFD'."
3894 if (type->is_string_type())
3895 {
3896 Numeric_constant nc;
3897 if (val->numeric_constant_value(&nc) && nc.is_int())
3898 {
3899 // An integer value doesn't fit in the Unicode code point range if it
3900 // overflows the Go "int" type or is negative.
3901 unsigned long ul;
3902 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3903 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3904 return Expression::make_string("\ufffd", location);
3905 }
3906 }
3907
3908 if (type->is_slice_type())
3909 {
3910 Type* element_type = type->array_type()->element_type()->forwarded();
3911 bool is_byte = (element_type->integer_type() != NULL
3912 && element_type->integer_type()->is_byte());
3913 bool is_rune = (element_type->integer_type() != NULL
3914 && element_type->integer_type()->is_rune());
3915 if (is_byte || is_rune)
3916 {
3917 std::string s;
3918 if (val->string_constant_value(&s))
3919 {
3920 Expression_list* vals = new Expression_list();
3921 if (is_byte)
3922 {
3923 for (std::string::const_iterator p = s.begin();
3924 p != s.end();
3925 p++)
3926 {
3927 unsigned char c = static_cast<unsigned char>(*p);
3928 vals->push_back(Expression::make_integer_ul(c,
3929 element_type,
3930 location));
3931 }
3932 }
3933 else
3934 {
3935 const char *p = s.data();
3936 const char *pend = s.data() + s.length();
3937 while (p < pend)
3938 {
3939 unsigned int c;
3940 int adv = Lex::fetch_char(p, &c);
3941 if (adv == 0)
3942 {
3943 go_warning_at(this->location(), 0,
3944 "invalid UTF-8 encoding");
3945 adv = 1;
3946 }
3947 p += adv;
3948 vals->push_back(Expression::make_integer_ul(c,
3949 element_type,
3950 location));
3951 }
3952 }
3953
3954 return Expression::make_slice_composite_literal(type, vals,
3955 location);
3956 }
3957 }
3958 }
3959
3960 return this;
3961 }
3962
3963 // Flatten a type conversion by using a temporary variable for the slice
3964 // in slice to string conversions.
3965
3966 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)3967 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3968 Statement_inserter* inserter)
3969 {
3970 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3971 {
3972 go_assert(saw_errors());
3973 return Expression::make_error(this->location());
3974 }
3975
3976 if (((this->type()->is_string_type()
3977 && this->expr_->type()->is_slice_type())
3978 || this->expr_->type()->interface_type() != NULL)
3979 && !this->expr_->is_multi_eval_safe())
3980 {
3981 Temporary_statement* temp =
3982 Statement::make_temporary(NULL, this->expr_, this->location());
3983 inserter->insert(temp);
3984 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3985 }
3986
3987 // For interface conversion and string to/from slice conversions,
3988 // decide if we can allocate on stack.
3989 if (this->type()->interface_type() != NULL
3990 || this->type()->is_string_type()
3991 || this->expr_->type()->is_string_type())
3992 {
3993 Node* n = Node::make_node(this);
3994 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
3995 this->no_escape_ = true;
3996 }
3997 return this;
3998 }
3999
4000 // Return whether a type conversion is a constant.
4001
4002 bool
do_is_constant() const4003 Type_conversion_expression::do_is_constant() const
4004 {
4005 if (!this->expr_->is_constant())
4006 return false;
4007
4008 // A conversion to a type that may not be used as a constant is not
4009 // a constant. For example, []byte(nil).
4010 Type* type = this->type_;
4011 if (type->integer_type() == NULL
4012 && type->float_type() == NULL
4013 && type->complex_type() == NULL
4014 && !type->is_boolean_type()
4015 && !type->is_string_type())
4016 return false;
4017
4018 return true;
4019 }
4020
4021 // Return whether a type conversion is a zero value.
4022
4023 bool
do_is_zero_value() const4024 Type_conversion_expression::do_is_zero_value() const
4025 {
4026 if (!this->expr_->is_zero_value())
4027 return false;
4028
4029 // Some type conversion from zero value is still not zero value.
4030 // For example, []byte("") or interface{}(0).
4031 // Conservatively, only report true if the RHS is nil.
4032 Type* type = this->type_;
4033 if (type->integer_type() == NULL
4034 && type->float_type() == NULL
4035 && type->complex_type() == NULL
4036 && !type->is_boolean_type()
4037 && !type->is_string_type())
4038 return this->expr_->is_nil_expression();
4039
4040 return true;
4041 }
4042
4043 // Return whether a type conversion can be used in a constant
4044 // initializer.
4045
4046 bool
do_is_static_initializer() const4047 Type_conversion_expression::do_is_static_initializer() const
4048 {
4049 Type* type = this->type_;
4050 Type* expr_type = this->expr_->type();
4051
4052 if (type->interface_type() != NULL
4053 || expr_type->interface_type() != NULL)
4054 return false;
4055
4056 if (!this->expr_->is_static_initializer())
4057 return false;
4058
4059 if (Type::are_identical(type, expr_type,
4060 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4061 NULL))
4062 return true;
4063
4064 if (type->is_string_type() && expr_type->is_string_type())
4065 return true;
4066
4067 if ((type->is_numeric_type()
4068 || type->is_boolean_type()
4069 || type->points_to() != NULL)
4070 && (expr_type->is_numeric_type()
4071 || expr_type->is_boolean_type()
4072 || expr_type->points_to() != NULL))
4073 return true;
4074
4075 return false;
4076 }
4077
4078 // Return the constant numeric value if there is one.
4079
4080 bool
do_numeric_constant_value(Numeric_constant * nc) const4081 Type_conversion_expression::do_numeric_constant_value(
4082 Numeric_constant* nc) const
4083 {
4084 if (!this->type_->is_numeric_type())
4085 return false;
4086 if (!this->expr_->numeric_constant_value(nc))
4087 return false;
4088 return nc->set_type(this->type_, false, this->location());
4089 }
4090
4091 // Return the constant string value if there is one.
4092
4093 bool
do_string_constant_value(std::string * val) const4094 Type_conversion_expression::do_string_constant_value(std::string* val) const
4095 {
4096 if (this->type_->is_string_type()
4097 && this->expr_->type()->integer_type() != NULL)
4098 {
4099 Numeric_constant nc;
4100 if (this->expr_->numeric_constant_value(&nc))
4101 {
4102 unsigned long ival;
4103 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
4104 {
4105 unsigned int cval = static_cast<unsigned int>(ival);
4106 if (static_cast<unsigned long>(cval) != ival)
4107 {
4108 go_warning_at(this->location(), 0,
4109 "unicode code point 0x%lx out of range",
4110 ival);
4111 cval = 0xfffd; // Unicode "replacement character."
4112 }
4113 val->clear();
4114 Lex::append_char(cval, true, val, this->location());
4115 return true;
4116 }
4117 }
4118 }
4119
4120 // FIXME: Could handle conversion from const []int here.
4121
4122 return false;
4123 }
4124
4125 // Return the constant boolean value if there is one.
4126
4127 bool
do_boolean_constant_value(bool * val) const4128 Type_conversion_expression::do_boolean_constant_value(bool* val) const
4129 {
4130 if (!this->type_->is_boolean_type())
4131 return false;
4132 return this->expr_->boolean_constant_value(val);
4133 }
4134
4135 // Determine the resulting type of the conversion.
4136
4137 void
do_determine_type(const Type_context *)4138 Type_conversion_expression::do_determine_type(const Type_context*)
4139 {
4140 Type_context subcontext(this->type_, false);
4141 this->expr_->determine_type(&subcontext);
4142 }
4143
4144 // Check that types are convertible.
4145
4146 void
do_check_types(Gogo *)4147 Type_conversion_expression::do_check_types(Gogo*)
4148 {
4149 Type* type = this->type_;
4150 Type* expr_type = this->expr_->type();
4151 std::string reason;
4152
4153 if (type->is_error() || expr_type->is_error())
4154 {
4155 this->set_is_error();
4156 return;
4157 }
4158
4159 if (this->may_convert_function_types_
4160 && type->function_type() != NULL
4161 && expr_type->function_type() != NULL)
4162 return;
4163
4164 if (Type::are_convertible(type, expr_type, &reason))
4165 return;
4166
4167 go_error_at(this->location(), "%s", reason.c_str());
4168 this->set_is_error();
4169 }
4170
4171 // Copy.
4172
4173 Expression*
do_copy()4174 Type_conversion_expression::do_copy()
4175 {
4176 Expression* ret = new Type_conversion_expression(this->type_->copy_expressions(),
4177 this->expr_->copy(),
4178 this->location());
4179 ret->conversion_expression()->set_no_copy(this->no_copy_);
4180 return ret;
4181 }
4182
4183 // Get the backend representation for a type conversion.
4184
4185 Bexpression*
do_get_backend(Translate_context * context)4186 Type_conversion_expression::do_get_backend(Translate_context* context)
4187 {
4188 Type* type = this->type_;
4189 Type* expr_type = this->expr_->type();
4190
4191 Gogo* gogo = context->gogo();
4192 Btype* btype = type->get_backend(gogo);
4193 Location loc = this->location();
4194
4195 if (Type::are_identical(type, expr_type,
4196 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
4197 NULL))
4198 {
4199 Bexpression* bexpr = this->expr_->get_backend(context);
4200 return gogo->backend()->convert_expression(btype, bexpr, loc);
4201 }
4202 else if (type->interface_type() != NULL
4203 && expr_type->interface_type() == NULL)
4204 {
4205 Expression* conversion =
4206 Expression::convert_type_to_interface(type, this->expr_,
4207 this->no_escape_, loc);
4208 return conversion->get_backend(context);
4209 }
4210 else if (type->interface_type() != NULL
4211 || expr_type->interface_type() != NULL)
4212 {
4213 Expression* conversion =
4214 Expression::convert_for_assignment(gogo, type, this->expr_,
4215 loc);
4216 return conversion->get_backend(context);
4217 }
4218 else if (type->is_string_type()
4219 && expr_type->integer_type() != NULL)
4220 {
4221 mpz_t intval;
4222 Numeric_constant nc;
4223 if (this->expr_->numeric_constant_value(&nc)
4224 && nc.to_int(&intval))
4225 {
4226 std::string s;
4227 unsigned int x;
4228 if (mpz_fits_uint_p(intval))
4229 x = mpz_get_ui(intval);
4230 else
4231 {
4232 char* ms = mpz_get_str(NULL, 16, intval);
4233 go_warning_at(loc, 0,
4234 "unicode code point 0x%s out of range in string",
4235 ms);
4236 free(ms);
4237 x = 0xfffd;
4238 }
4239 Lex::append_char(x, true, &s, loc);
4240 mpz_clear(intval);
4241 Expression* se = Expression::make_string(s, loc);
4242 return se->get_backend(context);
4243 }
4244
4245 Expression* buf;
4246 if (this->no_escape_)
4247 {
4248 Type* byte_type = Type::lookup_integer_type("uint8");
4249 Expression* buflen =
4250 Expression::make_integer_ul(4, NULL, loc);
4251 Type* array_type = Type::make_array_type(byte_type, buflen);
4252 buf = Expression::make_allocation(array_type, loc);
4253 buf->allocation_expression()->set_allocate_on_stack();
4254 buf->allocation_expression()->set_no_zero();
4255 }
4256 else
4257 buf = Expression::make_nil(loc);
4258 Expression* i2s_expr =
4259 Runtime::make_call(Runtime::INTSTRING, loc, 2, buf, this->expr_);
4260 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
4261 }
4262 else if (type->is_string_type() && expr_type->is_slice_type())
4263 {
4264 Array_type* a = expr_type->array_type();
4265 Type* e = a->element_type()->forwarded();
4266 go_assert(e->integer_type() != NULL);
4267 go_assert(this->expr_->is_multi_eval_safe());
4268
4269 Expression* buf;
4270 if (this->no_escape_ && !this->no_copy_)
4271 {
4272 Type* byte_type = Type::lookup_integer_type("uint8");
4273 Expression* buflen =
4274 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4275 Type* array_type = Type::make_array_type(byte_type, buflen);
4276 buf = Expression::make_allocation(array_type, loc);
4277 buf->allocation_expression()->set_allocate_on_stack();
4278 buf->allocation_expression()->set_no_zero();
4279 }
4280 else
4281 buf = Expression::make_nil(loc);
4282
4283 if (e->integer_type()->is_byte())
4284 {
4285 Expression* ptr =
4286 Expression::make_slice_info(this->expr_, SLICE_INFO_VALUE_POINTER,
4287 loc);
4288 Expression* len =
4289 Expression::make_slice_info(this->expr_, SLICE_INFO_LENGTH, loc);
4290 if (this->no_copy_)
4291 {
4292 if (gogo->debug_optimization())
4293 go_debug(loc, "no copy string([]byte)");
4294 Expression* str = Expression::make_string_value(ptr, len, loc);
4295 return str->get_backend(context);
4296 }
4297 return Runtime::make_call(Runtime::SLICEBYTETOSTRING, loc, 3, buf,
4298 ptr, len)->get_backend(context);
4299 }
4300 else
4301 {
4302 go_assert(e->integer_type()->is_rune());
4303 return Runtime::make_call(Runtime::SLICERUNETOSTRING, loc, 2, buf,
4304 this->expr_)->get_backend(context);
4305 }
4306 }
4307 else if (type->is_slice_type() && expr_type->is_string_type())
4308 {
4309 Type* e = type->array_type()->element_type()->forwarded();
4310 go_assert(e->integer_type() != NULL);
4311
4312 Runtime::Function code;
4313 if (e->integer_type()->is_byte())
4314 code = Runtime::STRINGTOSLICEBYTE;
4315 else
4316 {
4317 go_assert(e->integer_type()->is_rune());
4318 code = Runtime::STRINGTOSLICERUNE;
4319 }
4320
4321 Expression* buf;
4322 if (this->no_escape_)
4323 {
4324 Expression* buflen =
4325 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
4326 Type* array_type = Type::make_array_type(e, buflen);
4327 buf = Expression::make_allocation(array_type, loc);
4328 buf->allocation_expression()->set_allocate_on_stack();
4329 buf->allocation_expression()->set_no_zero();
4330 }
4331 else
4332 buf = Expression::make_nil(loc);
4333 Expression* s2a = Runtime::make_call(code, loc, 2, buf, this->expr_);
4334 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
4335 }
4336 else if (type->is_numeric_type())
4337 {
4338 go_assert(Type::are_convertible(type, expr_type, NULL));
4339 Bexpression* bexpr = this->expr_->get_backend(context);
4340 return gogo->backend()->convert_expression(btype, bexpr, loc);
4341 }
4342 else if ((type->is_unsafe_pointer_type()
4343 && (expr_type->points_to() != NULL
4344 || expr_type->integer_type()))
4345 || (expr_type->is_unsafe_pointer_type()
4346 && type->points_to() != NULL)
4347 || (this->may_convert_function_types_
4348 && type->function_type() != NULL
4349 && expr_type->function_type() != NULL))
4350 {
4351 Bexpression* bexpr = this->expr_->get_backend(context);
4352 return gogo->backend()->convert_expression(btype, bexpr, loc);
4353 }
4354 else
4355 {
4356 Expression* conversion =
4357 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
4358 return conversion->get_backend(context);
4359 }
4360 }
4361
4362 // Cost of inlining a type conversion.
4363
4364 int
do_inlining_cost() const4365 Type_conversion_expression::do_inlining_cost() const
4366 {
4367 Type* type = this->type_;
4368 Type* expr_type = this->expr_->type();
4369 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
4370 return 10;
4371 else if (type->is_string_type() && expr_type->integer_type() != NULL)
4372 return 10;
4373 else if (type->is_string_type() && expr_type->is_slice_type())
4374 return 10;
4375 else if (type->is_slice_type() && expr_type->is_string_type())
4376 return 10;
4377 else
4378 return 1;
4379 }
4380
4381 // Output a type conversion in a constant expression.
4382
4383 void
do_export(Export_function_body * efb) const4384 Type_conversion_expression::do_export(Export_function_body* efb) const
4385 {
4386 efb->write_c_string("$convert(");
4387 efb->write_type(this->type_);
4388 efb->write_c_string(", ");
4389
4390 Type* old_context = efb->type_context();
4391 efb->set_type_context(this->type_);
4392
4393 this->expr_->export_expression(efb);
4394
4395 efb->set_type_context(old_context);
4396
4397 efb->write_c_string(")");
4398 }
4399
4400 // Import a type conversion or a struct construction.
4401
4402 Expression*
do_import(Import_expression * imp,Location loc)4403 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
4404 {
4405 imp->require_c_string("$convert(");
4406 Type* type = imp->read_type();
4407 imp->require_c_string(", ");
4408 Expression* val = Expression::import_expression(imp, loc);
4409 imp->require_c_string(")");
4410 return Expression::make_cast(type, val, loc);
4411 }
4412
4413 // Dump ast representation for a type conversion expression.
4414
4415 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4416 Type_conversion_expression::do_dump_expression(
4417 Ast_dump_context* ast_dump_context) const
4418 {
4419 ast_dump_context->dump_type(this->type_);
4420 ast_dump_context->ostream() << "(";
4421 ast_dump_context->dump_expression(this->expr_);
4422 ast_dump_context->ostream() << ") ";
4423 }
4424
4425 // Make a type cast expression.
4426
4427 Expression*
make_cast(Type * type,Expression * val,Location location)4428 Expression::make_cast(Type* type, Expression* val, Location location)
4429 {
4430 if (type->is_error_type() || val->is_error_expression())
4431 return Expression::make_error(location);
4432 return new Type_conversion_expression(type, val, location);
4433 }
4434
4435 // Class Unsafe_type_conversion_expression.
4436
4437 // Traversal.
4438
4439 int
do_traverse(Traverse * traverse)4440 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
4441 {
4442 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
4443 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4444 return TRAVERSE_EXIT;
4445 return TRAVERSE_CONTINUE;
4446 }
4447
4448 // Return whether an unsafe type conversion can be used as a constant
4449 // initializer.
4450
4451 bool
do_is_static_initializer() const4452 Unsafe_type_conversion_expression::do_is_static_initializer() const
4453 {
4454 Type* type = this->type_;
4455 Type* expr_type = this->expr_->type();
4456
4457 if (type->interface_type() != NULL
4458 || expr_type->interface_type() != NULL)
4459 return false;
4460
4461 if (!this->expr_->is_static_initializer())
4462 return false;
4463
4464 if (Type::are_convertible(type, expr_type, NULL))
4465 return true;
4466
4467 if (type->is_string_type() && expr_type->is_string_type())
4468 return true;
4469
4470 if ((type->is_numeric_type()
4471 || type->is_boolean_type()
4472 || type->points_to() != NULL)
4473 && (expr_type->is_numeric_type()
4474 || expr_type->is_boolean_type()
4475 || expr_type->points_to() != NULL))
4476 return true;
4477
4478 return false;
4479 }
4480
4481 // Copy.
4482
4483 Expression*
do_copy()4484 Unsafe_type_conversion_expression::do_copy()
4485 {
4486 return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
4487 this->expr_->copy(),
4488 this->location());
4489 }
4490
4491 // Convert to backend representation.
4492
4493 Bexpression*
do_get_backend(Translate_context * context)4494 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
4495 {
4496 // We are only called for a limited number of cases.
4497
4498 Type* t = this->type_;
4499 Type* et = this->expr_->type();
4500
4501 if (t->is_error_type()
4502 || this->expr_->is_error_expression()
4503 || et->is_error_type())
4504 {
4505 go_assert(saw_errors());
4506 return context->backend()->error_expression();
4507 }
4508
4509 if (t->array_type() != NULL)
4510 go_assert(et->array_type() != NULL
4511 && t->is_slice_type() == et->is_slice_type());
4512 else if (t->struct_type() != NULL)
4513 {
4514 if (t->named_type() != NULL
4515 && et->named_type() != NULL
4516 && !Type::are_convertible(t, et, NULL))
4517 {
4518 go_assert(saw_errors());
4519 return context->backend()->error_expression();
4520 }
4521
4522 go_assert(et->struct_type() != NULL
4523 && Type::are_convertible(t, et, NULL));
4524 }
4525 else if (t->map_type() != NULL)
4526 go_assert(et->map_type() != NULL || et->points_to() != NULL);
4527 else if (t->channel_type() != NULL)
4528 go_assert(et->channel_type() != NULL || et->points_to() != NULL);
4529 else if (t->points_to() != NULL)
4530 go_assert(et->points_to() != NULL
4531 || et->channel_type() != NULL
4532 || et->map_type() != NULL
4533 || et->function_type() != NULL
4534 || et->integer_type() != NULL
4535 || et->is_nil_type());
4536 else if (t->function_type() != NULL)
4537 go_assert(et->points_to() != NULL);
4538 else if (et->is_unsafe_pointer_type())
4539 go_assert(t->points_to() != NULL
4540 || (t->integer_type() != NULL
4541 && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
4542 else if (t->interface_type() != NULL)
4543 {
4544 bool empty_iface = t->interface_type()->is_empty();
4545 go_assert(et->interface_type() != NULL
4546 && et->interface_type()->is_empty() == empty_iface);
4547 }
4548 else if (t->integer_type() != NULL)
4549 go_assert(et->is_boolean_type()
4550 || et->integer_type() != NULL
4551 || et->function_type() != NULL
4552 || et->points_to() != NULL
4553 || et->map_type() != NULL
4554 || et->channel_type() != NULL
4555 || et->is_nil_type());
4556 else
4557 go_unreachable();
4558
4559 Gogo* gogo = context->gogo();
4560 Btype* btype = t->get_backend(gogo);
4561 Bexpression* bexpr = this->expr_->get_backend(context);
4562 Location loc = this->location();
4563 return gogo->backend()->convert_expression(btype, bexpr, loc);
4564 }
4565
4566 // Dump ast representation for an unsafe type conversion expression.
4567
4568 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4569 Unsafe_type_conversion_expression::do_dump_expression(
4570 Ast_dump_context* ast_dump_context) const
4571 {
4572 ast_dump_context->dump_type(this->type_);
4573 ast_dump_context->ostream() << "(";
4574 ast_dump_context->dump_expression(this->expr_);
4575 ast_dump_context->ostream() << ") ";
4576 }
4577
4578 // Make an unsafe type conversion expression.
4579
4580 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)4581 Expression::make_unsafe_cast(Type* type, Expression* expr,
4582 Location location)
4583 {
4584 return new Unsafe_type_conversion_expression(type, expr, location);
4585 }
4586
4587 // Class Unary_expression.
4588
4589 // Call the address_taken method of the operand if needed. This is
4590 // called after escape analysis but before inserting write barriers.
4591
4592 void
check_operand_address_taken(Gogo *)4593 Unary_expression::check_operand_address_taken(Gogo*)
4594 {
4595 if (this->op_ != OPERATOR_AND)
4596 return;
4597
4598 // If this->escapes_ is false at this point, then it was set to
4599 // false by an explicit call to set_does_not_escape, and the value
4600 // does not escape. If this->escapes_ is true, we may be able to
4601 // set it to false based on the escape analysis pass.
4602 if (this->escapes_)
4603 {
4604 Node* n = Node::make_node(this);
4605 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
4606 this->escapes_ = false;
4607 }
4608
4609 this->expr_->address_taken(this->escapes_);
4610 }
4611
4612 // If we are taking the address of a composite literal, and the
4613 // contents are not constant, then we want to make a heap expression
4614 // instead.
4615
4616 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)4617 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4618 {
4619 Location loc = this->location();
4620 Operator op = this->op_;
4621 Expression* expr = this->expr_;
4622
4623 if (op == OPERATOR_MULT && expr->is_type_expression())
4624 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4625
4626 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
4627 // moving x to the heap. FIXME: Is it worth doing a real escape
4628 // analysis here? This case is found in math/unsafe.go and is
4629 // therefore worth special casing.
4630 if (op == OPERATOR_MULT)
4631 {
4632 Expression* e = expr;
4633 while (e->classification() == EXPRESSION_CONVERSION)
4634 {
4635 Type_conversion_expression* te
4636 = static_cast<Type_conversion_expression*>(e);
4637 e = te->expr();
4638 }
4639
4640 if (e->classification() == EXPRESSION_UNARY)
4641 {
4642 Unary_expression* ue = static_cast<Unary_expression*>(e);
4643 if (ue->op_ == OPERATOR_AND)
4644 {
4645 if (e == expr)
4646 {
4647 // *&x == x.
4648 if (!ue->expr_->is_addressable() && !ue->create_temp_)
4649 {
4650 go_error_at(ue->location(),
4651 "invalid operand for unary %<&%>");
4652 this->set_is_error();
4653 }
4654 return ue->expr_;
4655 }
4656 ue->set_does_not_escape();
4657 }
4658 }
4659 }
4660
4661 // Catching an invalid indirection of unsafe.Pointer here avoid
4662 // having to deal with TYPE_VOID in other places.
4663 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4664 {
4665 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4666 return Expression::make_error(this->location());
4667 }
4668
4669 // Check for an invalid pointer dereference. We need to do this
4670 // here because Unary_expression::do_type will return an error type
4671 // in this case. That can cause code to appear erroneous, and
4672 // therefore disappear at lowering time, without any error message.
4673 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
4674 {
4675 this->report_error(_("expected pointer"));
4676 return Expression::make_error(this->location());
4677 }
4678
4679 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
4680 {
4681 Numeric_constant nc;
4682 if (expr->numeric_constant_value(&nc))
4683 {
4684 Numeric_constant result;
4685 bool issued_error;
4686 if (Unary_expression::eval_constant(op, &nc, loc, &result,
4687 &issued_error))
4688 return result.expression(loc);
4689 else if (issued_error)
4690 return Expression::make_error(this->location());
4691 }
4692 }
4693
4694 return this;
4695 }
4696
4697 // Flatten expression if a nil check must be performed and create temporary
4698 // variables if necessary.
4699
4700 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)4701 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
4702 Statement_inserter* inserter)
4703 {
4704 if (this->is_error_expression()
4705 || this->expr_->is_error_expression()
4706 || this->expr_->type()->is_error_type())
4707 {
4708 go_assert(saw_errors());
4709 return Expression::make_error(this->location());
4710 }
4711
4712 Location location = this->location();
4713 if (this->op_ == OPERATOR_MULT
4714 && !this->expr_->is_multi_eval_safe())
4715 {
4716 go_assert(this->expr_->type()->points_to() != NULL);
4717 switch (this->requires_nil_check(gogo))
4718 {
4719 case NIL_CHECK_ERROR_ENCOUNTERED:
4720 {
4721 go_assert(saw_errors());
4722 return Expression::make_error(this->location());
4723 }
4724 case NIL_CHECK_NOT_NEEDED:
4725 break;
4726 case NIL_CHECK_NEEDED:
4727 this->create_temp_ = true;
4728 break;
4729 case NIL_CHECK_DEFAULT:
4730 go_unreachable();
4731 }
4732 }
4733
4734 if (this->create_temp_ && !this->expr_->is_multi_eval_safe())
4735 {
4736 Temporary_statement* temp =
4737 Statement::make_temporary(NULL, this->expr_, location);
4738 inserter->insert(temp);
4739 this->expr_ = Expression::make_temporary_reference(temp, location);
4740 }
4741
4742 return this;
4743 }
4744
4745 // Return whether a unary expression is a constant.
4746
4747 bool
do_is_constant() const4748 Unary_expression::do_is_constant() const
4749 {
4750 if (this->op_ == OPERATOR_MULT)
4751 {
4752 // Indirecting through a pointer is only constant if the object
4753 // to which the expression points is constant, but we currently
4754 // have no way to determine that.
4755 return false;
4756 }
4757 else if (this->op_ == OPERATOR_AND)
4758 {
4759 // Taking the address of a variable is constant if it is a
4760 // global variable, not constant otherwise. In other cases taking the
4761 // address is probably not a constant.
4762 Var_expression* ve = this->expr_->var_expression();
4763 if (ve != NULL)
4764 {
4765 Named_object* no = ve->named_object();
4766 return no->is_variable() && no->var_value()->is_global();
4767 }
4768 return false;
4769 }
4770 else
4771 return this->expr_->is_constant();
4772 }
4773
4774 // Return whether a unary expression can be used as a constant
4775 // initializer.
4776
4777 bool
do_is_static_initializer() const4778 Unary_expression::do_is_static_initializer() const
4779 {
4780 if (this->op_ == OPERATOR_MULT)
4781 return false;
4782 else if (this->op_ == OPERATOR_AND)
4783 return Unary_expression::base_is_static_initializer(this->expr_);
4784 else
4785 return this->expr_->is_static_initializer();
4786 }
4787
4788 // Return whether the address of EXPR can be used as a static
4789 // initializer.
4790
4791 bool
base_is_static_initializer(Expression * expr)4792 Unary_expression::base_is_static_initializer(Expression* expr)
4793 {
4794 // The address of a field reference can be a static initializer if
4795 // the base can be a static initializer.
4796 Field_reference_expression* fre = expr->field_reference_expression();
4797 if (fre != NULL)
4798 return Unary_expression::base_is_static_initializer(fre->expr());
4799
4800 // The address of an index expression can be a static initializer if
4801 // the base can be a static initializer and the index is constant.
4802 Array_index_expression* aind = expr->array_index_expression();
4803 if (aind != NULL)
4804 return (aind->end() == NULL
4805 && aind->start()->is_constant()
4806 && Unary_expression::base_is_static_initializer(aind->array()));
4807
4808 // The address of a global variable can be a static initializer.
4809 Var_expression* ve = expr->var_expression();
4810 if (ve != NULL)
4811 {
4812 Named_object* no = ve->named_object();
4813 return no->is_variable() && no->var_value()->is_global();
4814 }
4815
4816 // The address of a composite literal can be used as a static
4817 // initializer if the composite literal is itself usable as a
4818 // static initializer.
4819 if (expr->is_composite_literal() && expr->is_static_initializer())
4820 return true;
4821
4822 // The address of a string constant can be used as a static
4823 // initializer. This can not be written in Go itself but this is
4824 // used when building a type descriptor.
4825 if (expr->string_expression() != NULL)
4826 return true;
4827
4828 return false;
4829 }
4830
4831 // Return whether this dereference expression requires an explicit nil
4832 // check. If we are dereferencing the pointer to a large struct
4833 // (greater than the specified size threshold), we need to check for
4834 // nil. We don't bother to check for small structs because we expect
4835 // the system to crash on a nil pointer dereference. However, if we
4836 // know the address of this expression is being taken, we must always
4837 // check for nil.
4838 Unary_expression::Nil_check_classification
requires_nil_check(Gogo * gogo)4839 Unary_expression::requires_nil_check(Gogo* gogo)
4840 {
4841 go_assert(this->op_ == OPERATOR_MULT);
4842 go_assert(this->expr_->type()->points_to() != NULL);
4843
4844 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4845 return NIL_CHECK_NEEDED;
4846 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4847 return NIL_CHECK_NOT_NEEDED;
4848
4849 Type* ptype = this->expr_->type()->points_to();
4850 int64_t type_size = -1;
4851 if (!ptype->is_void_type())
4852 {
4853 bool ok = ptype->backend_type_size(gogo, &type_size);
4854 if (!ok)
4855 return NIL_CHECK_ERROR_ENCOUNTERED;
4856 }
4857
4858 int64_t size_cutoff = gogo->nil_check_size_threshold();
4859 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4860 this->issue_nil_check_ = NIL_CHECK_NEEDED;
4861 else
4862 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4863 return this->issue_nil_check_;
4864 }
4865
4866 // Apply unary opcode OP to UNC, setting NC. Return true if this
4867 // could be done, false if not. On overflow, issues an error and sets
4868 // *ISSUED_ERROR.
4869
4870 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)4871 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4872 Location location, Numeric_constant* nc,
4873 bool* issued_error)
4874 {
4875 *issued_error = false;
4876 switch (op)
4877 {
4878 case OPERATOR_PLUS:
4879 *nc = *unc;
4880 return true;
4881
4882 case OPERATOR_MINUS:
4883 if (unc->is_int() || unc->is_rune())
4884 break;
4885 else if (unc->is_float())
4886 {
4887 mpfr_t uval;
4888 unc->get_float(&uval);
4889 mpfr_t val;
4890 mpfr_init(val);
4891 mpfr_neg(val, uval, MPFR_RNDN);
4892 nc->set_float(unc->type(), val);
4893 mpfr_clear(uval);
4894 mpfr_clear(val);
4895 return true;
4896 }
4897 else if (unc->is_complex())
4898 {
4899 mpc_t uval;
4900 unc->get_complex(&uval);
4901 mpc_t val;
4902 mpc_init2(val, mpc_precision);
4903 mpc_neg(val, uval, MPC_RNDNN);
4904 nc->set_complex(unc->type(), val);
4905 mpc_clear(uval);
4906 mpc_clear(val);
4907 return true;
4908 }
4909 else
4910 go_unreachable();
4911
4912 case OPERATOR_XOR:
4913 break;
4914
4915 case OPERATOR_NOT:
4916 case OPERATOR_AND:
4917 case OPERATOR_MULT:
4918 return false;
4919
4920 default:
4921 go_unreachable();
4922 }
4923
4924 if (!unc->is_int() && !unc->is_rune())
4925 return false;
4926
4927 mpz_t uval;
4928 if (unc->is_rune())
4929 unc->get_rune(&uval);
4930 else
4931 unc->get_int(&uval);
4932 mpz_t val;
4933 mpz_init(val);
4934
4935 switch (op)
4936 {
4937 case OPERATOR_MINUS:
4938 mpz_neg(val, uval);
4939 break;
4940
4941 case OPERATOR_NOT:
4942 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4943 break;
4944
4945 case OPERATOR_XOR:
4946 {
4947 Type* utype = unc->type();
4948 if (utype->integer_type() == NULL
4949 || utype->integer_type()->is_abstract())
4950 mpz_com(val, uval);
4951 else
4952 {
4953 // The number of HOST_WIDE_INTs that it takes to represent
4954 // UVAL.
4955 size_t count = ((mpz_sizeinbase(uval, 2)
4956 + HOST_BITS_PER_WIDE_INT
4957 - 1)
4958 / HOST_BITS_PER_WIDE_INT);
4959
4960 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4961 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4962
4963 size_t obits = utype->integer_type()->bits();
4964
4965 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4966 {
4967 mpz_t adj;
4968 mpz_init_set_ui(adj, 1);
4969 mpz_mul_2exp(adj, adj, obits);
4970 mpz_add(uval, uval, adj);
4971 mpz_clear(adj);
4972 }
4973
4974 size_t ecount;
4975 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4976 go_assert(ecount <= count);
4977
4978 // Trim down to the number of words required by the type.
4979 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4980 / HOST_BITS_PER_WIDE_INT);
4981 go_assert(ocount <= count);
4982
4983 for (size_t i = 0; i < ocount; ++i)
4984 phwi[i] = ~phwi[i];
4985
4986 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4987 if (clearbits != 0)
4988 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4989 >> clearbits);
4990
4991 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4992
4993 if (!utype->integer_type()->is_unsigned()
4994 && mpz_tstbit(val, obits - 1))
4995 {
4996 mpz_t adj;
4997 mpz_init_set_ui(adj, 1);
4998 mpz_mul_2exp(adj, adj, obits);
4999 mpz_sub(val, val, adj);
5000 mpz_clear(adj);
5001 }
5002
5003 delete[] phwi;
5004 }
5005 }
5006 break;
5007
5008 default:
5009 go_unreachable();
5010 }
5011
5012 if (unc->is_rune())
5013 nc->set_rune(NULL, val);
5014 else
5015 nc->set_int(NULL, val);
5016
5017 mpz_clear(uval);
5018 mpz_clear(val);
5019
5020 if (!nc->set_type(unc->type(), true, location))
5021 {
5022 *issued_error = true;
5023 return false;
5024 }
5025 return true;
5026 }
5027
5028 // Return the integral constant value of a unary expression, if it has one.
5029
5030 bool
do_numeric_constant_value(Numeric_constant * nc) const5031 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5032 {
5033 Numeric_constant unc;
5034 if (!this->expr_->numeric_constant_value(&unc))
5035 return false;
5036 bool issued_error;
5037 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
5038 nc, &issued_error);
5039 }
5040
5041 // Return the boolean constant value of a unary expression, if it has one.
5042
5043 bool
do_boolean_constant_value(bool * val) const5044 Unary_expression::do_boolean_constant_value(bool* val) const
5045 {
5046 if (this->op_ == OPERATOR_NOT
5047 && this->expr_->boolean_constant_value(val))
5048 {
5049 *val = !*val;
5050 return true;
5051 }
5052 return false;
5053 }
5054
5055 // Return the type of a unary expression.
5056
5057 Type*
do_type()5058 Unary_expression::do_type()
5059 {
5060 switch (this->op_)
5061 {
5062 case OPERATOR_PLUS:
5063 case OPERATOR_MINUS:
5064 case OPERATOR_NOT:
5065 case OPERATOR_XOR:
5066 return this->expr_->type();
5067
5068 case OPERATOR_AND:
5069 return Type::make_pointer_type(this->expr_->type());
5070
5071 case OPERATOR_MULT:
5072 {
5073 Type* subtype = this->expr_->type();
5074 Type* points_to = subtype->points_to();
5075 if (points_to == NULL)
5076 return Type::make_error_type();
5077 return points_to;
5078 }
5079
5080 default:
5081 go_unreachable();
5082 }
5083 }
5084
5085 // Determine abstract types for a unary expression.
5086
5087 void
do_determine_type(const Type_context * context)5088 Unary_expression::do_determine_type(const Type_context* context)
5089 {
5090 switch (this->op_)
5091 {
5092 case OPERATOR_PLUS:
5093 case OPERATOR_MINUS:
5094 case OPERATOR_NOT:
5095 case OPERATOR_XOR:
5096 this->expr_->determine_type(context);
5097 break;
5098
5099 case OPERATOR_AND:
5100 // Taking the address of something.
5101 {
5102 Type* subtype = (context->type == NULL
5103 ? NULL
5104 : context->type->points_to());
5105 Type_context subcontext(subtype, false);
5106 this->expr_->determine_type(&subcontext);
5107 }
5108 break;
5109
5110 case OPERATOR_MULT:
5111 // Indirecting through a pointer.
5112 {
5113 Type* subtype = (context->type == NULL
5114 ? NULL
5115 : Type::make_pointer_type(context->type));
5116 Type_context subcontext(subtype, false);
5117 this->expr_->determine_type(&subcontext);
5118 }
5119 break;
5120
5121 default:
5122 go_unreachable();
5123 }
5124 }
5125
5126 // Check types for a unary expression.
5127
5128 void
do_check_types(Gogo *)5129 Unary_expression::do_check_types(Gogo*)
5130 {
5131 Type* type = this->expr_->type();
5132 if (type->is_error())
5133 {
5134 this->set_is_error();
5135 return;
5136 }
5137
5138 switch (this->op_)
5139 {
5140 case OPERATOR_PLUS:
5141 case OPERATOR_MINUS:
5142 if (type->integer_type() == NULL
5143 && type->float_type() == NULL
5144 && type->complex_type() == NULL)
5145 this->report_error(_("expected numeric type"));
5146 break;
5147
5148 case OPERATOR_NOT:
5149 if (!type->is_boolean_type())
5150 this->report_error(_("expected boolean type"));
5151 break;
5152
5153 case OPERATOR_XOR:
5154 if (type->integer_type() == NULL)
5155 this->report_error(_("expected integer"));
5156 break;
5157
5158 case OPERATOR_AND:
5159 if (!this->expr_->is_addressable())
5160 {
5161 if (!this->create_temp_)
5162 {
5163 go_error_at(this->location(), "invalid operand for unary %<&%>");
5164 this->set_is_error();
5165 }
5166 }
5167 else
5168 this->expr_->issue_nil_check();
5169 break;
5170
5171 case OPERATOR_MULT:
5172 // Indirecting through a pointer.
5173 if (type->points_to() == NULL)
5174 this->report_error(_("expected pointer"));
5175 if (type->points_to()->is_error())
5176 this->set_is_error();
5177 break;
5178
5179 default:
5180 go_unreachable();
5181 }
5182 }
5183
5184 // Get the backend representation for a unary expression.
5185
5186 Bexpression*
do_get_backend(Translate_context * context)5187 Unary_expression::do_get_backend(Translate_context* context)
5188 {
5189 Gogo* gogo = context->gogo();
5190 Location loc = this->location();
5191
5192 // Taking the address of a set-and-use-temporary expression requires
5193 // setting the temporary and then taking the address.
5194 if (this->op_ == OPERATOR_AND)
5195 {
5196 Set_and_use_temporary_expression* sut =
5197 this->expr_->set_and_use_temporary_expression();
5198 if (sut != NULL)
5199 {
5200 Temporary_statement* temp = sut->temporary();
5201 Bvariable* bvar = temp->get_backend_variable(context);
5202 Bexpression* bvar_expr =
5203 gogo->backend()->var_expression(bvar, loc);
5204 Bexpression* bval = sut->expression()->get_backend(context);
5205
5206 Named_object* fn = context->function();
5207 go_assert(fn != NULL);
5208 Bfunction* bfn =
5209 fn->func_value()->get_or_make_decl(gogo, fn);
5210 Bstatement* bassign =
5211 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
5212 Bexpression* bvar_addr =
5213 gogo->backend()->address_expression(bvar_expr, loc);
5214 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
5215 }
5216 }
5217
5218 Bexpression* ret;
5219 Bexpression* bexpr = this->expr_->get_backend(context);
5220 Btype* btype = this->expr_->type()->get_backend(gogo);
5221 switch (this->op_)
5222 {
5223 case OPERATOR_PLUS:
5224 ret = bexpr;
5225 break;
5226
5227 case OPERATOR_MINUS:
5228 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5229 ret = gogo->backend()->convert_expression(btype, ret, loc);
5230 break;
5231
5232 case OPERATOR_NOT:
5233 case OPERATOR_XOR:
5234 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
5235 break;
5236
5237 case OPERATOR_AND:
5238 if (!this->create_temp_)
5239 {
5240 // We should not see a non-constant constructor here; cases
5241 // where we would see one should have been moved onto the
5242 // heap at parse time. Taking the address of a nonconstant
5243 // constructor will not do what the programmer expects.
5244
5245 go_assert(!this->expr_->is_composite_literal()
5246 || this->expr_->is_static_initializer());
5247 if (this->expr_->classification() == EXPRESSION_UNARY)
5248 {
5249 Unary_expression* ue =
5250 static_cast<Unary_expression*>(this->expr_);
5251 go_assert(ue->op() != OPERATOR_AND);
5252 }
5253 }
5254
5255 if (this->is_gc_root_ || this->is_slice_init_)
5256 {
5257 std::string var_name;
5258 bool copy_to_heap = false;
5259 if (this->is_gc_root_)
5260 {
5261 // Build a decl for a GC root variable. GC roots are mutable, so
5262 // they cannot be represented as an immutable_struct in the
5263 // backend.
5264 var_name = gogo->gc_root_name();
5265 }
5266 else
5267 {
5268 // Build a decl for a slice value initializer. An immutable slice
5269 // value initializer may have to be copied to the heap if it
5270 // contains pointers in a non-constant context.
5271 var_name = gogo->initializer_name();
5272
5273 Array_type* at = this->expr_->type()->array_type();
5274 go_assert(at != NULL);
5275
5276 // If we are not copying the value to the heap, we will only
5277 // initialize the value once, so we can use this directly
5278 // rather than copying it. In that case we can't make it
5279 // read-only, because the program is permitted to change it.
5280 copy_to_heap = (context->function() != NULL
5281 || context->is_const());
5282 }
5283 Bvariable* implicit =
5284 gogo->backend()->implicit_variable(var_name, "", btype, true,
5285 copy_to_heap, false, 0);
5286 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
5287 true, copy_to_heap, false,
5288 bexpr);
5289 bexpr = gogo->backend()->var_expression(implicit, loc);
5290
5291 // If we are not copying a slice initializer to the heap,
5292 // then it can be changed by the program, so if it can
5293 // contain pointers we must register it as a GC root.
5294 if (this->is_slice_init_
5295 && !copy_to_heap
5296 && this->expr_->type()->has_pointer())
5297 {
5298 Bexpression* root =
5299 gogo->backend()->var_expression(implicit, loc);
5300 root = gogo->backend()->address_expression(root, loc);
5301 Type* type = Type::make_pointer_type(this->expr_->type());
5302 gogo->add_gc_root(Expression::make_backend(root, type, loc));
5303 }
5304 }
5305 else if ((this->expr_->is_composite_literal()
5306 || this->expr_->string_expression() != NULL)
5307 && this->expr_->is_static_initializer())
5308 {
5309 std::string var_name(gogo->initializer_name());
5310 Bvariable* decl =
5311 gogo->backend()->immutable_struct(var_name, "", true, false,
5312 btype, loc);
5313 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
5314 false, btype, loc, bexpr);
5315 bexpr = gogo->backend()->var_expression(decl, loc);
5316 }
5317 else if (this->expr_->is_constant())
5318 {
5319 std::string var_name(gogo->initializer_name());
5320 Bvariable* decl =
5321 gogo->backend()->implicit_variable(var_name, "", btype,
5322 true, true, false, 0);
5323 gogo->backend()->implicit_variable_set_init(decl, var_name, btype,
5324 true, true, false,
5325 bexpr);
5326 bexpr = gogo->backend()->var_expression(decl, loc);
5327 }
5328
5329 go_assert(!this->create_temp_ || this->expr_->is_multi_eval_safe());
5330 ret = gogo->backend()->address_expression(bexpr, loc);
5331 break;
5332
5333 case OPERATOR_MULT:
5334 {
5335 go_assert(this->expr_->type()->points_to() != NULL);
5336
5337 Type* ptype = this->expr_->type()->points_to();
5338 Btype* pbtype = ptype->get_backend(gogo);
5339 switch (this->requires_nil_check(gogo))
5340 {
5341 case NIL_CHECK_NOT_NEEDED:
5342 break;
5343 case NIL_CHECK_ERROR_ENCOUNTERED:
5344 {
5345 go_assert(saw_errors());
5346 return gogo->backend()->error_expression();
5347 }
5348 case NIL_CHECK_NEEDED:
5349 {
5350 go_assert(this->expr_->is_multi_eval_safe());
5351
5352 // If we're nil-checking the result of a set-and-use-temporary
5353 // expression, then pick out the target temp and use that
5354 // for the final result of the conditional.
5355 Bexpression* tbexpr = bexpr;
5356 Bexpression* ubexpr = bexpr;
5357 Set_and_use_temporary_expression* sut =
5358 this->expr_->set_and_use_temporary_expression();
5359 if (sut != NULL) {
5360 Temporary_statement* temp = sut->temporary();
5361 Bvariable* bvar = temp->get_backend_variable(context);
5362 ubexpr = gogo->backend()->var_expression(bvar, loc);
5363 }
5364 Bexpression* nil =
5365 Expression::make_nil(loc)->get_backend(context);
5366 Bexpression* compare =
5367 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
5368 nil, loc);
5369 Expression* crash = Runtime::make_call(Runtime::PANIC_MEM,
5370 loc, 0);
5371 Bexpression* bcrash = crash->get_backend(context);
5372 Bfunction* bfn = context->function()->func_value()->get_decl();
5373 bexpr = gogo->backend()->conditional_expression(bfn, btype,
5374 compare,
5375 bcrash, ubexpr,
5376 loc);
5377 break;
5378 }
5379 case NIL_CHECK_DEFAULT:
5380 go_unreachable();
5381 }
5382 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
5383 }
5384 break;
5385
5386 default:
5387 go_unreachable();
5388 }
5389
5390 return ret;
5391 }
5392
5393 // Export a unary expression.
5394
5395 void
do_export(Export_function_body * efb) const5396 Unary_expression::do_export(Export_function_body* efb) const
5397 {
5398 switch (this->op_)
5399 {
5400 case OPERATOR_PLUS:
5401 efb->write_c_string("+");
5402 break;
5403 case OPERATOR_MINUS:
5404 efb->write_c_string("-");
5405 break;
5406 case OPERATOR_NOT:
5407 efb->write_c_string("!");
5408 break;
5409 case OPERATOR_XOR:
5410 efb->write_c_string("^");
5411 break;
5412 case OPERATOR_AND:
5413 efb->write_c_string("&");
5414 break;
5415 case OPERATOR_MULT:
5416 efb->write_c_string("*");
5417 break;
5418 default:
5419 go_unreachable();
5420 }
5421 this->expr_->export_expression(efb);
5422 }
5423
5424 // Import a unary expression.
5425
5426 Expression*
do_import(Import_expression * imp,Location loc)5427 Unary_expression::do_import(Import_expression* imp, Location loc)
5428 {
5429 Operator op;
5430 switch (imp->get_char())
5431 {
5432 case '+':
5433 op = OPERATOR_PLUS;
5434 break;
5435 case '-':
5436 op = OPERATOR_MINUS;
5437 break;
5438 case '!':
5439 op = OPERATOR_NOT;
5440 break;
5441 case '^':
5442 op = OPERATOR_XOR;
5443 break;
5444 case '&':
5445 op = OPERATOR_AND;
5446 break;
5447 case '*':
5448 op = OPERATOR_MULT;
5449 break;
5450 default:
5451 go_unreachable();
5452 }
5453 if (imp->version() < EXPORT_FORMAT_V3)
5454 imp->require_c_string(" ");
5455 Expression* expr = Expression::import_expression(imp, loc);
5456 return Expression::make_unary(op, expr, loc);
5457 }
5458
5459 // Dump ast representation of an unary expression.
5460
5461 void
do_dump_expression(Ast_dump_context * ast_dump_context) const5462 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5463 {
5464 ast_dump_context->dump_operator(this->op_);
5465 ast_dump_context->ostream() << "(";
5466 ast_dump_context->dump_expression(this->expr_);
5467 ast_dump_context->ostream() << ") ";
5468 }
5469
5470 // Make a unary expression.
5471
5472 Expression*
make_unary(Operator op,Expression * expr,Location location)5473 Expression::make_unary(Operator op, Expression* expr, Location location)
5474 {
5475 return new Unary_expression(op, expr, location);
5476 }
5477
5478 Expression*
make_dereference(Expression * ptr,Nil_check_classification docheck,Location location)5479 Expression::make_dereference(Expression* ptr,
5480 Nil_check_classification docheck,
5481 Location location)
5482 {
5483 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
5484 if (docheck == NIL_CHECK_NEEDED)
5485 deref->unary_expression()->set_requires_nil_check(true);
5486 else if (docheck == NIL_CHECK_NOT_NEEDED)
5487 deref->unary_expression()->set_requires_nil_check(false);
5488 return deref;
5489 }
5490
5491 // If this is an indirection through a pointer, return the expression
5492 // being pointed through. Otherwise return this.
5493
5494 Expression*
deref()5495 Expression::deref()
5496 {
5497 if (this->classification_ == EXPRESSION_UNARY)
5498 {
5499 Unary_expression* ue = static_cast<Unary_expression*>(this);
5500 if (ue->op() == OPERATOR_MULT)
5501 return ue->operand();
5502 }
5503 return this;
5504 }
5505
5506 // Class Binary_expression.
5507
5508 // Traversal.
5509
5510 int
do_traverse(Traverse * traverse)5511 Binary_expression::do_traverse(Traverse* traverse)
5512 {
5513 int t = Expression::traverse(&this->left_, traverse);
5514 if (t == TRAVERSE_EXIT)
5515 return TRAVERSE_EXIT;
5516 return Expression::traverse(&this->right_, traverse);
5517 }
5518
5519 // Return whether this expression may be used as a static initializer.
5520
5521 bool
do_is_static_initializer() const5522 Binary_expression::do_is_static_initializer() const
5523 {
5524 if (!this->left_->is_static_initializer()
5525 || !this->right_->is_static_initializer())
5526 return false;
5527
5528 // Addresses can be static initializers, but we can't implement
5529 // arbitray binary expressions of them.
5530 Unary_expression* lu = this->left_->unary_expression();
5531 Unary_expression* ru = this->right_->unary_expression();
5532 if (lu != NULL && lu->op() == OPERATOR_AND)
5533 {
5534 if (ru != NULL && ru->op() == OPERATOR_AND)
5535 return this->op_ == OPERATOR_MINUS;
5536 else
5537 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5538 }
5539 else if (ru != NULL && ru->op() == OPERATOR_AND)
5540 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
5541
5542 // Other cases should resolve in the backend.
5543 return true;
5544 }
5545
5546 // Return the type to use for a binary operation on operands of
5547 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
5548 // such may be NULL or abstract.
5549
5550 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)5551 Binary_expression::operation_type(Operator op, Type* left_type,
5552 Type* right_type, Type** result_type)
5553 {
5554 if (left_type != right_type
5555 && !left_type->is_abstract()
5556 && !right_type->is_abstract()
5557 && left_type->base() != right_type->base()
5558 && op != OPERATOR_LSHIFT
5559 && op != OPERATOR_RSHIFT)
5560 {
5561 // May be a type error--let it be diagnosed elsewhere.
5562 return false;
5563 }
5564
5565 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5566 {
5567 if (left_type->integer_type() != NULL)
5568 *result_type = left_type;
5569 else
5570 *result_type = Type::make_abstract_integer_type();
5571 }
5572 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
5573 *result_type = left_type;
5574 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
5575 *result_type = right_type;
5576 else if (!left_type->is_abstract())
5577 *result_type = left_type;
5578 else if (!right_type->is_abstract())
5579 *result_type = right_type;
5580 else if (left_type->complex_type() != NULL)
5581 *result_type = left_type;
5582 else if (right_type->complex_type() != NULL)
5583 *result_type = right_type;
5584 else if (left_type->float_type() != NULL)
5585 *result_type = left_type;
5586 else if (right_type->float_type() != NULL)
5587 *result_type = right_type;
5588 else if (left_type->integer_type() != NULL
5589 && left_type->integer_type()->is_rune())
5590 *result_type = left_type;
5591 else if (right_type->integer_type() != NULL
5592 && right_type->integer_type()->is_rune())
5593 *result_type = right_type;
5594 else
5595 *result_type = left_type;
5596
5597 return true;
5598 }
5599
5600 // Convert an integer comparison code and an operator to a boolean
5601 // value.
5602
5603 bool
cmp_to_bool(Operator op,int cmp)5604 Binary_expression::cmp_to_bool(Operator op, int cmp)
5605 {
5606 switch (op)
5607 {
5608 case OPERATOR_EQEQ:
5609 return cmp == 0;
5610 break;
5611 case OPERATOR_NOTEQ:
5612 return cmp != 0;
5613 break;
5614 case OPERATOR_LT:
5615 return cmp < 0;
5616 break;
5617 case OPERATOR_LE:
5618 return cmp <= 0;
5619 case OPERATOR_GT:
5620 return cmp > 0;
5621 case OPERATOR_GE:
5622 return cmp >= 0;
5623 default:
5624 go_unreachable();
5625 }
5626 }
5627
5628 // Compare constants according to OP.
5629
5630 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)5631 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
5632 Numeric_constant* right_nc,
5633 Location location, bool* result)
5634 {
5635 Type* left_type = left_nc->type();
5636 Type* right_type = right_nc->type();
5637
5638 Type* type;
5639 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5640 return false;
5641
5642 // When comparing an untyped operand to a typed operand, we are
5643 // effectively coercing the untyped operand to the other operand's
5644 // type, so make sure that is valid.
5645 if (!left_nc->set_type(type, true, location)
5646 || !right_nc->set_type(type, true, location))
5647 return false;
5648
5649 bool ret;
5650 int cmp;
5651 if (type->complex_type() != NULL)
5652 {
5653 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
5654 return false;
5655 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
5656 }
5657 else if (type->float_type() != NULL)
5658 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
5659 else
5660 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
5661
5662 if (ret)
5663 *result = Binary_expression::cmp_to_bool(op, cmp);
5664
5665 return ret;
5666 }
5667
5668 // Compare integer constants.
5669
5670 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5671 Binary_expression::compare_integer(const Numeric_constant* left_nc,
5672 const Numeric_constant* right_nc,
5673 int* cmp)
5674 {
5675 mpz_t left_val;
5676 if (!left_nc->to_int(&left_val))
5677 return false;
5678 mpz_t right_val;
5679 if (!right_nc->to_int(&right_val))
5680 {
5681 mpz_clear(left_val);
5682 return false;
5683 }
5684
5685 *cmp = mpz_cmp(left_val, right_val);
5686
5687 mpz_clear(left_val);
5688 mpz_clear(right_val);
5689
5690 return true;
5691 }
5692
5693 // Compare floating point constants.
5694
5695 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5696 Binary_expression::compare_float(const Numeric_constant* left_nc,
5697 const Numeric_constant* right_nc,
5698 int* cmp)
5699 {
5700 mpfr_t left_val;
5701 if (!left_nc->to_float(&left_val))
5702 return false;
5703 mpfr_t right_val;
5704 if (!right_nc->to_float(&right_val))
5705 {
5706 mpfr_clear(left_val);
5707 return false;
5708 }
5709
5710 // We already coerced both operands to the same type. If that type
5711 // is not an abstract type, we need to round the values accordingly.
5712 Type* type = left_nc->type();
5713 if (!type->is_abstract() && type->float_type() != NULL)
5714 {
5715 int bits = type->float_type()->bits();
5716 mpfr_prec_round(left_val, bits, MPFR_RNDN);
5717 mpfr_prec_round(right_val, bits, MPFR_RNDN);
5718 }
5719
5720 *cmp = mpfr_cmp(left_val, right_val);
5721
5722 mpfr_clear(left_val);
5723 mpfr_clear(right_val);
5724
5725 return true;
5726 }
5727
5728 // Compare complex constants. Complex numbers may only be compared
5729 // for equality.
5730
5731 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5732 Binary_expression::compare_complex(const Numeric_constant* left_nc,
5733 const Numeric_constant* right_nc,
5734 int* cmp)
5735 {
5736 mpc_t left_val;
5737 if (!left_nc->to_complex(&left_val))
5738 return false;
5739 mpc_t right_val;
5740 if (!right_nc->to_complex(&right_val))
5741 {
5742 mpc_clear(left_val);
5743 return false;
5744 }
5745
5746 // We already coerced both operands to the same type. If that type
5747 // is not an abstract type, we need to round the values accordingly.
5748 Type* type = left_nc->type();
5749 if (!type->is_abstract() && type->complex_type() != NULL)
5750 {
5751 int bits = type->complex_type()->bits();
5752 mpfr_prec_round(mpc_realref(left_val), bits / 2, MPFR_RNDN);
5753 mpfr_prec_round(mpc_imagref(left_val), bits / 2, MPFR_RNDN);
5754 mpfr_prec_round(mpc_realref(right_val), bits / 2, MPFR_RNDN);
5755 mpfr_prec_round(mpc_imagref(right_val), bits / 2, MPFR_RNDN);
5756 }
5757
5758 *cmp = mpc_cmp(left_val, right_val) != 0;
5759
5760 mpc_clear(left_val);
5761 mpc_clear(right_val);
5762
5763 return true;
5764 }
5765
5766 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
5767 // true if this could be done, false if not. Issue errors at LOCATION
5768 // as appropriate, and sets *ISSUED_ERROR if it did.
5769
5770 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)5771 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
5772 Numeric_constant* right_nc,
5773 Location location, Numeric_constant* nc,
5774 bool* issued_error)
5775 {
5776 *issued_error = false;
5777 switch (op)
5778 {
5779 case OPERATOR_OROR:
5780 case OPERATOR_ANDAND:
5781 case OPERATOR_EQEQ:
5782 case OPERATOR_NOTEQ:
5783 case OPERATOR_LT:
5784 case OPERATOR_LE:
5785 case OPERATOR_GT:
5786 case OPERATOR_GE:
5787 // These return boolean values, not numeric.
5788 return false;
5789 default:
5790 break;
5791 }
5792
5793 Type* left_type = left_nc->type();
5794 Type* right_type = right_nc->type();
5795
5796 Type* type;
5797 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5798 return false;
5799
5800 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
5801
5802 // When combining an untyped operand with a typed operand, we are
5803 // effectively coercing the untyped operand to the other operand's
5804 // type, so make sure that is valid.
5805 if (!left_nc->set_type(type, true, location))
5806 return false;
5807 if (!is_shift && !right_nc->set_type(type, true, location))
5808 return false;
5809 if (is_shift
5810 && ((left_type->integer_type() == NULL
5811 && !left_type->is_abstract())
5812 || (right_type->integer_type() == NULL
5813 && !right_type->is_abstract())))
5814 return false;
5815
5816 bool r;
5817 if (type->complex_type() != NULL)
5818 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
5819 else if (type->float_type() != NULL)
5820 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
5821 else
5822 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
5823
5824 if (r)
5825 {
5826 r = nc->set_type(type, true, location);
5827 if (!r)
5828 *issued_error = true;
5829 }
5830
5831 return r;
5832 }
5833
5834 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5835 // integer operations. Return true if this could be done, false if
5836 // not.
5837
5838 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5839 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
5840 const Numeric_constant* right_nc,
5841 Location location, Numeric_constant* nc)
5842 {
5843 mpz_t left_val;
5844 if (!left_nc->to_int(&left_val))
5845 return false;
5846 mpz_t right_val;
5847 if (!right_nc->to_int(&right_val))
5848 {
5849 mpz_clear(left_val);
5850 return false;
5851 }
5852
5853 mpz_t val;
5854 mpz_init(val);
5855
5856 switch (op)
5857 {
5858 case OPERATOR_PLUS:
5859 mpz_add(val, left_val, right_val);
5860 if (mpz_sizeinbase(val, 2) > 0x100000)
5861 {
5862 go_error_at(location, "constant addition overflow");
5863 nc->set_invalid();
5864 mpz_set_ui(val, 1);
5865 }
5866 break;
5867 case OPERATOR_MINUS:
5868 mpz_sub(val, left_val, right_val);
5869 if (mpz_sizeinbase(val, 2) > 0x100000)
5870 {
5871 go_error_at(location, "constant subtraction overflow");
5872 nc->set_invalid();
5873 mpz_set_ui(val, 1);
5874 }
5875 break;
5876 case OPERATOR_OR:
5877 mpz_ior(val, left_val, right_val);
5878 break;
5879 case OPERATOR_XOR:
5880 mpz_xor(val, left_val, right_val);
5881 break;
5882 case OPERATOR_MULT:
5883 mpz_mul(val, left_val, right_val);
5884 if (mpz_sizeinbase(val, 2) > 0x100000)
5885 {
5886 go_error_at(location, "constant multiplication overflow");
5887 nc->set_invalid();
5888 mpz_set_ui(val, 1);
5889 }
5890 break;
5891 case OPERATOR_DIV:
5892 if (mpz_sgn(right_val) != 0)
5893 mpz_tdiv_q(val, left_val, right_val);
5894 else
5895 {
5896 go_error_at(location, "division by zero");
5897 nc->set_invalid();
5898 mpz_set_ui(val, 0);
5899 }
5900 break;
5901 case OPERATOR_MOD:
5902 if (mpz_sgn(right_val) != 0)
5903 mpz_tdiv_r(val, left_val, right_val);
5904 else
5905 {
5906 go_error_at(location, "division by zero");
5907 nc->set_invalid();
5908 mpz_set_ui(val, 0);
5909 }
5910 break;
5911 case OPERATOR_LSHIFT:
5912 {
5913 unsigned long shift = mpz_get_ui(right_val);
5914 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5915 mpz_mul_2exp(val, left_val, shift);
5916 else
5917 {
5918 go_error_at(location, "shift count overflow");
5919 nc->set_invalid();
5920 mpz_set_ui(val, 1);
5921 }
5922 break;
5923 }
5924 break;
5925 case OPERATOR_RSHIFT:
5926 {
5927 unsigned long shift = mpz_get_ui(right_val);
5928 if (mpz_cmp_ui(right_val, shift) != 0)
5929 {
5930 go_error_at(location, "shift count overflow");
5931 nc->set_invalid();
5932 mpz_set_ui(val, 1);
5933 }
5934 else
5935 {
5936 if (mpz_cmp_ui(left_val, 0) >= 0)
5937 mpz_tdiv_q_2exp(val, left_val, shift);
5938 else
5939 mpz_fdiv_q_2exp(val, left_val, shift);
5940 }
5941 break;
5942 }
5943 break;
5944 case OPERATOR_AND:
5945 mpz_and(val, left_val, right_val);
5946 break;
5947 case OPERATOR_BITCLEAR:
5948 {
5949 mpz_t tval;
5950 mpz_init(tval);
5951 mpz_com(tval, right_val);
5952 mpz_and(val, left_val, tval);
5953 mpz_clear(tval);
5954 }
5955 break;
5956 default:
5957 go_unreachable();
5958 }
5959
5960 mpz_clear(left_val);
5961 mpz_clear(right_val);
5962
5963 if (left_nc->is_rune()
5964 || (op != OPERATOR_LSHIFT
5965 && op != OPERATOR_RSHIFT
5966 && right_nc->is_rune()))
5967 nc->set_rune(NULL, val);
5968 else
5969 nc->set_int(NULL, val);
5970
5971 mpz_clear(val);
5972
5973 return true;
5974 }
5975
5976 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5977 // floating point operations. Return true if this could be done,
5978 // false if not.
5979
5980 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5981 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5982 const Numeric_constant* right_nc,
5983 Location location, Numeric_constant* nc)
5984 {
5985 mpfr_t left_val;
5986 if (!left_nc->to_float(&left_val))
5987 return false;
5988 mpfr_t right_val;
5989 if (!right_nc->to_float(&right_val))
5990 {
5991 mpfr_clear(left_val);
5992 return false;
5993 }
5994
5995 mpfr_t val;
5996 mpfr_init(val);
5997
5998 bool ret = true;
5999 switch (op)
6000 {
6001 case OPERATOR_PLUS:
6002 mpfr_add(val, left_val, right_val, MPFR_RNDN);
6003 break;
6004 case OPERATOR_MINUS:
6005 mpfr_sub(val, left_val, right_val, MPFR_RNDN);
6006 break;
6007 case OPERATOR_OR:
6008 case OPERATOR_XOR:
6009 case OPERATOR_AND:
6010 case OPERATOR_BITCLEAR:
6011 case OPERATOR_MOD:
6012 case OPERATOR_LSHIFT:
6013 case OPERATOR_RSHIFT:
6014 mpfr_set_ui(val, 0, MPFR_RNDN);
6015 ret = false;
6016 break;
6017 case OPERATOR_MULT:
6018 mpfr_mul(val, left_val, right_val, MPFR_RNDN);
6019 break;
6020 case OPERATOR_DIV:
6021 if (!mpfr_zero_p(right_val))
6022 mpfr_div(val, left_val, right_val, MPFR_RNDN);
6023 else
6024 {
6025 go_error_at(location, "division by zero");
6026 nc->set_invalid();
6027 mpfr_set_ui(val, 0, MPFR_RNDN);
6028 }
6029 break;
6030 default:
6031 go_unreachable();
6032 }
6033
6034 mpfr_clear(left_val);
6035 mpfr_clear(right_val);
6036
6037 nc->set_float(NULL, val);
6038 mpfr_clear(val);
6039
6040 return ret;
6041 }
6042
6043 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
6044 // complex operations. Return true if this could be done, false if
6045 // not.
6046
6047 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)6048 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
6049 const Numeric_constant* right_nc,
6050 Location location, Numeric_constant* nc)
6051 {
6052 mpc_t left_val;
6053 if (!left_nc->to_complex(&left_val))
6054 return false;
6055 mpc_t right_val;
6056 if (!right_nc->to_complex(&right_val))
6057 {
6058 mpc_clear(left_val);
6059 return false;
6060 }
6061
6062 mpc_t val;
6063 mpc_init2(val, mpc_precision);
6064
6065 bool ret = true;
6066 switch (op)
6067 {
6068 case OPERATOR_PLUS:
6069 mpc_add(val, left_val, right_val, MPC_RNDNN);
6070 break;
6071 case OPERATOR_MINUS:
6072 mpc_sub(val, left_val, right_val, MPC_RNDNN);
6073 break;
6074 case OPERATOR_OR:
6075 case OPERATOR_XOR:
6076 case OPERATOR_AND:
6077 case OPERATOR_BITCLEAR:
6078 case OPERATOR_MOD:
6079 case OPERATOR_LSHIFT:
6080 case OPERATOR_RSHIFT:
6081 mpc_set_ui(val, 0, MPC_RNDNN);
6082 ret = false;
6083 break;
6084 case OPERATOR_MULT:
6085 mpc_mul(val, left_val, right_val, MPC_RNDNN);
6086 break;
6087 case OPERATOR_DIV:
6088 if (mpc_cmp_si(right_val, 0) == 0)
6089 {
6090 go_error_at(location, "division by zero");
6091 nc->set_invalid();
6092 mpc_set_ui(val, 0, MPC_RNDNN);
6093 break;
6094 }
6095 mpc_div(val, left_val, right_val, MPC_RNDNN);
6096 break;
6097 default:
6098 go_unreachable();
6099 }
6100
6101 mpc_clear(left_val);
6102 mpc_clear(right_val);
6103
6104 nc->set_complex(NULL, val);
6105 mpc_clear(val);
6106
6107 return ret;
6108 }
6109
6110 // Lower a binary expression. We have to evaluate constant
6111 // expressions now, in order to implement Go's unlimited precision
6112 // constants.
6113
6114 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)6115 Binary_expression::do_lower(Gogo* gogo, Named_object*,
6116 Statement_inserter* inserter, int)
6117 {
6118 Location location = this->location();
6119 Operator op = this->op_;
6120 Expression* left = this->left_;
6121 Expression* right = this->right_;
6122
6123 const bool is_comparison = (op == OPERATOR_EQEQ
6124 || op == OPERATOR_NOTEQ
6125 || op == OPERATOR_LT
6126 || op == OPERATOR_LE
6127 || op == OPERATOR_GT
6128 || op == OPERATOR_GE);
6129
6130 // Numeric constant expressions.
6131 {
6132 Numeric_constant left_nc;
6133 Numeric_constant right_nc;
6134 if (left->numeric_constant_value(&left_nc)
6135 && right->numeric_constant_value(&right_nc))
6136 {
6137 if (is_comparison)
6138 {
6139 bool result;
6140 if (!Binary_expression::compare_constant(op, &left_nc,
6141 &right_nc, location,
6142 &result))
6143 return this;
6144 return Expression::make_boolean(result, location);
6145 }
6146 else
6147 {
6148 Numeric_constant nc;
6149 bool issued_error;
6150 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
6151 location, &nc,
6152 &issued_error))
6153 {
6154 if (issued_error)
6155 return Expression::make_error(location);
6156 return this;
6157 }
6158 return nc.expression(location);
6159 }
6160 }
6161 }
6162
6163 // String constant expressions.
6164 //
6165 // Avoid constant folding here if the left and right types are incompatible
6166 // (leave the operation intact so that the type checker can complain about it
6167 // later on). If concatenating an abstract string with a named string type,
6168 // result type needs to be of the named type (see issue 31412).
6169 if (left->type()->is_string_type()
6170 && right->type()->is_string_type()
6171 && (left->type()->named_type() == NULL
6172 || right->type()->named_type() == NULL
6173 || left->type()->named_type() == right->type()->named_type()))
6174 {
6175 std::string left_string;
6176 std::string right_string;
6177 if (left->string_constant_value(&left_string)
6178 && right->string_constant_value(&right_string))
6179 {
6180 if (op == OPERATOR_PLUS)
6181 {
6182 Type* result_type = (left->type()->named_type() != NULL
6183 ? left->type()
6184 : right->type());
6185 delete left;
6186 delete right;
6187 return Expression::make_string_typed(left_string + right_string,
6188 result_type, location);
6189 }
6190 else if (is_comparison)
6191 {
6192 int cmp = left_string.compare(right_string);
6193 bool r = Binary_expression::cmp_to_bool(op, cmp);
6194 delete left;
6195 delete right;
6196 return Expression::make_boolean(r, location);
6197 }
6198 }
6199 }
6200
6201 // Lower struct, array, and some interface comparisons.
6202 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6203 {
6204 if (left->type()->struct_type() != NULL
6205 && right->type()->struct_type() != NULL)
6206 return this->lower_struct_comparison(gogo, inserter);
6207 else if (left->type()->array_type() != NULL
6208 && !left->type()->is_slice_type()
6209 && right->type()->array_type() != NULL
6210 && !right->type()->is_slice_type())
6211 return this->lower_array_comparison(gogo, inserter);
6212 else if ((left->type()->interface_type() != NULL
6213 && right->type()->interface_type() == NULL)
6214 || (left->type()->interface_type() == NULL
6215 && right->type()->interface_type() != NULL))
6216 return this->lower_interface_value_comparison(gogo, inserter);
6217 }
6218
6219 // Lower string concatenation to String_concat_expression, so that
6220 // we can group sequences of string additions.
6221 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
6222 {
6223 Expression_list* exprs;
6224 String_concat_expression* left_sce =
6225 this->left_->string_concat_expression();
6226 if (left_sce != NULL)
6227 exprs = left_sce->exprs();
6228 else
6229 {
6230 exprs = new Expression_list();
6231 exprs->push_back(this->left_);
6232 }
6233
6234 String_concat_expression* right_sce =
6235 this->right_->string_concat_expression();
6236 if (right_sce != NULL)
6237 exprs->append(right_sce->exprs());
6238 else
6239 exprs->push_back(this->right_);
6240
6241 return Expression::make_string_concat(exprs);
6242 }
6243
6244 return this;
6245 }
6246
6247 // Lower a struct comparison.
6248
6249 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)6250 Binary_expression::lower_struct_comparison(Gogo* gogo,
6251 Statement_inserter* inserter)
6252 {
6253 Struct_type* st = this->left_->type()->struct_type();
6254 Struct_type* st2 = this->right_->type()->struct_type();
6255 if (st2 == NULL)
6256 return this;
6257 if (st != st2
6258 && !Type::are_identical(st, st2,
6259 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6260 NULL))
6261 return this;
6262 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6263 this->right_->type(), NULL))
6264 return this;
6265
6266 // See if we can compare using memcmp. As a heuristic, we use
6267 // memcmp rather than field references and comparisons if there are
6268 // more than two fields.
6269 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
6270 return this->lower_compare_to_memcmp(gogo, inserter);
6271
6272 Location loc = this->location();
6273
6274 Expression* left = this->left_;
6275 Temporary_statement* left_temp = NULL;
6276 if (left->var_expression() == NULL
6277 && left->temporary_reference_expression() == NULL)
6278 {
6279 left_temp = Statement::make_temporary(left->type(), NULL, loc);
6280 inserter->insert(left_temp);
6281 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
6282 }
6283
6284 Expression* right = this->right_;
6285 Temporary_statement* right_temp = NULL;
6286 if (right->var_expression() == NULL
6287 && right->temporary_reference_expression() == NULL)
6288 {
6289 right_temp = Statement::make_temporary(right->type(), NULL, loc);
6290 inserter->insert(right_temp);
6291 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
6292 }
6293
6294 Expression* ret = Expression::make_boolean(true, loc);
6295 const Struct_field_list* fields = st->fields();
6296 unsigned int field_index = 0;
6297 for (Struct_field_list::const_iterator pf = fields->begin();
6298 pf != fields->end();
6299 ++pf, ++field_index)
6300 {
6301 if (Gogo::is_sink_name(pf->field_name()))
6302 continue;
6303
6304 if (field_index > 0)
6305 {
6306 if (left_temp == NULL)
6307 left = left->copy();
6308 else
6309 left = Expression::make_temporary_reference(left_temp, loc);
6310 if (right_temp == NULL)
6311 right = right->copy();
6312 else
6313 right = Expression::make_temporary_reference(right_temp, loc);
6314 }
6315 Expression* f1 = Expression::make_field_reference(left, field_index,
6316 loc);
6317 Expression* f2 = Expression::make_field_reference(right, field_index,
6318 loc);
6319 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
6320 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
6321 }
6322
6323 if (this->op_ == OPERATOR_NOTEQ)
6324 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6325
6326 return ret;
6327 }
6328
6329 // Lower an array comparison.
6330
6331 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)6332 Binary_expression::lower_array_comparison(Gogo* gogo,
6333 Statement_inserter* inserter)
6334 {
6335 Array_type* at = this->left_->type()->array_type();
6336 Array_type* at2 = this->right_->type()->array_type();
6337 if (at2 == NULL)
6338 return this;
6339 if (at != at2
6340 && !Type::are_identical(at, at2,
6341 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
6342 NULL))
6343 return this;
6344 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6345 this->right_->type(), NULL))
6346 return this;
6347
6348 // Call memcmp directly if possible. This may let the middle-end
6349 // optimize the call.
6350 if (at->compare_is_identity(gogo))
6351 return this->lower_compare_to_memcmp(gogo, inserter);
6352
6353 // Call the array comparison function.
6354 Named_object* equal_fn =
6355 at->equal_function(gogo, this->left_->type()->named_type(), NULL);
6356
6357 Location loc = this->location();
6358
6359 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6360
6361 Expression_list* args = new Expression_list();
6362 args->push_back(this->operand_address(inserter, this->left_));
6363 args->push_back(this->operand_address(inserter, this->right_));
6364
6365 Call_expression* ce = Expression::make_call(func, args, false, loc);
6366
6367 // Record that this is a call to a generated equality function. We
6368 // need to do this because a comparison returns an abstract boolean
6369 // type, but the function necessarily returns "bool". The
6370 // difference shows up in code like
6371 // type mybool bool
6372 // var b mybool = [10]string{} == [10]string{}
6373 // The comparison function returns "bool", but since a comparison
6374 // has an abstract boolean type we need an implicit conversion to
6375 // "mybool". The implicit conversion is inserted in
6376 // Call_expression::do_flatten.
6377 ce->set_is_equal_function();
6378
6379 Expression* ret = ce;
6380 if (this->op_ == OPERATOR_NOTEQ)
6381 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6382
6383 return ret;
6384 }
6385
6386 // Lower an interface to value comparison.
6387
6388 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)6389 Binary_expression::lower_interface_value_comparison(Gogo*,
6390 Statement_inserter* inserter)
6391 {
6392 Type* left_type = this->left_->type();
6393 Type* right_type = this->right_->type();
6394 Interface_type* ift;
6395 if (left_type->interface_type() != NULL)
6396 {
6397 ift = left_type->interface_type();
6398 if (!ift->implements_interface(right_type, NULL))
6399 return this;
6400 }
6401 else
6402 {
6403 ift = right_type->interface_type();
6404 if (!ift->implements_interface(left_type, NULL))
6405 return this;
6406 }
6407 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
6408 return this;
6409
6410 Location loc = this->location();
6411
6412 if (left_type->interface_type() == NULL
6413 && left_type->points_to() == NULL
6414 && !this->left_->is_addressable())
6415 {
6416 Temporary_statement* temp =
6417 Statement::make_temporary(left_type, NULL, loc);
6418 inserter->insert(temp);
6419 this->left_ =
6420 Expression::make_set_and_use_temporary(temp, this->left_, loc);
6421 }
6422
6423 if (right_type->interface_type() == NULL
6424 && right_type->points_to() == NULL
6425 && !this->right_->is_addressable())
6426 {
6427 Temporary_statement* temp =
6428 Statement::make_temporary(right_type, NULL, loc);
6429 inserter->insert(temp);
6430 this->right_ =
6431 Expression::make_set_and_use_temporary(temp, this->right_, loc);
6432 }
6433
6434 return this;
6435 }
6436
6437 // Lower a struct or array comparison to a call to memcmp.
6438
6439 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)6440 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6441 {
6442 Location loc = this->location();
6443
6444 Expression* a1 = this->operand_address(inserter, this->left_);
6445 Expression* a2 = this->operand_address(inserter, this->right_);
6446 Expression* len = Expression::make_type_info(this->left_->type(),
6447 TYPE_INFO_SIZE);
6448
6449 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6450 Type* int32_type = Type::lookup_integer_type("int32");
6451 Expression* zero = Expression::make_integer_ul(0, int32_type, loc);
6452 return Expression::make_binary(this->op_, call, zero, loc);
6453 }
6454
6455 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)6456 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
6457 Statement_inserter* inserter)
6458 {
6459 Location loc = this->location();
6460 if (this->left_->type()->is_error_type()
6461 || this->right_->type()->is_error_type()
6462 || this->left_->is_error_expression()
6463 || this->right_->is_error_expression())
6464 {
6465 go_assert(saw_errors());
6466 return Expression::make_error(loc);
6467 }
6468
6469 Temporary_statement* temp;
6470
6471 Type* left_type = this->left_->type();
6472 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6473 || this->op_ == OPERATOR_RSHIFT);
6474 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
6475 left_type->integer_type() != NULL)
6476 || this->op_ == OPERATOR_MOD);
6477 bool is_string_op = (left_type->is_string_type()
6478 && this->right_->type()->is_string_type());
6479
6480 if (is_string_op)
6481 {
6482 // Mark string([]byte) operands to reuse the backing store.
6483 // String comparison does not keep the reference, so it is safe.
6484 Type_conversion_expression* lce =
6485 this->left_->conversion_expression();
6486 if (lce != NULL && lce->expr()->type()->is_slice_type())
6487 lce->set_no_copy(true);
6488 Type_conversion_expression* rce =
6489 this->right_->conversion_expression();
6490 if (rce != NULL && rce->expr()->type()->is_slice_type())
6491 rce->set_no_copy(true);
6492 }
6493
6494 if (is_shift_op
6495 || (is_idiv_op
6496 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow()))
6497 || is_string_op)
6498 {
6499 if (!this->left_->is_multi_eval_safe())
6500 {
6501 temp = Statement::make_temporary(NULL, this->left_, loc);
6502 inserter->insert(temp);
6503 this->left_ = Expression::make_temporary_reference(temp, loc);
6504 }
6505 if (!this->right_->is_multi_eval_safe())
6506 {
6507 temp =
6508 Statement::make_temporary(NULL, this->right_, loc);
6509 this->right_ = Expression::make_temporary_reference(temp, loc);
6510 inserter->insert(temp);
6511 }
6512 }
6513 return this;
6514 }
6515
6516
6517 // Return the address of EXPR, cast to unsafe.Pointer.
6518
6519 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)6520 Binary_expression::operand_address(Statement_inserter* inserter,
6521 Expression* expr)
6522 {
6523 Location loc = this->location();
6524
6525 if (!expr->is_addressable())
6526 {
6527 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6528 loc);
6529 inserter->insert(temp);
6530 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6531 }
6532 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6533 static_cast<Unary_expression*>(expr)->set_does_not_escape();
6534 Type* void_type = Type::make_void_type();
6535 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6536 return Expression::make_cast(unsafe_pointer_type, expr, loc);
6537 }
6538
6539 // Return the numeric constant value, if it has one.
6540
6541 bool
do_numeric_constant_value(Numeric_constant * nc) const6542 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
6543 {
6544 Numeric_constant left_nc;
6545 if (!this->left_->numeric_constant_value(&left_nc))
6546 return false;
6547 Numeric_constant right_nc;
6548 if (!this->right_->numeric_constant_value(&right_nc))
6549 return false;
6550 bool issued_error;
6551 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
6552 this->location(), nc, &issued_error);
6553 }
6554
6555 // Return the boolean constant value, if it has one.
6556
6557 bool
do_boolean_constant_value(bool * val) const6558 Binary_expression::do_boolean_constant_value(bool* val) const
6559 {
6560 bool is_comparison = false;
6561 switch (this->op_)
6562 {
6563 case OPERATOR_EQEQ:
6564 case OPERATOR_NOTEQ:
6565 case OPERATOR_LT:
6566 case OPERATOR_LE:
6567 case OPERATOR_GT:
6568 case OPERATOR_GE:
6569 is_comparison = true;
6570 break;
6571 case OPERATOR_ANDAND:
6572 case OPERATOR_OROR:
6573 break;
6574 default:
6575 return false;
6576 }
6577
6578 Numeric_constant left_nc, right_nc;
6579 if (is_comparison
6580 && this->left_->numeric_constant_value(&left_nc)
6581 && this->right_->numeric_constant_value(&right_nc))
6582 return Binary_expression::compare_constant(this->op_, &left_nc,
6583 &right_nc,
6584 this->location(),
6585 val);
6586
6587 std::string left_str, right_str;
6588 if (is_comparison
6589 && this->left_->string_constant_value(&left_str)
6590 && this->right_->string_constant_value(&right_str))
6591 {
6592 *val = Binary_expression::cmp_to_bool(this->op_,
6593 left_str.compare(right_str));
6594 return true;
6595 }
6596
6597 bool left_bval;
6598 if (this->left_->boolean_constant_value(&left_bval))
6599 {
6600 if (this->op_ == OPERATOR_ANDAND && !left_bval)
6601 {
6602 *val = false;
6603 return true;
6604 }
6605 else if (this->op_ == OPERATOR_OROR && left_bval)
6606 {
6607 *val = true;
6608 return true;
6609 }
6610
6611 bool right_bval;
6612 if (this->right_->boolean_constant_value(&right_bval))
6613 {
6614 switch (this->op_)
6615 {
6616 case OPERATOR_EQEQ:
6617 *val = (left_bval == right_bval);
6618 return true;
6619 case OPERATOR_NOTEQ:
6620 *val = (left_bval != right_bval);
6621 return true;
6622 case OPERATOR_ANDAND:
6623 case OPERATOR_OROR:
6624 *val = right_bval;
6625 return true;
6626 default:
6627 go_unreachable();
6628 }
6629 }
6630 }
6631
6632 return false;
6633 }
6634
6635 // Note that the value is being discarded.
6636
6637 bool
do_discarding_value()6638 Binary_expression::do_discarding_value()
6639 {
6640 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6641 return this->right_->discarding_value();
6642 else
6643 {
6644 this->unused_value_error();
6645 return false;
6646 }
6647 }
6648
6649 // Get type.
6650
6651 Type*
do_type()6652 Binary_expression::do_type()
6653 {
6654 if (this->classification() == EXPRESSION_ERROR)
6655 return Type::make_error_type();
6656
6657 switch (this->op_)
6658 {
6659 case OPERATOR_EQEQ:
6660 case OPERATOR_NOTEQ:
6661 case OPERATOR_LT:
6662 case OPERATOR_LE:
6663 case OPERATOR_GT:
6664 case OPERATOR_GE:
6665 if (this->type_ == NULL)
6666 this->type_ = Type::make_boolean_type();
6667 return this->type_;
6668
6669 case OPERATOR_PLUS:
6670 case OPERATOR_MINUS:
6671 case OPERATOR_OR:
6672 case OPERATOR_XOR:
6673 case OPERATOR_MULT:
6674 case OPERATOR_DIV:
6675 case OPERATOR_MOD:
6676 case OPERATOR_AND:
6677 case OPERATOR_BITCLEAR:
6678 case OPERATOR_OROR:
6679 case OPERATOR_ANDAND:
6680 {
6681 Type* type;
6682 if (!Binary_expression::operation_type(this->op_,
6683 this->left_->type(),
6684 this->right_->type(),
6685 &type))
6686 return Type::make_error_type();
6687 return type;
6688 }
6689
6690 case OPERATOR_LSHIFT:
6691 case OPERATOR_RSHIFT:
6692 return this->left_->type();
6693
6694 default:
6695 go_unreachable();
6696 }
6697 }
6698
6699 // Set type for a binary expression.
6700
6701 void
do_determine_type(const Type_context * context)6702 Binary_expression::do_determine_type(const Type_context* context)
6703 {
6704 Type* tleft = this->left_->type();
6705 Type* tright = this->right_->type();
6706
6707 // Both sides should have the same type, except for the shift
6708 // operations. For a comparison, we should ignore the incoming
6709 // type.
6710
6711 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6712 || this->op_ == OPERATOR_RSHIFT);
6713
6714 bool is_comparison = (this->op_ == OPERATOR_EQEQ
6715 || this->op_ == OPERATOR_NOTEQ
6716 || this->op_ == OPERATOR_LT
6717 || this->op_ == OPERATOR_LE
6718 || this->op_ == OPERATOR_GT
6719 || this->op_ == OPERATOR_GE);
6720
6721 // For constant expressions, the context of the result is not useful in
6722 // determining the types of the operands. It is only legal to use abstract
6723 // boolean, numeric, and string constants as operands where it is legal to
6724 // use non-abstract boolean, numeric, and string constants, respectively.
6725 // Any issues with the operation will be resolved in the check_types pass.
6726 bool is_constant_expr = (this->left_->is_constant()
6727 && this->right_->is_constant());
6728
6729 Type_context subcontext(*context);
6730
6731 if (is_constant_expr && !is_shift_op)
6732 {
6733 subcontext.type = NULL;
6734 subcontext.may_be_abstract = true;
6735 }
6736 else if (is_comparison)
6737 {
6738 // In a comparison, the context does not determine the types of
6739 // the operands.
6740 subcontext.type = NULL;
6741 }
6742
6743 // Set the context for the left hand operand.
6744 if (is_shift_op)
6745 {
6746 // The right hand operand of a shift plays no role in
6747 // determining the type of the left hand operand.
6748 }
6749 else if (!tleft->is_abstract())
6750 subcontext.type = tleft;
6751 else if (!tright->is_abstract())
6752 subcontext.type = tright;
6753 else if (subcontext.type == NULL)
6754 {
6755 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6756 || (tleft->float_type() != NULL && tright->float_type() != NULL)
6757 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6758 {
6759 // Both sides have an abstract integer, abstract float, or
6760 // abstract complex type. Just let CONTEXT determine
6761 // whether they may remain abstract or not.
6762 }
6763 else if (tleft->complex_type() != NULL)
6764 subcontext.type = tleft;
6765 else if (tright->complex_type() != NULL)
6766 subcontext.type = tright;
6767 else if (tleft->float_type() != NULL)
6768 subcontext.type = tleft;
6769 else if (tright->float_type() != NULL)
6770 subcontext.type = tright;
6771 else
6772 subcontext.type = tleft;
6773
6774 if (subcontext.type != NULL && !context->may_be_abstract)
6775 subcontext.type = subcontext.type->make_non_abstract_type();
6776 }
6777
6778 this->left_->determine_type(&subcontext);
6779
6780 if (is_shift_op)
6781 {
6782 // We may have inherited an unusable type for the shift operand.
6783 // Give a useful error if that happened.
6784 if (tleft->is_abstract()
6785 && subcontext.type != NULL
6786 && !subcontext.may_be_abstract
6787 && subcontext.type->interface_type() == NULL
6788 && subcontext.type->integer_type() == NULL)
6789 this->report_error(("invalid context-determined non-integer type "
6790 "for left operand of shift"));
6791
6792 // The context for the right hand operand is the same as for the
6793 // left hand operand, except for a shift operator.
6794 subcontext.type = Type::lookup_integer_type("uint");
6795 subcontext.may_be_abstract = false;
6796 }
6797
6798 this->right_->determine_type(&subcontext);
6799
6800 if (is_comparison)
6801 {
6802 if (this->type_ != NULL && !this->type_->is_abstract())
6803 ;
6804 else if (context->type != NULL && context->type->is_boolean_type())
6805 this->type_ = context->type;
6806 else if (!context->may_be_abstract)
6807 this->type_ = Type::lookup_bool_type();
6808 }
6809 }
6810
6811 // Report an error if the binary operator OP does not support TYPE.
6812 // OTYPE is the type of the other operand. Return whether the
6813 // operation is OK. This should not be used for shift.
6814
6815 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)6816 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6817 Location location)
6818 {
6819 switch (op)
6820 {
6821 case OPERATOR_OROR:
6822 case OPERATOR_ANDAND:
6823 if (!type->is_boolean_type()
6824 || !otype->is_boolean_type())
6825 {
6826 go_error_at(location, "expected boolean type");
6827 return false;
6828 }
6829 break;
6830
6831 case OPERATOR_EQEQ:
6832 case OPERATOR_NOTEQ:
6833 {
6834 std::string reason;
6835 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6836 {
6837 go_error_at(location, "%s", reason.c_str());
6838 return false;
6839 }
6840 }
6841 break;
6842
6843 case OPERATOR_LT:
6844 case OPERATOR_LE:
6845 case OPERATOR_GT:
6846 case OPERATOR_GE:
6847 {
6848 std::string reason;
6849 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6850 {
6851 go_error_at(location, "%s", reason.c_str());
6852 return false;
6853 }
6854 }
6855 break;
6856
6857 case OPERATOR_PLUS:
6858 case OPERATOR_PLUSEQ:
6859 if ((!type->is_numeric_type() && !type->is_string_type())
6860 || (!otype->is_numeric_type() && !otype->is_string_type()))
6861 {
6862 go_error_at(location,
6863 "expected integer, floating, complex, or string type");
6864 return false;
6865 }
6866 break;
6867
6868 case OPERATOR_MINUS:
6869 case OPERATOR_MINUSEQ:
6870 case OPERATOR_MULT:
6871 case OPERATOR_MULTEQ:
6872 case OPERATOR_DIV:
6873 case OPERATOR_DIVEQ:
6874 if (!type->is_numeric_type() || !otype->is_numeric_type())
6875 {
6876 go_error_at(location, "expected integer, floating, or complex type");
6877 return false;
6878 }
6879 break;
6880
6881 case OPERATOR_MOD:
6882 case OPERATOR_MODEQ:
6883 case OPERATOR_OR:
6884 case OPERATOR_OREQ:
6885 case OPERATOR_AND:
6886 case OPERATOR_ANDEQ:
6887 case OPERATOR_XOR:
6888 case OPERATOR_XOREQ:
6889 case OPERATOR_BITCLEAR:
6890 case OPERATOR_BITCLEAREQ:
6891 if (type->integer_type() == NULL || otype->integer_type() == NULL)
6892 {
6893 go_error_at(location, "expected integer type");
6894 return false;
6895 }
6896 break;
6897
6898 default:
6899 go_unreachable();
6900 }
6901
6902 return true;
6903 }
6904
6905 // Check types.
6906
6907 void
do_check_types(Gogo *)6908 Binary_expression::do_check_types(Gogo*)
6909 {
6910 if (this->classification() == EXPRESSION_ERROR)
6911 return;
6912
6913 Type* left_type = this->left_->type();
6914 Type* right_type = this->right_->type();
6915 if (left_type->is_error() || right_type->is_error())
6916 {
6917 this->set_is_error();
6918 return;
6919 }
6920
6921 if (this->op_ == OPERATOR_EQEQ
6922 || this->op_ == OPERATOR_NOTEQ
6923 || this->op_ == OPERATOR_LT
6924 || this->op_ == OPERATOR_LE
6925 || this->op_ == OPERATOR_GT
6926 || this->op_ == OPERATOR_GE)
6927 {
6928 if (left_type->is_nil_type() && right_type->is_nil_type())
6929 {
6930 this->report_error(_("invalid comparison of nil with nil"));
6931 return;
6932 }
6933 if (!Type::are_assignable(left_type, right_type, NULL)
6934 && !Type::are_assignable(right_type, left_type, NULL))
6935 {
6936 this->report_error(_("incompatible types in binary expression"));
6937 return;
6938 }
6939 if (!Binary_expression::check_operator_type(this->op_, left_type,
6940 right_type,
6941 this->location())
6942 || !Binary_expression::check_operator_type(this->op_, right_type,
6943 left_type,
6944 this->location()))
6945 {
6946 this->set_is_error();
6947 return;
6948 }
6949 }
6950 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6951 {
6952 if (!Type::are_compatible_for_binop(left_type, right_type))
6953 {
6954 this->report_error(_("incompatible types in binary expression"));
6955 return;
6956 }
6957 if (!Binary_expression::check_operator_type(this->op_, left_type,
6958 right_type,
6959 this->location()))
6960 {
6961 this->set_is_error();
6962 return;
6963 }
6964 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
6965 {
6966 // Division by a zero integer constant is an error.
6967 Numeric_constant rconst;
6968 unsigned long rval;
6969 if (left_type->integer_type() != NULL
6970 && this->right_->numeric_constant_value(&rconst)
6971 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6972 && rval == 0)
6973 {
6974 this->report_error(_("integer division by zero"));
6975 return;
6976 }
6977 }
6978 }
6979 else
6980 {
6981 if (left_type->integer_type() == NULL)
6982 this->report_error(_("shift of non-integer operand"));
6983
6984 if (right_type->is_string_type())
6985 this->report_error(_("shift count not integer"));
6986 else if (!right_type->is_abstract()
6987 && right_type->integer_type() == NULL)
6988 this->report_error(_("shift count not integer"));
6989 else
6990 {
6991 Numeric_constant nc;
6992 if (this->right_->numeric_constant_value(&nc))
6993 {
6994 mpz_t val;
6995 if (!nc.to_int(&val))
6996 this->report_error(_("shift count not integer"));
6997 else
6998 {
6999 if (mpz_sgn(val) < 0)
7000 {
7001 this->report_error(_("negative shift count"));
7002 Location rloc = this->right_->location();
7003 this->right_ = Expression::make_integer_ul(0, right_type,
7004 rloc);
7005 }
7006 mpz_clear(val);
7007 }
7008 }
7009 }
7010 }
7011 }
7012
7013 // Get the backend representation for a binary expression.
7014
7015 Bexpression*
do_get_backend(Translate_context * context)7016 Binary_expression::do_get_backend(Translate_context* context)
7017 {
7018 Gogo* gogo = context->gogo();
7019 Location loc = this->location();
7020 Type* left_type = this->left_->type();
7021 Type* right_type = this->right_->type();
7022
7023 bool use_left_type = true;
7024 bool is_shift_op = false;
7025 bool is_idiv_op = false;
7026 switch (this->op_)
7027 {
7028 case OPERATOR_EQEQ:
7029 case OPERATOR_NOTEQ:
7030 case OPERATOR_LT:
7031 case OPERATOR_LE:
7032 case OPERATOR_GT:
7033 case OPERATOR_GE:
7034 return Expression::comparison(context, this->type_, this->op_,
7035 this->left_, this->right_, loc);
7036
7037 case OPERATOR_OROR:
7038 case OPERATOR_ANDAND:
7039 use_left_type = false;
7040 break;
7041 case OPERATOR_PLUS:
7042 case OPERATOR_MINUS:
7043 case OPERATOR_OR:
7044 case OPERATOR_XOR:
7045 case OPERATOR_MULT:
7046 break;
7047 case OPERATOR_DIV:
7048 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
7049 break;
7050 // Fall through.
7051 case OPERATOR_MOD:
7052 is_idiv_op = true;
7053 break;
7054 case OPERATOR_LSHIFT:
7055 case OPERATOR_RSHIFT:
7056 is_shift_op = true;
7057 break;
7058 case OPERATOR_BITCLEAR:
7059 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
7060 case OPERATOR_AND:
7061 break;
7062 default:
7063 go_unreachable();
7064 }
7065
7066 // The only binary operation for string is +, and that should have
7067 // been converted to a String_concat_expression in do_lower.
7068 go_assert(!left_type->is_string_type());
7069
7070 Bexpression* left = this->left_->get_backend(context);
7071 Bexpression* right = this->right_->get_backend(context);
7072
7073 Type* type = use_left_type ? left_type : right_type;
7074 Btype* btype = type->get_backend(gogo);
7075
7076 Bexpression* ret =
7077 gogo->backend()->binary_expression(this->op_, left, right, loc);
7078 ret = gogo->backend()->convert_expression(btype, ret, loc);
7079
7080 // Initialize overflow constants.
7081 Bexpression* overflow;
7082 mpz_t zero;
7083 mpz_init_set_ui(zero, 0UL);
7084 mpz_t one;
7085 mpz_init_set_ui(one, 1UL);
7086 mpz_t neg_one;
7087 mpz_init_set_si(neg_one, -1);
7088
7089 Btype* left_btype = left_type->get_backend(gogo);
7090 Btype* right_btype = right_type->get_backend(gogo);
7091
7092 // In Go, a shift larger than the size of the type is well-defined.
7093 // This is not true in C, so we need to insert a conditional.
7094 // We also need to check for a negative shift count.
7095 if (is_shift_op)
7096 {
7097 go_assert(left_type->integer_type() != NULL);
7098 go_assert(right_type->integer_type() != NULL);
7099
7100 int bits = left_type->integer_type()->bits();
7101
7102 Numeric_constant nc;
7103 unsigned long ul;
7104 if (!this->right_->numeric_constant_value(&nc)
7105 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
7106 || ul >= static_cast<unsigned long>(bits))
7107 {
7108 mpz_t bitsval;
7109 mpz_init_set_ui(bitsval, bits);
7110 Bexpression* bits_expr =
7111 gogo->backend()->integer_constant_expression(right_btype, bitsval);
7112 Bexpression* compare =
7113 gogo->backend()->binary_expression(OPERATOR_LT,
7114 right, bits_expr, loc);
7115
7116 Bexpression* zero_expr =
7117 gogo->backend()->integer_constant_expression(left_btype, zero);
7118 overflow = zero_expr;
7119 Bfunction* bfn = context->function()->func_value()->get_decl();
7120 if (this->op_ == OPERATOR_RSHIFT
7121 && !left_type->integer_type()->is_unsigned())
7122 {
7123 Bexpression* neg_expr =
7124 gogo->backend()->binary_expression(OPERATOR_LT, left,
7125 zero_expr, loc);
7126 Bexpression* neg_one_expr =
7127 gogo->backend()->integer_constant_expression(left_btype,
7128 neg_one);
7129 overflow = gogo->backend()->conditional_expression(bfn,
7130 btype,
7131 neg_expr,
7132 neg_one_expr,
7133 zero_expr,
7134 loc);
7135 }
7136 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7137 ret, overflow, loc);
7138 mpz_clear(bitsval);
7139 }
7140
7141 if (!right_type->integer_type()->is_unsigned()
7142 && (!this->right_->numeric_constant_value(&nc)
7143 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID))
7144 {
7145 Bexpression* zero_expr =
7146 gogo->backend()->integer_constant_expression(right_btype, zero);
7147 Bexpression* compare =
7148 gogo->backend()->binary_expression(OPERATOR_LT, right, zero_expr,
7149 loc);
7150 Expression* crash = Runtime::make_call(Runtime::PANIC_SHIFT,
7151 loc, 0);
7152 Bexpression* bcrash = crash->get_backend(context);
7153 Bfunction* bfn = context->function()->func_value()->get_decl();
7154 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
7155 bcrash, ret, loc);
7156 }
7157 }
7158
7159 // Add checks for division by zero and division overflow as needed.
7160 if (is_idiv_op)
7161 {
7162 if (gogo->check_divide_by_zero())
7163 {
7164 // right == 0
7165 Bexpression* zero_expr =
7166 gogo->backend()->integer_constant_expression(right_btype, zero);
7167 Bexpression* check =
7168 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7169 right, zero_expr, loc);
7170
7171 Expression* crash = Runtime::make_call(Runtime::PANIC_DIVIDE,
7172 loc, 0);
7173 Bexpression* bcrash = crash->get_backend(context);
7174
7175 // right == 0 ? (panicdivide(), 0) : ret
7176 Bfunction* bfn = context->function()->func_value()->get_decl();
7177 ret = gogo->backend()->conditional_expression(bfn, btype,
7178 check, bcrash,
7179 ret, loc);
7180 }
7181
7182 if (gogo->check_divide_overflow())
7183 {
7184 // right == -1
7185 // FIXME: It would be nice to say that this test is expected
7186 // to return false.
7187
7188 Bexpression* neg_one_expr =
7189 gogo->backend()->integer_constant_expression(right_btype, neg_one);
7190 Bexpression* check =
7191 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7192 right, neg_one_expr, loc);
7193
7194 Bexpression* zero_expr =
7195 gogo->backend()->integer_constant_expression(btype, zero);
7196 Bexpression* one_expr =
7197 gogo->backend()->integer_constant_expression(btype, one);
7198 Bfunction* bfn = context->function()->func_value()->get_decl();
7199
7200 if (type->integer_type()->is_unsigned())
7201 {
7202 // An unsigned -1 is the largest possible number, so
7203 // dividing is always 1 or 0.
7204
7205 Bexpression* cmp =
7206 gogo->backend()->binary_expression(OPERATOR_EQEQ,
7207 left, right, loc);
7208 if (this->op_ == OPERATOR_DIV)
7209 overflow =
7210 gogo->backend()->conditional_expression(bfn, btype, cmp,
7211 one_expr, zero_expr,
7212 loc);
7213 else
7214 overflow =
7215 gogo->backend()->conditional_expression(bfn, btype, cmp,
7216 zero_expr, left,
7217 loc);
7218 }
7219 else
7220 {
7221 // Computing left / -1 is the same as computing - left,
7222 // which does not overflow since Go sets -fwrapv.
7223 if (this->op_ == OPERATOR_DIV)
7224 {
7225 Expression* negate_expr =
7226 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
7227 overflow = negate_expr->get_backend(context);
7228 }
7229 else
7230 overflow = zero_expr;
7231 }
7232 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
7233
7234 // right == -1 ? - left : ret
7235 ret = gogo->backend()->conditional_expression(bfn, btype,
7236 check, overflow,
7237 ret, loc);
7238 }
7239 }
7240
7241 mpz_clear(zero);
7242 mpz_clear(one);
7243 mpz_clear(neg_one);
7244 return ret;
7245 }
7246
7247 // Export a binary expression.
7248
7249 void
do_export(Export_function_body * efb) const7250 Binary_expression::do_export(Export_function_body* efb) const
7251 {
7252 efb->write_c_string("(");
7253 this->left_->export_expression(efb);
7254 switch (this->op_)
7255 {
7256 case OPERATOR_OROR:
7257 efb->write_c_string(" || ");
7258 break;
7259 case OPERATOR_ANDAND:
7260 efb->write_c_string(" && ");
7261 break;
7262 case OPERATOR_EQEQ:
7263 efb->write_c_string(" == ");
7264 break;
7265 case OPERATOR_NOTEQ:
7266 efb->write_c_string(" != ");
7267 break;
7268 case OPERATOR_LT:
7269 efb->write_c_string(" < ");
7270 break;
7271 case OPERATOR_LE:
7272 efb->write_c_string(" <= ");
7273 break;
7274 case OPERATOR_GT:
7275 efb->write_c_string(" > ");
7276 break;
7277 case OPERATOR_GE:
7278 efb->write_c_string(" >= ");
7279 break;
7280 case OPERATOR_PLUS:
7281 efb->write_c_string(" + ");
7282 break;
7283 case OPERATOR_MINUS:
7284 efb->write_c_string(" - ");
7285 break;
7286 case OPERATOR_OR:
7287 efb->write_c_string(" | ");
7288 break;
7289 case OPERATOR_XOR:
7290 efb->write_c_string(" ^ ");
7291 break;
7292 case OPERATOR_MULT:
7293 efb->write_c_string(" * ");
7294 break;
7295 case OPERATOR_DIV:
7296 efb->write_c_string(" / ");
7297 break;
7298 case OPERATOR_MOD:
7299 efb->write_c_string(" % ");
7300 break;
7301 case OPERATOR_LSHIFT:
7302 efb->write_c_string(" << ");
7303 break;
7304 case OPERATOR_RSHIFT:
7305 efb->write_c_string(" >> ");
7306 break;
7307 case OPERATOR_AND:
7308 efb->write_c_string(" & ");
7309 break;
7310 case OPERATOR_BITCLEAR:
7311 efb->write_c_string(" &^ ");
7312 break;
7313 default:
7314 go_unreachable();
7315 }
7316 this->right_->export_expression(efb);
7317 efb->write_c_string(")");
7318 }
7319
7320 // Import a binary expression.
7321
7322 Expression*
do_import(Import_expression * imp,Location loc)7323 Binary_expression::do_import(Import_expression* imp, Location loc)
7324 {
7325 imp->require_c_string("(");
7326
7327 Expression* left = Expression::import_expression(imp, loc);
7328
7329 Operator op;
7330 if (imp->match_c_string(" || "))
7331 {
7332 op = OPERATOR_OROR;
7333 imp->advance(4);
7334 }
7335 else if (imp->match_c_string(" && "))
7336 {
7337 op = OPERATOR_ANDAND;
7338 imp->advance(4);
7339 }
7340 else if (imp->match_c_string(" == "))
7341 {
7342 op = OPERATOR_EQEQ;
7343 imp->advance(4);
7344 }
7345 else if (imp->match_c_string(" != "))
7346 {
7347 op = OPERATOR_NOTEQ;
7348 imp->advance(4);
7349 }
7350 else if (imp->match_c_string(" < "))
7351 {
7352 op = OPERATOR_LT;
7353 imp->advance(3);
7354 }
7355 else if (imp->match_c_string(" <= "))
7356 {
7357 op = OPERATOR_LE;
7358 imp->advance(4);
7359 }
7360 else if (imp->match_c_string(" > "))
7361 {
7362 op = OPERATOR_GT;
7363 imp->advance(3);
7364 }
7365 else if (imp->match_c_string(" >= "))
7366 {
7367 op = OPERATOR_GE;
7368 imp->advance(4);
7369 }
7370 else if (imp->match_c_string(" + "))
7371 {
7372 op = OPERATOR_PLUS;
7373 imp->advance(3);
7374 }
7375 else if (imp->match_c_string(" - "))
7376 {
7377 op = OPERATOR_MINUS;
7378 imp->advance(3);
7379 }
7380 else if (imp->match_c_string(" | "))
7381 {
7382 op = OPERATOR_OR;
7383 imp->advance(3);
7384 }
7385 else if (imp->match_c_string(" ^ "))
7386 {
7387 op = OPERATOR_XOR;
7388 imp->advance(3);
7389 }
7390 else if (imp->match_c_string(" * "))
7391 {
7392 op = OPERATOR_MULT;
7393 imp->advance(3);
7394 }
7395 else if (imp->match_c_string(" / "))
7396 {
7397 op = OPERATOR_DIV;
7398 imp->advance(3);
7399 }
7400 else if (imp->match_c_string(" % "))
7401 {
7402 op = OPERATOR_MOD;
7403 imp->advance(3);
7404 }
7405 else if (imp->match_c_string(" << "))
7406 {
7407 op = OPERATOR_LSHIFT;
7408 imp->advance(4);
7409 }
7410 else if (imp->match_c_string(" >> "))
7411 {
7412 op = OPERATOR_RSHIFT;
7413 imp->advance(4);
7414 }
7415 else if (imp->match_c_string(" & "))
7416 {
7417 op = OPERATOR_AND;
7418 imp->advance(3);
7419 }
7420 else if (imp->match_c_string(" &^ "))
7421 {
7422 op = OPERATOR_BITCLEAR;
7423 imp->advance(4);
7424 }
7425 else if (imp->match_c_string(")"))
7426 {
7427 // Not a binary operator after all.
7428 imp->advance(1);
7429 return left;
7430 }
7431 else
7432 {
7433 go_error_at(imp->location(), "unrecognized binary operator");
7434 return Expression::make_error(loc);
7435 }
7436
7437 Expression* right = Expression::import_expression(imp, loc);
7438
7439 imp->require_c_string(")");
7440
7441 return Expression::make_binary(op, left, right, loc);
7442 }
7443
7444 // Dump ast representation of a binary expression.
7445
7446 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7447 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
7448 {
7449 ast_dump_context->ostream() << "(";
7450 ast_dump_context->dump_expression(this->left_);
7451 ast_dump_context->ostream() << " ";
7452 ast_dump_context->dump_operator(this->op_);
7453 ast_dump_context->ostream() << " ";
7454 ast_dump_context->dump_expression(this->right_);
7455 ast_dump_context->ostream() << ") ";
7456 }
7457
7458 // Make a binary expression.
7459
7460 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)7461 Expression::make_binary(Operator op, Expression* left, Expression* right,
7462 Location location)
7463 {
7464 return new Binary_expression(op, left, right, location);
7465 }
7466
7467 // Implement a comparison.
7468
7469 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)7470 Expression::comparison(Translate_context* context, Type* result_type,
7471 Operator op, Expression* left, Expression* right,
7472 Location location)
7473 {
7474 Type* left_type = left->type();
7475 Type* right_type = right->type();
7476
7477 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
7478
7479 if (left_type->is_string_type() && right_type->is_string_type())
7480 {
7481 go_assert(left->is_multi_eval_safe());
7482 go_assert(right->is_multi_eval_safe());
7483
7484 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
7485 {
7486 // (l.len == r.len
7487 // ? (l.ptr == r.ptr ? true : memcmp(l.ptr, r.ptr, r.len) == 0)
7488 // : false)
7489 Expression* llen = Expression::make_string_info(left,
7490 STRING_INFO_LENGTH,
7491 location);
7492 Expression* rlen = Expression::make_string_info(right,
7493 STRING_INFO_LENGTH,
7494 location);
7495 Expression* leneq = Expression::make_binary(OPERATOR_EQEQ, llen, rlen,
7496 location);
7497 Expression* lptr = Expression::make_string_info(left->copy(),
7498 STRING_INFO_DATA,
7499 location);
7500 Expression* rptr = Expression::make_string_info(right->copy(),
7501 STRING_INFO_DATA,
7502 location);
7503 Expression* ptreq = Expression::make_binary(OPERATOR_EQEQ, lptr, rptr,
7504 location);
7505 Expression* btrue = Expression::make_boolean(true, location);
7506 Expression* call = Runtime::make_call(Runtime::MEMCMP, location, 3,
7507 lptr->copy(), rptr->copy(),
7508 rlen->copy());
7509 Type* int32_type = Type::lookup_integer_type("int32");
7510 Expression* zero = Expression::make_integer_ul(0, int32_type, location);
7511 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, call, zero,
7512 location);
7513 Expression* cond = Expression::make_conditional(ptreq, btrue, cmp,
7514 location);
7515 Expression* bfalse = Expression::make_boolean(false, location);
7516 left = Expression::make_conditional(leneq, cond, bfalse, location);
7517 right = Expression::make_boolean(true, location);
7518 }
7519 else
7520 {
7521 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
7522 left, right);
7523 right = zexpr;
7524 }
7525 }
7526 else if ((left_type->interface_type() != NULL
7527 && right_type->interface_type() == NULL
7528 && !right_type->is_nil_type())
7529 || (left_type->interface_type() == NULL
7530 && !left_type->is_nil_type()
7531 && right_type->interface_type() != NULL))
7532 {
7533 // Comparing an interface value to a non-interface value.
7534 if (left_type->interface_type() == NULL)
7535 {
7536 std::swap(left_type, right_type);
7537 std::swap(left, right);
7538 }
7539
7540 // The right operand is not an interface. We need to take its
7541 // address if it is not a direct interface type.
7542 Expression* pointer_arg = NULL;
7543 if (right_type->is_direct_iface_type())
7544 pointer_arg = Expression::unpack_direct_iface(right, location);
7545 else
7546 {
7547 go_assert(right->is_addressable());
7548 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
7549 location);
7550 }
7551
7552 Expression* descriptor =
7553 Expression::make_type_descriptor(right_type, location);
7554 left =
7555 Runtime::make_call((left_type->interface_type()->is_empty()
7556 ? Runtime::EFACEVALEQ
7557 : Runtime::IFACEVALEQ),
7558 location, 3, left, descriptor,
7559 pointer_arg);
7560 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7561 right = Expression::make_boolean(true, location);
7562 }
7563 else if (left_type->interface_type() != NULL
7564 && right_type->interface_type() != NULL)
7565 {
7566 Runtime::Function compare_function;
7567 if (left_type->interface_type()->is_empty()
7568 && right_type->interface_type()->is_empty())
7569 compare_function = Runtime::EFACEEQ;
7570 else if (!left_type->interface_type()->is_empty()
7571 && !right_type->interface_type()->is_empty())
7572 compare_function = Runtime::IFACEEQ;
7573 else
7574 {
7575 if (left_type->interface_type()->is_empty())
7576 {
7577 std::swap(left_type, right_type);
7578 std::swap(left, right);
7579 }
7580 go_assert(!left_type->interface_type()->is_empty());
7581 go_assert(right_type->interface_type()->is_empty());
7582 compare_function = Runtime::IFACEEFACEEQ;
7583 }
7584
7585 left = Runtime::make_call(compare_function, location, 2, left, right);
7586 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7587 right = Expression::make_boolean(true, location);
7588 }
7589
7590 if (left_type->is_nil_type()
7591 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7592 {
7593 std::swap(left_type, right_type);
7594 std::swap(left, right);
7595 }
7596
7597 if (right_type->is_nil_type())
7598 {
7599 right = Expression::make_nil(location);
7600 if (left_type->array_type() != NULL
7601 && left_type->array_type()->length() == NULL)
7602 {
7603 Array_type* at = left_type->array_type();
7604 bool is_lvalue = false;
7605 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
7606 }
7607 else if (left_type->interface_type() != NULL)
7608 {
7609 // An interface is nil if the first field is nil.
7610 left = Expression::make_field_reference(left, 0, location);
7611 }
7612 }
7613
7614 Bexpression* left_bexpr = left->get_backend(context);
7615 Bexpression* right_bexpr = right->get_backend(context);
7616
7617 Gogo* gogo = context->gogo();
7618 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
7619 right_bexpr, location);
7620 if (result_type != NULL)
7621 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
7622 ret, location);
7623 return ret;
7624 }
7625
7626 // Class String_concat_expression.
7627
7628 bool
do_is_constant() const7629 String_concat_expression::do_is_constant() const
7630 {
7631 for (Expression_list::const_iterator pe = this->exprs_->begin();
7632 pe != this->exprs_->end();
7633 ++pe)
7634 {
7635 if (!(*pe)->is_constant())
7636 return false;
7637 }
7638 return true;
7639 }
7640
7641 bool
do_is_zero_value() const7642 String_concat_expression::do_is_zero_value() const
7643 {
7644 for (Expression_list::const_iterator pe = this->exprs_->begin();
7645 pe != this->exprs_->end();
7646 ++pe)
7647 {
7648 if (!(*pe)->is_zero_value())
7649 return false;
7650 }
7651 return true;
7652 }
7653
7654 bool
do_is_static_initializer() const7655 String_concat_expression::do_is_static_initializer() const
7656 {
7657 for (Expression_list::const_iterator pe = this->exprs_->begin();
7658 pe != this->exprs_->end();
7659 ++pe)
7660 {
7661 if (!(*pe)->is_static_initializer())
7662 return false;
7663 }
7664 return true;
7665 }
7666
7667 Type*
do_type()7668 String_concat_expression::do_type()
7669 {
7670 Type* t = this->exprs_->front()->type();
7671 Expression_list::iterator pe = this->exprs_->begin();
7672 ++pe;
7673 for (; pe != this->exprs_->end(); ++pe)
7674 {
7675 Type* t1;
7676 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
7677 (*pe)->type(),
7678 &t1))
7679 return Type::make_error_type();
7680 t = t1;
7681 }
7682 return t;
7683 }
7684
7685 void
do_determine_type(const Type_context * context)7686 String_concat_expression::do_determine_type(const Type_context* context)
7687 {
7688 Type_context subcontext(*context);
7689 for (Expression_list::iterator pe = this->exprs_->begin();
7690 pe != this->exprs_->end();
7691 ++pe)
7692 {
7693 Type* t = (*pe)->type();
7694 if (!t->is_abstract())
7695 {
7696 subcontext.type = t;
7697 break;
7698 }
7699 }
7700 if (subcontext.type == NULL)
7701 subcontext.type = this->exprs_->front()->type();
7702 for (Expression_list::iterator pe = this->exprs_->begin();
7703 pe != this->exprs_->end();
7704 ++pe)
7705 (*pe)->determine_type(&subcontext);
7706 }
7707
7708 void
do_check_types(Gogo *)7709 String_concat_expression::do_check_types(Gogo*)
7710 {
7711 if (this->is_error_expression())
7712 return;
7713 Type* t = this->exprs_->front()->type();
7714 if (t->is_error())
7715 {
7716 this->set_is_error();
7717 return;
7718 }
7719 Expression_list::iterator pe = this->exprs_->begin();
7720 ++pe;
7721 for (; pe != this->exprs_->end(); ++pe)
7722 {
7723 Type* t1 = (*pe)->type();
7724 if (!Type::are_compatible_for_binop(t, t1))
7725 {
7726 this->report_error("incompatible types in binary expression");
7727 return;
7728 }
7729 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
7730 this->location()))
7731 {
7732 this->set_is_error();
7733 return;
7734 }
7735 }
7736 }
7737
7738 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)7739 String_concat_expression::do_flatten(Gogo*, Named_object*,
7740 Statement_inserter* inserter)
7741 {
7742 if (this->is_error_expression())
7743 return this;
7744 Location loc = this->location();
7745 Type* type = this->type();
7746
7747 // Mark string([]byte) operands to reuse the backing store.
7748 // runtime.concatstrings does not keep the reference.
7749 //
7750 // Note: in the gc runtime, if all but one inputs are empty,
7751 // concatstrings returns the only nonempty input without copy.
7752 // So it is not safe to reuse the backing store if it is a
7753 // string([]byte) conversion. So the gc compiler does the
7754 // no-copy optimization only when there is at least one
7755 // constant nonempty input. Currently the gccgo runtime
7756 // doesn't do this, so we don't do the check.
7757 for (Expression_list::iterator p = this->exprs_->begin();
7758 p != this->exprs_->end();
7759 ++p)
7760 {
7761 Type_conversion_expression* tce = (*p)->conversion_expression();
7762 if (tce != NULL)
7763 tce->set_no_copy(true);
7764 }
7765
7766 Expression* buf = NULL;
7767 Node* n = Node::make_node(this);
7768 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7769 {
7770 size_t size = 0;
7771 for (Expression_list::iterator p = this->exprs_->begin();
7772 p != this->exprs_->end();
7773 ++p)
7774 {
7775 std::string s;
7776 if ((*p)->string_constant_value(&s))
7777 size += s.length();
7778 }
7779 // Make a buffer on stack if the result does not escape.
7780 // But don't do this if we know it won't fit.
7781 if (size < (size_t)tmp_string_buf_size)
7782 {
7783 Type* byte_type = Type::lookup_integer_type("uint8");
7784 Expression* buflen =
7785 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7786 Expression::make_integer_ul(tmp_string_buf_size, NULL, loc);
7787 Type* array_type = Type::make_array_type(byte_type, buflen);
7788 buf = Expression::make_allocation(array_type, loc);
7789 buf->allocation_expression()->set_allocate_on_stack();
7790 buf->allocation_expression()->set_no_zero();
7791 }
7792 }
7793 if (buf == NULL)
7794 buf = Expression::make_nil(loc);
7795 go_assert(this->exprs_->size() > 1);
7796 Expression* len =
7797 Expression::make_integer_ul(this->exprs_->size(), NULL, loc);
7798 Array_type* array_type = Type::make_array_type(type, len);
7799 array_type->set_is_array_incomparable();
7800 Expression* array =
7801 Expression::make_array_composite_literal(array_type, this->exprs_,
7802 loc);
7803 Temporary_statement* ts =
7804 Statement::make_temporary(array_type, array, loc);
7805 inserter->insert(ts);
7806 Expression* ref = Expression::make_temporary_reference(ts, loc);
7807 ref = Expression::make_unary(OPERATOR_AND, ref, loc);
7808 Expression* call =
7809 Runtime::make_call(Runtime::CONCATSTRINGS, loc, 3, buf,
7810 ref, len->copy());
7811 return Expression::make_cast(type, call, loc);
7812 }
7813
7814 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7815 String_concat_expression::do_dump_expression(
7816 Ast_dump_context* ast_dump_context) const
7817 {
7818 ast_dump_context->ostream() << "concat(";
7819 ast_dump_context->dump_expression_list(this->exprs_, false);
7820 ast_dump_context->ostream() << ")";
7821 }
7822
7823 Expression*
make_string_concat(Expression_list * exprs)7824 Expression::make_string_concat(Expression_list* exprs)
7825 {
7826 return new String_concat_expression(exprs);
7827 }
7828
7829 // Class Bound_method_expression.
7830
7831 // Traversal.
7832
7833 int
do_traverse(Traverse * traverse)7834 Bound_method_expression::do_traverse(Traverse* traverse)
7835 {
7836 return Expression::traverse(&this->expr_, traverse);
7837 }
7838
7839 // Return the type of a bound method expression. The type of this
7840 // object is simply the type of the method with no receiver.
7841
7842 Type*
do_type()7843 Bound_method_expression::do_type()
7844 {
7845 Named_object* fn = this->method_->named_object();
7846 Function_type* fntype;
7847 if (fn->is_function())
7848 fntype = fn->func_value()->type();
7849 else if (fn->is_function_declaration())
7850 fntype = fn->func_declaration_value()->type();
7851 else
7852 return Type::make_error_type();
7853 return fntype->copy_without_receiver();
7854 }
7855
7856 // Determine the types of a method expression.
7857
7858 void
do_determine_type(const Type_context *)7859 Bound_method_expression::do_determine_type(const Type_context*)
7860 {
7861 Named_object* fn = this->method_->named_object();
7862 Function_type* fntype;
7863 if (fn->is_function())
7864 fntype = fn->func_value()->type();
7865 else if (fn->is_function_declaration())
7866 fntype = fn->func_declaration_value()->type();
7867 else
7868 fntype = NULL;
7869 if (fntype == NULL || !fntype->is_method())
7870 this->expr_->determine_type_no_context();
7871 else
7872 {
7873 Type_context subcontext(fntype->receiver()->type(), false);
7874 this->expr_->determine_type(&subcontext);
7875 }
7876 }
7877
7878 // Check the types of a method expression.
7879
7880 void
do_check_types(Gogo *)7881 Bound_method_expression::do_check_types(Gogo*)
7882 {
7883 Named_object* fn = this->method_->named_object();
7884 if (!fn->is_function() && !fn->is_function_declaration())
7885 {
7886 this->report_error(_("object is not a method"));
7887 return;
7888 }
7889
7890 Function_type* fntype;
7891 if (fn->is_function())
7892 fntype = fn->func_value()->type();
7893 else if (fn->is_function_declaration())
7894 fntype = fn->func_declaration_value()->type();
7895 else
7896 go_unreachable();
7897 Type* rtype = fntype->receiver()->type()->deref();
7898 Type* etype = (this->expr_type_ != NULL
7899 ? this->expr_type_
7900 : this->expr_->type());
7901 etype = etype->deref();
7902 if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
7903 this->report_error(_("method type does not match object type"));
7904 }
7905
7906 // If a bound method expression is not simply called, then it is
7907 // represented as a closure. The closure will hold a single variable,
7908 // the receiver to pass to the method. The function will be a simple
7909 // thunk that pulls that value from the closure and calls the method
7910 // with the remaining arguments.
7911 //
7912 // Because method values are not common, we don't build all thunks for
7913 // every methods, but instead only build them as we need them. In
7914 // particular, we even build them on demand for methods defined in
7915 // other packages.
7916
7917 Bound_method_expression::Method_value_thunks
7918 Bound_method_expression::method_value_thunks;
7919
7920 // Find or create the thunk for METHOD.
7921
7922 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)7923 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
7924 Named_object* fn)
7925 {
7926 std::pair<Named_object*, Named_object*> val(fn, NULL);
7927 std::pair<Method_value_thunks::iterator, bool> ins =
7928 Bound_method_expression::method_value_thunks.insert(val);
7929 if (!ins.second)
7930 {
7931 // We have seen this method before.
7932 go_assert(ins.first->second != NULL);
7933 return ins.first->second;
7934 }
7935
7936 Location loc = fn->location();
7937
7938 Function_type* orig_fntype;
7939 if (fn->is_function())
7940 orig_fntype = fn->func_value()->type();
7941 else if (fn->is_function_declaration())
7942 orig_fntype = fn->func_declaration_value()->type();
7943 else
7944 orig_fntype = NULL;
7945
7946 if (orig_fntype == NULL || !orig_fntype->is_method())
7947 {
7948 ins.first->second =
7949 Named_object::make_erroneous_name(gogo->thunk_name());
7950 return ins.first->second;
7951 }
7952
7953 Struct_field_list* sfl = new Struct_field_list();
7954 // The type here is wrong--it should be the C function type. But it
7955 // doesn't really matter.
7956 Type* vt = Type::make_pointer_type(Type::make_void_type());
7957 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
7958 sfl->push_back(Struct_field(Typed_identifier("val",
7959 orig_fntype->receiver()->type(),
7960 loc)));
7961 Struct_type* st = Type::make_struct_type(sfl, loc);
7962 st->set_is_struct_incomparable();
7963 Type* closure_type = Type::make_pointer_type(st);
7964
7965 Function_type* new_fntype = orig_fntype->copy_with_names();
7966
7967 std::string thunk_name = gogo->thunk_name();
7968 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
7969 false, loc);
7970
7971 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
7972 cvar->set_is_used();
7973 cvar->set_is_closure();
7974 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
7975 NULL, cvar);
7976 new_no->func_value()->set_closure_var(cp);
7977
7978 gogo->start_block(loc);
7979
7980 // Field 0 of the closure is the function code pointer, field 1 is
7981 // the value on which to invoke the method.
7982 Expression* arg = Expression::make_var_reference(cp, loc);
7983 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
7984 arg = Expression::make_field_reference(arg, 1, loc);
7985
7986 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
7987
7988 const Typed_identifier_list* orig_params = orig_fntype->parameters();
7989 Expression_list* args;
7990 if (orig_params == NULL || orig_params->empty())
7991 args = NULL;
7992 else
7993 {
7994 const Typed_identifier_list* new_params = new_fntype->parameters();
7995 args = new Expression_list();
7996 for (Typed_identifier_list::const_iterator p = new_params->begin();
7997 p != new_params->end();
7998 ++p)
7999 {
8000 Named_object* p_no = gogo->lookup(p->name(), NULL);
8001 go_assert(p_no != NULL
8002 && p_no->is_variable()
8003 && p_no->var_value()->is_parameter());
8004 args->push_back(Expression::make_var_reference(p_no, loc));
8005 }
8006 }
8007
8008 Call_expression* call = Expression::make_call(bme, args,
8009 orig_fntype->is_varargs(),
8010 loc);
8011 call->set_varargs_are_lowered();
8012
8013 Statement* s = Statement::make_return_from_call(call, loc);
8014 gogo->add_statement(s);
8015 Block* b = gogo->finish_block(loc);
8016 gogo->add_block(b, loc);
8017 gogo->lower_block(new_no, b);
8018 gogo->flatten_block(new_no, b);
8019 gogo->finish_function(loc);
8020
8021 ins.first->second = new_no;
8022 return new_no;
8023 }
8024
8025 // Return an expression to check *REF for nil while dereferencing
8026 // according to FIELD_INDEXES. Update *REF to build up the field
8027 // reference. This is a static function so that we don't have to
8028 // worry about declaring Field_indexes in expressions.h.
8029
8030 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)8031 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
8032 Expression** ref)
8033 {
8034 if (field_indexes == NULL)
8035 return Expression::make_boolean(false, loc);
8036 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
8037 Struct_type* stype = (*ref)->type()->deref()->struct_type();
8038 go_assert(stype != NULL
8039 && field_indexes->field_index < stype->field_count());
8040 if ((*ref)->type()->struct_type() == NULL)
8041 {
8042 go_assert((*ref)->type()->points_to() != NULL);
8043 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
8044 Expression::make_nil(loc),
8045 loc);
8046 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
8047 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
8048 loc);
8049 go_assert((*ref)->type()->struct_type() == stype);
8050 }
8051 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
8052 loc);
8053 return cond;
8054 }
8055
8056 // Flatten a method value into a struct with nil checks. We can't do
8057 // this in the lowering phase, because if the method value is called
8058 // directly we don't need a thunk. That case will have been handled
8059 // by Call_expression::do_lower, so if we get here then we do need a
8060 // thunk.
8061
8062 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)8063 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
8064 Statement_inserter* inserter)
8065 {
8066 Location loc = this->location();
8067
8068 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
8069 this->method_,
8070 this->function_);
8071 if (thunk->is_erroneous())
8072 {
8073 go_assert(saw_errors());
8074 return Expression::make_error(loc);
8075 }
8076
8077 // Force the expression into a variable. This is only necessary if
8078 // we are going to do nil checks below, but it's easy enough to
8079 // always do it.
8080 Expression* expr = this->expr_;
8081 if (!expr->is_multi_eval_safe())
8082 {
8083 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
8084 inserter->insert(etemp);
8085 expr = Expression::make_temporary_reference(etemp, loc);
8086 }
8087
8088 // If the method expects a value, and we have a pointer, we need to
8089 // dereference the pointer.
8090
8091 Named_object* fn = this->method_->named_object();
8092 Function_type *fntype;
8093 if (fn->is_function())
8094 fntype = fn->func_value()->type();
8095 else if (fn->is_function_declaration())
8096 fntype = fn->func_declaration_value()->type();
8097 else
8098 go_unreachable();
8099
8100 Expression* val = expr;
8101 if (fntype->receiver()->type()->points_to() == NULL
8102 && val->type()->points_to() != NULL)
8103 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
8104
8105 // Note that we are ignoring this->expr_type_ here. The thunk will
8106 // expect a closure whose second field has type this->expr_type_ (if
8107 // that is not NULL). We are going to pass it a closure whose
8108 // second field has type this->expr_->type(). Since
8109 // this->expr_type_ is only not-NULL for pointer types, we can get
8110 // away with this.
8111
8112 Struct_field_list* fields = new Struct_field_list();
8113 fields->push_back(Struct_field(Typed_identifier("fn",
8114 thunk->func_value()->type(),
8115 loc)));
8116 fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
8117 Struct_type* st = Type::make_struct_type(fields, loc);
8118 st->set_is_struct_incomparable();
8119
8120 Expression_list* vals = new Expression_list();
8121 vals->push_back(Expression::make_func_code_reference(thunk, loc));
8122 vals->push_back(val);
8123
8124 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
8125 ret = Expression::make_heap_expression(ret, loc);
8126
8127 Node* node = Node::make_node(this);
8128 if ((node->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
8129 ret->heap_expression()->set_allocate_on_stack();
8130 else if (gogo->compiling_runtime()
8131 && gogo->package_name() == "runtime"
8132 && !saw_errors())
8133 go_error_at(loc, "%s escapes to heap, not allowed in runtime",
8134 node->ast_format(gogo).c_str());
8135
8136 // If necessary, check whether the expression or any embedded
8137 // pointers are nil.
8138
8139 Expression* nil_check = NULL;
8140 if (this->method_->field_indexes() != NULL)
8141 {
8142 Expression* ref = expr;
8143 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
8144 expr = ref;
8145 }
8146
8147 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
8148 {
8149 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
8150 Expression::make_nil(loc),
8151 loc);
8152 if (nil_check == NULL)
8153 nil_check = n;
8154 else
8155 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
8156 }
8157
8158 if (nil_check != NULL)
8159 {
8160 Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
8161 // Fix the type of the conditional expression by pretending to
8162 // evaluate to RET either way through the conditional.
8163 crash = Expression::make_compound(crash, ret, loc);
8164 ret = Expression::make_conditional(nil_check, crash, ret, loc);
8165 }
8166
8167 // RET is a pointer to a struct, but we want a function type.
8168 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
8169
8170 return ret;
8171 }
8172
8173 // Dump ast representation of a bound method expression.
8174
8175 void
do_dump_expression(Ast_dump_context * ast_dump_context) const8176 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
8177 const
8178 {
8179 if (this->expr_type_ != NULL)
8180 ast_dump_context->ostream() << "(";
8181 ast_dump_context->dump_expression(this->expr_);
8182 if (this->expr_type_ != NULL)
8183 {
8184 ast_dump_context->ostream() << ":";
8185 ast_dump_context->dump_type(this->expr_type_);
8186 ast_dump_context->ostream() << ")";
8187 }
8188
8189 ast_dump_context->ostream() << "." << this->function_->name();
8190 }
8191
8192 // Make a method expression.
8193
8194 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)8195 Expression::make_bound_method(Expression* expr, const Method* method,
8196 Named_object* function, Location location)
8197 {
8198 return new Bound_method_expression(expr, method, function, location);
8199 }
8200
8201 // Class Builtin_call_expression. This is used for a call to a
8202 // builtin function.
8203
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)8204 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
8205 Expression* fn,
8206 Expression_list* args,
8207 bool is_varargs,
8208 Location location)
8209 : Call_expression(fn, args, is_varargs, location),
8210 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
8211 recover_arg_is_set_(false)
8212 {
8213 Func_expression* fnexp = this->fn()->func_expression();
8214 if (fnexp == NULL)
8215 {
8216 this->code_ = BUILTIN_INVALID;
8217 return;
8218 }
8219 const std::string& name(fnexp->named_object()->name());
8220 if (name == "append")
8221 this->code_ = BUILTIN_APPEND;
8222 else if (name == "cap")
8223 this->code_ = BUILTIN_CAP;
8224 else if (name == "close")
8225 this->code_ = BUILTIN_CLOSE;
8226 else if (name == "complex")
8227 this->code_ = BUILTIN_COMPLEX;
8228 else if (name == "copy")
8229 this->code_ = BUILTIN_COPY;
8230 else if (name == "delete")
8231 this->code_ = BUILTIN_DELETE;
8232 else if (name == "imag")
8233 this->code_ = BUILTIN_IMAG;
8234 else if (name == "len")
8235 this->code_ = BUILTIN_LEN;
8236 else if (name == "make")
8237 this->code_ = BUILTIN_MAKE;
8238 else if (name == "new")
8239 this->code_ = BUILTIN_NEW;
8240 else if (name == "panic")
8241 this->code_ = BUILTIN_PANIC;
8242 else if (name == "print")
8243 this->code_ = BUILTIN_PRINT;
8244 else if (name == "println")
8245 this->code_ = BUILTIN_PRINTLN;
8246 else if (name == "real")
8247 this->code_ = BUILTIN_REAL;
8248 else if (name == "recover")
8249 this->code_ = BUILTIN_RECOVER;
8250 else if (name == "Alignof")
8251 this->code_ = BUILTIN_ALIGNOF;
8252 else if (name == "Offsetof")
8253 this->code_ = BUILTIN_OFFSETOF;
8254 else if (name == "Sizeof")
8255 this->code_ = BUILTIN_SIZEOF;
8256 else
8257 go_unreachable();
8258 }
8259
8260 // Return whether this is a call to recover. This is a virtual
8261 // function called from the parent class.
8262
8263 bool
do_is_recover_call() const8264 Builtin_call_expression::do_is_recover_call() const
8265 {
8266 if (this->classification() == EXPRESSION_ERROR)
8267 return false;
8268 return this->code_ == BUILTIN_RECOVER;
8269 }
8270
8271 // Set the argument for a call to recover.
8272
8273 void
do_set_recover_arg(Expression * arg)8274 Builtin_call_expression::do_set_recover_arg(Expression* arg)
8275 {
8276 const Expression_list* args = this->args();
8277 go_assert(args == NULL || args->empty());
8278 Expression_list* new_args = new Expression_list();
8279 new_args->push_back(arg);
8280 this->set_args(new_args);
8281 this->recover_arg_is_set_ = true;
8282 }
8283
8284 // Lower a builtin call expression. This turns new and make into
8285 // specific expressions. We also convert to a constant if we can.
8286
8287 Expression*
do_lower(Gogo *,Named_object * function,Statement_inserter * inserter,int)8288 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
8289 Statement_inserter* inserter, int)
8290 {
8291 if (this->is_error_expression())
8292 return this;
8293
8294 Location loc = this->location();
8295
8296 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
8297 {
8298 this->report_error(_("invalid use of %<...%> with builtin function"));
8299 return Expression::make_error(loc);
8300 }
8301
8302 if (this->code_ == BUILTIN_OFFSETOF)
8303 {
8304 Expression* arg = this->one_arg();
8305
8306 if (arg->bound_method_expression() != NULL
8307 || arg->interface_field_reference_expression() != NULL)
8308 {
8309 this->report_error(_("invalid use of method value as argument "
8310 "of Offsetof"));
8311 return this;
8312 }
8313
8314 Field_reference_expression* farg = arg->field_reference_expression();
8315 while (farg != NULL)
8316 {
8317 if (!farg->implicit())
8318 break;
8319 // When the selector refers to an embedded field,
8320 // it must not be reached through pointer indirections.
8321 if (farg->expr()->deref() != farg->expr())
8322 {
8323 this->report_error(_("argument of Offsetof implies "
8324 "indirection of an embedded field"));
8325 return this;
8326 }
8327 // Go up until we reach the original base.
8328 farg = farg->expr()->field_reference_expression();
8329 }
8330 }
8331
8332 if (this->is_constant())
8333 {
8334 Numeric_constant nc;
8335 if (this->numeric_constant_value(&nc))
8336 return nc.expression(loc);
8337 }
8338
8339 switch (this->code_)
8340 {
8341 default:
8342 break;
8343
8344 case BUILTIN_NEW:
8345 {
8346 const Expression_list* args = this->args();
8347 if (args == NULL || args->size() < 1)
8348 this->report_error(_("not enough arguments"));
8349 else if (args->size() > 1)
8350 this->report_error(_("too many arguments"));
8351 else
8352 {
8353 Expression* arg = args->front();
8354 if (!arg->is_type_expression())
8355 {
8356 go_error_at(arg->location(), "expected type");
8357 this->set_is_error();
8358 }
8359 else
8360 return Expression::make_allocation(arg->type(), loc);
8361 }
8362 }
8363 break;
8364
8365 case BUILTIN_MAKE:
8366 return this->lower_make(inserter);
8367
8368 case BUILTIN_RECOVER:
8369 if (function != NULL)
8370 function->func_value()->set_calls_recover();
8371 else
8372 {
8373 // Calling recover outside of a function always returns the
8374 // nil empty interface.
8375 Type* eface = Type::make_empty_interface_type(loc);
8376 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
8377 }
8378 break;
8379
8380 case BUILTIN_DELETE:
8381 {
8382 const Expression_list* args = this->args();
8383 if (args == NULL || args->size() < 2)
8384 this->report_error(_("not enough arguments"));
8385 else if (args->size() > 2)
8386 this->report_error(_("too many arguments"));
8387 else if (args->front()->type()->map_type() == NULL)
8388 this->report_error(_("argument 1 must be a map"));
8389 else
8390 {
8391 Type* key_type =
8392 args->front()->type()->map_type()->key_type();
8393 Expression_list::iterator pa = this->args()->begin();
8394 pa++;
8395 Type* arg_type = (*pa)->type();
8396 std::string reason;
8397 if (!Type::are_assignable(key_type, arg_type, &reason))
8398 {
8399 if (reason.empty())
8400 go_error_at(loc, "argument 2 has incompatible type");
8401 else
8402 go_error_at(loc, "argument 2 has incompatible type (%s)",
8403 reason.c_str());
8404 this->set_is_error();
8405 }
8406 else if (!Type::are_identical(key_type, arg_type, 0, NULL))
8407 *pa = Expression::make_cast(key_type, *pa, loc);
8408 }
8409 }
8410 break;
8411
8412 case BUILTIN_PRINT:
8413 case BUILTIN_PRINTLN:
8414 // Force all the arguments into temporary variables, so that we
8415 // don't try to evaluate something while holding the print lock.
8416 if (this->args() == NULL)
8417 break;
8418 for (Expression_list::iterator pa = this->args()->begin();
8419 pa != this->args()->end();
8420 ++pa)
8421 {
8422 if (!(*pa)->is_multi_eval_safe())
8423 {
8424 Temporary_statement* temp =
8425 Statement::make_temporary(NULL, *pa, loc);
8426 inserter->insert(temp);
8427 *pa = Expression::make_temporary_reference(temp, loc);
8428 }
8429 }
8430 break;
8431 }
8432
8433 return this;
8434 }
8435
8436 // Flatten a builtin call expression. This turns the arguments of some
8437 // builtin calls into temporary expressions. Also expand copy and append
8438 // to runtime calls.
8439
8440 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)8441 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
8442 Statement_inserter* inserter)
8443 {
8444 if (this->is_error_expression())
8445 {
8446 go_assert(saw_errors());
8447 return this;
8448 }
8449
8450 Location loc = this->location();
8451
8452 switch (this->code_)
8453 {
8454 default:
8455 break;
8456
8457 case BUILTIN_APPEND:
8458 return this->flatten_append(gogo, function, inserter, NULL, NULL);
8459
8460 case BUILTIN_COPY:
8461 {
8462 Type* at = this->args()->front()->type();
8463 for (Expression_list::iterator pa = this->args()->begin();
8464 pa != this->args()->end();
8465 ++pa)
8466 {
8467 if ((*pa)->is_nil_expression())
8468 {
8469 Expression* nil = Expression::make_nil(loc);
8470 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
8471 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
8472 }
8473 if (!(*pa)->is_multi_eval_safe())
8474 {
8475 Temporary_statement* temp =
8476 Statement::make_temporary(NULL, *pa, loc);
8477 inserter->insert(temp);
8478 *pa = Expression::make_temporary_reference(temp, loc);
8479 }
8480 }
8481
8482 // Lower to runtime call.
8483 const Expression_list* args = this->args();
8484 go_assert(args != NULL && args->size() == 2);
8485 Expression* arg1 = args->front();
8486 Expression* arg2 = args->back();
8487 go_assert(arg1->is_multi_eval_safe());
8488 go_assert(arg2->is_multi_eval_safe());
8489 bool arg2_is_string = arg2->type()->is_string_type();
8490
8491 Expression* ret;
8492 Type* et = at->array_type()->element_type();
8493 if (et->has_pointer())
8494 {
8495 Expression* td = Expression::make_type_descriptor(et, loc);
8496 Expression* pd =
8497 Expression::make_slice_info(arg1, SLICE_INFO_VALUE_POINTER, loc);
8498 Expression* ld =
8499 Expression::make_slice_info(arg1, SLICE_INFO_LENGTH, loc);
8500 Expression* ps =
8501 Expression::make_slice_info(arg2, SLICE_INFO_VALUE_POINTER, loc);
8502 Expression* ls =
8503 Expression::make_slice_info(arg2, SLICE_INFO_LENGTH, loc);
8504 ret = Runtime::make_call(Runtime::TYPEDSLICECOPY, loc,
8505 5, td, pd, ld, ps, ls);
8506 }
8507 else
8508 {
8509 Type* int_type = Type::lookup_integer_type("int");
8510 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8511
8512 // l1 = len(arg1)
8513 Named_object* lenfn = gogo->lookup_global("len");
8514 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8515 Expression_list* len_args = new Expression_list();
8516 len_args->push_back(arg1->copy());
8517 Expression* len1 = Expression::make_call(lenref, len_args, false, loc);
8518 gogo->lower_expression(function, inserter, &len1);
8519 gogo->flatten_expression(function, inserter, &len1);
8520 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len1, loc);
8521 inserter->insert(l1tmp);
8522
8523 // l2 = len(arg2)
8524 len_args = new Expression_list();
8525 len_args->push_back(arg2->copy());
8526 Expression* len2 = Expression::make_call(lenref, len_args, false, loc);
8527 gogo->lower_expression(function, inserter, &len2);
8528 gogo->flatten_expression(function, inserter, &len2);
8529 Temporary_statement* l2tmp = Statement::make_temporary(int_type, len2, loc);
8530 inserter->insert(l2tmp);
8531
8532 // n = (l1 < l2 ? l1 : l2)
8533 Expression* l1ref = Expression::make_temporary_reference(l1tmp, loc);
8534 Expression* l2ref = Expression::make_temporary_reference(l2tmp, loc);
8535 Expression* cond = Expression::make_binary(OPERATOR_LT, l1ref, l2ref, loc);
8536 Expression* n = Expression::make_conditional(cond,
8537 l1ref->copy(),
8538 l2ref->copy(),
8539 loc);
8540 Temporary_statement* ntmp = Statement::make_temporary(NULL, n, loc);
8541 inserter->insert(ntmp);
8542
8543 // sz = n * sizeof(elem_type)
8544 Expression* nref = Expression::make_temporary_reference(ntmp, loc);
8545 nref = Expression::make_cast(uintptr_type, nref, loc);
8546 Expression* sz = Expression::make_type_info(et, TYPE_INFO_SIZE);
8547 sz = Expression::make_binary(OPERATOR_MULT, sz, nref, loc);
8548
8549 // memmove(arg1.ptr, arg2.ptr, sz)
8550 Expression* p1 = Expression::make_slice_info(arg1,
8551 SLICE_INFO_VALUE_POINTER,
8552 loc);
8553 Expression* p2 = (arg2_is_string
8554 ? Expression::make_string_info(arg2,
8555 STRING_INFO_DATA,
8556 loc)
8557 : Expression::make_slice_info(arg2,
8558 SLICE_INFO_VALUE_POINTER,
8559 loc));
8560 Expression* call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
8561 p1, p2, sz);
8562
8563 // n is the return value of copy
8564 nref = Expression::make_temporary_reference(ntmp, loc);
8565 ret = Expression::make_compound(call, nref, loc);
8566 }
8567 return ret;
8568 }
8569 break;
8570
8571 case BUILTIN_PANIC:
8572 for (Expression_list::iterator pa = this->args()->begin();
8573 pa != this->args()->end();
8574 ++pa)
8575 {
8576 if (!(*pa)->is_multi_eval_safe()
8577 && (*pa)->type()->interface_type() != NULL)
8578 {
8579 Temporary_statement* temp =
8580 Statement::make_temporary(NULL, *pa, loc);
8581 inserter->insert(temp);
8582 *pa = Expression::make_temporary_reference(temp, loc);
8583 }
8584 }
8585 break;
8586
8587 case BUILTIN_LEN:
8588 case BUILTIN_CAP:
8589 {
8590 Expression_list::iterator pa = this->args()->begin();
8591 if (!(*pa)->is_multi_eval_safe()
8592 && ((*pa)->type()->map_type() != NULL
8593 || (*pa)->type()->channel_type() != NULL))
8594 {
8595 Temporary_statement* temp =
8596 Statement::make_temporary(NULL, *pa, loc);
8597 inserter->insert(temp);
8598 *pa = Expression::make_temporary_reference(temp, loc);
8599 }
8600 }
8601 break;
8602
8603 case BUILTIN_DELETE:
8604 {
8605 // Lower to a runtime function call.
8606 const Expression_list* args = this->args();
8607
8608 // Since this function returns no value it must appear in
8609 // a statement by itself, so we don't have to worry about
8610 // order of evaluation of values around it. Evaluate the
8611 // map first to get order of evaluation right.
8612 Map_type* mt = args->front()->type()->map_type();
8613 Temporary_statement* map_temp =
8614 Statement::make_temporary(mt, args->front(), loc);
8615 inserter->insert(map_temp);
8616
8617 Temporary_statement* key_temp =
8618 Statement::make_temporary(mt->key_type(), args->back(), loc);
8619 inserter->insert(key_temp);
8620
8621 Expression* e1 = Expression::make_type_descriptor(mt, loc);
8622 Expression* e2 = Expression::make_temporary_reference(map_temp,
8623 loc);
8624 Expression* e3 = Expression::make_temporary_reference(key_temp,
8625 loc);
8626
8627 Runtime::Function code;
8628 switch (mt->algorithm(gogo))
8629 {
8630 case Map_type::MAP_ALG_FAST32:
8631 case Map_type::MAP_ALG_FAST32PTR:
8632 {
8633 code = Runtime::MAPDELETE_FAST32;
8634 Type* uint32_type = Type::lookup_integer_type("uint32");
8635 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
8636 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8637 e3 = Expression::make_unsafe_cast(uint32_ptr_type, e3,
8638 loc);
8639 e3 = Expression::make_dereference(e3,
8640 Expression::NIL_CHECK_NOT_NEEDED,
8641 loc);
8642 break;
8643 }
8644 case Map_type::MAP_ALG_FAST64:
8645 case Map_type::MAP_ALG_FAST64PTR:
8646 {
8647 code = Runtime::MAPDELETE_FAST64;
8648 Type* uint64_type = Type::lookup_integer_type("uint64");
8649 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
8650 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8651 e3 = Expression::make_unsafe_cast(uint64_ptr_type, e3,
8652 loc);
8653 e3 = Expression::make_dereference(e3,
8654 Expression::NIL_CHECK_NOT_NEEDED,
8655 loc);
8656 break;
8657 }
8658 case Map_type::MAP_ALG_FASTSTR:
8659 code = Runtime::MAPDELETE_FASTSTR;
8660 break;
8661 default:
8662 code = Runtime::MAPDELETE;
8663
8664 // If the call to delete is deferred, and is in a loop,
8665 // then the loop will only have a single instance of the
8666 // temporary variable. Passing the address of the
8667 // temporary variable here means that the deferred call
8668 // will see the last value in the loop, not the current
8669 // value. So for this unusual case copy the value into
8670 // the heap.
8671 if (!this->is_deferred())
8672 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
8673 else
8674 {
8675 Expression* a = Expression::make_allocation(mt->key_type(),
8676 loc);
8677 Temporary_statement* atemp =
8678 Statement::make_temporary(NULL, a, loc);
8679 inserter->insert(atemp);
8680
8681 a = Expression::make_temporary_reference(atemp, loc);
8682 a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
8683 Statement* s = Statement::make_assignment(a, e3, loc);
8684 inserter->insert(s);
8685
8686 e3 = Expression::make_temporary_reference(atemp, loc);
8687 }
8688 }
8689
8690 return Runtime::make_call(code, loc, 3, e1, e2, e3);
8691 }
8692 }
8693
8694 return this;
8695 }
8696
8697 // Lower a make expression.
8698
8699 Expression*
lower_make(Statement_inserter * inserter)8700 Builtin_call_expression::lower_make(Statement_inserter* inserter)
8701 {
8702 Location loc = this->location();
8703
8704 const Expression_list* args = this->args();
8705 if (args == NULL || args->size() < 1)
8706 {
8707 this->report_error(_("not enough arguments"));
8708 return Expression::make_error(this->location());
8709 }
8710
8711 Expression_list::const_iterator parg = args->begin();
8712
8713 Expression* first_arg = *parg;
8714 if (!first_arg->is_type_expression())
8715 {
8716 go_error_at(first_arg->location(), "expected type");
8717 this->set_is_error();
8718 return Expression::make_error(this->location());
8719 }
8720 Type* type = first_arg->type();
8721
8722 if (!type->in_heap())
8723 go_error_at(first_arg->location(),
8724 "cannot make slice of go:notinheap type");
8725
8726 bool is_slice = false;
8727 bool is_map = false;
8728 bool is_chan = false;
8729 if (type->is_slice_type())
8730 is_slice = true;
8731 else if (type->map_type() != NULL)
8732 is_map = true;
8733 else if (type->channel_type() != NULL)
8734 is_chan = true;
8735 else
8736 {
8737 this->report_error(_("invalid type for make function"));
8738 return Expression::make_error(this->location());
8739 }
8740
8741 Type_context int_context(Type::lookup_integer_type("int"), false);
8742
8743 ++parg;
8744 Expression* len_arg;
8745 bool len_small = false;
8746 if (parg == args->end())
8747 {
8748 if (is_slice)
8749 {
8750 this->report_error(_("length required when allocating a slice"));
8751 return Expression::make_error(this->location());
8752 }
8753 len_arg = Expression::make_integer_ul(0, NULL, loc);
8754 len_small = true;
8755 }
8756 else
8757 {
8758 len_arg = *parg;
8759 len_arg->determine_type(&int_context);
8760 if (len_arg->type()->integer_type() == NULL)
8761 {
8762 go_error_at(len_arg->location(), "non-integer len argument in make");
8763 return Expression::make_error(this->location());
8764 }
8765 if (!this->check_int_value(len_arg, true, &len_small))
8766 return Expression::make_error(this->location());
8767 ++parg;
8768 }
8769
8770 Expression* cap_arg = NULL;
8771 bool cap_small = false;
8772 Numeric_constant nclen;
8773 Numeric_constant nccap;
8774 unsigned long vlen;
8775 unsigned long vcap;
8776 if (is_slice && parg != args->end())
8777 {
8778 cap_arg = *parg;
8779 cap_arg->determine_type(&int_context);
8780 if (cap_arg->type()->integer_type() == NULL)
8781 {
8782 go_error_at(cap_arg->location(), "non-integer cap argument in make");
8783 return Expression::make_error(this->location());
8784 }
8785 if (!this->check_int_value(cap_arg, false, &cap_small))
8786 return Expression::make_error(this->location());
8787
8788 if (len_arg->numeric_constant_value(&nclen)
8789 && cap_arg->numeric_constant_value(&nccap)
8790 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8791 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
8792 && vlen > vcap)
8793 {
8794 this->report_error(_("len larger than cap"));
8795 return Expression::make_error(this->location());
8796 }
8797
8798 ++parg;
8799 }
8800
8801 if (parg != args->end())
8802 {
8803 this->report_error(_("too many arguments to make"));
8804 return Expression::make_error(this->location());
8805 }
8806
8807 Location type_loc = first_arg->location();
8808
8809 Expression* call;
8810 if (is_slice)
8811 {
8812 Temporary_statement* len_temp = NULL;
8813 if (!len_arg->is_constant())
8814 {
8815 len_temp = Statement::make_temporary(NULL, len_arg, loc);
8816 inserter->insert(len_temp);
8817 len_arg = Expression::make_temporary_reference(len_temp, loc);
8818 }
8819
8820 if (cap_arg == NULL)
8821 {
8822 cap_small = len_small;
8823 if (len_temp == NULL)
8824 cap_arg = len_arg->copy();
8825 else
8826 cap_arg = Expression::make_temporary_reference(len_temp, loc);
8827 }
8828 else if (!cap_arg->is_constant())
8829 {
8830 Temporary_statement* cap_temp = Statement::make_temporary(NULL,
8831 cap_arg,
8832 loc);
8833 inserter->insert(cap_temp);
8834 cap_arg = Expression::make_temporary_reference(cap_temp, loc);
8835 }
8836
8837 Type* et = type->array_type()->element_type();
8838 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
8839 Runtime::Function code = Runtime::MAKESLICE;
8840 if (!len_small || !cap_small)
8841 code = Runtime::MAKESLICE64;
8842 Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
8843 cap_arg);
8844 mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
8845 loc);
8846 Type* int_type = Type::lookup_integer_type("int");
8847 len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
8848 cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
8849 call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
8850 }
8851 else if (is_map)
8852 {
8853 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8854 if (!len_small)
8855 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
8856 len_arg,
8857 Expression::make_nil(loc));
8858 else
8859 {
8860 if (len_arg->numeric_constant_value(&nclen)
8861 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
8862 && vlen <= Map_type::bucket_size)
8863 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
8864 else
8865 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
8866 len_arg,
8867 Expression::make_nil(loc));
8868 }
8869 }
8870 else if (is_chan)
8871 {
8872 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
8873 Runtime::Function code = Runtime::MAKECHAN;
8874 if (!len_small)
8875 code = Runtime::MAKECHAN64;
8876 call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
8877 }
8878 else
8879 go_unreachable();
8880
8881 return Expression::make_unsafe_cast(type, call, loc);
8882 }
8883
8884 // Flatten a call to the predeclared append function. We do this in
8885 // the flatten phase, not the lowering phase, so that we run after
8886 // type checking and after order_evaluations. If ASSIGN_LHS is not
8887 // NULL, this append is the right-hand-side of an assignment and
8888 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
8889 // rather than returning a slice. This lets us omit a write barrier
8890 // in common cases like a = append(a, ...) when the slice does not
8891 // need to grow. ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
8892
8893 Expression*
flatten_append(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Expression * assign_lhs,Block * enclosing)8894 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
8895 Statement_inserter* inserter,
8896 Expression* assign_lhs,
8897 Block* enclosing)
8898 {
8899 if (this->is_error_expression())
8900 return this;
8901
8902 Location loc = this->location();
8903
8904 const Expression_list* args = this->args();
8905 go_assert(args != NULL && !args->empty());
8906
8907 Type* slice_type = args->front()->type();
8908 go_assert(slice_type->is_slice_type());
8909 Type* element_type = slice_type->array_type()->element_type();
8910
8911 if (args->size() == 1)
8912 {
8913 // append(s) evaluates to s.
8914 if (assign_lhs != NULL)
8915 return NULL;
8916 return args->front();
8917 }
8918
8919 Type* int_type = Type::lookup_integer_type("int");
8920 Type* uint_type = Type::lookup_integer_type("uint");
8921
8922 // Implementing
8923 // append(s1, s2...)
8924 // or
8925 // append(s1, a1, a2, a3, ...)
8926
8927 // s1tmp := s1
8928 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
8929 loc);
8930 inserter->insert(s1tmp);
8931
8932 // l1tmp := len(s1tmp)
8933 Named_object* lenfn = gogo->lookup_global("len");
8934 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
8935 Expression_list* call_args = new Expression_list();
8936 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8937 Expression* len = Expression::make_call(lenref, call_args, false, loc);
8938 gogo->lower_expression(function, inserter, &len);
8939 gogo->flatten_expression(function, inserter, &len);
8940 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
8941 inserter->insert(l1tmp);
8942
8943 Temporary_statement* s2tmp = NULL;
8944 Temporary_statement* l2tmp = NULL;
8945 Expression_list* add = NULL;
8946 Expression* len2;
8947 Call_expression* makecall = NULL;
8948 if (this->is_varargs())
8949 {
8950 go_assert(args->size() == 2);
8951
8952 std::pair<Call_expression*, Temporary_statement*> p =
8953 Expression::find_makeslice_call(args->back());
8954 makecall = p.first;
8955 if (makecall != NULL)
8956 {
8957 // We are handling
8958 // append(s, make([]T, len[, cap])...))
8959 // which has already been lowered to
8960 // append(s, runtime.makeslice(T, len, cap)).
8961 // We will optimize this to directly zeroing the tail,
8962 // instead of allocating a new slice then copy.
8963
8964 // Retrieve the length and capacity. Cannot reference s2 as
8965 // we will remove the makeslice call.
8966 Expression* len_arg = makecall->args()->at(1);
8967 len_arg = Expression::make_cast(int_type, len_arg, loc);
8968 l2tmp = Statement::make_temporary(int_type, len_arg, loc);
8969 inserter->insert(l2tmp);
8970
8971 Expression* cap_arg = makecall->args()->at(2);
8972 cap_arg = Expression::make_cast(int_type, cap_arg, loc);
8973 Temporary_statement* c2tmp =
8974 Statement::make_temporary(int_type, cap_arg, loc);
8975 inserter->insert(c2tmp);
8976
8977 // Check bad len/cap here.
8978 // checkmakeslice(type, len, cap)
8979 // (Note that if len and cap are constants, we won't see a
8980 // makeslice call here, as it will be rewritten to a stack
8981 // allocated array by Mark_address_taken::expression.)
8982 Expression* elem = Expression::make_type_descriptor(element_type,
8983 loc);
8984 len2 = Expression::make_temporary_reference(l2tmp, loc);
8985 Expression* cap2 = Expression::make_temporary_reference(c2tmp, loc);
8986 Expression* check = Runtime::make_call(Runtime::CHECK_MAKE_SLICE,
8987 loc, 3, elem, len2, cap2);
8988 gogo->lower_expression(function, inserter, &check);
8989 gogo->flatten_expression(function, inserter, &check);
8990 Statement* s = Statement::make_statement(check, false);
8991 inserter->insert(s);
8992
8993 // Remove the original makeslice call.
8994 Temporary_statement* ts = p.second;
8995 if (ts != NULL && ts->uses() == 1)
8996 ts->set_init(Expression::make_nil(loc));
8997 }
8998 else
8999 {
9000 // s2tmp := s2
9001 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
9002 inserter->insert(s2tmp);
9003
9004 // l2tmp := len(s2tmp)
9005 lenref = Expression::make_func_reference(lenfn, NULL, loc);
9006 call_args = new Expression_list();
9007 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
9008 len = Expression::make_call(lenref, call_args, false, loc);
9009 gogo->lower_expression(function, inserter, &len);
9010 gogo->flatten_expression(function, inserter, &len);
9011 l2tmp = Statement::make_temporary(int_type, len, loc);
9012 inserter->insert(l2tmp);
9013 }
9014
9015 // len2 = l2tmp
9016 len2 = Expression::make_temporary_reference(l2tmp, loc);
9017 }
9018 else
9019 {
9020 // We have to ensure that all the arguments are in variables
9021 // now, because otherwise if one of them is an index expression
9022 // into the current slice we could overwrite it before we fetch
9023 // it.
9024 add = new Expression_list();
9025 Expression_list::const_iterator pa = args->begin();
9026 for (++pa; pa != args->end(); ++pa)
9027 {
9028 if ((*pa)->is_multi_eval_safe())
9029 add->push_back(*pa);
9030 else
9031 {
9032 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
9033 loc);
9034 inserter->insert(tmp);
9035 add->push_back(Expression::make_temporary_reference(tmp, loc));
9036 }
9037 }
9038
9039 // len2 = len(add)
9040 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
9041 }
9042
9043 // ntmp := l1tmp + len2
9044 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
9045 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
9046 gogo->lower_expression(function, inserter, &sum);
9047 gogo->flatten_expression(function, inserter, &sum);
9048 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
9049 inserter->insert(ntmp);
9050
9051 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
9052 // growslice(type, s1tmp, ntmp) :
9053 // s1tmp[:ntmp]
9054 // Using uint here means that if the computation of ntmp overflowed,
9055 // we will call growslice which will panic.
9056
9057 Named_object* capfn = gogo->lookup_global("cap");
9058 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
9059 call_args = new Expression_list();
9060 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
9061 Expression* cap = Expression::make_call(capref, call_args, false, loc);
9062 gogo->lower_expression(function, inserter, &cap);
9063 gogo->flatten_expression(function, inserter, &cap);
9064 Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
9065 inserter->insert(c1tmp);
9066
9067 Expression* left = Expression::make_temporary_reference(ntmp, loc);
9068 left = Expression::make_cast(uint_type, left, loc);
9069 Expression* right = Expression::make_temporary_reference(c1tmp, loc);
9070 right = Expression::make_cast(uint_type, right, loc);
9071
9072 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
9073
9074 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
9075 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
9076 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
9077 a2 = slice_type->array_type()->get_value_pointer(gogo, a2, false);
9078 a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
9079 Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
9080 Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
9081 Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
9082 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
9083 a1, a2, a3, a4, a5);
9084 call = Expression::make_unsafe_cast(slice_type, call, loc);
9085
9086 ref = Expression::make_temporary_reference(s1tmp, loc);
9087 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
9088 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
9089 ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
9090 ref->array_index_expression()->set_needs_bounds_check(false);
9091
9092 if (assign_lhs == NULL)
9093 {
9094 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
9095
9096 gogo->lower_expression(function, inserter, &rhs);
9097 gogo->flatten_expression(function, inserter, &rhs);
9098
9099 ref = Expression::make_temporary_reference(s1tmp, loc);
9100 Statement* assign = Statement::make_assignment(ref, rhs, loc);
9101 inserter->insert(assign);
9102 }
9103 else
9104 {
9105 gogo->lower_expression(function, inserter, &cond);
9106 gogo->flatten_expression(function, inserter, &cond);
9107 gogo->lower_expression(function, inserter, &call);
9108 gogo->flatten_expression(function, inserter, &call);
9109 gogo->lower_expression(function, inserter, &ref);
9110 gogo->flatten_expression(function, inserter, &ref);
9111
9112 Block* then_block = new Block(enclosing, loc);
9113 Assignment_statement* assign =
9114 Statement::make_assignment(assign_lhs, call, loc);
9115 then_block->add_statement(assign);
9116
9117 Block* else_block = new Block(enclosing, loc);
9118 assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
9119 // This assignment will not change the pointer value, so it does
9120 // not need a write barrier.
9121 assign->set_omit_write_barrier();
9122 else_block->add_statement(assign);
9123
9124 Statement* s = Statement::make_if_statement(cond, then_block,
9125 else_block, loc);
9126 inserter->insert(s);
9127
9128 ref = Expression::make_temporary_reference(s1tmp, loc);
9129 assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
9130 inserter->insert(assign);
9131 }
9132
9133 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9134
9135 if (this->is_varargs())
9136 {
9137 if (makecall != NULL)
9138 {
9139 // memclr(&s1tmp[l1tmp], l2tmp*sizeof(elem))
9140 a1 = Expression::make_temporary_reference(s1tmp, loc);
9141 ref = Expression::make_temporary_reference(l1tmp, loc);
9142 a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9143 a1->array_index_expression()->set_needs_bounds_check(false);
9144 a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9145
9146 ref = Expression::make_temporary_reference(l2tmp, loc);
9147 ref = Expression::make_cast(uintptr_type, ref, loc);
9148 a2 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9149 a2 = Expression::make_binary(OPERATOR_MULT, a2, ref, loc);
9150
9151 if (element_type->has_pointer())
9152 call = Runtime::make_call(Runtime::MEMCLRHASPTR, loc, 2, a1, a2);
9153 else
9154 {
9155 Type* int32_type = Type::lookup_integer_type("int32");
9156 zero = Expression::make_integer_ul(0, int32_type, loc);
9157 call = Runtime::make_call(Runtime::BUILTIN_MEMSET, loc, 3, a1,
9158 zero, a2);
9159 }
9160
9161 if (element_type->has_pointer())
9162 {
9163 // For a slice containing pointers, growslice already zeroed
9164 // the memory. We only need to zero in non-growing case.
9165 // Note: growslice does not zero the memory in non-pointer case.
9166 ref = Expression::make_temporary_reference(ntmp, loc);
9167 ref = Expression::make_cast(uint_type, ref, loc);
9168 ref2 = Expression::make_temporary_reference(c1tmp, loc);
9169 ref2 = Expression::make_cast(uint_type, ref2, loc);
9170 cond = Expression::make_binary(OPERATOR_GT, ref, ref2, loc);
9171 zero = Expression::make_integer_ul(0, int_type, loc);
9172 call = Expression::make_conditional(cond, zero, call, loc);
9173 }
9174 }
9175 else
9176 {
9177 if (element_type->has_pointer())
9178 {
9179 // copy(s1tmp[l1tmp:], s2tmp)
9180 a1 = Expression::make_temporary_reference(s1tmp, loc);
9181 ref = Expression::make_temporary_reference(l1tmp, loc);
9182 Expression* nil = Expression::make_nil(loc);
9183 a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
9184 a1->array_index_expression()->set_needs_bounds_check(false);
9185
9186 a2 = Expression::make_temporary_reference(s2tmp, loc);
9187
9188 Named_object* copyfn = gogo->lookup_global("copy");
9189 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
9190 call_args = new Expression_list();
9191 call_args->push_back(a1);
9192 call_args->push_back(a2);
9193 call = Expression::make_call(copyref, call_args, false, loc);
9194 }
9195 else
9196 {
9197 // memmove(&s1tmp[l1tmp], s2tmp.ptr, l2tmp*sizeof(elem))
9198 a1 = Expression::make_temporary_reference(s1tmp, loc);
9199 ref = Expression::make_temporary_reference(l1tmp, loc);
9200 a1 = Expression::make_array_index(a1, ref, NULL, NULL, loc);
9201 a1->array_index_expression()->set_needs_bounds_check(false);
9202 a1 = Expression::make_unary(OPERATOR_AND, a1, loc);
9203
9204 a2 = Expression::make_temporary_reference(s2tmp, loc);
9205 a2 = (a2->type()->is_string_type()
9206 ? Expression::make_string_info(a2,
9207 STRING_INFO_DATA,
9208 loc)
9209 : Expression::make_slice_info(a2,
9210 SLICE_INFO_VALUE_POINTER,
9211 loc));
9212
9213 ref = Expression::make_temporary_reference(l2tmp, loc);
9214 ref = Expression::make_cast(uintptr_type, ref, loc);
9215 a3 = Expression::make_type_info(element_type, TYPE_INFO_SIZE);
9216 a3 = Expression::make_binary(OPERATOR_MULT, a3, ref, loc);
9217
9218 call = Runtime::make_call(Runtime::BUILTIN_MEMMOVE, loc, 3,
9219 a1, a2, a3);
9220 }
9221 }
9222 gogo->lower_expression(function, inserter, &call);
9223 gogo->flatten_expression(function, inserter, &call);
9224 inserter->insert(Statement::make_statement(call, false));
9225 }
9226 else
9227 {
9228 // For each argument:
9229 // s1tmp[l1tmp+i] = a
9230 unsigned long i = 0;
9231 for (Expression_list::const_iterator pa = add->begin();
9232 pa != add->end();
9233 ++pa, ++i)
9234 {
9235 ref = Expression::make_temporary_reference(s1tmp, loc);
9236 ref2 = Expression::make_temporary_reference(l1tmp, loc);
9237 Expression* off = Expression::make_integer_ul(i, int_type, loc);
9238 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
9239 Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
9240 NULL, loc);
9241 lhs->array_index_expression()->set_needs_bounds_check(false);
9242 gogo->lower_expression(function, inserter, &lhs);
9243 gogo->flatten_expression(function, inserter, &lhs);
9244 Expression* elem = *pa;
9245 if (!Type::are_identical(element_type, elem->type(), 0, NULL)
9246 && element_type->interface_type() != NULL)
9247 elem = Expression::make_cast(element_type, elem, loc);
9248 // The flatten pass runs after the write barrier pass, so we
9249 // need to insert a write barrier here if necessary.
9250 // However, if ASSIGN_LHS is not NULL, we have been called
9251 // directly before the write barrier pass.
9252 Statement* assign;
9253 if (assign_lhs != NULL
9254 || !gogo->assign_needs_write_barrier(lhs, NULL))
9255 assign = Statement::make_assignment(lhs, elem, loc);
9256 else
9257 {
9258 Function* f = function == NULL ? NULL : function->func_value();
9259 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
9260 lhs, elem, loc);
9261 }
9262 inserter->insert(assign);
9263 }
9264 }
9265
9266 if (assign_lhs != NULL)
9267 return NULL;
9268
9269 return Expression::make_temporary_reference(s1tmp, loc);
9270 }
9271
9272 // Return whether an expression has an integer value. Report an error
9273 // if not. This is used when handling calls to the predeclared make
9274 // function. Set *SMALL if the value is known to fit in type "int".
9275
9276 bool
check_int_value(Expression * e,bool is_length,bool * small)9277 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
9278 bool *small)
9279 {
9280 *small = false;
9281
9282 Numeric_constant nc;
9283 if (e->numeric_constant_value(&nc))
9284 {
9285 unsigned long v;
9286 switch (nc.to_unsigned_long(&v))
9287 {
9288 case Numeric_constant::NC_UL_VALID:
9289 break;
9290 case Numeric_constant::NC_UL_NOTINT:
9291 go_error_at(e->location(), "non-integer %s argument to make",
9292 is_length ? "len" : "cap");
9293 return false;
9294 case Numeric_constant::NC_UL_NEGATIVE:
9295 go_error_at(e->location(), "negative %s argument to make",
9296 is_length ? "len" : "cap");
9297 return false;
9298 case Numeric_constant::NC_UL_BIG:
9299 // We don't want to give a compile-time error for a 64-bit
9300 // value on a 32-bit target.
9301 break;
9302 }
9303
9304 mpz_t val;
9305 if (!nc.to_int(&val))
9306 go_unreachable();
9307 int bits = mpz_sizeinbase(val, 2);
9308 mpz_clear(val);
9309 Type* int_type = Type::lookup_integer_type("int");
9310 if (bits >= int_type->integer_type()->bits())
9311 {
9312 go_error_at(e->location(), "%s argument too large for make",
9313 is_length ? "len" : "cap");
9314 return false;
9315 }
9316
9317 *small = true;
9318 return true;
9319 }
9320
9321 if (e->type()->integer_type() != NULL)
9322 {
9323 int ebits = e->type()->integer_type()->bits();
9324 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
9325
9326 // We can treat ebits == intbits as small even for an unsigned
9327 // integer type, because we will convert the value to int and
9328 // then reject it in the runtime if it is negative.
9329 *small = ebits <= intbits;
9330
9331 return true;
9332 }
9333
9334 go_error_at(e->location(), "non-integer %s argument to make",
9335 is_length ? "len" : "cap");
9336 return false;
9337 }
9338
9339 // Return the type of the real or imag functions, given the type of
9340 // the argument. We need to map complex64 to float32 and complex128
9341 // to float64, so it has to be done by name. This returns NULL if it
9342 // can't figure out the type.
9343
9344 Type*
real_imag_type(Type * arg_type)9345 Builtin_call_expression::real_imag_type(Type* arg_type)
9346 {
9347 if (arg_type == NULL || arg_type->is_abstract())
9348 return NULL;
9349 Named_type* nt = arg_type->named_type();
9350 if (nt == NULL)
9351 return NULL;
9352 while (nt->real_type()->named_type() != NULL)
9353 nt = nt->real_type()->named_type();
9354 if (nt->name() == "complex64")
9355 return Type::lookup_float_type("float32");
9356 else if (nt->name() == "complex128")
9357 return Type::lookup_float_type("float64");
9358 else
9359 return NULL;
9360 }
9361
9362 // Return the type of the complex function, given the type of one of the
9363 // argments. Like real_imag_type, we have to map by name.
9364
9365 Type*
complex_type(Type * arg_type)9366 Builtin_call_expression::complex_type(Type* arg_type)
9367 {
9368 if (arg_type == NULL || arg_type->is_abstract())
9369 return NULL;
9370 Named_type* nt = arg_type->named_type();
9371 if (nt == NULL)
9372 return NULL;
9373 while (nt->real_type()->named_type() != NULL)
9374 nt = nt->real_type()->named_type();
9375 if (nt->name() == "float32")
9376 return Type::lookup_complex_type("complex64");
9377 else if (nt->name() == "float64")
9378 return Type::lookup_complex_type("complex128");
9379 else
9380 return NULL;
9381 }
9382
9383 // Return a single argument, or NULL if there isn't one.
9384
9385 Expression*
one_arg() const9386 Builtin_call_expression::one_arg() const
9387 {
9388 const Expression_list* args = this->args();
9389 if (args == NULL || args->size() != 1)
9390 return NULL;
9391 return args->front();
9392 }
9393
9394 // A traversal class which looks for a call or receive expression.
9395
9396 class Find_call_expression : public Traverse
9397 {
9398 public:
Find_call_expression()9399 Find_call_expression()
9400 : Traverse(traverse_expressions),
9401 found_(false)
9402 { }
9403
9404 int
9405 expression(Expression**);
9406
9407 bool
found()9408 found()
9409 { return this->found_; }
9410
9411 private:
9412 bool found_;
9413 };
9414
9415 int
expression(Expression ** pexpr)9416 Find_call_expression::expression(Expression** pexpr)
9417 {
9418 Expression* expr = *pexpr;
9419 if (!expr->is_constant()
9420 && (expr->call_expression() != NULL
9421 || expr->receive_expression() != NULL))
9422 {
9423 this->found_ = true;
9424 return TRAVERSE_EXIT;
9425 }
9426 return TRAVERSE_CONTINUE;
9427 }
9428
9429 // Return whether calling len or cap on EXPR, of array type, is a
9430 // constant. The language spec says "the expressions len(s) and
9431 // cap(s) are constants if the type of s is an array or pointer to an
9432 // array and the expression s does not contain channel receives or
9433 // (non-constant) function calls."
9434
9435 bool
array_len_is_constant(Expression * expr)9436 Builtin_call_expression::array_len_is_constant(Expression* expr)
9437 {
9438 go_assert(expr->type()->deref()->array_type() != NULL
9439 && !expr->type()->deref()->is_slice_type());
9440 if (expr->is_constant())
9441 return true;
9442 Find_call_expression find_call;
9443 Expression::traverse(&expr, &find_call);
9444 return !find_call.found();
9445 }
9446
9447 // Return whether this is constant: len of a string constant, or len
9448 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
9449 // unsafe.Alignof.
9450
9451 bool
do_is_constant() const9452 Builtin_call_expression::do_is_constant() const
9453 {
9454 if (this->is_error_expression())
9455 return true;
9456 switch (this->code_)
9457 {
9458 case BUILTIN_LEN:
9459 case BUILTIN_CAP:
9460 {
9461 if (this->seen_)
9462 return false;
9463
9464 Expression* arg = this->one_arg();
9465 if (arg == NULL)
9466 return false;
9467 Type* arg_type = arg->type();
9468 if (arg_type->is_error())
9469 return true;
9470
9471 if (arg_type->points_to() != NULL
9472 && arg_type->points_to()->array_type() != NULL
9473 && !arg_type->points_to()->is_slice_type())
9474 arg_type = arg_type->points_to();
9475
9476 if (arg_type->array_type() != NULL
9477 && arg_type->array_type()->length() != NULL)
9478 {
9479 this->seen_ = true;
9480 bool ret = Builtin_call_expression::array_len_is_constant(arg);
9481 this->seen_ = false;
9482 return ret;
9483 }
9484
9485 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9486 {
9487 this->seen_ = true;
9488 bool ret = arg->is_constant();
9489 this->seen_ = false;
9490 return ret;
9491 }
9492 }
9493 break;
9494
9495 case BUILTIN_SIZEOF:
9496 case BUILTIN_ALIGNOF:
9497 return this->one_arg() != NULL;
9498
9499 case BUILTIN_OFFSETOF:
9500 {
9501 Expression* arg = this->one_arg();
9502 if (arg == NULL)
9503 return false;
9504 return arg->field_reference_expression() != NULL;
9505 }
9506
9507 case BUILTIN_COMPLEX:
9508 {
9509 const Expression_list* args = this->args();
9510 if (args != NULL && args->size() == 2)
9511 return args->front()->is_constant() && args->back()->is_constant();
9512 }
9513 break;
9514
9515 case BUILTIN_REAL:
9516 case BUILTIN_IMAG:
9517 {
9518 Expression* arg = this->one_arg();
9519 return arg != NULL && arg->is_constant();
9520 }
9521
9522 default:
9523 break;
9524 }
9525
9526 return false;
9527 }
9528
9529 // Return a numeric constant if possible.
9530
9531 bool
do_numeric_constant_value(Numeric_constant * nc) const9532 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
9533 {
9534 if (this->code_ == BUILTIN_LEN
9535 || this->code_ == BUILTIN_CAP)
9536 {
9537 Expression* arg = this->one_arg();
9538 if (arg == NULL)
9539 return false;
9540 Type* arg_type = arg->type();
9541 if (arg_type->is_error())
9542 return false;
9543
9544 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
9545 {
9546 std::string sval;
9547 if (arg->string_constant_value(&sval))
9548 {
9549 nc->set_unsigned_long(Type::lookup_integer_type("int"),
9550 sval.length());
9551 return true;
9552 }
9553 }
9554
9555 if (arg_type->points_to() != NULL
9556 && arg_type->points_to()->array_type() != NULL
9557 && !arg_type->points_to()->is_slice_type())
9558 arg_type = arg_type->points_to();
9559
9560 if (arg_type->array_type() != NULL
9561 && arg_type->array_type()->length() != NULL)
9562 {
9563 if (this->seen_)
9564 return false;
9565
9566 // We may be replacing this expression with a constant
9567 // during lowering, so verify the type to report any errors.
9568 // It's OK to verify an array type more than once.
9569 arg_type->verify();
9570 if (!arg_type->is_error())
9571 {
9572 Expression* e = arg_type->array_type()->length();
9573 this->seen_ = true;
9574 bool r = e->numeric_constant_value(nc);
9575 this->seen_ = false;
9576 if (r)
9577 {
9578 if (!nc->set_type(Type::lookup_integer_type("int"), false,
9579 this->location()))
9580 r = false;
9581 }
9582 return r;
9583 }
9584 }
9585 }
9586 else if (this->code_ == BUILTIN_SIZEOF
9587 || this->code_ == BUILTIN_ALIGNOF)
9588 {
9589 Expression* arg = this->one_arg();
9590 if (arg == NULL)
9591 return false;
9592 Type* arg_type = arg->type();
9593 if (arg_type->is_error())
9594 return false;
9595 if (arg_type->is_abstract())
9596 arg_type = arg_type->make_non_abstract_type();
9597 if (this->seen_)
9598 return false;
9599
9600 int64_t ret;
9601 if (this->code_ == BUILTIN_SIZEOF)
9602 {
9603 this->seen_ = true;
9604 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
9605 this->seen_ = false;
9606 if (!ok)
9607 return false;
9608 }
9609 else if (this->code_ == BUILTIN_ALIGNOF)
9610 {
9611 bool ok;
9612 this->seen_ = true;
9613 if (arg->field_reference_expression() == NULL)
9614 ok = arg_type->backend_type_align(this->gogo_, &ret);
9615 else
9616 {
9617 // Calling unsafe.Alignof(s.f) returns the alignment of
9618 // the type of f when it is used as a field in a struct.
9619 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
9620 }
9621 this->seen_ = false;
9622 if (!ok)
9623 return false;
9624 }
9625 else
9626 go_unreachable();
9627
9628 mpz_t zval;
9629 set_mpz_from_int64(&zval, ret);
9630 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9631 mpz_clear(zval);
9632 return true;
9633 }
9634 else if (this->code_ == BUILTIN_OFFSETOF)
9635 {
9636 Expression* arg = this->one_arg();
9637 if (arg == NULL)
9638 return false;
9639 Field_reference_expression* farg = arg->field_reference_expression();
9640 if (farg == NULL)
9641 return false;
9642 if (this->seen_)
9643 return false;
9644
9645 int64_t total_offset = 0;
9646 while (true)
9647 {
9648 Expression* struct_expr = farg->expr();
9649 Type* st = struct_expr->type();
9650 if (st->struct_type() == NULL)
9651 return false;
9652 if (st->named_type() != NULL)
9653 st->named_type()->convert(this->gogo_);
9654 if (st->is_error_type())
9655 {
9656 go_assert(saw_errors());
9657 return false;
9658 }
9659 int64_t offset;
9660 this->seen_ = true;
9661 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
9662 farg->field_index(),
9663 &offset);
9664 this->seen_ = false;
9665 if (!ok)
9666 return false;
9667 total_offset += offset;
9668 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
9669 {
9670 // Go up until we reach the original base.
9671 farg = struct_expr->field_reference_expression();
9672 continue;
9673 }
9674 break;
9675 }
9676 mpz_t zval;
9677 set_mpz_from_int64(&zval, total_offset);
9678 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
9679 mpz_clear(zval);
9680 return true;
9681 }
9682 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
9683 {
9684 Expression* arg = this->one_arg();
9685 if (arg == NULL)
9686 return false;
9687
9688 Numeric_constant argnc;
9689 if (!arg->numeric_constant_value(&argnc))
9690 return false;
9691
9692 mpc_t val;
9693 if (!argnc.to_complex(&val))
9694 return false;
9695
9696 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
9697 if (this->code_ == BUILTIN_REAL)
9698 nc->set_float(type, mpc_realref(val));
9699 else
9700 nc->set_float(type, mpc_imagref(val));
9701 mpc_clear(val);
9702 return true;
9703 }
9704 else if (this->code_ == BUILTIN_COMPLEX)
9705 {
9706 const Expression_list* args = this->args();
9707 if (args == NULL || args->size() != 2)
9708 return false;
9709
9710 Numeric_constant rnc;
9711 if (!args->front()->numeric_constant_value(&rnc))
9712 return false;
9713 Numeric_constant inc;
9714 if (!args->back()->numeric_constant_value(&inc))
9715 return false;
9716
9717 if (rnc.type() != NULL
9718 && !rnc.type()->is_abstract()
9719 && inc.type() != NULL
9720 && !inc.type()->is_abstract()
9721 && !Type::are_identical(rnc.type(), inc.type(),
9722 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
9723 NULL))
9724 return false;
9725
9726 mpfr_t r;
9727 if (!rnc.to_float(&r))
9728 return false;
9729 mpfr_t i;
9730 if (!inc.to_float(&i))
9731 {
9732 mpfr_clear(r);
9733 return false;
9734 }
9735
9736 Type* arg_type = rnc.type();
9737 if (arg_type == NULL || arg_type->is_abstract())
9738 arg_type = inc.type();
9739
9740 mpc_t val;
9741 mpc_init2(val, mpc_precision);
9742 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
9743 mpfr_clear(r);
9744 mpfr_clear(i);
9745
9746 Type* type = Builtin_call_expression::complex_type(arg_type);
9747 nc->set_complex(type, val);
9748
9749 mpc_clear(val);
9750
9751 return true;
9752 }
9753
9754 return false;
9755 }
9756
9757 // Give an error if we are discarding the value of an expression which
9758 // should not normally be discarded. We don't give an error for
9759 // discarding the value of an ordinary function call, but we do for
9760 // builtin functions, purely for consistency with the gc compiler.
9761
9762 bool
do_discarding_value()9763 Builtin_call_expression::do_discarding_value()
9764 {
9765 switch (this->code_)
9766 {
9767 case BUILTIN_INVALID:
9768 default:
9769 go_unreachable();
9770
9771 case BUILTIN_APPEND:
9772 case BUILTIN_CAP:
9773 case BUILTIN_COMPLEX:
9774 case BUILTIN_IMAG:
9775 case BUILTIN_LEN:
9776 case BUILTIN_MAKE:
9777 case BUILTIN_NEW:
9778 case BUILTIN_REAL:
9779 case BUILTIN_ALIGNOF:
9780 case BUILTIN_OFFSETOF:
9781 case BUILTIN_SIZEOF:
9782 this->unused_value_error();
9783 return false;
9784
9785 case BUILTIN_CLOSE:
9786 case BUILTIN_COPY:
9787 case BUILTIN_DELETE:
9788 case BUILTIN_PANIC:
9789 case BUILTIN_PRINT:
9790 case BUILTIN_PRINTLN:
9791 case BUILTIN_RECOVER:
9792 return true;
9793 }
9794 }
9795
9796 // Return the type.
9797
9798 Type*
do_type()9799 Builtin_call_expression::do_type()
9800 {
9801 if (this->is_error_expression())
9802 return Type::make_error_type();
9803 switch (this->code_)
9804 {
9805 case BUILTIN_INVALID:
9806 default:
9807 return Type::make_error_type();
9808
9809 case BUILTIN_NEW:
9810 {
9811 const Expression_list* args = this->args();
9812 if (args == NULL || args->empty())
9813 return Type::make_error_type();
9814 return Type::make_pointer_type(args->front()->type());
9815 }
9816
9817 case BUILTIN_MAKE:
9818 {
9819 const Expression_list* args = this->args();
9820 if (args == NULL || args->empty())
9821 return Type::make_error_type();
9822 return args->front()->type();
9823 }
9824
9825 case BUILTIN_CAP:
9826 case BUILTIN_COPY:
9827 case BUILTIN_LEN:
9828 return Type::lookup_integer_type("int");
9829
9830 case BUILTIN_ALIGNOF:
9831 case BUILTIN_OFFSETOF:
9832 case BUILTIN_SIZEOF:
9833 return Type::lookup_integer_type("uintptr");
9834
9835 case BUILTIN_CLOSE:
9836 case BUILTIN_DELETE:
9837 case BUILTIN_PANIC:
9838 case BUILTIN_PRINT:
9839 case BUILTIN_PRINTLN:
9840 return Type::make_void_type();
9841
9842 case BUILTIN_RECOVER:
9843 return Type::make_empty_interface_type(Linemap::predeclared_location());
9844
9845 case BUILTIN_APPEND:
9846 {
9847 const Expression_list* args = this->args();
9848 if (args == NULL || args->empty())
9849 return Type::make_error_type();
9850 Type *ret = args->front()->type();
9851 if (!ret->is_slice_type())
9852 return Type::make_error_type();
9853 return ret;
9854 }
9855
9856 case BUILTIN_REAL:
9857 case BUILTIN_IMAG:
9858 {
9859 Expression* arg = this->one_arg();
9860 if (arg == NULL)
9861 return Type::make_error_type();
9862 Type* t = arg->type();
9863 if (t->is_abstract())
9864 t = t->make_non_abstract_type();
9865 t = Builtin_call_expression::real_imag_type(t);
9866 if (t == NULL)
9867 t = Type::make_error_type();
9868 return t;
9869 }
9870
9871 case BUILTIN_COMPLEX:
9872 {
9873 const Expression_list* args = this->args();
9874 if (args == NULL || args->size() != 2)
9875 return Type::make_error_type();
9876 Type* t = args->front()->type();
9877 if (t->is_abstract())
9878 {
9879 t = args->back()->type();
9880 if (t->is_abstract())
9881 t = t->make_non_abstract_type();
9882 }
9883 t = Builtin_call_expression::complex_type(t);
9884 if (t == NULL)
9885 t = Type::make_error_type();
9886 return t;
9887 }
9888 }
9889 }
9890
9891 // Determine the type.
9892
9893 void
do_determine_type(const Type_context * context)9894 Builtin_call_expression::do_determine_type(const Type_context* context)
9895 {
9896 if (!this->determining_types())
9897 return;
9898
9899 this->fn()->determine_type_no_context();
9900
9901 const Expression_list* args = this->args();
9902
9903 bool is_print;
9904 Type* arg_type = NULL;
9905 Type* trailing_arg_types = NULL;
9906 switch (this->code_)
9907 {
9908 case BUILTIN_PRINT:
9909 case BUILTIN_PRINTLN:
9910 // Do not force a large integer constant to "int".
9911 is_print = true;
9912 break;
9913
9914 case BUILTIN_REAL:
9915 case BUILTIN_IMAG:
9916 arg_type = Builtin_call_expression::complex_type(context->type);
9917 if (arg_type == NULL)
9918 arg_type = Type::lookup_complex_type("complex128");
9919 is_print = false;
9920 break;
9921
9922 case BUILTIN_COMPLEX:
9923 {
9924 // For the complex function the type of one operand can
9925 // determine the type of the other, as in a binary expression.
9926 arg_type = Builtin_call_expression::real_imag_type(context->type);
9927 if (arg_type == NULL)
9928 arg_type = Type::lookup_float_type("float64");
9929 if (args != NULL && args->size() == 2)
9930 {
9931 Type* t1 = args->front()->type();
9932 Type* t2 = args->back()->type();
9933 if (!t1->is_abstract())
9934 arg_type = t1;
9935 else if (!t2->is_abstract())
9936 arg_type = t2;
9937 }
9938 is_print = false;
9939 }
9940 break;
9941
9942 case BUILTIN_APPEND:
9943 if (!this->is_varargs()
9944 && args != NULL
9945 && !args->empty()
9946 && args->front()->type()->is_slice_type())
9947 trailing_arg_types =
9948 args->front()->type()->array_type()->element_type();
9949 is_print = false;
9950 break;
9951
9952 default:
9953 is_print = false;
9954 break;
9955 }
9956
9957 if (args != NULL)
9958 {
9959 for (Expression_list::const_iterator pa = args->begin();
9960 pa != args->end();
9961 ++pa)
9962 {
9963 Type_context subcontext;
9964 subcontext.type = arg_type;
9965
9966 if (is_print)
9967 {
9968 // We want to print large constants, we so can't just
9969 // use the appropriate nonabstract type. Use uint64 for
9970 // an integer if we know it is nonnegative, otherwise
9971 // use int64 for a integer, otherwise use float64 for a
9972 // float or complex128 for a complex.
9973 Type* want_type = NULL;
9974 Type* atype = (*pa)->type();
9975 if (atype->is_abstract())
9976 {
9977 if (atype->integer_type() != NULL)
9978 {
9979 Numeric_constant nc;
9980 if (this->numeric_constant_value(&nc))
9981 {
9982 mpz_t val;
9983 if (nc.to_int(&val))
9984 {
9985 if (mpz_sgn(val) >= 0)
9986 want_type = Type::lookup_integer_type("uint64");
9987 mpz_clear(val);
9988 }
9989 }
9990 if (want_type == NULL)
9991 want_type = Type::lookup_integer_type("int64");
9992 }
9993 else if (atype->float_type() != NULL)
9994 want_type = Type::lookup_float_type("float64");
9995 else if (atype->complex_type() != NULL)
9996 want_type = Type::lookup_complex_type("complex128");
9997 else if (atype->is_abstract_string_type())
9998 want_type = Type::lookup_string_type();
9999 else if (atype->is_abstract_boolean_type())
10000 want_type = Type::lookup_bool_type();
10001 else
10002 go_unreachable();
10003 subcontext.type = want_type;
10004 }
10005 }
10006
10007 (*pa)->determine_type(&subcontext);
10008
10009 if (trailing_arg_types != NULL)
10010 {
10011 arg_type = trailing_arg_types;
10012 trailing_arg_types = NULL;
10013 }
10014 }
10015 }
10016 }
10017
10018 // If there is exactly one argument, return true. Otherwise give an
10019 // error message and return false.
10020
10021 bool
check_one_arg()10022 Builtin_call_expression::check_one_arg()
10023 {
10024 const Expression_list* args = this->args();
10025 if (args == NULL || args->size() < 1)
10026 {
10027 this->report_error(_("not enough arguments"));
10028 return false;
10029 }
10030 else if (args->size() > 1)
10031 {
10032 this->report_error(_("too many arguments"));
10033 return false;
10034 }
10035 if (args->front()->is_error_expression()
10036 || args->front()->type()->is_error())
10037 {
10038 this->set_is_error();
10039 return false;
10040 }
10041 return true;
10042 }
10043
10044 // Check argument types for a builtin function.
10045
10046 void
do_check_types(Gogo *)10047 Builtin_call_expression::do_check_types(Gogo*)
10048 {
10049 if (this->is_error_expression())
10050 return;
10051 switch (this->code_)
10052 {
10053 case BUILTIN_INVALID:
10054 case BUILTIN_NEW:
10055 case BUILTIN_MAKE:
10056 case BUILTIN_DELETE:
10057 return;
10058
10059 case BUILTIN_LEN:
10060 case BUILTIN_CAP:
10061 {
10062 // The single argument may be either a string or an array or a
10063 // map or a channel, or a pointer to a closed array.
10064 if (this->check_one_arg())
10065 {
10066 Type* arg_type = this->one_arg()->type();
10067 if (arg_type->points_to() != NULL
10068 && arg_type->points_to()->array_type() != NULL
10069 && !arg_type->points_to()->is_slice_type())
10070 arg_type = arg_type->points_to();
10071 if (this->code_ == BUILTIN_CAP)
10072 {
10073 if (!arg_type->is_error()
10074 && arg_type->array_type() == NULL
10075 && arg_type->channel_type() == NULL)
10076 this->report_error(_("argument must be array or slice "
10077 "or channel"));
10078 }
10079 else
10080 {
10081 if (!arg_type->is_error()
10082 && !arg_type->is_string_type()
10083 && arg_type->array_type() == NULL
10084 && arg_type->map_type() == NULL
10085 && arg_type->channel_type() == NULL)
10086 this->report_error(_("argument must be string or "
10087 "array or slice or map or channel"));
10088 }
10089 }
10090 }
10091 break;
10092
10093 case BUILTIN_PRINT:
10094 case BUILTIN_PRINTLN:
10095 {
10096 const Expression_list* args = this->args();
10097 if (args == NULL)
10098 {
10099 if (this->code_ == BUILTIN_PRINT)
10100 go_warning_at(this->location(), 0,
10101 "no arguments for built-in function %<%s%>",
10102 (this->code_ == BUILTIN_PRINT
10103 ? "print"
10104 : "println"));
10105 }
10106 else
10107 {
10108 for (Expression_list::const_iterator p = args->begin();
10109 p != args->end();
10110 ++p)
10111 {
10112 Type* type = (*p)->type();
10113 if (type->is_error()
10114 || type->is_string_type()
10115 || type->integer_type() != NULL
10116 || type->float_type() != NULL
10117 || type->complex_type() != NULL
10118 || type->is_boolean_type()
10119 || type->points_to() != NULL
10120 || type->interface_type() != NULL
10121 || type->channel_type() != NULL
10122 || type->map_type() != NULL
10123 || type->function_type() != NULL
10124 || type->is_slice_type())
10125 ;
10126 else if ((*p)->is_type_expression())
10127 {
10128 // If this is a type expression it's going to give
10129 // an error anyhow, so we don't need one here.
10130 }
10131 else
10132 this->report_error(_("unsupported argument type to "
10133 "builtin function"));
10134 }
10135 }
10136 }
10137 break;
10138
10139 case BUILTIN_CLOSE:
10140 if (this->check_one_arg())
10141 {
10142 if (this->one_arg()->type()->channel_type() == NULL)
10143 this->report_error(_("argument must be channel"));
10144 else if (!this->one_arg()->type()->channel_type()->may_send())
10145 this->report_error(_("cannot close receive-only channel"));
10146 }
10147 break;
10148
10149 case BUILTIN_PANIC:
10150 case BUILTIN_SIZEOF:
10151 case BUILTIN_ALIGNOF:
10152 this->check_one_arg();
10153 break;
10154
10155 case BUILTIN_RECOVER:
10156 if (this->args() != NULL
10157 && !this->args()->empty()
10158 && !this->recover_arg_is_set_)
10159 this->report_error(_("too many arguments"));
10160 break;
10161
10162 case BUILTIN_OFFSETOF:
10163 if (this->check_one_arg())
10164 {
10165 Expression* arg = this->one_arg();
10166 if (arg->field_reference_expression() == NULL)
10167 this->report_error(_("argument must be a field reference"));
10168 }
10169 break;
10170
10171 case BUILTIN_COPY:
10172 {
10173 const Expression_list* args = this->args();
10174 if (args == NULL || args->size() < 2)
10175 {
10176 this->report_error(_("not enough arguments"));
10177 break;
10178 }
10179 else if (args->size() > 2)
10180 {
10181 this->report_error(_("too many arguments"));
10182 break;
10183 }
10184 Type* arg1_type = args->front()->type();
10185 Type* arg2_type = args->back()->type();
10186 if (arg1_type->is_error() || arg2_type->is_error())
10187 {
10188 this->set_is_error();
10189 break;
10190 }
10191
10192 Type* e1;
10193 if (arg1_type->is_slice_type())
10194 e1 = arg1_type->array_type()->element_type();
10195 else
10196 {
10197 this->report_error(_("left argument must be a slice"));
10198 break;
10199 }
10200
10201 if (arg2_type->is_slice_type())
10202 {
10203 Type* e2 = arg2_type->array_type()->element_type();
10204 if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
10205 this->report_error(_("element types must be the same"));
10206 }
10207 else if (arg2_type->is_string_type())
10208 {
10209 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
10210 this->report_error(_("first argument must be []byte"));
10211 }
10212 else
10213 this->report_error(_("second argument must be slice or string"));
10214 }
10215 break;
10216
10217 case BUILTIN_APPEND:
10218 {
10219 const Expression_list* args = this->args();
10220 if (args == NULL || args->empty())
10221 {
10222 this->report_error(_("not enough arguments"));
10223 break;
10224 }
10225
10226 Type* slice_type = args->front()->type();
10227 if (!slice_type->is_slice_type())
10228 {
10229 if (slice_type->is_error_type())
10230 break;
10231 if (slice_type->is_nil_type())
10232 go_error_at(args->front()->location(), "use of untyped nil");
10233 else
10234 go_error_at(args->front()->location(),
10235 "argument 1 must be a slice");
10236 this->set_is_error();
10237 break;
10238 }
10239
10240 Type* element_type = slice_type->array_type()->element_type();
10241 if (!element_type->in_heap())
10242 go_error_at(args->front()->location(),
10243 "cannot append to slice of go:notinheap type");
10244 if (this->is_varargs())
10245 {
10246 if (!args->back()->type()->is_slice_type()
10247 && !args->back()->type()->is_string_type())
10248 {
10249 go_error_at(args->back()->location(),
10250 "invalid use of %<...%> with non-slice/non-string");
10251 this->set_is_error();
10252 break;
10253 }
10254
10255 if (args->size() < 2)
10256 {
10257 this->report_error(_("not enough arguments"));
10258 break;
10259 }
10260 if (args->size() > 2)
10261 {
10262 this->report_error(_("too many arguments"));
10263 break;
10264 }
10265
10266 if (args->back()->type()->is_string_type()
10267 && element_type->integer_type() != NULL
10268 && element_type->integer_type()->is_byte())
10269 {
10270 // Permit append(s1, s2...) when s1 is a slice of
10271 // bytes and s2 is a string type.
10272 }
10273 else
10274 {
10275 // We have to test for assignment compatibility to a
10276 // slice of the element type, which is not necessarily
10277 // the same as the type of the first argument: the
10278 // first argument might have a named type.
10279 Type* check_type = Type::make_array_type(element_type, NULL);
10280 std::string reason;
10281 if (!Type::are_assignable(check_type, args->back()->type(),
10282 &reason))
10283 {
10284 if (reason.empty())
10285 go_error_at(args->back()->location(),
10286 "argument 2 has invalid type");
10287 else
10288 go_error_at(args->back()->location(),
10289 "argument 2 has invalid type (%s)",
10290 reason.c_str());
10291 this->set_is_error();
10292 break;
10293 }
10294 }
10295 }
10296 else
10297 {
10298 Expression_list::const_iterator pa = args->begin();
10299 int i = 2;
10300 for (++pa; pa != args->end(); ++pa, ++i)
10301 {
10302 std::string reason;
10303 if (!Type::are_assignable(element_type, (*pa)->type(),
10304 &reason))
10305 {
10306 if (reason.empty())
10307 go_error_at((*pa)->location(),
10308 "argument %d has incompatible type", i);
10309 else
10310 go_error_at((*pa)->location(),
10311 "argument %d has incompatible type (%s)",
10312 i, reason.c_str());
10313 this->set_is_error();
10314 }
10315 }
10316 }
10317 }
10318 break;
10319
10320 case BUILTIN_REAL:
10321 case BUILTIN_IMAG:
10322 if (this->check_one_arg())
10323 {
10324 if (this->one_arg()->type()->complex_type() == NULL)
10325 this->report_error(_("argument must have complex type"));
10326 }
10327 break;
10328
10329 case BUILTIN_COMPLEX:
10330 {
10331 const Expression_list* args = this->args();
10332 if (args == NULL || args->size() < 2)
10333 this->report_error(_("not enough arguments"));
10334 else if (args->size() > 2)
10335 this->report_error(_("too many arguments"));
10336 else if (args->front()->is_error_expression()
10337 || args->front()->type()->is_error()
10338 || args->back()->is_error_expression()
10339 || args->back()->type()->is_error())
10340 this->set_is_error();
10341 else if (!Type::are_identical(args->front()->type(),
10342 args->back()->type(),
10343 Type::COMPARE_TAGS, NULL))
10344 this->report_error(_("complex arguments must have identical types"));
10345 else if (args->front()->type()->float_type() == NULL)
10346 this->report_error(_("complex arguments must have "
10347 "floating-point type"));
10348 }
10349 break;
10350
10351 default:
10352 go_unreachable();
10353 }
10354 }
10355
10356 Expression*
do_copy()10357 Builtin_call_expression::do_copy()
10358 {
10359 Call_expression* bce =
10360 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
10361 (this->args() == NULL
10362 ? NULL
10363 : this->args()->copy()),
10364 this->is_varargs(),
10365 this->location());
10366
10367 if (this->varargs_are_lowered())
10368 bce->set_varargs_are_lowered();
10369 if (this->is_deferred())
10370 bce->set_is_deferred();
10371 if (this->is_concurrent())
10372 bce->set_is_concurrent();
10373 return bce;
10374 }
10375
10376 // Return the backend representation for a builtin function.
10377
10378 Bexpression*
do_get_backend(Translate_context * context)10379 Builtin_call_expression::do_get_backend(Translate_context* context)
10380 {
10381 Gogo* gogo = context->gogo();
10382 Location location = this->location();
10383
10384 if (this->is_erroneous_call())
10385 {
10386 go_assert(saw_errors());
10387 return gogo->backend()->error_expression();
10388 }
10389
10390 switch (this->code_)
10391 {
10392 case BUILTIN_INVALID:
10393 case BUILTIN_NEW:
10394 case BUILTIN_MAKE:
10395 go_unreachable();
10396
10397 case BUILTIN_LEN:
10398 case BUILTIN_CAP:
10399 {
10400 const Expression_list* args = this->args();
10401 go_assert(args != NULL && args->size() == 1);
10402 Expression* arg = args->front();
10403 Type* arg_type = arg->type();
10404
10405 if (this->seen_)
10406 {
10407 go_assert(saw_errors());
10408 return context->backend()->error_expression();
10409 }
10410 this->seen_ = true;
10411 this->seen_ = false;
10412 if (arg_type->points_to() != NULL)
10413 {
10414 arg_type = arg_type->points_to();
10415 go_assert(arg_type->array_type() != NULL
10416 && !arg_type->is_slice_type());
10417 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
10418 location);
10419 }
10420
10421 Type* int_type = Type::lookup_integer_type("int");
10422 Expression* val;
10423 if (this->code_ == BUILTIN_LEN)
10424 {
10425 if (arg_type->is_string_type())
10426 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
10427 location);
10428 else if (arg_type->array_type() != NULL)
10429 {
10430 if (this->seen_)
10431 {
10432 go_assert(saw_errors());
10433 return context->backend()->error_expression();
10434 }
10435 this->seen_ = true;
10436 val = arg_type->array_type()->get_length(gogo, arg);
10437 this->seen_ = false;
10438 }
10439 else if (arg_type->map_type() != NULL
10440 || arg_type->channel_type() != NULL)
10441 {
10442 // The first field is the length. If the pointer is
10443 // nil, the length is zero.
10444 Type* pint_type = Type::make_pointer_type(int_type);
10445 arg = Expression::make_unsafe_cast(pint_type, arg, location);
10446 Expression* nil = Expression::make_nil(location);
10447 nil = Expression::make_cast(pint_type, nil, location);
10448 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10449 arg, nil, location);
10450 Expression* zero = Expression::make_integer_ul(0, int_type,
10451 location);
10452 Expression* indir =
10453 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
10454 location);
10455 val = Expression::make_conditional(cmp, zero, indir, location);
10456 }
10457 else
10458 go_unreachable();
10459 }
10460 else
10461 {
10462 if (arg_type->array_type() != NULL)
10463 {
10464 if (this->seen_)
10465 {
10466 go_assert(saw_errors());
10467 return context->backend()->error_expression();
10468 }
10469 this->seen_ = true;
10470 val = arg_type->array_type()->get_capacity(gogo, arg);
10471 this->seen_ = false;
10472 }
10473 else if (arg_type->channel_type() != NULL)
10474 {
10475 // The second field is the capacity. If the pointer
10476 // is nil, the capacity is zero.
10477 Type* uintptr_type = Type::lookup_integer_type("uintptr");
10478 Type* pint_type = Type::make_pointer_type(int_type);
10479 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
10480 arg,
10481 location);
10482 int off = int_type->integer_type()->bits() / 8;
10483 Expression* eoff = Expression::make_integer_ul(off,
10484 uintptr_type,
10485 location);
10486 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
10487 location);
10488 parg = Expression::make_unsafe_cast(pint_type, parg, location);
10489 Expression* nil = Expression::make_nil(location);
10490 nil = Expression::make_cast(pint_type, nil, location);
10491 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
10492 arg, nil, location);
10493 Expression* zero = Expression::make_integer_ul(0, int_type,
10494 location);
10495 Expression* indir =
10496 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
10497 location);
10498 val = Expression::make_conditional(cmp, zero, indir, location);
10499 }
10500 else
10501 go_unreachable();
10502 }
10503
10504 return Expression::make_cast(int_type, val,
10505 location)->get_backend(context);
10506 }
10507
10508 case BUILTIN_PRINT:
10509 case BUILTIN_PRINTLN:
10510 {
10511 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
10512
10513 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
10514 location, 0);
10515
10516 const Expression_list* call_args = this->args();
10517 if (call_args != NULL)
10518 {
10519 for (Expression_list::const_iterator p = call_args->begin();
10520 p != call_args->end();
10521 ++p)
10522 {
10523 if (is_ln && p != call_args->begin())
10524 {
10525 Expression* print_space =
10526 Runtime::make_call(Runtime::PRINTSP, location, 0);
10527
10528 print_stmts =
10529 Expression::make_compound(print_stmts, print_space,
10530 location);
10531 }
10532
10533 Expression* arg = *p;
10534 Type* type = arg->type();
10535 Runtime::Function code;
10536 if (type->is_string_type())
10537 code = Runtime::PRINTSTRING;
10538 else if (type->integer_type() != NULL
10539 && type->integer_type()->is_unsigned())
10540 {
10541 Type* itype = Type::lookup_integer_type("uint64");
10542 arg = Expression::make_cast(itype, arg, location);
10543 if (gogo->compiling_runtime()
10544 && type->named_type() != NULL
10545 && gogo->unpack_hidden_name(type->named_type()->name())
10546 == "hex")
10547 code = Runtime::PRINTHEX;
10548 else
10549 code = Runtime::PRINTUINT;
10550 }
10551 else if (type->integer_type() != NULL)
10552 {
10553 Type* itype = Type::lookup_integer_type("int64");
10554 arg = Expression::make_cast(itype, arg, location);
10555 code = Runtime::PRINTINT;
10556 }
10557 else if (type->float_type() != NULL)
10558 {
10559 Type* dtype = Type::lookup_float_type("float64");
10560 arg = Expression::make_cast(dtype, arg, location);
10561 code = Runtime::PRINTFLOAT;
10562 }
10563 else if (type->complex_type() != NULL)
10564 {
10565 Type* ctype = Type::lookup_complex_type("complex128");
10566 arg = Expression::make_cast(ctype, arg, location);
10567 code = Runtime::PRINTCOMPLEX;
10568 }
10569 else if (type->is_boolean_type())
10570 code = Runtime::PRINTBOOL;
10571 else if (type->points_to() != NULL
10572 || type->channel_type() != NULL
10573 || type->map_type() != NULL
10574 || type->function_type() != NULL)
10575 {
10576 arg = Expression::make_cast(type, arg, location);
10577 code = Runtime::PRINTPOINTER;
10578 }
10579 else if (type->interface_type() != NULL)
10580 {
10581 if (type->interface_type()->is_empty())
10582 code = Runtime::PRINTEFACE;
10583 else
10584 code = Runtime::PRINTIFACE;
10585 }
10586 else if (type->is_slice_type())
10587 code = Runtime::PRINTSLICE;
10588 else
10589 {
10590 go_assert(saw_errors());
10591 return context->backend()->error_expression();
10592 }
10593
10594 Expression* call = Runtime::make_call(code, location, 1, arg);
10595 print_stmts = Expression::make_compound(print_stmts, call,
10596 location);
10597 }
10598 }
10599
10600 if (is_ln)
10601 {
10602 Expression* print_nl =
10603 Runtime::make_call(Runtime::PRINTNL, location, 0);
10604 print_stmts = Expression::make_compound(print_stmts, print_nl,
10605 location);
10606 }
10607
10608 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
10609 location, 0);
10610 print_stmts = Expression::make_compound(print_stmts, unlock, location);
10611
10612 return print_stmts->get_backend(context);
10613 }
10614
10615 case BUILTIN_PANIC:
10616 {
10617 const Expression_list* args = this->args();
10618 go_assert(args != NULL && args->size() == 1);
10619 Expression* arg = args->front();
10620 Type *empty =
10621 Type::make_empty_interface_type(Linemap::predeclared_location());
10622 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
10623
10624 Expression* panic =
10625 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
10626 return panic->get_backend(context);
10627 }
10628
10629 case BUILTIN_RECOVER:
10630 {
10631 // The argument is set when building recover thunks. It's a
10632 // boolean value which is true if we can recover a value now.
10633 const Expression_list* args = this->args();
10634 go_assert(args != NULL && args->size() == 1);
10635 Expression* arg = args->front();
10636 Type *empty =
10637 Type::make_empty_interface_type(Linemap::predeclared_location());
10638
10639 Expression* nil = Expression::make_nil(location);
10640 nil = Expression::make_interface_value(empty, nil, nil, location);
10641
10642 // We need to handle a deferred call to recover specially,
10643 // because it changes whether it can recover a panic or not.
10644 // See test7 in test/recover1.go.
10645 Expression* recover = Runtime::make_call((this->is_deferred()
10646 ? Runtime::DEFERREDRECOVER
10647 : Runtime::GORECOVER),
10648 location, 0);
10649 Expression* cond =
10650 Expression::make_conditional(arg, recover, nil, location);
10651 return cond->get_backend(context);
10652 }
10653
10654 case BUILTIN_CLOSE:
10655 {
10656 const Expression_list* args = this->args();
10657 go_assert(args != NULL && args->size() == 1);
10658 Expression* arg = args->front();
10659 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
10660 1, arg);
10661 return close->get_backend(context);
10662 }
10663
10664 case BUILTIN_SIZEOF:
10665 case BUILTIN_OFFSETOF:
10666 case BUILTIN_ALIGNOF:
10667 {
10668 Numeric_constant nc;
10669 unsigned long val;
10670 if (!this->numeric_constant_value(&nc)
10671 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
10672 {
10673 go_assert(saw_errors());
10674 return context->backend()->error_expression();
10675 }
10676 Type* uintptr_type = Type::lookup_integer_type("uintptr");
10677 mpz_t ival;
10678 nc.get_int(&ival);
10679 Expression* int_cst =
10680 Expression::make_integer_z(&ival, uintptr_type, location);
10681 mpz_clear(ival);
10682 return int_cst->get_backend(context);
10683 }
10684
10685 case BUILTIN_COPY:
10686 // Handled in Builtin_call_expression::do_flatten.
10687 go_unreachable();
10688
10689 case BUILTIN_APPEND:
10690 // Handled in Builtin_call_expression::flatten_append.
10691 go_unreachable();
10692
10693 case BUILTIN_REAL:
10694 case BUILTIN_IMAG:
10695 {
10696 const Expression_list* args = this->args();
10697 go_assert(args != NULL && args->size() == 1);
10698
10699 Bexpression* ret;
10700 Bexpression* bcomplex = args->front()->get_backend(context);
10701 if (this->code_ == BUILTIN_REAL)
10702 ret = gogo->backend()->real_part_expression(bcomplex, location);
10703 else
10704 ret = gogo->backend()->imag_part_expression(bcomplex, location);
10705 return ret;
10706 }
10707
10708 case BUILTIN_COMPLEX:
10709 {
10710 const Expression_list* args = this->args();
10711 go_assert(args != NULL && args->size() == 2);
10712 Bexpression* breal = args->front()->get_backend(context);
10713 Bexpression* bimag = args->back()->get_backend(context);
10714 return gogo->backend()->complex_expression(breal, bimag, location);
10715 }
10716
10717 default:
10718 go_unreachable();
10719 }
10720 }
10721
10722 // We have to support exporting a builtin call expression, because
10723 // code can set a constant to the result of a builtin expression.
10724
10725 void
do_export(Export_function_body * efb) const10726 Builtin_call_expression::do_export(Export_function_body* efb) const
10727 {
10728 Numeric_constant nc;
10729 if (this->numeric_constant_value(&nc))
10730 {
10731 if (nc.is_int())
10732 {
10733 mpz_t val;
10734 nc.get_int(&val);
10735 Integer_expression::export_integer(efb, val);
10736 mpz_clear(val);
10737 }
10738 else if (nc.is_float())
10739 {
10740 mpfr_t fval;
10741 nc.get_float(&fval);
10742 Float_expression::export_float(efb, fval);
10743 mpfr_clear(fval);
10744 }
10745 else if (nc.is_complex())
10746 {
10747 mpc_t cval;
10748 nc.get_complex(&cval);
10749 Complex_expression::export_complex(efb, cval);
10750 mpc_clear(cval);
10751 }
10752 else
10753 go_unreachable();
10754
10755 // A trailing space lets us reliably identify the end of the number.
10756 efb->write_c_string(" ");
10757 }
10758 else
10759 {
10760 const char *s = NULL;
10761 switch (this->code_)
10762 {
10763 default:
10764 go_unreachable();
10765 case BUILTIN_APPEND:
10766 s = "append";
10767 break;
10768 case BUILTIN_COPY:
10769 s = "copy";
10770 break;
10771 case BUILTIN_LEN:
10772 s = "len";
10773 break;
10774 case BUILTIN_CAP:
10775 s = "cap";
10776 break;
10777 case BUILTIN_DELETE:
10778 s = "delete";
10779 break;
10780 case BUILTIN_PRINT:
10781 s = "print";
10782 break;
10783 case BUILTIN_PRINTLN:
10784 s = "println";
10785 break;
10786 case BUILTIN_PANIC:
10787 s = "panic";
10788 break;
10789 case BUILTIN_RECOVER:
10790 s = "recover";
10791 break;
10792 case BUILTIN_CLOSE:
10793 s = "close";
10794 break;
10795 case BUILTIN_REAL:
10796 s = "real";
10797 break;
10798 case BUILTIN_IMAG:
10799 s = "imag";
10800 break;
10801 case BUILTIN_COMPLEX:
10802 s = "complex";
10803 break;
10804 }
10805 efb->write_c_string(s);
10806 this->export_arguments(efb);
10807 }
10808 }
10809
10810 // Class Call_expression.
10811
10812 // A Go function can be viewed in a couple of different ways. The
10813 // code of a Go function becomes a backend function with parameters
10814 // whose types are simply the backend representation of the Go types.
10815 // If there are multiple results, they are returned as a backend
10816 // struct.
10817
10818 // However, when Go code refers to a function other than simply
10819 // calling it, the backend type of that function is actually a struct.
10820 // The first field of the struct points to the Go function code
10821 // (sometimes a wrapper as described below). The remaining fields
10822 // hold addresses of closed-over variables. This struct is called a
10823 // closure.
10824
10825 // There are a few cases to consider.
10826
10827 // A direct function call of a known function in package scope. In
10828 // this case there are no closed-over variables, and we know the name
10829 // of the function code. We can simply produce a backend call to the
10830 // function directly, and not worry about the closure.
10831
10832 // A direct function call of a known function literal. In this case
10833 // we know the function code and we know the closure. We generate the
10834 // function code such that it expects an additional final argument of
10835 // the closure type. We pass the closure as the last argument, after
10836 // the other arguments.
10837
10838 // An indirect function call. In this case we have a closure. We
10839 // load the pointer to the function code from the first field of the
10840 // closure. We pass the address of the closure as the last argument.
10841
10842 // A call to a method of an interface. Type methods are always at
10843 // package scope, so we call the function directly, and don't worry
10844 // about the closure.
10845
10846 // This means that for a function at package scope we have two cases.
10847 // One is the direct call, which has no closure. The other is the
10848 // indirect call, which does have a closure. We can't simply ignore
10849 // the closure, even though it is the last argument, because that will
10850 // fail on targets where the function pops its arguments. So when
10851 // generating a closure for a package-scope function we set the
10852 // function code pointer in the closure to point to a wrapper
10853 // function. This wrapper function accepts a final argument that
10854 // points to the closure, ignores it, and calls the real function as a
10855 // direct function call. This wrapper will normally be efficient, and
10856 // can often simply be a tail call to the real function.
10857
10858 // We don't use GCC's static chain pointer because 1) we don't need
10859 // it; 2) GCC only permits using a static chain to call a known
10860 // function, so we can't use it for an indirect call anyhow. Since we
10861 // can't use it for an indirect call, we may as well not worry about
10862 // using it for a direct call either.
10863
10864 // We pass the closure last rather than first because it means that
10865 // the function wrapper we put into a closure for a package-scope
10866 // function can normally just be a tail call to the real function.
10867
10868 // For method expressions we generate a wrapper that loads the
10869 // receiver from the closure and then calls the method. This
10870 // unfortunately forces reshuffling the arguments, since there is a
10871 // new first argument, but we can't avoid reshuffling either for
10872 // method expressions or for indirect calls of package-scope
10873 // functions, and since the latter are more common we reshuffle for
10874 // method expressions.
10875
10876 // Note that the Go code retains the Go types. The extra final
10877 // argument only appears when we convert to the backend
10878 // representation.
10879
10880 // Traversal.
10881
10882 int
do_traverse(Traverse * traverse)10883 Call_expression::do_traverse(Traverse* traverse)
10884 {
10885 // If we are calling a function in a different package that returns
10886 // an unnamed type, this may be the only chance we get to traverse
10887 // that type. We don't traverse this->type_ because it may be a
10888 // Call_multiple_result_type that will just lead back here.
10889 if (this->type_ != NULL && !this->type_->is_error_type())
10890 {
10891 Function_type *fntype = this->get_function_type();
10892 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
10893 return TRAVERSE_EXIT;
10894 }
10895 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
10896 return TRAVERSE_EXIT;
10897 if (this->args_ != NULL)
10898 {
10899 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
10900 return TRAVERSE_EXIT;
10901 }
10902 return TRAVERSE_CONTINUE;
10903 }
10904
10905 // Lower a call statement.
10906
10907 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)10908 Call_expression::do_lower(Gogo* gogo, Named_object* function,
10909 Statement_inserter* inserter, int)
10910 {
10911 Location loc = this->location();
10912
10913 // A type cast can look like a function call.
10914 if (this->fn_->is_type_expression()
10915 && this->args_ != NULL
10916 && this->args_->size() == 1)
10917 return Expression::make_cast(this->fn_->type(), this->args_->front(),
10918 loc);
10919
10920 // Because do_type will return an error type and thus prevent future
10921 // errors, check for that case now to ensure that the error gets
10922 // reported.
10923 Function_type* fntype = this->get_function_type();
10924 if (fntype == NULL)
10925 {
10926 if (!this->fn_->type()->is_error())
10927 this->report_error(_("expected function"));
10928 this->set_is_error();
10929 return this;
10930 }
10931
10932 // Handle an argument which is a call to a function which returns
10933 // multiple results.
10934 if (this->args_ != NULL
10935 && this->args_->size() == 1
10936 && this->args_->front()->call_expression() != NULL)
10937 {
10938 size_t rc = this->args_->front()->call_expression()->result_count();
10939 if (rc > 1
10940 && ((fntype->parameters() != NULL
10941 && (fntype->parameters()->size() == rc
10942 || (fntype->is_varargs()
10943 && fntype->parameters()->size() - 1 <= rc)))
10944 || fntype->is_builtin()))
10945 {
10946 Call_expression* call = this->args_->front()->call_expression();
10947 call->set_is_multi_value_arg();
10948 if (this->is_varargs_)
10949 {
10950 // It is not clear which result of a multiple result call
10951 // the ellipsis operator should be applied to. If we unpack the
10952 // the call into its individual results here, the ellipsis will be
10953 // applied to the last result.
10954 go_error_at(call->location(),
10955 _("multiple-value argument in single-value context"));
10956 return Expression::make_error(call->location());
10957 }
10958
10959 Expression_list* args = new Expression_list;
10960 for (size_t i = 0; i < rc; ++i)
10961 args->push_back(Expression::make_call_result(call, i));
10962 // We can't return a new call expression here, because this
10963 // one may be referenced by Call_result expressions. We
10964 // also can't delete the old arguments, because we may still
10965 // traverse them somewhere up the call stack. FIXME.
10966 this->args_ = args;
10967 }
10968 }
10969
10970 // Recognize a call to a builtin function.
10971 if (fntype->is_builtin())
10972 {
10973 Builtin_call_expression* bce =
10974 new Builtin_call_expression(gogo, this->fn_, this->args_,
10975 this->is_varargs_, loc);
10976 if (this->is_deferred_)
10977 bce->set_is_deferred();
10978 if (this->is_concurrent_)
10979 bce->set_is_concurrent();
10980 return bce;
10981 }
10982
10983 // If this call returns multiple results, create a temporary
10984 // variable to hold them.
10985 if (this->result_count() > 1 && this->call_temp_ == NULL)
10986 {
10987 Struct_field_list* sfl = new Struct_field_list();
10988 const Typed_identifier_list* results = fntype->results();
10989
10990 int i = 0;
10991 char buf[20];
10992 for (Typed_identifier_list::const_iterator p = results->begin();
10993 p != results->end();
10994 ++p, ++i)
10995 {
10996 snprintf(buf, sizeof buf, "res%d", i);
10997 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
10998 }
10999
11000 Struct_type* st = Type::make_struct_type(sfl, loc);
11001 st->set_is_struct_incomparable();
11002 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
11003 inserter->insert(this->call_temp_);
11004 }
11005
11006 // Handle a call to a varargs function by packaging up the extra
11007 // parameters.
11008 if (fntype->is_varargs())
11009 {
11010 const Typed_identifier_list* parameters = fntype->parameters();
11011 go_assert(parameters != NULL && !parameters->empty());
11012 Type* varargs_type = parameters->back().type();
11013 this->lower_varargs(gogo, function, inserter, varargs_type,
11014 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
11015 }
11016
11017 // If this is call to a method, call the method directly passing the
11018 // object as the first parameter.
11019 Bound_method_expression* bme = this->fn_->bound_method_expression();
11020 if (bme != NULL && !this->is_deferred_ && !this->is_concurrent_)
11021 {
11022 Named_object* methodfn = bme->function();
11023 Function_type* mft = (methodfn->is_function()
11024 ? methodfn->func_value()->type()
11025 : methodfn->func_declaration_value()->type());
11026 Expression* first_arg = bme->first_argument();
11027
11028 // We always pass a pointer when calling a method, except for
11029 // direct interface types when calling a value method.
11030 if (!first_arg->type()->is_error()
11031 && !first_arg->type()->is_direct_iface_type())
11032 {
11033 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
11034 // We may need to create a temporary variable so that we can
11035 // take the address. We can't do that here because it will
11036 // mess up the order of evaluation.
11037 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
11038 ue->set_create_temp();
11039 }
11040 else if (mft->receiver()->type()->points_to() == NULL
11041 && first_arg->type()->points_to() != NULL
11042 && first_arg->type()->points_to()->is_direct_iface_type())
11043 first_arg = Expression::make_dereference(first_arg,
11044 Expression::NIL_CHECK_DEFAULT,
11045 loc);
11046
11047 // If we are calling a method which was inherited from an
11048 // embedded struct, and the method did not get a stub, then the
11049 // first type may be wrong.
11050 Type* fatype = bme->first_argument_type();
11051 if (fatype != NULL)
11052 {
11053 if (fatype->points_to() == NULL)
11054 fatype = Type::make_pointer_type(fatype);
11055 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
11056 }
11057
11058 Expression_list* new_args = new Expression_list();
11059 new_args->push_back(first_arg);
11060 if (this->args_ != NULL)
11061 {
11062 for (Expression_list::const_iterator p = this->args_->begin();
11063 p != this->args_->end();
11064 ++p)
11065 new_args->push_back(*p);
11066 }
11067
11068 // We have to change in place because this structure may be
11069 // referenced by Call_result_expressions. We can't delete the
11070 // old arguments, because we may be traversing them up in some
11071 // caller. FIXME.
11072 this->args_ = new_args;
11073 this->fn_ = Expression::make_func_reference(methodfn, NULL,
11074 bme->location());
11075 }
11076
11077 // If this is a call to an imported function for which we have an
11078 // inlinable function body, add it to the list of functions to give
11079 // to the backend as inlining opportunities.
11080 Func_expression* fe = this->fn_->func_expression();
11081 if (fe != NULL
11082 && fe->named_object()->is_function_declaration()
11083 && fe->named_object()->func_declaration_value()->has_imported_body())
11084 gogo->add_imported_inlinable_function(fe->named_object());
11085
11086 return this;
11087 }
11088
11089 // Lower a call to a varargs function. FUNCTION is the function in
11090 // which the call occurs--it's not the function we are calling.
11091 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
11092 // PARAM_COUNT is the number of parameters of the function we are
11093 // calling; the last of these parameters will be the varargs
11094 // parameter.
11095
11096 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count,Slice_storage_escape_disp escape_disp)11097 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
11098 Statement_inserter* inserter,
11099 Type* varargs_type, size_t param_count,
11100 Slice_storage_escape_disp escape_disp)
11101 {
11102 if (this->varargs_are_lowered_)
11103 return;
11104
11105 Location loc = this->location();
11106
11107 go_assert(param_count > 0);
11108 go_assert(varargs_type->is_slice_type());
11109
11110 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
11111 if (arg_count < param_count - 1)
11112 {
11113 // Not enough arguments; will be caught in check_types.
11114 return;
11115 }
11116
11117 Expression_list* old_args = this->args_;
11118 Expression_list* new_args = new Expression_list();
11119 bool push_empty_arg = false;
11120 if (old_args == NULL || old_args->empty())
11121 {
11122 go_assert(param_count == 1);
11123 push_empty_arg = true;
11124 }
11125 else
11126 {
11127 Expression_list::const_iterator pa;
11128 int i = 1;
11129 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
11130 {
11131 if (static_cast<size_t>(i) == param_count)
11132 break;
11133 new_args->push_back(*pa);
11134 }
11135
11136 // We have reached the varargs parameter.
11137
11138 bool issued_error = false;
11139 if (pa == old_args->end())
11140 push_empty_arg = true;
11141 else if (pa + 1 == old_args->end() && this->is_varargs_)
11142 new_args->push_back(*pa);
11143 else if (this->is_varargs_)
11144 {
11145 if ((*pa)->type()->is_slice_type())
11146 this->report_error(_("too many arguments"));
11147 else
11148 {
11149 go_error_at(this->location(),
11150 _("invalid use of %<...%> with non-slice"));
11151 this->set_is_error();
11152 }
11153 return;
11154 }
11155 else
11156 {
11157 Type* element_type = varargs_type->array_type()->element_type();
11158 Expression_list* vals = new Expression_list;
11159 for (; pa != old_args->end(); ++pa, ++i)
11160 {
11161 // Check types here so that we get a better message.
11162 Type* patype = (*pa)->type();
11163 Location paloc = (*pa)->location();
11164 if (!this->check_argument_type(i, element_type, patype,
11165 paloc, issued_error))
11166 continue;
11167 vals->push_back(*pa);
11168 }
11169 Slice_construction_expression* sce =
11170 Expression::make_slice_composite_literal(varargs_type, vals, loc);
11171 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
11172 sce->set_storage_does_not_escape();
11173 Expression* val = sce;
11174 gogo->lower_expression(function, inserter, &val);
11175 new_args->push_back(val);
11176 }
11177 }
11178
11179 if (push_empty_arg)
11180 new_args->push_back(Expression::make_nil(loc));
11181
11182 // We can't return a new call expression here, because this one may
11183 // be referenced by Call_result expressions. FIXME. We can't
11184 // delete OLD_ARGS because we may have both a Call_expression and a
11185 // Builtin_call_expression which refer to them. FIXME.
11186 this->args_ = new_args;
11187 this->varargs_are_lowered_ = true;
11188 }
11189
11190 // Flatten a call with multiple results into a temporary.
11191
11192 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)11193 Call_expression::do_flatten(Gogo* gogo, Named_object*,
11194 Statement_inserter* inserter)
11195 {
11196 if (this->is_erroneous_call())
11197 {
11198 go_assert(saw_errors());
11199 return Expression::make_error(this->location());
11200 }
11201
11202 if (this->is_flattened_)
11203 return this;
11204 this->is_flattened_ = true;
11205
11206 // Add temporary variables for all arguments that require type
11207 // conversion.
11208 Function_type* fntype = this->get_function_type();
11209 if (fntype == NULL)
11210 {
11211 go_assert(saw_errors());
11212 return this;
11213 }
11214 if (this->args_ != NULL && !this->args_->empty()
11215 && fntype->parameters() != NULL && !fntype->parameters()->empty())
11216 {
11217 bool is_interface_method =
11218 this->fn_->interface_field_reference_expression() != NULL;
11219
11220 Expression_list *args = new Expression_list();
11221 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11222 Expression_list::const_iterator pa = this->args_->begin();
11223 if (!is_interface_method && fntype->is_method())
11224 {
11225 // The receiver argument.
11226 args->push_back(*pa);
11227 ++pa;
11228 }
11229 for (; pa != this->args_->end(); ++pa, ++pp)
11230 {
11231 go_assert(pp != fntype->parameters()->end());
11232 if (Type::are_identical(pp->type(), (*pa)->type(),
11233 Type::COMPARE_TAGS, NULL))
11234 args->push_back(*pa);
11235 else
11236 {
11237 Location loc = (*pa)->location();
11238 Expression* arg = *pa;
11239 if (!arg->is_multi_eval_safe())
11240 {
11241 Temporary_statement *temp =
11242 Statement::make_temporary(NULL, arg, loc);
11243 inserter->insert(temp);
11244 arg = Expression::make_temporary_reference(temp, loc);
11245 }
11246 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
11247 loc);
11248 args->push_back(arg);
11249 }
11250 }
11251 delete this->args_;
11252 this->args_ = args;
11253 }
11254
11255 // Lower to compiler intrinsic if possible.
11256 Func_expression* fe = this->fn_->func_expression();
11257 if (!this->is_concurrent_ && !this->is_deferred_
11258 && fe != NULL
11259 && (fe->named_object()->is_function_declaration()
11260 || fe->named_object()->is_function()))
11261 {
11262 Expression* ret = this->intrinsify(gogo, inserter);
11263 if (ret != NULL)
11264 return ret;
11265 }
11266
11267 // Add an implicit conversion to a boolean type, if needed. See the
11268 // comment in Binary_expression::lower_array_comparison.
11269 if (this->is_equal_function_
11270 && this->type_ != NULL
11271 && this->type_ != Type::lookup_bool_type())
11272 return Expression::make_cast(this->type_, this, this->location());
11273
11274 return this;
11275 }
11276
11277 // Lower a call to a compiler intrinsic if possible.
11278 // Returns NULL if it is not an intrinsic.
11279
11280 Expression*
intrinsify(Gogo * gogo,Statement_inserter * inserter)11281 Call_expression::intrinsify(Gogo* gogo,
11282 Statement_inserter* inserter)
11283 {
11284 Func_expression* fe = this->fn_->func_expression();
11285 Named_object* no = fe->named_object();
11286 std::string name = Gogo::unpack_hidden_name(no->name());
11287 std::string package = (no->package() != NULL
11288 ? no->package()->pkgpath()
11289 : gogo->pkgpath());
11290 Location loc = this->location();
11291
11292 Type* int_type = Type::lookup_integer_type("int");
11293 Type* int32_type = Type::lookup_integer_type("int32");
11294 Type* int64_type = Type::lookup_integer_type("int64");
11295 Type* uint_type = Type::lookup_integer_type("uint");
11296 Type* uint32_type = Type::lookup_integer_type("uint32");
11297 Type* uint64_type = Type::lookup_integer_type("uint64");
11298 Type* uintptr_type = Type::lookup_integer_type("uintptr");
11299 Type* pointer_type = Type::make_pointer_type(Type::make_void_type());
11300
11301 int int_size = int_type->named_type()->real_type()->integer_type()->bits() / 8;
11302 int ptr_size = uintptr_type->named_type()->real_type()->integer_type()->bits() / 8;
11303
11304 if (package == "sync/atomic")
11305 {
11306 // sync/atomic functions and runtime/internal/atomic functions
11307 // are very similar. In order not to duplicate code, we just
11308 // redirect to the latter and let the code below to handle them.
11309 // In case there is no equivalent functions (slight variance
11310 // in types), we just make an artificial name (begin with '$').
11311 // Note: no StorePointer, SwapPointer, and CompareAndSwapPointer,
11312 // as they need write barriers.
11313 if (name == "LoadInt32")
11314 name = "$Loadint32";
11315 else if (name == "LoadInt64")
11316 name = "Loadint64";
11317 else if (name == "LoadUint32")
11318 name = "Load";
11319 else if (name == "LoadUint64")
11320 name = "Load64";
11321 else if (name == "LoadUintptr")
11322 name = "Loaduintptr";
11323 else if (name == "LoadPointer")
11324 name = "Loadp";
11325 else if (name == "StoreInt32")
11326 name = "$Storeint32";
11327 else if (name == "StoreInt64")
11328 name = "$Storeint64";
11329 else if (name == "StoreUint32")
11330 name = "Store";
11331 else if (name == "StoreUint64")
11332 name = "Store64";
11333 else if (name == "StoreUintptr")
11334 name = "Storeuintptr";
11335 else if (name == "AddInt32")
11336 name = "$Xaddint32";
11337 else if (name == "AddInt64")
11338 name = "Xaddint64";
11339 else if (name == "AddUint32")
11340 name = "Xadd";
11341 else if (name == "AddUint64")
11342 name = "Xadd64";
11343 else if (name == "AddUintptr")
11344 name = "Xadduintptr";
11345 else if (name == "SwapInt32")
11346 name = "$Xchgint32";
11347 else if (name == "SwapInt64")
11348 name = "$Xchgint64";
11349 else if (name == "SwapUint32")
11350 name = "Xchg";
11351 else if (name == "SwapUint64")
11352 name = "Xchg64";
11353 else if (name == "SwapUintptr")
11354 name = "Xchguintptr";
11355 else if (name == "CompareAndSwapInt32")
11356 name = "$Casint32";
11357 else if (name == "CompareAndSwapInt64")
11358 name = "$Casint64";
11359 else if (name == "CompareAndSwapUint32")
11360 name = "Cas";
11361 else if (name == "CompareAndSwapUint64")
11362 name = "Cas64";
11363 else if (name == "CompareAndSwapUintptr")
11364 name = "Casuintptr";
11365 else
11366 return NULL;
11367
11368 package = "runtime/internal/atomic";
11369 }
11370
11371 if (package == "runtime/internal/sys")
11372 {
11373 // runtime/internal/sys functions and math/bits functions
11374 // are very similar. In order not to duplicate code, we just
11375 // redirect to the latter and let the code below to handle them.
11376 if (name == "Bswap32")
11377 name = "ReverseBytes32";
11378 else if (name == "Bswap64")
11379 name = "ReverseBytes64";
11380 else if (name == "Ctz32")
11381 name = "TrailingZeros32";
11382 else if (name == "Ctz64")
11383 name = "TrailingZeros64";
11384 else
11385 return NULL;
11386
11387 package = "math/bits";
11388 }
11389
11390 if (package == "runtime")
11391 {
11392 // Handle a couple of special runtime functions. In the runtime
11393 // package, getcallerpc returns the PC of the caller, and
11394 // getcallersp returns the frame pointer of the caller. Implement
11395 // these by turning them into calls to GCC builtin functions. We
11396 // could implement them in normal code, but then we would have to
11397 // explicitly unwind the stack. These functions are intended to be
11398 // efficient. Note that this technique obviously only works for
11399 // direct calls, but that is the only way they are used.
11400 if (name == "getcallerpc"
11401 && (this->args_ == NULL || this->args_->size() == 0))
11402 {
11403 Expression* arg = Expression::make_integer_ul(0, uint32_type, loc);
11404 Expression* call =
11405 Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS, loc,
11406 1, arg);
11407 // The builtin functions return void*, but the Go functions return uintptr.
11408 return Expression::make_cast(uintptr_type, call, loc);
11409 }
11410 else if (name == "getcallersp"
11411 && (this->args_ == NULL || this->args_->size() == 0))
11412
11413 {
11414 Expression* call =
11415 Runtime::make_call(Runtime::BUILTIN_DWARF_CFA, loc, 0);
11416 // The builtin functions return void*, but the Go functions return uintptr.
11417 return Expression::make_cast(uintptr_type, call, loc);
11418 }
11419 }
11420 else if (package == "math/bits")
11421 {
11422 if ((name == "ReverseBytes16" || name == "ReverseBytes32"
11423 || name == "ReverseBytes64" || name == "ReverseBytes")
11424 && this->args_ != NULL && this->args_->size() == 1)
11425 {
11426 Runtime::Function code;
11427 if (name == "ReverseBytes16")
11428 code = Runtime::BUILTIN_BSWAP16;
11429 else if (name == "ReverseBytes32")
11430 code = Runtime::BUILTIN_BSWAP32;
11431 else if (name == "ReverseBytes64")
11432 code = Runtime::BUILTIN_BSWAP64;
11433 else if (name == "ReverseBytes")
11434 code = (int_size == 8 ? Runtime::BUILTIN_BSWAP64 : Runtime::BUILTIN_BSWAP32);
11435 else
11436 go_unreachable();
11437 Expression* arg = this->args_->front();
11438 Expression* call = Runtime::make_call(code, loc, 1, arg);
11439 if (name == "ReverseBytes")
11440 return Expression::make_cast(uint_type, call, loc);
11441 return call;
11442 }
11443 else if ((name == "TrailingZeros8" || name == "TrailingZeros16")
11444 && this->args_ != NULL && this->args_->size() == 1)
11445 {
11446 // GCC does not have a ctz8 or ctz16 intrinsic. We do
11447 // ctz32(0x100 | arg) or ctz32(0x10000 | arg).
11448 Expression* arg = this->args_->front();
11449 arg = Expression::make_cast(uint32_type, arg, loc);
11450 unsigned long mask = (name == "TrailingZeros8" ? 0x100 : 0x10000);
11451 Expression* c = Expression::make_integer_ul(mask, uint32_type, loc);
11452 arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11453 Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg);
11454 return Expression::make_cast(int_type, call, loc);
11455 }
11456 else if ((name == "TrailingZeros32"
11457 || (name == "TrailingZeros" && int_size == 4))
11458 && this->args_ != NULL && this->args_->size() == 1)
11459 {
11460 Expression* arg = this->args_->front();
11461 if (!arg->is_multi_eval_safe())
11462 {
11463 Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11464 inserter->insert(ts);
11465 arg = Expression::make_temporary_reference(ts, loc);
11466 }
11467 // arg == 0 ? 32 : __builtin_ctz(arg)
11468 Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11469 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11470 Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11471 Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZ, loc, 1, arg->copy());
11472 call = Expression::make_cast(int_type, call, loc);
11473 return Expression::make_conditional(cmp, c32, call, loc);
11474 }
11475 else if ((name == "TrailingZeros64"
11476 || (name == "TrailingZeros" && int_size == 8))
11477 && this->args_ != NULL && this->args_->size() == 1)
11478 {
11479 Expression* arg = this->args_->front();
11480 if (!arg->is_multi_eval_safe())
11481 {
11482 Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11483 inserter->insert(ts);
11484 arg = Expression::make_temporary_reference(ts, loc);
11485 }
11486 // arg == 0 ? 64 : __builtin_ctzll(arg)
11487 Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11488 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11489 Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11490 Expression* call = Runtime::make_call(Runtime::BUILTIN_CTZLL, loc, 1, arg->copy());
11491 call = Expression::make_cast(int_type, call, loc);
11492 return Expression::make_conditional(cmp, c64, call, loc);
11493 }
11494 else if ((name == "LeadingZeros8" || name == "LeadingZeros16"
11495 || name == "Len8" || name == "Len16")
11496 && this->args_ != NULL && this->args_->size() == 1)
11497 {
11498 // GCC does not have a clz8 ir clz16 intrinsic. We do
11499 // clz32(arg<<24 | 0xffffff) or clz32(arg<<16 | 0xffff).
11500 Expression* arg = this->args_->front();
11501 arg = Expression::make_cast(uint32_type, arg, loc);
11502 unsigned long shift =
11503 ((name == "LeadingZeros8" || name == "Len8") ? 24 : 16);
11504 Expression* c = Expression::make_integer_ul(shift, uint32_type, loc);
11505 arg = Expression::make_binary(OPERATOR_LSHIFT, arg, c, loc);
11506 unsigned long mask =
11507 ((name == "LeadingZeros8" || name == "Len8") ? 0xffffff : 0xffff);
11508 c = Expression::make_integer_ul(mask, uint32_type, loc);
11509 arg = Expression::make_binary(OPERATOR_OR, arg, c, loc);
11510 Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg);
11511 call = Expression::make_cast(int_type, call, loc);
11512 // len = width - clz
11513 if (name == "Len8")
11514 {
11515 c = Expression::make_integer_ul(8, int_type, loc);
11516 return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11517 }
11518 else if (name == "Len16")
11519 {
11520 c = Expression::make_integer_ul(16, int_type, loc);
11521 return Expression::make_binary(OPERATOR_MINUS, c, call, loc);
11522 }
11523 return call;
11524 }
11525 else if ((name == "LeadingZeros32" || name == "Len32"
11526 || ((name == "LeadingZeros" || name == "Len") && int_size == 4))
11527 && this->args_ != NULL && this->args_->size() == 1)
11528 {
11529 Expression* arg = this->args_->front();
11530 if (!arg->is_multi_eval_safe())
11531 {
11532 Temporary_statement* ts = Statement::make_temporary(uint32_type, arg, loc);
11533 inserter->insert(ts);
11534 arg = Expression::make_temporary_reference(ts, loc);
11535 }
11536 // arg == 0 ? 32 : __builtin_clz(arg)
11537 Expression* zero = Expression::make_integer_ul(0, uint32_type, loc);
11538 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11539 Expression* c32 = Expression::make_integer_ul(32, int_type, loc);
11540 Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZ, loc, 1, arg->copy());
11541 call = Expression::make_cast(int_type, call, loc);
11542 Expression* cond = Expression::make_conditional(cmp, c32, call, loc);
11543 // len = 32 - clz
11544 if (name == "Len32" || name == "Len")
11545 return Expression::make_binary(OPERATOR_MINUS, c32->copy(), cond, loc);
11546 return cond;
11547 }
11548 else if ((name == "LeadingZeros64" || name == "Len64"
11549 || ((name == "LeadingZeros" || name == "Len") && int_size == 8))
11550 && this->args_ != NULL && this->args_->size() == 1)
11551 {
11552 Expression* arg = this->args_->front();
11553 if (!arg->is_multi_eval_safe())
11554 {
11555 Temporary_statement* ts = Statement::make_temporary(uint64_type, arg, loc);
11556 inserter->insert(ts);
11557 arg = Expression::make_temporary_reference(ts, loc);
11558 }
11559 // arg == 0 ? 64 : __builtin_clzll(arg)
11560 Expression* zero = Expression::make_integer_ul(0, uint64_type, loc);
11561 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ, arg, zero, loc);
11562 Expression* c64 = Expression::make_integer_ul(64, int_type, loc);
11563 Expression* call = Runtime::make_call(Runtime::BUILTIN_CLZLL, loc, 1, arg->copy());
11564 call = Expression::make_cast(int_type, call, loc);
11565 Expression* cond = Expression::make_conditional(cmp, c64, call, loc);
11566 // len = 64 - clz
11567 if (name == "Len64" || name == "Len")
11568 return Expression::make_binary(OPERATOR_MINUS, c64->copy(), cond, loc);
11569 return cond;
11570 }
11571 else if ((name == "OnesCount8" || name == "OnesCount16"
11572 || name == "OnesCount32" || name == "OnesCount64"
11573 || name == "OnesCount")
11574 && this->args_ != NULL && this->args_->size() == 1)
11575 {
11576 Runtime::Function code;
11577 if (name == "OnesCount64")
11578 code = Runtime::BUILTIN_POPCOUNTLL;
11579 else if (name == "OnesCount")
11580 code = (int_size == 8 ? Runtime::BUILTIN_POPCOUNTLL : Runtime::BUILTIN_POPCOUNT);
11581 else
11582 code = Runtime::BUILTIN_POPCOUNT;
11583 Expression* arg = this->args_->front();
11584 Expression* call = Runtime::make_call(code, loc, 1, arg);
11585 return Expression::make_cast(int_type, call, loc);
11586 }
11587 }
11588 else if (package == "runtime/internal/atomic")
11589 {
11590 int memorder = __ATOMIC_SEQ_CST;
11591
11592 if ((name == "Load" || name == "Load64" || name == "Loadint64" || name == "Loadp"
11593 || name == "Loaduint" || name == "Loaduintptr" || name == "LoadAcq"
11594 || name == "$Loadint32")
11595 && this->args_ != NULL && this->args_->size() == 1)
11596 {
11597 if (int_size < 8 && (name == "Load64" || name == "Loadint64"))
11598 // On 32-bit architectures we need to check alignment.
11599 // Not intrinsify for now.
11600 return NULL;
11601
11602 Runtime::Function code;
11603 Type* res_type;
11604 if (name == "Load")
11605 {
11606 code = Runtime::ATOMIC_LOAD_4;
11607 res_type = uint32_type;
11608 }
11609 else if (name == "Load64")
11610 {
11611 code = Runtime::ATOMIC_LOAD_8;
11612 res_type = uint64_type;
11613 }
11614 else if (name == "$Loadint32")
11615 {
11616 code = Runtime::ATOMIC_LOAD_4;
11617 res_type = int32_type;
11618 }
11619 else if (name == "Loadint64")
11620 {
11621 code = Runtime::ATOMIC_LOAD_8;
11622 res_type = int64_type;
11623 }
11624 else if (name == "Loaduint")
11625 {
11626 code = (int_size == 8
11627 ? Runtime::ATOMIC_LOAD_8
11628 : Runtime::ATOMIC_LOAD_4);
11629 res_type = uint_type;
11630 }
11631 else if (name == "Loaduintptr")
11632 {
11633 code = (ptr_size == 8
11634 ? Runtime::ATOMIC_LOAD_8
11635 : Runtime::ATOMIC_LOAD_4);
11636 res_type = uintptr_type;
11637 }
11638 else if (name == "Loadp")
11639 {
11640 code = (ptr_size == 8
11641 ? Runtime::ATOMIC_LOAD_8
11642 : Runtime::ATOMIC_LOAD_4);
11643 res_type = pointer_type;
11644 }
11645 else if (name == "LoadAcq")
11646 {
11647 code = Runtime::ATOMIC_LOAD_4;
11648 res_type = uint32_type;
11649 memorder = __ATOMIC_ACQUIRE;
11650 }
11651 else
11652 go_unreachable();
11653 Expression* a1 = this->args_->front();
11654 Expression* a2 = Expression::make_integer_ul(memorder, int32_type, loc);
11655 Expression* call = Runtime::make_call(code, loc, 2, a1, a2);
11656 return Expression::make_unsafe_cast(res_type, call, loc);
11657 }
11658
11659 if ((name == "Store" || name == "Store64" || name == "StorepNoWB"
11660 || name == "Storeuintptr" || name == "StoreRel"
11661 || name == "$Storeint32" || name == "$Storeint64")
11662 && this->args_ != NULL && this->args_->size() == 2)
11663 {
11664 if (int_size < 8 && (name == "Store64" || name == "$Storeint64"))
11665 return NULL;
11666
11667 Runtime::Function code;
11668 Expression* a1 = this->args_->at(0);
11669 Expression* a2 = this->args_->at(1);
11670 if (name == "Store")
11671 code = Runtime::ATOMIC_STORE_4;
11672 else if (name == "Store64")
11673 code = Runtime::ATOMIC_STORE_8;
11674 else if (name == "$Storeint32")
11675 code = Runtime::ATOMIC_STORE_4;
11676 else if (name == "$Storeint64")
11677 code = Runtime::ATOMIC_STORE_8;
11678 else if (name == "Storeuintptr")
11679 code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11680 else if (name == "StorepNoWB")
11681 {
11682 code = (ptr_size == 8 ? Runtime::ATOMIC_STORE_8 : Runtime::ATOMIC_STORE_4);
11683 a2 = Expression::make_unsafe_cast(uintptr_type, a2, loc);
11684 a2 = Expression::make_cast(uint64_type, a2, loc);
11685 }
11686 else if (name == "StoreRel")
11687 {
11688 code = Runtime::ATOMIC_STORE_4;
11689 memorder = __ATOMIC_RELEASE;
11690 }
11691 else
11692 go_unreachable();
11693 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11694 return Runtime::make_call(code, loc, 3, a1, a2, a3);
11695 }
11696
11697 if ((name == "Xchg" || name == "Xchg64" || name == "Xchguintptr"
11698 || name == "$Xchgint32" || name == "$Xchgint64")
11699 && this->args_ != NULL && this->args_->size() == 2)
11700 {
11701 if (int_size < 8 && (name == "Xchg64" || name == "Xchgint64"))
11702 return NULL;
11703
11704 Runtime::Function code;
11705 Type* res_type;
11706 if (name == "Xchg")
11707 {
11708 code = Runtime::ATOMIC_EXCHANGE_4;
11709 res_type = uint32_type;
11710 }
11711 else if (name == "Xchg64")
11712 {
11713 code = Runtime::ATOMIC_EXCHANGE_8;
11714 res_type = uint64_type;
11715 }
11716 else if (name == "$Xchgint32")
11717 {
11718 code = Runtime::ATOMIC_EXCHANGE_4;
11719 res_type = int32_type;
11720 }
11721 else if (name == "$Xchgint64")
11722 {
11723 code = Runtime::ATOMIC_EXCHANGE_8;
11724 res_type = int64_type;
11725 }
11726 else if (name == "Xchguintptr")
11727 {
11728 code = (ptr_size == 8
11729 ? Runtime::ATOMIC_EXCHANGE_8
11730 : Runtime::ATOMIC_EXCHANGE_4);
11731 res_type = uintptr_type;
11732 }
11733 else
11734 go_unreachable();
11735 Expression* a1 = this->args_->at(0);
11736 Expression* a2 = this->args_->at(1);
11737 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11738 Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11739 return Expression::make_cast(res_type, call, loc);
11740 }
11741
11742 if ((name == "Cas" || name == "Cas64" || name == "Casuintptr"
11743 || name == "Casp1" || name == "CasRel"
11744 || name == "$Casint32" || name == "$Casint64")
11745 && this->args_ != NULL && this->args_->size() == 3)
11746 {
11747 if (int_size < 8 && (name == "Cas64" || name == "$Casint64"))
11748 return NULL;
11749
11750 Runtime::Function code;
11751 Expression* a1 = this->args_->at(0);
11752
11753 // Builtin cas takes a pointer to the old value.
11754 // Store it in a temporary and take the address.
11755 Expression* a2 = this->args_->at(1);
11756 Temporary_statement* ts = Statement::make_temporary(NULL, a2, loc);
11757 inserter->insert(ts);
11758 a2 = Expression::make_temporary_reference(ts, loc);
11759 a2 = Expression::make_unary(OPERATOR_AND, a2, loc);
11760
11761 Expression* a3 = this->args_->at(2);
11762 if (name == "Cas")
11763 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11764 else if (name == "Cas64")
11765 code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11766 else if (name == "$Casint32")
11767 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11768 else if (name == "$Casint64")
11769 code = Runtime::ATOMIC_COMPARE_EXCHANGE_8;
11770 else if (name == "Casuintptr")
11771 code = (ptr_size == 8
11772 ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11773 : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11774 else if (name == "Casp1")
11775 {
11776 code = (ptr_size == 8
11777 ? Runtime::ATOMIC_COMPARE_EXCHANGE_8
11778 : Runtime::ATOMIC_COMPARE_EXCHANGE_4);
11779 a3 = Expression::make_unsafe_cast(uintptr_type, a3, loc);
11780 a3 = Expression::make_cast(uint64_type, a3, loc);
11781 }
11782 else if (name == "CasRel")
11783 {
11784 code = Runtime::ATOMIC_COMPARE_EXCHANGE_4;
11785 memorder = __ATOMIC_RELEASE;
11786 }
11787 else
11788 go_unreachable();
11789 Expression* a4 = Expression::make_boolean(false, loc);
11790 Expression* a5 = Expression::make_integer_ul(memorder, int32_type, loc);
11791 Expression* a6 = Expression::make_integer_ul(__ATOMIC_RELAXED, int32_type, loc);
11792 return Runtime::make_call(code, loc, 6, a1, a2, a3, a4, a5, a6);
11793 }
11794
11795 if ((name == "Xadd" || name == "Xadd64" || name == "Xaddint64"
11796 || name == "Xadduintptr" || name == "$Xaddint32")
11797 && this->args_ != NULL && this->args_->size() == 2)
11798 {
11799 if (int_size < 8 && (name == "Xadd64" || name == "Xaddint64"))
11800 return NULL;
11801
11802 Runtime::Function code;
11803 Type* res_type;
11804 if (name == "Xadd")
11805 {
11806 code = Runtime::ATOMIC_ADD_FETCH_4;
11807 res_type = uint32_type;
11808 }
11809 else if (name == "Xadd64")
11810 {
11811 code = Runtime::ATOMIC_ADD_FETCH_8;
11812 res_type = uint64_type;
11813 }
11814 else if (name == "$Xaddint32")
11815 {
11816 code = Runtime::ATOMIC_ADD_FETCH_4;
11817 res_type = int32_type;
11818 }
11819 else if (name == "Xaddint64")
11820 {
11821 code = Runtime::ATOMIC_ADD_FETCH_8;
11822 res_type = int64_type;
11823 }
11824 else if (name == "Xadduintptr")
11825 {
11826 code = (ptr_size == 8
11827 ? Runtime::ATOMIC_ADD_FETCH_8
11828 : Runtime::ATOMIC_ADD_FETCH_4);
11829 res_type = uintptr_type;
11830 }
11831 else
11832 go_unreachable();
11833 Expression* a1 = this->args_->at(0);
11834 Expression* a2 = this->args_->at(1);
11835 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11836 Expression* call = Runtime::make_call(code, loc, 3, a1, a2, a3);
11837 return Expression::make_cast(res_type, call, loc);
11838 }
11839
11840 if ((name == "And8" || name == "Or8")
11841 && this->args_ != NULL && this->args_->size() == 2)
11842 {
11843 Runtime::Function code;
11844 if (name == "And8")
11845 code = Runtime::ATOMIC_AND_FETCH_1;
11846 else if (name == "Or8")
11847 code = Runtime::ATOMIC_OR_FETCH_1;
11848 else
11849 go_unreachable();
11850 Expression* a1 = this->args_->at(0);
11851 Expression* a2 = this->args_->at(1);
11852 Expression* a3 = Expression::make_integer_ul(memorder, int32_type, loc);
11853 return Runtime::make_call(code, loc, 3, a1, a2, a3);
11854 }
11855 }
11856
11857 return NULL;
11858 }
11859
11860 // Make implicit type conversions explicit.
11861
11862 void
do_add_conversions()11863 Call_expression::do_add_conversions()
11864 {
11865 // Skip call that requires a thunk. We generate conversions inside the thunk.
11866 if (this->is_concurrent_ || this->is_deferred_)
11867 return;
11868
11869 if (this->args_ == NULL || this->args_->empty())
11870 return;
11871
11872 Function_type* fntype = this->get_function_type();
11873 if (fntype == NULL)
11874 {
11875 go_assert(saw_errors());
11876 return;
11877 }
11878 if (fntype->parameters() == NULL || fntype->parameters()->empty())
11879 return;
11880
11881 Location loc = this->location();
11882 Expression_list::iterator pa = this->args_->begin();
11883 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
11884 bool is_interface_method =
11885 this->fn_->interface_field_reference_expression() != NULL;
11886 size_t argcount = this->args_->size();
11887 if (!is_interface_method && fntype->is_method())
11888 {
11889 // Skip the receiver argument, which cannot be interface.
11890 pa++;
11891 argcount--;
11892 }
11893 if (argcount != fntype->parameters()->size())
11894 {
11895 go_assert(saw_errors());
11896 return;
11897 }
11898 for (; pa != this->args_->end(); ++pa, ++pp)
11899 {
11900 Type* pt = pp->type();
11901 if (!Type::are_identical(pt, (*pa)->type(), 0, NULL)
11902 && pt->interface_type() != NULL)
11903 *pa = Expression::make_cast(pt, *pa, loc);
11904 }
11905 }
11906
11907 // Get the function type. This can return NULL in error cases.
11908
11909 Function_type*
get_function_type() const11910 Call_expression::get_function_type() const
11911 {
11912 return this->fn_->type()->function_type();
11913 }
11914
11915 // Return the number of values which this call will return.
11916
11917 size_t
result_count() const11918 Call_expression::result_count() const
11919 {
11920 const Function_type* fntype = this->get_function_type();
11921 if (fntype == NULL)
11922 return 0;
11923 if (fntype->results() == NULL)
11924 return 0;
11925 return fntype->results()->size();
11926 }
11927
11928 // Return the temporary that holds the result for a call with multiple
11929 // results.
11930
11931 Temporary_statement*
results() const11932 Call_expression::results() const
11933 {
11934 if (this->call_temp_ == NULL)
11935 {
11936 go_assert(saw_errors());
11937 return NULL;
11938 }
11939 return this->call_temp_;
11940 }
11941
11942 // Set the number of results expected from a call expression.
11943
11944 void
set_expected_result_count(size_t count)11945 Call_expression::set_expected_result_count(size_t count)
11946 {
11947 go_assert(this->expected_result_count_ == 0);
11948 this->expected_result_count_ = count;
11949 }
11950
11951 // Return whether this is a call to the predeclared function recover.
11952
11953 bool
is_recover_call() const11954 Call_expression::is_recover_call() const
11955 {
11956 return this->do_is_recover_call();
11957 }
11958
11959 // Set the argument to the recover function.
11960
11961 void
set_recover_arg(Expression * arg)11962 Call_expression::set_recover_arg(Expression* arg)
11963 {
11964 this->do_set_recover_arg(arg);
11965 }
11966
11967 // Virtual functions also implemented by Builtin_call_expression.
11968
11969 bool
do_is_recover_call() const11970 Call_expression::do_is_recover_call() const
11971 {
11972 return false;
11973 }
11974
11975 void
do_set_recover_arg(Expression *)11976 Call_expression::do_set_recover_arg(Expression*)
11977 {
11978 go_unreachable();
11979 }
11980
11981 // We have found an error with this call expression; return true if
11982 // we should report it.
11983
11984 bool
issue_error()11985 Call_expression::issue_error()
11986 {
11987 if (this->issued_error_)
11988 return false;
11989 else
11990 {
11991 this->issued_error_ = true;
11992 return true;
11993 }
11994 }
11995
11996 // Whether or not this call contains errors, either in the call or the
11997 // arguments to the call.
11998
11999 bool
is_erroneous_call()12000 Call_expression::is_erroneous_call()
12001 {
12002 if (this->is_error_expression() || this->fn()->is_error_expression())
12003 return true;
12004
12005 if (this->args() == NULL)
12006 return false;
12007 for (Expression_list::iterator pa = this->args()->begin();
12008 pa != this->args()->end();
12009 ++pa)
12010 {
12011 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
12012 return true;
12013 }
12014 return false;
12015 }
12016
12017 // Get the type.
12018
12019 Type*
do_type()12020 Call_expression::do_type()
12021 {
12022 if (this->is_error_expression())
12023 return Type::make_error_type();
12024 if (this->type_ != NULL)
12025 return this->type_;
12026
12027 Type* ret;
12028 Function_type* fntype = this->get_function_type();
12029 if (fntype == NULL)
12030 return Type::make_error_type();
12031
12032 const Typed_identifier_list* results = fntype->results();
12033 if (results == NULL)
12034 ret = Type::make_void_type();
12035 else if (results->size() == 1)
12036 ret = results->begin()->type();
12037 else
12038 ret = Type::make_call_multiple_result_type(this);
12039
12040 this->type_ = ret;
12041
12042 return this->type_;
12043 }
12044
12045 // Determine types for a call expression. We can use the function
12046 // parameter types to set the types of the arguments.
12047
12048 void
do_determine_type(const Type_context * context)12049 Call_expression::do_determine_type(const Type_context* context)
12050 {
12051 if (!this->determining_types())
12052 return;
12053
12054 this->fn_->determine_type_no_context();
12055 Function_type* fntype = this->get_function_type();
12056 const Typed_identifier_list* parameters = NULL;
12057 if (fntype != NULL)
12058 parameters = fntype->parameters();
12059 if (this->args_ != NULL)
12060 {
12061 Typed_identifier_list::const_iterator pt;
12062 if (parameters != NULL)
12063 pt = parameters->begin();
12064 bool first = true;
12065 for (Expression_list::const_iterator pa = this->args_->begin();
12066 pa != this->args_->end();
12067 ++pa)
12068 {
12069 if (first)
12070 {
12071 first = false;
12072 // If this is a method, the first argument is the
12073 // receiver.
12074 if (fntype != NULL && fntype->is_method())
12075 {
12076 Type* rtype = fntype->receiver()->type();
12077 // The receiver is always passed as a pointer.
12078 if (rtype->points_to() == NULL)
12079 rtype = Type::make_pointer_type(rtype);
12080 Type_context subcontext(rtype, false);
12081 (*pa)->determine_type(&subcontext);
12082 continue;
12083 }
12084 }
12085
12086 if (parameters != NULL && pt != parameters->end())
12087 {
12088 Type_context subcontext(pt->type(), false);
12089 (*pa)->determine_type(&subcontext);
12090 ++pt;
12091 }
12092 else
12093 (*pa)->determine_type_no_context();
12094 }
12095 }
12096
12097 // If this is a call to a generated equality function, we determine
12098 // the type based on the context. See the comment in
12099 // Binary_expression::lower_array_comparison.
12100 if (this->is_equal_function_
12101 && !context->may_be_abstract
12102 && context->type != NULL
12103 && context->type->is_boolean_type()
12104 && context->type != Type::lookup_bool_type())
12105 {
12106 go_assert(this->type_ == NULL
12107 || this->type_ == Type::lookup_bool_type()
12108 || this->type_ == context->type
12109 || this->type_->is_error());
12110 this->type_ = context->type;
12111 }
12112 }
12113
12114 // Called when determining types for a Call_expression. Return true
12115 // if we should go ahead, false if they have already been determined.
12116
12117 bool
determining_types()12118 Call_expression::determining_types()
12119 {
12120 if (this->types_are_determined_)
12121 return false;
12122 else
12123 {
12124 this->types_are_determined_ = true;
12125 return true;
12126 }
12127 }
12128
12129 // Check types for parameter I.
12130
12131 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)12132 Call_expression::check_argument_type(int i, const Type* parameter_type,
12133 const Type* argument_type,
12134 Location argument_location,
12135 bool issued_error)
12136 {
12137 std::string reason;
12138 if (!Type::are_assignable(parameter_type, argument_type, &reason))
12139 {
12140 if (!issued_error)
12141 {
12142 if (reason.empty())
12143 go_error_at(argument_location, "argument %d has incompatible type", i);
12144 else
12145 go_error_at(argument_location,
12146 "argument %d has incompatible type (%s)",
12147 i, reason.c_str());
12148 }
12149 this->set_is_error();
12150 return false;
12151 }
12152 return true;
12153 }
12154
12155 // Check types.
12156
12157 void
do_check_types(Gogo *)12158 Call_expression::do_check_types(Gogo*)
12159 {
12160 if (this->classification() == EXPRESSION_ERROR)
12161 return;
12162
12163 Function_type* fntype = this->get_function_type();
12164 if (fntype == NULL)
12165 {
12166 if (!this->fn_->type()->is_error())
12167 this->report_error(_("expected function"));
12168 return;
12169 }
12170
12171 if (this->expected_result_count_ != 0
12172 && this->expected_result_count_ != this->result_count())
12173 {
12174 if (this->issue_error())
12175 this->report_error(_("function result count mismatch"));
12176 this->set_is_error();
12177 return;
12178 }
12179
12180 bool is_method = fntype->is_method();
12181 if (is_method)
12182 {
12183 go_assert(this->args_ != NULL && !this->args_->empty());
12184 Type* rtype = fntype->receiver()->type();
12185 Expression* first_arg = this->args_->front();
12186 // We dereference the values since receivers are always passed
12187 // as pointers.
12188 std::string reason;
12189 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
12190 &reason))
12191 {
12192 if (reason.empty())
12193 this->report_error(_("incompatible type for receiver"));
12194 else
12195 {
12196 go_error_at(this->location(),
12197 "incompatible type for receiver (%s)",
12198 reason.c_str());
12199 this->set_is_error();
12200 }
12201 }
12202 }
12203
12204 // Note that varargs was handled by the lower_varargs() method, so
12205 // we don't have to worry about it here unless something is wrong.
12206 if (this->is_varargs_ && !this->varargs_are_lowered_)
12207 {
12208 if (!fntype->is_varargs())
12209 {
12210 go_error_at(this->location(),
12211 _("invalid use of %<...%> calling non-variadic function"));
12212 this->set_is_error();
12213 return;
12214 }
12215 }
12216
12217 const Typed_identifier_list* parameters = fntype->parameters();
12218 if (this->args_ == NULL || this->args_->size() == 0)
12219 {
12220 if (parameters != NULL && !parameters->empty())
12221 this->report_error(_("not enough arguments"));
12222 }
12223 else if (parameters == NULL)
12224 {
12225 if (!is_method || this->args_->size() > 1)
12226 this->report_error(_("too many arguments"));
12227 }
12228 else if (this->args_->size() == 1
12229 && this->args_->front()->call_expression() != NULL
12230 && this->args_->front()->call_expression()->result_count() > 1)
12231 {
12232 // This is F(G()) when G returns more than one result. If the
12233 // results can be matched to parameters, it would have been
12234 // lowered in do_lower. If we get here we know there is a
12235 // mismatch.
12236 if (this->args_->front()->call_expression()->result_count()
12237 < parameters->size())
12238 this->report_error(_("not enough arguments"));
12239 else
12240 this->report_error(_("too many arguments"));
12241 }
12242 else
12243 {
12244 int i = 0;
12245 Expression_list::const_iterator pa = this->args_->begin();
12246 if (is_method)
12247 ++pa;
12248 for (Typed_identifier_list::const_iterator pt = parameters->begin();
12249 pt != parameters->end();
12250 ++pt, ++pa, ++i)
12251 {
12252 if (pa == this->args_->end())
12253 {
12254 this->report_error(_("not enough arguments"));
12255 return;
12256 }
12257 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
12258 (*pa)->location(), false);
12259 }
12260 if (pa != this->args_->end())
12261 this->report_error(_("too many arguments"));
12262 }
12263 }
12264
12265 Expression*
do_copy()12266 Call_expression::do_copy()
12267 {
12268 Call_expression* call =
12269 Expression::make_call(this->fn_->copy(),
12270 (this->args_ == NULL
12271 ? NULL
12272 : this->args_->copy()),
12273 this->is_varargs_, this->location());
12274
12275 if (this->varargs_are_lowered_)
12276 call->set_varargs_are_lowered();
12277 if (this->is_deferred_)
12278 call->set_is_deferred();
12279 if (this->is_concurrent_)
12280 call->set_is_concurrent();
12281 return call;
12282 }
12283
12284 // Return whether we have to use a temporary variable to ensure that
12285 // we evaluate this call expression in order. If the call returns no
12286 // results then it will inevitably be executed last.
12287
12288 bool
do_must_eval_in_order() const12289 Call_expression::do_must_eval_in_order() const
12290 {
12291 return this->result_count() > 0;
12292 }
12293
12294 // Get the function and the first argument to use when calling an
12295 // interface method.
12296
12297 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr,Location location)12298 Call_expression::interface_method_function(
12299 Interface_field_reference_expression* interface_method,
12300 Expression** first_arg_ptr,
12301 Location location)
12302 {
12303 Expression* object = interface_method->get_underlying_object();
12304 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
12305 *first_arg_ptr =
12306 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
12307 return interface_method->get_function();
12308 }
12309
12310 // Build the call expression.
12311
12312 Bexpression*
do_get_backend(Translate_context * context)12313 Call_expression::do_get_backend(Translate_context* context)
12314 {
12315 Location location = this->location();
12316
12317 if (this->call_ != NULL)
12318 {
12319 // If the call returns multiple results, make a new reference to
12320 // the temporary.
12321 if (this->call_temp_ != NULL)
12322 {
12323 Expression* ref =
12324 Expression::make_temporary_reference(this->call_temp_, location);
12325 return ref->get_backend(context);
12326 }
12327
12328 return this->call_;
12329 }
12330
12331 Function_type* fntype = this->get_function_type();
12332 if (fntype == NULL)
12333 return context->backend()->error_expression();
12334
12335 if (this->fn_->is_error_expression())
12336 return context->backend()->error_expression();
12337
12338 Gogo* gogo = context->gogo();
12339
12340 Func_expression* func = this->fn_->func_expression();
12341 Interface_field_reference_expression* interface_method =
12342 this->fn_->interface_field_reference_expression();
12343 const bool has_closure = func != NULL && func->closure() != NULL;
12344 const bool is_interface_method = interface_method != NULL;
12345
12346 bool has_closure_arg;
12347 if (has_closure)
12348 has_closure_arg = true;
12349 else if (func != NULL)
12350 has_closure_arg = false;
12351 else if (is_interface_method)
12352 has_closure_arg = false;
12353 else
12354 has_closure_arg = true;
12355
12356 Expression* first_arg = NULL;
12357 if (!is_interface_method && fntype->is_method())
12358 {
12359 first_arg = this->args_->front();
12360 if (first_arg->type()->points_to() == NULL
12361 && first_arg->type()->is_direct_iface_type())
12362 first_arg = Expression::unpack_direct_iface(first_arg,
12363 first_arg->location());
12364 }
12365
12366 int nargs;
12367 std::vector<Bexpression*> fn_args;
12368 if (this->args_ == NULL || this->args_->empty())
12369 {
12370 nargs = is_interface_method ? 1 : 0;
12371 if (nargs > 0)
12372 fn_args.resize(1);
12373 }
12374 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
12375 {
12376 // Passing a receiver parameter.
12377 go_assert(!is_interface_method
12378 && fntype->is_method()
12379 && this->args_->size() == 1);
12380 nargs = 1;
12381 fn_args.resize(1);
12382 fn_args[0] = first_arg->get_backend(context);
12383 }
12384 else
12385 {
12386 const Typed_identifier_list* params = fntype->parameters();
12387
12388 nargs = this->args_->size();
12389 int i = is_interface_method ? 1 : 0;
12390 nargs += i;
12391 fn_args.resize(nargs);
12392
12393 Typed_identifier_list::const_iterator pp = params->begin();
12394 Expression_list::const_iterator pe = this->args_->begin();
12395 if (!is_interface_method && fntype->is_method())
12396 {
12397 fn_args[i] = first_arg->get_backend(context);
12398 ++pe;
12399 ++i;
12400 }
12401 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
12402 {
12403 go_assert(pp != params->end());
12404 Expression* arg =
12405 Expression::convert_for_assignment(gogo, pp->type(), *pe,
12406 location);
12407 fn_args[i] = arg->get_backend(context);
12408 }
12409 go_assert(pp == params->end());
12410 go_assert(i == nargs);
12411 }
12412
12413 Expression* fn;
12414 Expression* closure = NULL;
12415 if (func != NULL)
12416 {
12417 Named_object* no = func->named_object();
12418 fn = Expression::make_func_code_reference(no, location);
12419 if (has_closure)
12420 closure = func->closure();
12421 }
12422 else if (!is_interface_method)
12423 {
12424 closure = this->fn_;
12425
12426 // The backend representation of this function type is a pointer
12427 // to a struct whose first field is the actual function to call.
12428 Type* pfntype =
12429 Type::make_pointer_type(
12430 Type::make_pointer_type(Type::make_void_type()));
12431 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
12432 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
12433 }
12434 else
12435 {
12436 Expression* arg0;
12437 fn = this->interface_method_function(interface_method, &arg0,
12438 location);
12439 fn_args[0] = arg0->get_backend(context);
12440 }
12441
12442 Bexpression* bclosure = NULL;
12443 if (has_closure_arg)
12444 bclosure = closure->get_backend(context);
12445 else
12446 go_assert(closure == NULL);
12447
12448 Bexpression* bfn = fn->get_backend(context);
12449
12450 // When not calling a named function directly, use a type conversion
12451 // in case the type of the function is a recursive type which refers
12452 // to itself. We don't do this for an interface method because 1)
12453 // an interface method never refers to itself, so we always have a
12454 // function type here; 2) we pass an extra first argument to an
12455 // interface method, so fntype is not correct.
12456 if (func == NULL && !is_interface_method)
12457 {
12458 Btype* bft = fntype->get_backend_fntype(gogo);
12459 bfn = gogo->backend()->convert_expression(bft, bfn, location);
12460 }
12461
12462 Bfunction* bfunction = NULL;
12463 if (context->function())
12464 bfunction = context->function()->func_value()->get_decl();
12465 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
12466 fn_args, bclosure,
12467 location);
12468
12469 if (this->call_temp_ != NULL)
12470 {
12471 // This case occurs when the call returns multiple results.
12472
12473 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
12474 location);
12475 Bexpression* bref = ref->get_backend(context);
12476 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
12477 bref, call,
12478 location);
12479
12480 ref = Expression::make_temporary_reference(this->call_temp_, location);
12481 this->call_ = ref->get_backend(context);
12482
12483 return gogo->backend()->compound_expression(bassn, this->call_,
12484 location);
12485 }
12486
12487 this->call_ = call;
12488 return this->call_;
12489 }
12490
12491 // The cost of inlining a call expression.
12492
12493 int
do_inlining_cost() const12494 Call_expression::do_inlining_cost() const
12495 {
12496 Func_expression* fn = this->fn_->func_expression();
12497
12498 // FIXME: We don't yet support all kinds of calls.
12499 if (fn != NULL && fn->closure() != NULL)
12500 return 0x100000;
12501 if (this->fn_->interface_field_reference_expression())
12502 return 0x100000;
12503 if (this->get_function_type()->is_method())
12504 return 0x100000;
12505
12506 return 5;
12507 }
12508
12509 // Export a call expression.
12510
12511 void
do_export(Export_function_body * efb) const12512 Call_expression::do_export(Export_function_body* efb) const
12513 {
12514 bool simple_call = (this->fn_->func_expression() != NULL);
12515 if (!simple_call)
12516 efb->write_c_string("(");
12517 this->fn_->export_expression(efb);
12518 if (!simple_call)
12519 efb->write_c_string(")");
12520 this->export_arguments(efb);
12521 }
12522
12523 // Export call expression arguments.
12524
12525 void
export_arguments(Export_function_body * efb) const12526 Call_expression::export_arguments(Export_function_body* efb) const
12527 {
12528 efb->write_c_string("(");
12529 if (this->args_ != NULL && !this->args_->empty())
12530 {
12531 Expression_list::const_iterator pa = this->args_->begin();
12532 (*pa)->export_expression(efb);
12533 for (pa++; pa != this->args_->end(); pa++)
12534 {
12535 efb->write_c_string(", ");
12536 (*pa)->export_expression(efb);
12537 }
12538 if (this->is_varargs_)
12539 efb->write_c_string("...");
12540 }
12541 efb->write_c_string(")");
12542 }
12543
12544 // Dump ast representation for a call expression.
12545
12546 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12547 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12548 {
12549 this->fn_->dump_expression(ast_dump_context);
12550 ast_dump_context->ostream() << "(";
12551 if (args_ != NULL)
12552 ast_dump_context->dump_expression_list(this->args_);
12553
12554 ast_dump_context->ostream() << ") ";
12555 }
12556
12557 // Make a call expression.
12558
12559 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)12560 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
12561 Location location)
12562 {
12563 return new Call_expression(fn, args, is_varargs, location);
12564 }
12565
12566 // Class Call_result_expression.
12567
12568 // Traverse a call result.
12569
12570 int
do_traverse(Traverse * traverse)12571 Call_result_expression::do_traverse(Traverse* traverse)
12572 {
12573 if (traverse->remember_expression(this->call_))
12574 {
12575 // We have already traversed the call expression.
12576 return TRAVERSE_CONTINUE;
12577 }
12578 return Expression::traverse(&this->call_, traverse);
12579 }
12580
12581 // Get the type.
12582
12583 Type*
do_type()12584 Call_result_expression::do_type()
12585 {
12586 if (this->classification() == EXPRESSION_ERROR)
12587 return Type::make_error_type();
12588
12589 // THIS->CALL_ can be replaced with a temporary reference due to
12590 // Call_expression::do_must_eval_in_order when there is an error.
12591 Call_expression* ce = this->call_->call_expression();
12592 if (ce == NULL)
12593 {
12594 this->set_is_error();
12595 return Type::make_error_type();
12596 }
12597 Function_type* fntype = ce->get_function_type();
12598 if (fntype == NULL)
12599 {
12600 if (ce->issue_error())
12601 {
12602 if (!ce->fn()->type()->is_error())
12603 this->report_error(_("expected function"));
12604 }
12605 this->set_is_error();
12606 return Type::make_error_type();
12607 }
12608 const Typed_identifier_list* results = fntype->results();
12609 if (results == NULL || results->size() < 2)
12610 {
12611 if (ce->issue_error())
12612 this->report_error(_("number of results does not match "
12613 "number of values"));
12614 return Type::make_error_type();
12615 }
12616 Typed_identifier_list::const_iterator pr = results->begin();
12617 for (unsigned int i = 0; i < this->index_; ++i)
12618 {
12619 if (pr == results->end())
12620 break;
12621 ++pr;
12622 }
12623 if (pr == results->end())
12624 {
12625 if (ce->issue_error())
12626 this->report_error(_("number of results does not match "
12627 "number of values"));
12628 return Type::make_error_type();
12629 }
12630 return pr->type();
12631 }
12632
12633 // Check the type. Just make sure that we trigger the warning in
12634 // do_type.
12635
12636 void
do_check_types(Gogo *)12637 Call_result_expression::do_check_types(Gogo*)
12638 {
12639 this->type();
12640 }
12641
12642 // Determine the type. We have nothing to do here, but the 0 result
12643 // needs to pass down to the caller.
12644
12645 void
do_determine_type(const Type_context *)12646 Call_result_expression::do_determine_type(const Type_context*)
12647 {
12648 this->call_->determine_type_no_context();
12649 }
12650
12651 // Return the backend representation. We just refer to the temporary set by the
12652 // call expression. We don't do this at lowering time because it makes it
12653 // hard to evaluate the call at the right time.
12654
12655 Bexpression*
do_get_backend(Translate_context * context)12656 Call_result_expression::do_get_backend(Translate_context* context)
12657 {
12658 Call_expression* ce = this->call_->call_expression();
12659 if (ce == NULL)
12660 {
12661 go_assert(this->call_->is_error_expression());
12662 return context->backend()->error_expression();
12663 }
12664 Temporary_statement* ts = ce->results();
12665 if (ts == NULL)
12666 {
12667 go_assert(saw_errors());
12668 return context->backend()->error_expression();
12669 }
12670 Expression* ref = Expression::make_temporary_reference(ts, this->location());
12671 ref = Expression::make_field_reference(ref, this->index_, this->location());
12672 return ref->get_backend(context);
12673 }
12674
12675 // Dump ast representation for a call result expression.
12676
12677 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12678 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12679 const
12680 {
12681 // FIXME: Wouldn't it be better if the call is assigned to a temporary
12682 // (struct) and the fields are referenced instead.
12683 ast_dump_context->ostream() << this->index_ << "@(";
12684 ast_dump_context->dump_expression(this->call_);
12685 ast_dump_context->ostream() << ")";
12686 }
12687
12688 // Make a reference to a single result of a call which returns
12689 // multiple results.
12690
12691 Expression*
make_call_result(Call_expression * call,unsigned int index)12692 Expression::make_call_result(Call_expression* call, unsigned int index)
12693 {
12694 return new Call_result_expression(call, index);
12695 }
12696
12697 // Class Index_expression.
12698
12699 // Traversal.
12700
12701 int
do_traverse(Traverse * traverse)12702 Index_expression::do_traverse(Traverse* traverse)
12703 {
12704 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
12705 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
12706 || (this->end_ != NULL
12707 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12708 || (this->cap_ != NULL
12709 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
12710 return TRAVERSE_EXIT;
12711 return TRAVERSE_CONTINUE;
12712 }
12713
12714 // Lower an index expression. This converts the generic index
12715 // expression into an array index, a string index, or a map index.
12716
12717 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)12718 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
12719 {
12720 Location location = this->location();
12721 Expression* left = this->left_;
12722 Expression* start = this->start_;
12723 Expression* end = this->end_;
12724 Expression* cap = this->cap_;
12725
12726 Type* type = left->type();
12727 if (type->is_error())
12728 {
12729 go_assert(saw_errors());
12730 return Expression::make_error(location);
12731 }
12732 else if (left->is_type_expression())
12733 {
12734 go_error_at(location, "attempt to index type expression");
12735 return Expression::make_error(location);
12736 }
12737 else if (type->array_type() != NULL)
12738 return Expression::make_array_index(left, start, end, cap, location);
12739 else if (type->points_to() != NULL
12740 && type->points_to()->array_type() != NULL
12741 && !type->points_to()->is_slice_type())
12742 {
12743 Expression* deref =
12744 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
12745
12746 // For an ordinary index into the array, the pointer will be
12747 // dereferenced. For a slice it will not--the resulting slice
12748 // will simply reuse the pointer, which is incorrect if that
12749 // pointer is nil.
12750 if (end != NULL || cap != NULL)
12751 deref->issue_nil_check();
12752
12753 return Expression::make_array_index(deref, start, end, cap, location);
12754 }
12755 else if (type->is_string_type())
12756 {
12757 if (cap != NULL)
12758 {
12759 go_error_at(location, "invalid 3-index slice of string");
12760 return Expression::make_error(location);
12761 }
12762 return Expression::make_string_index(left, start, end, location);
12763 }
12764 else if (type->map_type() != NULL)
12765 {
12766 if (end != NULL || cap != NULL)
12767 {
12768 go_error_at(location, "invalid slice of map");
12769 return Expression::make_error(location);
12770 }
12771 return Expression::make_map_index(left, start, location);
12772 }
12773 else if (cap != NULL)
12774 {
12775 go_error_at(location,
12776 "invalid 3-index slice of object that is not a slice");
12777 return Expression::make_error(location);
12778 }
12779 else if (end != NULL)
12780 {
12781 go_error_at(location,
12782 ("attempt to slice object that is not "
12783 "array, slice, or string"));
12784 return Expression::make_error(location);
12785 }
12786 else
12787 {
12788 go_error_at(location,
12789 ("attempt to index object that is not "
12790 "array, slice, string, or map"));
12791 return Expression::make_error(location);
12792 }
12793 }
12794
12795 // Write an indexed expression
12796 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
12797
12798 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)12799 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
12800 const Expression* expr,
12801 const Expression* start,
12802 const Expression* end,
12803 const Expression* cap)
12804 {
12805 expr->dump_expression(ast_dump_context);
12806 ast_dump_context->ostream() << "[";
12807 start->dump_expression(ast_dump_context);
12808 if (end != NULL)
12809 {
12810 ast_dump_context->ostream() << ":";
12811 end->dump_expression(ast_dump_context);
12812 }
12813 if (cap != NULL)
12814 {
12815 ast_dump_context->ostream() << ":";
12816 cap->dump_expression(ast_dump_context);
12817 }
12818 ast_dump_context->ostream() << "]";
12819 }
12820
12821 // Dump ast representation for an index expression.
12822
12823 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12824 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12825 const
12826 {
12827 Index_expression::dump_index_expression(ast_dump_context, this->left_,
12828 this->start_, this->end_, this->cap_);
12829 }
12830
12831 // Make an index expression.
12832
12833 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)12834 Expression::make_index(Expression* left, Expression* start, Expression* end,
12835 Expression* cap, Location location)
12836 {
12837 return new Index_expression(left, start, end, cap, location);
12838 }
12839
12840 // Class Array_index_expression.
12841
12842 // Array index traversal.
12843
12844 int
do_traverse(Traverse * traverse)12845 Array_index_expression::do_traverse(Traverse* traverse)
12846 {
12847 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
12848 return TRAVERSE_EXIT;
12849 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
12850 return TRAVERSE_EXIT;
12851 if (this->end_ != NULL)
12852 {
12853 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
12854 return TRAVERSE_EXIT;
12855 }
12856 if (this->cap_ != NULL)
12857 {
12858 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
12859 return TRAVERSE_EXIT;
12860 }
12861 return TRAVERSE_CONTINUE;
12862 }
12863
12864 // Return the type of an array index.
12865
12866 Type*
do_type()12867 Array_index_expression::do_type()
12868 {
12869 if (this->type_ == NULL)
12870 {
12871 Array_type* type = this->array_->type()->array_type();
12872 if (type == NULL)
12873 this->type_ = Type::make_error_type();
12874 else if (this->end_ == NULL)
12875 this->type_ = type->element_type();
12876 else if (type->is_slice_type())
12877 {
12878 // A slice of a slice has the same type as the original
12879 // slice.
12880 this->type_ = this->array_->type()->deref();
12881 }
12882 else
12883 {
12884 // A slice of an array is a slice.
12885 this->type_ = Type::make_array_type(type->element_type(), NULL);
12886 }
12887 }
12888 return this->type_;
12889 }
12890
12891 // Set the type of an array index.
12892
12893 void
do_determine_type(const Type_context *)12894 Array_index_expression::do_determine_type(const Type_context*)
12895 {
12896 this->array_->determine_type_no_context();
12897
12898 Type_context index_context(Type::lookup_integer_type("int"), false);
12899 this->start_->determine_type(&index_context);
12900 if (this->end_ != NULL)
12901 this->end_->determine_type(&index_context);
12902 if (this->cap_ != NULL)
12903 this->cap_->determine_type(&index_context);
12904 }
12905
12906 // Check types of an array index.
12907
12908 void
do_check_types(Gogo *)12909 Array_index_expression::do_check_types(Gogo*)
12910 {
12911 Numeric_constant nc;
12912 unsigned long v;
12913 if (this->start_->type()->integer_type() == NULL
12914 && !this->start_->type()->is_error()
12915 && (!this->start_->type()->is_abstract()
12916 || !this->start_->numeric_constant_value(&nc)
12917 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12918 this->report_error(_("index must be integer"));
12919 if (this->end_ != NULL
12920 && this->end_->type()->integer_type() == NULL
12921 && !this->end_->type()->is_error()
12922 && !this->end_->is_nil_expression()
12923 && !this->end_->is_error_expression()
12924 && (!this->end_->type()->is_abstract()
12925 || !this->end_->numeric_constant_value(&nc)
12926 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12927 this->report_error(_("slice end must be integer"));
12928 if (this->cap_ != NULL
12929 && this->cap_->type()->integer_type() == NULL
12930 && !this->cap_->type()->is_error()
12931 && !this->cap_->is_nil_expression()
12932 && !this->cap_->is_error_expression()
12933 && (!this->cap_->type()->is_abstract()
12934 || !this->cap_->numeric_constant_value(&nc)
12935 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
12936 this->report_error(_("slice capacity must be integer"));
12937
12938 Array_type* array_type = this->array_->type()->array_type();
12939 if (array_type == NULL)
12940 {
12941 go_assert(this->array_->type()->is_error());
12942 return;
12943 }
12944
12945 unsigned int int_bits =
12946 Type::lookup_integer_type("int")->integer_type()->bits();
12947
12948 Numeric_constant lvalnc;
12949 mpz_t lval;
12950 bool lval_valid = (array_type->length() != NULL
12951 && array_type->length()->numeric_constant_value(&lvalnc)
12952 && lvalnc.to_int(&lval));
12953 Numeric_constant inc;
12954 mpz_t ival;
12955 bool ival_valid = false;
12956 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
12957 {
12958 ival_valid = true;
12959 if (mpz_sgn(ival) < 0
12960 || mpz_sizeinbase(ival, 2) >= int_bits
12961 || (lval_valid
12962 && (this->end_ == NULL
12963 ? mpz_cmp(ival, lval) >= 0
12964 : mpz_cmp(ival, lval) > 0)))
12965 {
12966 go_error_at(this->start_->location(), "array index out of bounds");
12967 this->set_is_error();
12968 }
12969 }
12970 if (this->end_ != NULL && !this->end_->is_nil_expression())
12971 {
12972 Numeric_constant enc;
12973 mpz_t eval;
12974 bool eval_valid = false;
12975 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
12976 {
12977 eval_valid = true;
12978 if (mpz_sgn(eval) < 0
12979 || mpz_sizeinbase(eval, 2) >= int_bits
12980 || (lval_valid && mpz_cmp(eval, lval) > 0))
12981 {
12982 go_error_at(this->end_->location(), "array index out of bounds");
12983 this->set_is_error();
12984 }
12985 else if (ival_valid && mpz_cmp(ival, eval) > 0)
12986 this->report_error(_("inverted slice range"));
12987 }
12988
12989 Numeric_constant cnc;
12990 mpz_t cval;
12991 if (this->cap_ != NULL
12992 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
12993 {
12994 if (mpz_sgn(cval) < 0
12995 || mpz_sizeinbase(cval, 2) >= int_bits
12996 || (lval_valid && mpz_cmp(cval, lval) > 0))
12997 {
12998 go_error_at(this->cap_->location(), "array index out of bounds");
12999 this->set_is_error();
13000 }
13001 else if (ival_valid && mpz_cmp(ival, cval) > 0)
13002 {
13003 go_error_at(this->cap_->location(),
13004 "invalid slice index: capacity less than start");
13005 this->set_is_error();
13006 }
13007 else if (eval_valid && mpz_cmp(eval, cval) > 0)
13008 {
13009 go_error_at(this->cap_->location(),
13010 "invalid slice index: capacity less than length");
13011 this->set_is_error();
13012 }
13013 mpz_clear(cval);
13014 }
13015
13016 if (eval_valid)
13017 mpz_clear(eval);
13018 }
13019 if (ival_valid)
13020 mpz_clear(ival);
13021 if (lval_valid)
13022 mpz_clear(lval);
13023
13024 // A slice of an array requires an addressable array. A slice of a
13025 // slice is always possible.
13026 if (this->end_ != NULL && !array_type->is_slice_type())
13027 {
13028 if (!this->array_->is_addressable())
13029 this->report_error(_("slice of unaddressable value"));
13030 else
13031 // Set the array address taken but not escape. The escape
13032 // analysis will make it escape to heap when needed.
13033 this->array_->address_taken(false);
13034 }
13035 }
13036
13037 // The subexpressions of an array index must be evaluated in order.
13038 // If this is indexing into an array, rather than a slice, then only
13039 // the index should be evaluated. Since this is called for values on
13040 // the left hand side of an assigment, evaluating the array, meaning
13041 // copying the array, will cause a different array to be modified.
13042
13043 bool
do_must_eval_subexpressions_in_order(int * skip) const13044 Array_index_expression::do_must_eval_subexpressions_in_order(
13045 int* skip) const
13046 {
13047 *skip = this->array_->type()->is_slice_type() ? 0 : 1;
13048 return true;
13049 }
13050
13051 // Flatten array indexing: add temporary variables and bounds checks.
13052
13053 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13054 Array_index_expression::do_flatten(Gogo* gogo, Named_object*,
13055 Statement_inserter* inserter)
13056 {
13057 if (this->is_flattened_)
13058 return this;
13059 this->is_flattened_ = true;
13060
13061 Location loc = this->location();
13062
13063 if (this->is_error_expression())
13064 return Expression::make_error(loc);
13065
13066 Expression* array = this->array_;
13067 Expression* start = this->start_;
13068 Expression* end = this->end_;
13069 Expression* cap = this->cap_;
13070 if (array->is_error_expression()
13071 || array->type()->is_error_type()
13072 || start->is_error_expression()
13073 || start->type()->is_error_type()
13074 || (end != NULL
13075 && (end->is_error_expression() || end->type()->is_error_type()))
13076 || (cap != NULL
13077 && (cap->is_error_expression() || cap->type()->is_error_type())))
13078 {
13079 go_assert(saw_errors());
13080 return Expression::make_error(loc);
13081 }
13082
13083 Array_type* array_type = this->array_->type()->array_type();
13084 if (array_type == NULL)
13085 {
13086 go_assert(saw_errors());
13087 return Expression::make_error(loc);
13088 }
13089
13090 Temporary_statement* temp;
13091 if (array_type->is_slice_type() && !array->is_multi_eval_safe())
13092 {
13093 temp = Statement::make_temporary(NULL, array, loc);
13094 inserter->insert(temp);
13095 this->array_ = Expression::make_temporary_reference(temp, loc);
13096 array = this->array_;
13097 }
13098 if (!start->is_multi_eval_safe())
13099 {
13100 temp = Statement::make_temporary(NULL, start, loc);
13101 inserter->insert(temp);
13102 this->start_ = Expression::make_temporary_reference(temp, loc);
13103 start = this->start_;
13104 }
13105 if (end != NULL
13106 && !end->is_nil_expression()
13107 && !end->is_multi_eval_safe())
13108 {
13109 temp = Statement::make_temporary(NULL, end, loc);
13110 inserter->insert(temp);
13111 this->end_ = Expression::make_temporary_reference(temp, loc);
13112 end = this->end_;
13113 }
13114 if (cap != NULL && !cap->is_multi_eval_safe())
13115 {
13116 temp = Statement::make_temporary(NULL, cap, loc);
13117 inserter->insert(temp);
13118 this->cap_ = Expression::make_temporary_reference(temp, loc);
13119 cap = this->cap_;
13120 }
13121
13122 if (!this->needs_bounds_check_)
13123 return this;
13124
13125 Expression* len;
13126 if (!array_type->is_slice_type())
13127 {
13128 len = array_type->get_length(gogo, this->array_);
13129 go_assert(len->is_constant());
13130 }
13131 else
13132 {
13133 len = array_type->get_length(gogo, this->array_->copy());
13134 temp = Statement::make_temporary(NULL, len, loc);
13135 inserter->insert(temp);
13136 len = Expression::make_temporary_reference(temp, loc);
13137 }
13138
13139 Expression* scap = NULL;
13140 if (array_type->is_slice_type())
13141 {
13142 scap = array_type->get_capacity(gogo, this->array_->copy());
13143 temp = Statement::make_temporary(NULL, scap, loc);
13144 inserter->insert(temp);
13145 scap = Expression::make_temporary_reference(temp, loc);
13146 }
13147
13148 // The order of bounds checks here matches the order used by the gc
13149 // compiler, as tested by issue30116[u].go.
13150
13151 if (cap != NULL)
13152 {
13153 if (array_type->is_slice_type())
13154 Expression::check_bounds(cap, OPERATOR_LE, scap,
13155 Runtime::PANIC_SLICE3_ACAP,
13156 Runtime::PANIC_SLICE3_ACAP_U,
13157 Runtime::PANIC_EXTEND_SLICE3_ACAP,
13158 Runtime::PANIC_EXTEND_SLICE3_ACAP_U,
13159 inserter, loc);
13160 else
13161 Expression::check_bounds(cap, OPERATOR_LE, len,
13162 Runtime::PANIC_SLICE3_ALEN,
13163 Runtime::PANIC_SLICE3_ALEN_U,
13164 Runtime::PANIC_EXTEND_SLICE3_ALEN,
13165 Runtime::PANIC_EXTEND_SLICE3_ALEN_U,
13166 inserter, loc);
13167
13168 Expression* start_bound = cap;
13169 if (end != NULL && !end->is_nil_expression())
13170 {
13171 Expression::check_bounds(end, OPERATOR_LE, cap,
13172 Runtime::PANIC_SLICE3_B,
13173 Runtime::PANIC_SLICE3_B_U,
13174 Runtime::PANIC_EXTEND_SLICE3_B,
13175 Runtime::PANIC_EXTEND_SLICE3_B_U,
13176 inserter, loc);
13177 start_bound = end;
13178 }
13179
13180 Expression::check_bounds(start, OPERATOR_LE, start_bound,
13181 Runtime::PANIC_SLICE3_C,
13182 Runtime::PANIC_SLICE3_C_U,
13183 Runtime::PANIC_EXTEND_SLICE3_C,
13184 Runtime::PANIC_EXTEND_SLICE3_C_U,
13185 inserter, loc);
13186 }
13187 else if (end != NULL && !end->is_nil_expression())
13188 {
13189 if (array_type->is_slice_type())
13190 Expression::check_bounds(end, OPERATOR_LE, scap,
13191 Runtime::PANIC_SLICE_ACAP,
13192 Runtime::PANIC_SLICE_ACAP_U,
13193 Runtime::PANIC_EXTEND_SLICE_ACAP,
13194 Runtime::PANIC_EXTEND_SLICE_ACAP_U,
13195 inserter, loc);
13196 else
13197 Expression::check_bounds(end, OPERATOR_LE, len,
13198 Runtime::PANIC_SLICE_ALEN,
13199 Runtime::PANIC_SLICE_ALEN_U,
13200 Runtime::PANIC_EXTEND_SLICE_ALEN,
13201 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13202 inserter, loc);
13203
13204 Expression::check_bounds(start, OPERATOR_LE, end,
13205 Runtime::PANIC_SLICE_B,
13206 Runtime::PANIC_SLICE_B_U,
13207 Runtime::PANIC_EXTEND_SLICE_B,
13208 Runtime::PANIC_EXTEND_SLICE_B_U,
13209 inserter, loc);
13210 }
13211 else if (end != NULL)
13212 {
13213 Expression* start_bound;
13214 if (array_type->is_slice_type())
13215 start_bound = scap;
13216 else
13217 start_bound = len;
13218 Expression::check_bounds(start, OPERATOR_LE, start_bound,
13219 Runtime::PANIC_SLICE_B,
13220 Runtime::PANIC_SLICE_B_U,
13221 Runtime::PANIC_EXTEND_SLICE_B,
13222 Runtime::PANIC_EXTEND_SLICE_B_U,
13223 inserter, loc);
13224 }
13225 else
13226 Expression::check_bounds(start, OPERATOR_LT, len,
13227 Runtime::PANIC_INDEX,
13228 Runtime::PANIC_INDEX_U,
13229 Runtime::PANIC_EXTEND_INDEX,
13230 Runtime::PANIC_EXTEND_INDEX_U,
13231 inserter, loc);
13232
13233 return this;
13234 }
13235
13236 // Return whether this expression is addressable.
13237
13238 bool
do_is_addressable() const13239 Array_index_expression::do_is_addressable() const
13240 {
13241 // A slice expression is not addressable.
13242 if (this->end_ != NULL)
13243 return false;
13244
13245 // An index into a slice is addressable.
13246 if (this->array_->type()->is_slice_type())
13247 return true;
13248
13249 // An index into an array is addressable if the array is
13250 // addressable.
13251 return this->array_->is_addressable();
13252 }
13253
13254 void
do_address_taken(bool escapes)13255 Array_index_expression::do_address_taken(bool escapes)
13256 {
13257 // In &x[0], if x is a slice, then x's address is not taken.
13258 if (!this->array_->type()->is_slice_type())
13259 this->array_->address_taken(escapes);
13260 }
13261
13262 // Get the backend representation for an array index.
13263
13264 Bexpression*
do_get_backend(Translate_context * context)13265 Array_index_expression::do_get_backend(Translate_context* context)
13266 {
13267 Array_type* array_type = this->array_->type()->array_type();
13268 if (array_type == NULL)
13269 {
13270 go_assert(this->array_->type()->is_error());
13271 return context->backend()->error_expression();
13272 }
13273 go_assert(!array_type->is_slice_type()
13274 || this->array_->is_multi_eval_safe());
13275
13276 Location loc = this->location();
13277 Gogo* gogo = context->gogo();
13278
13279 Type* int_type = Type::lookup_integer_type("int");
13280 Btype* int_btype = int_type->get_backend(gogo);
13281
13282 // Convert the length and capacity to "int". FIXME: Do we need to
13283 // do this?
13284 Bexpression* length = NULL;
13285 if (this->end_ == NULL || this->end_->is_nil_expression())
13286 {
13287 Expression* len = array_type->get_length(gogo, this->array_);
13288 length = len->get_backend(context);
13289 length = gogo->backend()->convert_expression(int_btype, length, loc);
13290 }
13291
13292 Bexpression* capacity = NULL;
13293 if (this->end_ != NULL)
13294 {
13295 Expression* cap = array_type->get_capacity(gogo, this->array_);
13296 capacity = cap->get_backend(context);
13297 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
13298 }
13299
13300 Bexpression* cap_arg = capacity;
13301 if (this->cap_ != NULL)
13302 {
13303 cap_arg = this->cap_->get_backend(context);
13304 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
13305 }
13306
13307 if (length == NULL)
13308 length = cap_arg;
13309
13310 if (this->start_->type()->integer_type() == NULL
13311 && !Type::are_convertible(int_type, this->start_->type(), NULL))
13312 {
13313 go_assert(saw_errors());
13314 return context->backend()->error_expression();
13315 }
13316
13317 Bexpression* start = this->start_->get_backend(context);
13318 start = gogo->backend()->convert_expression(int_btype, start, loc);
13319
13320 Bfunction* bfn = context->function()->func_value()->get_decl();
13321 if (this->end_ == NULL)
13322 {
13323 // Simple array indexing.
13324 Bexpression* ret;
13325 if (!array_type->is_slice_type())
13326 {
13327 Bexpression* array = this->array_->get_backend(context);
13328 ret = gogo->backend()->array_index_expression(array, start, loc);
13329 }
13330 else
13331 {
13332 Expression* valptr =
13333 array_type->get_value_pointer(gogo, this->array_,
13334 this->is_lvalue_);
13335 Bexpression* ptr = valptr->get_backend(context);
13336 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
13337
13338 Type* ele_type = this->array_->type()->array_type()->element_type();
13339 Btype* ele_btype = ele_type->get_backend(gogo);
13340 ret = gogo->backend()->indirect_expression(ele_btype, ptr, false,
13341 loc);
13342 }
13343 return ret;
13344 }
13345
13346 // Slice expression.
13347
13348 Bexpression* end;
13349 if (this->end_->is_nil_expression())
13350 end = length;
13351 else
13352 {
13353 end = this->end_->get_backend(context);
13354 end = gogo->backend()->convert_expression(int_btype, end, loc);
13355 }
13356
13357 Bexpression* result_length =
13358 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
13359
13360 Bexpression* result_capacity =
13361 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
13362
13363 // If the new capacity is zero, don't change val. Otherwise we can
13364 // get a pointer to the next object in memory, keeping it live
13365 // unnecessarily. When the capacity is zero, the actual pointer
13366 // value doesn't matter.
13367 Bexpression* zero =
13368 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13369 Bexpression* cond =
13370 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
13371 loc);
13372 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
13373 cond, zero,
13374 start, loc);
13375 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
13376 this->is_lvalue_);
13377 Bexpression* val = valptr->get_backend(context);
13378 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
13379
13380 Btype* struct_btype = this->type()->get_backend(gogo);
13381 std::vector<Bexpression*> init;
13382 init.push_back(val);
13383 init.push_back(result_length);
13384 init.push_back(result_capacity);
13385
13386 return gogo->backend()->constructor_expression(struct_btype, init, loc);
13387 }
13388
13389 // Export an array index expression.
13390
13391 void
do_export(Export_function_body * efb) const13392 Array_index_expression::do_export(Export_function_body* efb) const
13393 {
13394 efb->write_c_string("(");
13395 this->array_->export_expression(efb);
13396 efb->write_c_string(")[");
13397
13398 Type* old_context = efb->type_context();
13399 efb->set_type_context(Type::lookup_integer_type("int"));
13400
13401 this->start_->export_expression(efb);
13402 if (this->end_ == NULL)
13403 go_assert(this->cap_ == NULL);
13404 else
13405 {
13406 efb->write_c_string(":");
13407 if (!this->end_->is_nil_expression())
13408 this->end_->export_expression(efb);
13409 if (this->cap_ != NULL)
13410 {
13411 efb->write_c_string(":");
13412 this->cap_->export_expression(efb);
13413 }
13414 }
13415
13416 efb->set_type_context(old_context);
13417
13418 efb->write_c_string("]");
13419 }
13420
13421 // Dump ast representation for an array index expression.
13422
13423 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13424 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13425 const
13426 {
13427 Index_expression::dump_index_expression(ast_dump_context, this->array_,
13428 this->start_, this->end_, this->cap_);
13429 }
13430
13431 // Make an array index expression. END and CAP may be NULL.
13432
13433 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)13434 Expression::make_array_index(Expression* array, Expression* start,
13435 Expression* end, Expression* cap,
13436 Location location)
13437 {
13438 return new Array_index_expression(array, start, end, cap, location);
13439 }
13440
13441 // Class String_index_expression.
13442
13443 // String index traversal.
13444
13445 int
do_traverse(Traverse * traverse)13446 String_index_expression::do_traverse(Traverse* traverse)
13447 {
13448 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
13449 return TRAVERSE_EXIT;
13450 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
13451 return TRAVERSE_EXIT;
13452 if (this->end_ != NULL)
13453 {
13454 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
13455 return TRAVERSE_EXIT;
13456 }
13457 return TRAVERSE_CONTINUE;
13458 }
13459
13460 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13461 String_index_expression::do_flatten(Gogo*, Named_object*,
13462 Statement_inserter* inserter)
13463 {
13464 if (this->is_flattened_)
13465 return this;
13466 this->is_flattened_ = true;
13467
13468 Location loc = this->location();
13469
13470 if (this->is_error_expression())
13471 return Expression::make_error(loc);
13472
13473 Expression* string = this->string_;
13474 Expression* start = this->start_;
13475 Expression* end = this->end_;
13476 if (string->is_error_expression()
13477 || string->type()->is_error_type()
13478 || start->is_error_expression()
13479 || start->type()->is_error_type()
13480 || (end != NULL
13481 && (end->is_error_expression() || end->type()->is_error_type())))
13482 {
13483 go_assert(saw_errors());
13484 return Expression::make_error(loc);
13485 }
13486
13487 Temporary_statement* temp;
13488 if (!string->is_multi_eval_safe())
13489 {
13490 temp = Statement::make_temporary(NULL, string, loc);
13491 inserter->insert(temp);
13492 this->string_ = Expression::make_temporary_reference(temp, loc);
13493 string = this->string_;
13494 }
13495 if (!start->is_multi_eval_safe())
13496 {
13497 temp = Statement::make_temporary(NULL, start, loc);
13498 inserter->insert(temp);
13499 this->start_ = Expression::make_temporary_reference(temp, loc);
13500 start = this->start_;
13501 }
13502 if (end != NULL
13503 && !end->is_nil_expression()
13504 && !end->is_multi_eval_safe())
13505 {
13506 temp = Statement::make_temporary(NULL, end, loc);
13507 inserter->insert(temp);
13508 this->end_ = Expression::make_temporary_reference(temp, loc);
13509 end = this->end_;
13510 }
13511
13512 Expression* len = Expression::make_string_info(string->copy(),
13513 STRING_INFO_LENGTH, loc);
13514 temp = Statement::make_temporary(NULL, len, loc);
13515 inserter->insert(temp);
13516 len = Expression::make_temporary_reference(temp, loc);
13517
13518 // The order of bounds checks here matches the order used by the gc
13519 // compiler, as tested by issue30116[u].go.
13520
13521 if (end != NULL && !end->is_nil_expression())
13522 {
13523 Expression::check_bounds(end, OPERATOR_LE, len,
13524 Runtime::PANIC_SLICE_ALEN,
13525 Runtime::PANIC_SLICE_ALEN_U,
13526 Runtime::PANIC_EXTEND_SLICE_ALEN,
13527 Runtime::PANIC_EXTEND_SLICE_ALEN_U,
13528 inserter, loc);
13529 Expression::check_bounds(start, OPERATOR_LE, end,
13530 Runtime::PANIC_SLICE_B,
13531 Runtime::PANIC_SLICE_B_U,
13532 Runtime::PANIC_EXTEND_SLICE_B,
13533 Runtime::PANIC_EXTEND_SLICE_B_U,
13534 inserter, loc);
13535 }
13536 else if (end != NULL)
13537 Expression::check_bounds(start, OPERATOR_LE, len,
13538 Runtime::PANIC_SLICE_B,
13539 Runtime::PANIC_SLICE_B_U,
13540 Runtime::PANIC_EXTEND_SLICE_B,
13541 Runtime::PANIC_EXTEND_SLICE_B_U,
13542 inserter, loc);
13543 else
13544 Expression::check_bounds(start, OPERATOR_LT, len,
13545 Runtime::PANIC_INDEX,
13546 Runtime::PANIC_INDEX_U,
13547 Runtime::PANIC_EXTEND_INDEX,
13548 Runtime::PANIC_EXTEND_INDEX_U,
13549 inserter, loc);
13550
13551 return this;
13552 }
13553
13554 // Return the type of a string index.
13555
13556 Type*
do_type()13557 String_index_expression::do_type()
13558 {
13559 if (this->end_ == NULL)
13560 return Type::lookup_integer_type("byte");
13561 else
13562 return this->string_->type();
13563 }
13564
13565 // Determine the type of a string index.
13566
13567 void
do_determine_type(const Type_context *)13568 String_index_expression::do_determine_type(const Type_context*)
13569 {
13570 this->string_->determine_type_no_context();
13571
13572 Type_context index_context(Type::lookup_integer_type("int"), false);
13573 this->start_->determine_type(&index_context);
13574 if (this->end_ != NULL)
13575 this->end_->determine_type(&index_context);
13576 }
13577
13578 // Check types of a string index.
13579
13580 void
do_check_types(Gogo *)13581 String_index_expression::do_check_types(Gogo*)
13582 {
13583 Numeric_constant nc;
13584 unsigned long v;
13585 if (this->start_->type()->integer_type() == NULL
13586 && !this->start_->type()->is_error()
13587 && (!this->start_->type()->is_abstract()
13588 || !this->start_->numeric_constant_value(&nc)
13589 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13590 this->report_error(_("index must be integer"));
13591 if (this->end_ != NULL
13592 && this->end_->type()->integer_type() == NULL
13593 && !this->end_->type()->is_error()
13594 && !this->end_->is_nil_expression()
13595 && !this->end_->is_error_expression()
13596 && (!this->end_->type()->is_abstract()
13597 || !this->end_->numeric_constant_value(&nc)
13598 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
13599 this->report_error(_("slice end must be integer"));
13600
13601 std::string sval;
13602 bool sval_valid = this->string_->string_constant_value(&sval);
13603
13604 Numeric_constant inc;
13605 mpz_t ival;
13606 bool ival_valid = false;
13607 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
13608 {
13609 ival_valid = true;
13610 if (mpz_sgn(ival) < 0
13611 || (sval_valid
13612 && (this->end_ == NULL
13613 ? mpz_cmp_ui(ival, sval.length()) >= 0
13614 : mpz_cmp_ui(ival, sval.length()) > 0)))
13615 {
13616 go_error_at(this->start_->location(), "string index out of bounds");
13617 this->set_is_error();
13618 }
13619 }
13620 if (this->end_ != NULL && !this->end_->is_nil_expression())
13621 {
13622 Numeric_constant enc;
13623 mpz_t eval;
13624 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
13625 {
13626 if (mpz_sgn(eval) < 0
13627 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
13628 {
13629 go_error_at(this->end_->location(), "string index out of bounds");
13630 this->set_is_error();
13631 }
13632 else if (ival_valid && mpz_cmp(ival, eval) > 0)
13633 this->report_error(_("inverted slice range"));
13634 mpz_clear(eval);
13635 }
13636 }
13637 if (ival_valid)
13638 mpz_clear(ival);
13639 }
13640
13641 // Get the backend representation for a string index.
13642
13643 Bexpression*
do_get_backend(Translate_context * context)13644 String_index_expression::do_get_backend(Translate_context* context)
13645 {
13646 Location loc = this->location();
13647 Gogo* gogo = context->gogo();
13648
13649 Type* int_type = Type::lookup_integer_type("int");
13650
13651 // It is possible that an error occurred earlier because the start index
13652 // cannot be represented as an integer type. In this case, we shouldn't
13653 // try casting the starting index into an integer since
13654 // Type_conversion_expression will fail to get the backend representation.
13655 // FIXME.
13656 if (this->start_->type()->integer_type() == NULL
13657 && !Type::are_convertible(int_type, this->start_->type(), NULL))
13658 {
13659 go_assert(saw_errors());
13660 return context->backend()->error_expression();
13661 }
13662
13663 go_assert(this->string_->is_multi_eval_safe());
13664 go_assert(this->start_->is_multi_eval_safe());
13665
13666 Expression* start = Expression::make_cast(int_type, this->start_, loc);
13667 Bfunction* bfn = context->function()->func_value()->get_decl();
13668
13669 Expression* length =
13670 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
13671 Expression* bytes =
13672 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
13673
13674 Bexpression* bstart = start->get_backend(context);
13675 Bexpression* ptr = bytes->get_backend(context);
13676
13677 if (this->end_ == NULL)
13678 {
13679 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
13680 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
13681 return gogo->backend()->indirect_expression(ubtype, ptr, false, loc);
13682 }
13683
13684 Expression* end = NULL;
13685 if (this->end_->is_nil_expression())
13686 end = length;
13687 else
13688 {
13689 go_assert(this->end_->is_multi_eval_safe());
13690 end = Expression::make_cast(int_type, this->end_, loc);
13691 }
13692
13693 end = end->copy();
13694 Bexpression* bend = end->get_backend(context);
13695 Bexpression* new_length =
13696 gogo->backend()->binary_expression(OPERATOR_MINUS, bend, bstart, loc);
13697
13698 // If the new length is zero, don't change pointer. Otherwise we can
13699 // get a pointer to the next object in memory, keeping it live
13700 // unnecessarily. When the length is zero, the actual pointer
13701 // value doesn't matter.
13702 Btype* int_btype = int_type->get_backend(gogo);
13703 Bexpression* zero =
13704 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
13705 Bexpression* cond =
13706 gogo->backend()->binary_expression(OPERATOR_EQEQ, new_length, zero,
13707 loc);
13708 Bexpression* offset =
13709 gogo->backend()->conditional_expression(bfn, int_btype, cond, zero,
13710 bstart, loc);
13711
13712 ptr = gogo->backend()->pointer_offset_expression(ptr, offset, loc);
13713
13714 Btype* str_btype = this->type()->get_backend(gogo);
13715 std::vector<Bexpression*> init;
13716 init.push_back(ptr);
13717 init.push_back(new_length);
13718 return gogo->backend()->constructor_expression(str_btype, init, loc);
13719 }
13720
13721 // Export a string index expression.
13722
13723 void
do_export(Export_function_body * efb) const13724 String_index_expression::do_export(Export_function_body* efb) const
13725 {
13726 efb->write_c_string("(");
13727 this->string_->export_expression(efb);
13728 efb->write_c_string(")[");
13729
13730 Type* old_context = efb->type_context();
13731 efb->set_type_context(Type::lookup_integer_type("int"));
13732
13733 this->start_->export_expression(efb);
13734 if (this->end_ != NULL)
13735 {
13736 efb->write_c_string(":");
13737 if (!this->end_->is_nil_expression())
13738 this->end_->export_expression(efb);
13739 }
13740
13741 efb->set_type_context(old_context);
13742
13743 efb->write_c_string("]");
13744 }
13745
13746 // Dump ast representation for a string index expression.
13747
13748 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13749 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13750 const
13751 {
13752 Index_expression::dump_index_expression(ast_dump_context, this->string_,
13753 this->start_, this->end_, NULL);
13754 }
13755
13756 // Make a string index expression. END may be NULL.
13757
13758 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)13759 Expression::make_string_index(Expression* string, Expression* start,
13760 Expression* end, Location location)
13761 {
13762 return new String_index_expression(string, start, end, location);
13763 }
13764
13765 // Class Map_index.
13766
13767 // Get the type of the map.
13768
13769 Map_type*
get_map_type() const13770 Map_index_expression::get_map_type() const
13771 {
13772 Map_type* mt = this->map_->type()->map_type();
13773 if (mt == NULL)
13774 go_assert(saw_errors());
13775 return mt;
13776 }
13777
13778 // Map index traversal.
13779
13780 int
do_traverse(Traverse * traverse)13781 Map_index_expression::do_traverse(Traverse* traverse)
13782 {
13783 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
13784 return TRAVERSE_EXIT;
13785 return Expression::traverse(&this->index_, traverse);
13786 }
13787
13788 // We need to pass in a pointer to the key, so flatten the index into a
13789 // temporary variable if it isn't already. The value pointer will be
13790 // dereferenced and checked for nil, so flatten into a temporary to avoid
13791 // recomputation.
13792
13793 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13794 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
13795 Statement_inserter* inserter)
13796 {
13797 Location loc = this->location();
13798 Map_type* mt = this->get_map_type();
13799 if (this->index()->is_error_expression()
13800 || this->index()->type()->is_error_type()
13801 || mt->is_error_type())
13802 {
13803 go_assert(saw_errors());
13804 return Expression::make_error(loc);
13805 }
13806
13807 // Avoid copy for string([]byte) conversions used in map keys.
13808 // mapaccess doesn't keep the reference, so this is safe.
13809 Type_conversion_expression* ce = this->index_->conversion_expression();
13810 if (ce != NULL && ce->type()->is_string_type()
13811 && ce->expr()->type()->is_slice_type())
13812 ce->set_no_copy(true);
13813
13814 if (!Type::are_identical(mt->key_type(), this->index_->type(),
13815 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
13816 NULL))
13817 {
13818 if (this->index_->type()->interface_type() != NULL
13819 && !this->index_->is_multi_eval_safe())
13820 {
13821 Temporary_statement* temp =
13822 Statement::make_temporary(NULL, this->index_, loc);
13823 inserter->insert(temp);
13824 this->index_ = Expression::make_temporary_reference(temp, loc);
13825 }
13826 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
13827 this->index_, loc);
13828 }
13829
13830 if (!this->index_->is_multi_eval_safe())
13831 {
13832 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
13833 loc);
13834 inserter->insert(temp);
13835 this->index_ = Expression::make_temporary_reference(temp, loc);
13836 }
13837
13838 if (this->value_pointer_ == NULL)
13839 this->get_value_pointer(gogo);
13840 if (this->value_pointer_->is_error_expression()
13841 || this->value_pointer_->type()->is_error_type())
13842 return Expression::make_error(loc);
13843 if (!this->value_pointer_->is_multi_eval_safe())
13844 {
13845 Temporary_statement* temp =
13846 Statement::make_temporary(NULL, this->value_pointer_, loc);
13847 inserter->insert(temp);
13848 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
13849 }
13850
13851 return this;
13852 }
13853
13854 // Return the type of a map index.
13855
13856 Type*
do_type()13857 Map_index_expression::do_type()
13858 {
13859 Map_type* mt = this->get_map_type();
13860 if (mt == NULL)
13861 return Type::make_error_type();
13862 return mt->val_type();
13863 }
13864
13865 // Fix the type of a map index.
13866
13867 void
do_determine_type(const Type_context *)13868 Map_index_expression::do_determine_type(const Type_context*)
13869 {
13870 this->map_->determine_type_no_context();
13871 Map_type* mt = this->get_map_type();
13872 Type* key_type = mt == NULL ? NULL : mt->key_type();
13873 Type_context subcontext(key_type, false);
13874 this->index_->determine_type(&subcontext);
13875 }
13876
13877 // Check types of a map index.
13878
13879 void
do_check_types(Gogo *)13880 Map_index_expression::do_check_types(Gogo*)
13881 {
13882 std::string reason;
13883 Map_type* mt = this->get_map_type();
13884 if (mt == NULL)
13885 return;
13886 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
13887 {
13888 if (reason.empty())
13889 this->report_error(_("incompatible type for map index"));
13890 else
13891 {
13892 go_error_at(this->location(), "incompatible type for map index (%s)",
13893 reason.c_str());
13894 this->set_is_error();
13895 }
13896 }
13897 }
13898
13899 // Add explicit type conversions.
13900
13901 void
do_add_conversions()13902 Map_index_expression::do_add_conversions()
13903 {
13904 Map_type* mt = this->get_map_type();
13905 if (mt == NULL)
13906 return;
13907 Type* lt = mt->key_type();
13908 Type* rt = this->index_->type();
13909 if (!Type::are_identical(lt, rt, 0, NULL)
13910 && lt->interface_type() != NULL)
13911 this->index_ = Expression::make_cast(lt, this->index_, this->location());
13912 }
13913
13914 // Get the backend representation for a map index.
13915
13916 Bexpression*
do_get_backend(Translate_context * context)13917 Map_index_expression::do_get_backend(Translate_context* context)
13918 {
13919 Map_type* type = this->get_map_type();
13920 if (type == NULL)
13921 {
13922 go_assert(saw_errors());
13923 return context->backend()->error_expression();
13924 }
13925
13926 go_assert(this->value_pointer_ != NULL
13927 && this->value_pointer_->is_multi_eval_safe());
13928
13929 Expression* val = Expression::make_dereference(this->value_pointer_,
13930 NIL_CHECK_NOT_NEEDED,
13931 this->location());
13932 return val->get_backend(context);
13933 }
13934
13935 // Get an expression for the map index. This returns an expression
13936 // that evaluates to a pointer to a value. If the key is not in the
13937 // map, the pointer will point to a zero value.
13938
13939 Expression*
get_value_pointer(Gogo * gogo)13940 Map_index_expression::get_value_pointer(Gogo* gogo)
13941 {
13942 if (this->value_pointer_ == NULL)
13943 {
13944 Map_type* type = this->get_map_type();
13945 if (type == NULL)
13946 {
13947 go_assert(saw_errors());
13948 return Expression::make_error(this->location());
13949 }
13950
13951 Location loc = this->location();
13952 Expression* map_ref = this->map_;
13953
13954 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
13955 this->index_,
13956 loc);
13957
13958 Expression* type_expr = Expression::make_type_descriptor(type, loc);
13959 Expression* zero = type->fat_zero_value(gogo);
13960 Expression* map_index;
13961 if (zero == NULL)
13962 {
13963 Runtime::Function code;
13964 Expression* key;
13965 switch (type->algorithm(gogo))
13966 {
13967 case Map_type::MAP_ALG_FAST32:
13968 case Map_type::MAP_ALG_FAST32PTR:
13969 {
13970 Type* uint32_type = Type::lookup_integer_type("uint32");
13971 Type* uint32_ptr_type = Type::make_pointer_type(uint32_type);
13972 key = Expression::make_unsafe_cast(uint32_ptr_type, index_ptr,
13973 loc);
13974 key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13975 loc);
13976 code = Runtime::MAPACCESS1_FAST32;
13977 break;
13978 }
13979 case Map_type::MAP_ALG_FAST64:
13980 case Map_type::MAP_ALG_FAST64PTR:
13981 {
13982 Type* uint64_type = Type::lookup_integer_type("uint64");
13983 Type* uint64_ptr_type = Type::make_pointer_type(uint64_type);
13984 key = Expression::make_unsafe_cast(uint64_ptr_type, index_ptr,
13985 loc);
13986 key = Expression::make_dereference(key, NIL_CHECK_NOT_NEEDED,
13987 loc);
13988 code = Runtime::MAPACCESS1_FAST64;
13989 break;
13990 }
13991 case Map_type::MAP_ALG_FASTSTR:
13992 key = this->index_;
13993 code = Runtime::MAPACCESS1_FASTSTR;
13994 break;
13995 default:
13996 key = index_ptr;
13997 code = Runtime::MAPACCESS1;
13998 break;
13999 }
14000 map_index = Runtime::make_call(code, loc, 3,
14001 type_expr, map_ref, key);
14002 }
14003 else
14004 map_index = Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
14005 type_expr, map_ref, index_ptr, zero);
14006
14007 Type* val_type = type->val_type();
14008 this->value_pointer_ =
14009 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
14010 map_index, this->location());
14011 }
14012
14013 return this->value_pointer_;
14014 }
14015
14016 // Export a map index expression.
14017
14018 void
do_export(Export_function_body * efb) const14019 Map_index_expression::do_export(Export_function_body* efb) const
14020 {
14021 efb->write_c_string("(");
14022 this->map_->export_expression(efb);
14023 efb->write_c_string(")[");
14024
14025 Type* old_context = efb->type_context();
14026 efb->set_type_context(this->get_map_type()->key_type());
14027
14028 this->index_->export_expression(efb);
14029
14030 efb->set_type_context(old_context);
14031
14032 efb->write_c_string("]");
14033 }
14034
14035 // Dump ast representation for a map index expression
14036
14037 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14038 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14039 const
14040 {
14041 Index_expression::dump_index_expression(ast_dump_context, this->map_,
14042 this->index_, NULL, NULL);
14043 }
14044
14045 // Make a map index expression.
14046
14047 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)14048 Expression::make_map_index(Expression* map, Expression* index,
14049 Location location)
14050 {
14051 return new Map_index_expression(map, index, location);
14052 }
14053
14054 // Class Field_reference_expression.
14055
14056 // Lower a field reference expression. There is nothing to lower, but
14057 // this is where we generate the tracking information for fields with
14058 // the magic go:"track" tag.
14059
14060 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)14061 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
14062 Statement_inserter* inserter, int)
14063 {
14064 Struct_type* struct_type = this->expr_->type()->struct_type();
14065 if (struct_type == NULL)
14066 {
14067 // Error will be reported elsewhere.
14068 return this;
14069 }
14070 const Struct_field* field = struct_type->field(this->field_index_);
14071 if (field == NULL)
14072 return this;
14073 if (!field->has_tag())
14074 return this;
14075 if (field->tag().find("go:\"track\"") == std::string::npos)
14076 return this;
14077
14078 // References from functions generated by the compiler don't count.
14079 if (function != NULL && function->func_value()->is_type_specific_function())
14080 return this;
14081
14082 // We have found a reference to a tracked field. Build a call to
14083 // the runtime function __go_fieldtrack with a string that describes
14084 // the field. FIXME: We should only call this once per referenced
14085 // field per function, not once for each reference to the field.
14086
14087 if (this->called_fieldtrack_)
14088 return this;
14089 this->called_fieldtrack_ = true;
14090
14091 Location loc = this->location();
14092
14093 std::string s = "fieldtrack \"";
14094 Named_type* nt = this->expr_->type()->unalias()->named_type();
14095 if (nt == NULL || nt->named_object()->package() == NULL)
14096 s.append(gogo->pkgpath());
14097 else
14098 s.append(nt->named_object()->package()->pkgpath());
14099 s.push_back('.');
14100 if (nt != NULL)
14101 s.append(Gogo::unpack_hidden_name(nt->name()));
14102 s.push_back('.');
14103 s.append(Gogo::unpack_hidden_name(field->field_name()));
14104 s.push_back('"');
14105
14106 // We can't use a string here, because internally a string holds a
14107 // pointer to the actual bytes; when the linker garbage collects the
14108 // string, it won't garbage collect the bytes. So we use a
14109 // [...]byte.
14110
14111 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
14112
14113 Type* byte_type = Type::lookup_integer_type("byte");
14114 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
14115 array_type->set_is_array_incomparable();
14116
14117 Expression_list* bytes = new Expression_list();
14118 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
14119 {
14120 unsigned char c = static_cast<unsigned char>(*p);
14121 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
14122 }
14123
14124 Expression* e = Expression::make_composite_literal(array_type, 0, false,
14125 bytes, false, loc);
14126
14127 Variable* var = new Variable(array_type, e, true, false, false, loc);
14128
14129 static int count;
14130 char buf[50];
14131 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
14132 ++count;
14133
14134 Named_object* no = gogo->add_variable(buf, var);
14135 e = Expression::make_var_reference(no, loc);
14136 e = Expression::make_unary(OPERATOR_AND, e, loc);
14137
14138 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
14139 gogo->lower_expression(function, inserter, &call);
14140 inserter->insert(Statement::make_statement(call, false));
14141
14142 // Put this function, and the global variable we just created, into
14143 // unique sections. This will permit the linker to garbage collect
14144 // them if they are not referenced. The effect is that the only
14145 // strings, indicating field references, that will wind up in the
14146 // executable will be those for functions that are actually needed.
14147 if (function != NULL)
14148 function->func_value()->set_in_unique_section();
14149 var->set_in_unique_section();
14150
14151 return this;
14152 }
14153
14154 // Return the type of a field reference.
14155
14156 Type*
do_type()14157 Field_reference_expression::do_type()
14158 {
14159 Type* type = this->expr_->type();
14160 if (type->is_error())
14161 return type;
14162 Struct_type* struct_type = type->struct_type();
14163 go_assert(struct_type != NULL);
14164 return struct_type->field(this->field_index_)->type();
14165 }
14166
14167 // Check the types for a field reference.
14168
14169 void
do_check_types(Gogo *)14170 Field_reference_expression::do_check_types(Gogo*)
14171 {
14172 Type* type = this->expr_->type();
14173 if (type->is_error())
14174 return;
14175 Struct_type* struct_type = type->struct_type();
14176 go_assert(struct_type != NULL);
14177 go_assert(struct_type->field(this->field_index_) != NULL);
14178 }
14179
14180 // Get the backend representation for a field reference.
14181
14182 Bexpression*
do_get_backend(Translate_context * context)14183 Field_reference_expression::do_get_backend(Translate_context* context)
14184 {
14185 Bexpression* bstruct = this->expr_->get_backend(context);
14186 return context->gogo()->backend()->struct_field_expression(bstruct,
14187 this->field_index_,
14188 this->location());
14189 }
14190
14191 // Dump ast representation for a field reference expression.
14192
14193 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14194 Field_reference_expression::do_dump_expression(
14195 Ast_dump_context* ast_dump_context) const
14196 {
14197 this->expr_->dump_expression(ast_dump_context);
14198 ast_dump_context->ostream() << "." << this->field_index_;
14199 }
14200
14201 // Make a reference to a qualified identifier in an expression.
14202
14203 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)14204 Expression::make_field_reference(Expression* expr, unsigned int field_index,
14205 Location location)
14206 {
14207 return new Field_reference_expression(expr, field_index, location);
14208 }
14209
14210 // Class Interface_field_reference_expression.
14211
14212 // Return an expression for the pointer to the function to call.
14213
14214 Expression*
get_function()14215 Interface_field_reference_expression::get_function()
14216 {
14217 Expression* ref = this->expr_;
14218 Location loc = this->location();
14219 if (ref->type()->points_to() != NULL)
14220 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
14221
14222 Expression* mtable =
14223 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
14224 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
14225
14226 std::string name = Gogo::unpack_hidden_name(this->name_);
14227 unsigned int index;
14228 const Struct_field* field = mtable_type->find_local_field(name, &index);
14229 go_assert(field != NULL);
14230
14231 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
14232 return Expression::make_field_reference(mtable, index, loc);
14233 }
14234
14235 // Return an expression for the first argument to pass to the interface
14236 // function.
14237
14238 Expression*
get_underlying_object()14239 Interface_field_reference_expression::get_underlying_object()
14240 {
14241 Expression* expr = this->expr_;
14242 if (expr->type()->points_to() != NULL)
14243 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
14244 this->location());
14245 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
14246 this->location());
14247 }
14248
14249 // Traversal.
14250
14251 int
do_traverse(Traverse * traverse)14252 Interface_field_reference_expression::do_traverse(Traverse* traverse)
14253 {
14254 return Expression::traverse(&this->expr_, traverse);
14255 }
14256
14257 // Lower the expression. If this expression is not called, we need to
14258 // evaluate the expression twice when converting to the backend
14259 // interface. So introduce a temporary variable if necessary.
14260
14261 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14262 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
14263 Statement_inserter* inserter)
14264 {
14265 if (this->expr_->is_error_expression()
14266 || this->expr_->type()->is_error_type())
14267 {
14268 go_assert(saw_errors());
14269 return Expression::make_error(this->location());
14270 }
14271
14272 if (!this->expr_->is_multi_eval_safe())
14273 {
14274 Temporary_statement* temp =
14275 Statement::make_temporary(NULL, this->expr_, this->location());
14276 inserter->insert(temp);
14277 this->expr_ = Expression::make_temporary_reference(temp, this->location());
14278 }
14279 return this;
14280 }
14281
14282 // Return the type of an interface field reference.
14283
14284 Type*
do_type()14285 Interface_field_reference_expression::do_type()
14286 {
14287 Type* expr_type = this->expr_->type();
14288
14289 Type* points_to = expr_type->points_to();
14290 if (points_to != NULL)
14291 expr_type = points_to;
14292
14293 Interface_type* interface_type = expr_type->interface_type();
14294 if (interface_type == NULL)
14295 return Type::make_error_type();
14296
14297 const Typed_identifier* method = interface_type->find_method(this->name_);
14298 if (method == NULL)
14299 return Type::make_error_type();
14300
14301 return method->type();
14302 }
14303
14304 // Determine types.
14305
14306 void
do_determine_type(const Type_context *)14307 Interface_field_reference_expression::do_determine_type(const Type_context*)
14308 {
14309 this->expr_->determine_type_no_context();
14310 }
14311
14312 // Check the types for an interface field reference.
14313
14314 void
do_check_types(Gogo *)14315 Interface_field_reference_expression::do_check_types(Gogo*)
14316 {
14317 Type* type = this->expr_->type();
14318
14319 Type* points_to = type->points_to();
14320 if (points_to != NULL)
14321 type = points_to;
14322
14323 Interface_type* interface_type = type->interface_type();
14324 if (interface_type == NULL)
14325 {
14326 if (!type->is_error_type())
14327 this->report_error(_("expected interface or pointer to interface"));
14328 }
14329 else
14330 {
14331 const Typed_identifier* method =
14332 interface_type->find_method(this->name_);
14333 if (method == NULL)
14334 {
14335 go_error_at(this->location(), "method %qs not in interface",
14336 Gogo::message_name(this->name_).c_str());
14337 this->set_is_error();
14338 }
14339 }
14340 }
14341
14342 // If an interface field reference is not simply called, then it is
14343 // represented as a closure. The closure will hold a single variable,
14344 // the value of the interface on which the method should be called.
14345 // The function will be a simple thunk that pulls the value from the
14346 // closure and calls the method with the remaining arguments.
14347
14348 // Because method values are not common, we don't build all thunks for
14349 // all possible interface methods, but instead only build them as we
14350 // need them. In particular, we even build them on demand for
14351 // interface methods defined in other packages.
14352
14353 Interface_field_reference_expression::Interface_method_thunks
14354 Interface_field_reference_expression::interface_method_thunks;
14355
14356 // Find or create the thunk to call method NAME on TYPE.
14357
14358 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)14359 Interface_field_reference_expression::create_thunk(Gogo* gogo,
14360 Interface_type* type,
14361 const std::string& name)
14362 {
14363 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
14364 std::pair<Interface_method_thunks::iterator, bool> ins =
14365 Interface_field_reference_expression::interface_method_thunks.insert(val);
14366 if (ins.second)
14367 {
14368 // This is the first time we have seen this interface.
14369 ins.first->second = new Method_thunks();
14370 }
14371
14372 for (Method_thunks::const_iterator p = ins.first->second->begin();
14373 p != ins.first->second->end();
14374 p++)
14375 if (p->first == name)
14376 return p->second;
14377
14378 Location loc = type->location();
14379
14380 const Typed_identifier* method_id = type->find_method(name);
14381 if (method_id == NULL)
14382 return Named_object::make_erroneous_name(gogo->thunk_name());
14383
14384 Function_type* orig_fntype = method_id->type()->function_type();
14385 if (orig_fntype == NULL)
14386 return Named_object::make_erroneous_name(gogo->thunk_name());
14387
14388 Struct_field_list* sfl = new Struct_field_list();
14389 // The type here is wrong--it should be the C function type. But it
14390 // doesn't really matter.
14391 Type* vt = Type::make_pointer_type(Type::make_void_type());
14392 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
14393 sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
14394 Struct_type* st = Type::make_struct_type(sfl, loc);
14395 st->set_is_struct_incomparable();
14396 Type* closure_type = Type::make_pointer_type(st);
14397
14398 Function_type* new_fntype = orig_fntype->copy_with_names();
14399
14400 std::string thunk_name = gogo->thunk_name();
14401 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
14402 false, loc);
14403
14404 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
14405 cvar->set_is_used();
14406 cvar->set_is_closure();
14407 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
14408 NULL, cvar);
14409 new_no->func_value()->set_closure_var(cp);
14410
14411 gogo->start_block(loc);
14412
14413 // Field 0 of the closure is the function code pointer, field 1 is
14414 // the value on which to invoke the method.
14415 Expression* arg = Expression::make_var_reference(cp, loc);
14416 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
14417 arg = Expression::make_field_reference(arg, 1, loc);
14418
14419 Expression *ifre = Expression::make_interface_field_reference(arg, name,
14420 loc);
14421
14422 const Typed_identifier_list* orig_params = orig_fntype->parameters();
14423 Expression_list* args;
14424 if (orig_params == NULL || orig_params->empty())
14425 args = NULL;
14426 else
14427 {
14428 const Typed_identifier_list* new_params = new_fntype->parameters();
14429 args = new Expression_list();
14430 for (Typed_identifier_list::const_iterator p = new_params->begin();
14431 p != new_params->end();
14432 ++p)
14433 {
14434 Named_object* p_no = gogo->lookup(p->name(), NULL);
14435 go_assert(p_no != NULL
14436 && p_no->is_variable()
14437 && p_no->var_value()->is_parameter());
14438 args->push_back(Expression::make_var_reference(p_no, loc));
14439 }
14440 }
14441
14442 Call_expression* call = Expression::make_call(ifre, args,
14443 orig_fntype->is_varargs(),
14444 loc);
14445 call->set_varargs_are_lowered();
14446
14447 Statement* s = Statement::make_return_from_call(call, loc);
14448 gogo->add_statement(s);
14449 Block* b = gogo->finish_block(loc);
14450 gogo->add_block(b, loc);
14451 gogo->lower_block(new_no, b);
14452 gogo->flatten_block(new_no, b);
14453 gogo->finish_function(loc);
14454
14455 ins.first->second->push_back(std::make_pair(name, new_no));
14456 return new_no;
14457 }
14458
14459 // Get the backend representation for a method value.
14460
14461 Bexpression*
do_get_backend(Translate_context * context)14462 Interface_field_reference_expression::do_get_backend(Translate_context* context)
14463 {
14464 Interface_type* type = this->expr_->type()->interface_type();
14465 if (type == NULL)
14466 {
14467 go_assert(saw_errors());
14468 return context->backend()->error_expression();
14469 }
14470
14471 Named_object* thunk =
14472 Interface_field_reference_expression::create_thunk(context->gogo(),
14473 type, this->name_);
14474 if (thunk->is_erroneous())
14475 {
14476 go_assert(saw_errors());
14477 return context->backend()->error_expression();
14478 }
14479
14480 // FIXME: We should lower this earlier, but we can't it lower it in
14481 // the lowering pass because at that point we don't know whether we
14482 // need to create the thunk or not. If the expression is called, we
14483 // don't need the thunk.
14484
14485 Location loc = this->location();
14486
14487 Struct_field_list* fields = new Struct_field_list();
14488 fields->push_back(Struct_field(Typed_identifier("fn",
14489 thunk->func_value()->type(),
14490 loc)));
14491 fields->push_back(Struct_field(Typed_identifier("val",
14492 this->expr_->type(),
14493 loc)));
14494 Struct_type* st = Type::make_struct_type(fields, loc);
14495 st->set_is_struct_incomparable();
14496
14497 Expression_list* vals = new Expression_list();
14498 vals->push_back(Expression::make_func_code_reference(thunk, loc));
14499 vals->push_back(this->expr_);
14500
14501 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
14502 Bexpression* bclosure =
14503 Expression::make_heap_expression(expr, loc)->get_backend(context);
14504
14505 Gogo* gogo = context->gogo();
14506 Btype* btype = this->type()->get_backend(gogo);
14507 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
14508
14509 Expression* nil_check =
14510 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
14511 Expression::make_nil(loc), loc);
14512 Bexpression* bnil_check = nil_check->get_backend(context);
14513
14514 Expression* crash = Runtime::make_call(Runtime::PANIC_MEM, loc, 0);
14515 Bexpression* bcrash = crash->get_backend(context);
14516
14517 Bfunction* bfn = context->function()->func_value()->get_decl();
14518 Bexpression* bcond =
14519 gogo->backend()->conditional_expression(bfn, NULL,
14520 bnil_check, bcrash, NULL, loc);
14521 Bfunction* bfunction = context->function()->func_value()->get_decl();
14522 Bstatement* cond_statement =
14523 gogo->backend()->expression_statement(bfunction, bcond);
14524 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
14525 }
14526
14527 // Dump ast representation for an interface field reference.
14528
14529 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14530 Interface_field_reference_expression::do_dump_expression(
14531 Ast_dump_context* ast_dump_context) const
14532 {
14533 this->expr_->dump_expression(ast_dump_context);
14534 ast_dump_context->ostream() << "." << this->name_;
14535 }
14536
14537 // Make a reference to a field in an interface.
14538
14539 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)14540 Expression::make_interface_field_reference(Expression* expr,
14541 const std::string& field,
14542 Location location)
14543 {
14544 return new Interface_field_reference_expression(expr, field, location);
14545 }
14546
14547 // A general selector. This is a Parser_expression for LEFT.NAME. It
14548 // is lowered after we know the type of the left hand side.
14549
14550 class Selector_expression : public Parser_expression
14551 {
14552 public:
Selector_expression(Expression * left,const std::string & name,Location location)14553 Selector_expression(Expression* left, const std::string& name,
14554 Location location)
14555 : Parser_expression(EXPRESSION_SELECTOR, location),
14556 left_(left), name_(name)
14557 { }
14558
14559 protected:
14560 int
do_traverse(Traverse * traverse)14561 do_traverse(Traverse* traverse)
14562 { return Expression::traverse(&this->left_, traverse); }
14563
14564 Expression*
14565 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
14566
14567 Expression*
do_copy()14568 do_copy()
14569 {
14570 return new Selector_expression(this->left_->copy(), this->name_,
14571 this->location());
14572 }
14573
14574 void
14575 do_dump_expression(Ast_dump_context* ast_dump_context) const;
14576
14577 private:
14578 Expression*
14579 lower_method_expression(Gogo*);
14580
14581 // The expression on the left hand side.
14582 Expression* left_;
14583 // The name on the right hand side.
14584 std::string name_;
14585 };
14586
14587 // Lower a selector expression once we know the real type of the left
14588 // hand side.
14589
14590 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)14591 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
14592 int)
14593 {
14594 Expression* left = this->left_;
14595 if (left->is_type_expression())
14596 return this->lower_method_expression(gogo);
14597 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
14598 this->location());
14599 }
14600
14601 // Lower a method expression T.M or (*T).M. We turn this into a
14602 // function literal.
14603
14604 Expression*
lower_method_expression(Gogo * gogo)14605 Selector_expression::lower_method_expression(Gogo* gogo)
14606 {
14607 Location location = this->location();
14608 Type* left_type = this->left_->type();
14609 Type* type = left_type;
14610 const std::string& name(this->name_);
14611
14612 bool is_pointer;
14613 if (type->points_to() == NULL)
14614 is_pointer = false;
14615 else
14616 {
14617 is_pointer = true;
14618 type = type->points_to();
14619 }
14620
14621 Named_type* nt = type->named_type();
14622 Struct_type* st = type->struct_type();
14623 bool is_ambiguous;
14624 Method* method = NULL;
14625 if (nt != NULL)
14626 method = nt->method_function(name, &is_ambiguous);
14627 else if (st != NULL)
14628 method = st->method_function(name, &is_ambiguous);
14629 const Typed_identifier* imethod = NULL;
14630 if (method == NULL && !is_pointer)
14631 {
14632 Interface_type* it = type->interface_type();
14633 if (it != NULL)
14634 imethod = it->find_method(name);
14635 }
14636
14637 if ((method == NULL && imethod == NULL)
14638 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
14639 {
14640 if (nt != NULL)
14641 {
14642 if (!is_ambiguous)
14643 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
14644 is_pointer ? "*" : "",
14645 nt->message_name().c_str(),
14646 Gogo::message_name(name).c_str());
14647 else
14648 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
14649 Gogo::message_name(name).c_str(),
14650 is_pointer ? "*" : "",
14651 nt->message_name().c_str());
14652 }
14653 else
14654 {
14655 if (!is_ambiguous)
14656 go_error_at(location, "type has no method %<%s%>",
14657 Gogo::message_name(name).c_str());
14658 else
14659 go_error_at(location, "method %<%s%> is ambiguous",
14660 Gogo::message_name(name).c_str());
14661 }
14662 return Expression::make_error(location);
14663 }
14664
14665 if (method != NULL && !is_pointer && !method->is_value_method())
14666 {
14667 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
14668 nt->message_name().c_str(),
14669 Gogo::message_name(name).c_str());
14670 return Expression::make_error(location);
14671 }
14672
14673 // Build a new function type in which the receiver becomes the first
14674 // argument.
14675 Function_type* method_type;
14676 if (method != NULL)
14677 {
14678 method_type = method->type();
14679 go_assert(method_type->is_method());
14680 }
14681 else
14682 {
14683 method_type = imethod->type()->function_type();
14684 go_assert(method_type != NULL && !method_type->is_method());
14685 }
14686
14687 const char* const receiver_name = "$this";
14688 Typed_identifier_list* parameters = new Typed_identifier_list();
14689 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
14690 location));
14691
14692 const Typed_identifier_list* method_parameters = method_type->parameters();
14693 if (method_parameters != NULL)
14694 {
14695 int i = 0;
14696 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
14697 p != method_parameters->end();
14698 ++p, ++i)
14699 {
14700 if (!p->name().empty())
14701 parameters->push_back(*p);
14702 else
14703 {
14704 char buf[20];
14705 snprintf(buf, sizeof buf, "$param%d", i);
14706 parameters->push_back(Typed_identifier(buf, p->type(),
14707 p->location()));
14708 }
14709 }
14710 }
14711
14712 const Typed_identifier_list* method_results = method_type->results();
14713 Typed_identifier_list* results;
14714 if (method_results == NULL)
14715 results = NULL;
14716 else
14717 {
14718 results = new Typed_identifier_list();
14719 for (Typed_identifier_list::const_iterator p = method_results->begin();
14720 p != method_results->end();
14721 ++p)
14722 results->push_back(*p);
14723 }
14724
14725 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
14726 location);
14727 if (method_type->is_varargs())
14728 fntype->set_is_varargs();
14729
14730 // We generate methods which always takes a pointer to the receiver
14731 // as their first argument. If this is for a pointer type, we can
14732 // simply reuse the existing function. We use an internal hack to
14733 // get the right type.
14734 // FIXME: This optimization is disabled because it doesn't yet work
14735 // with function descriptors when the method expression is not
14736 // directly called.
14737 if (method != NULL && is_pointer && false)
14738 {
14739 Named_object* mno = (method->needs_stub_method()
14740 ? method->stub_object()
14741 : method->named_object());
14742 Expression* f = Expression::make_func_reference(mno, NULL, location);
14743 f = Expression::make_cast(fntype, f, location);
14744 Type_conversion_expression* tce =
14745 static_cast<Type_conversion_expression*>(f);
14746 tce->set_may_convert_function_types();
14747 return f;
14748 }
14749
14750 Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
14751 location);
14752
14753 Named_object* vno = gogo->lookup(receiver_name, NULL);
14754 go_assert(vno != NULL);
14755 Expression* ve = Expression::make_var_reference(vno, location);
14756 Expression* bm;
14757 if (method != NULL)
14758 bm = Type::bind_field_or_method(gogo, type, ve, name, location);
14759 else
14760 bm = Expression::make_interface_field_reference(ve, name, location);
14761
14762 // Even though we found the method above, if it has an error type we
14763 // may see an error here.
14764 if (bm->is_error_expression())
14765 {
14766 gogo->finish_function(location);
14767 return bm;
14768 }
14769
14770 Expression_list* args;
14771 if (parameters->size() <= 1)
14772 args = NULL;
14773 else
14774 {
14775 args = new Expression_list();
14776 Typed_identifier_list::const_iterator p = parameters->begin();
14777 ++p;
14778 for (; p != parameters->end(); ++p)
14779 {
14780 vno = gogo->lookup(p->name(), NULL);
14781 go_assert(vno != NULL);
14782 args->push_back(Expression::make_var_reference(vno, location));
14783 }
14784 }
14785
14786 gogo->start_block(location);
14787
14788 Call_expression* call = Expression::make_call(bm, args,
14789 method_type->is_varargs(),
14790 location);
14791
14792 Statement* s = Statement::make_return_from_call(call, location);
14793 gogo->add_statement(s);
14794
14795 Block* b = gogo->finish_block(location);
14796
14797 gogo->add_block(b, location);
14798
14799 // Lower the call in case there are multiple results.
14800 gogo->lower_block(no, b);
14801 gogo->flatten_block(no, b);
14802
14803 gogo->finish_function(location);
14804
14805 return Expression::make_func_reference(no, NULL, location);
14806 }
14807
14808 // Dump the ast for a selector expression.
14809
14810 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14811 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14812 const
14813 {
14814 ast_dump_context->dump_expression(this->left_);
14815 ast_dump_context->ostream() << ".";
14816 ast_dump_context->ostream() << this->name_;
14817 }
14818
14819 // Make a selector expression.
14820
14821 Expression*
make_selector(Expression * left,const std::string & name,Location location)14822 Expression::make_selector(Expression* left, const std::string& name,
14823 Location location)
14824 {
14825 return new Selector_expression(left, name, location);
14826 }
14827
14828 // Class Allocation_expression.
14829
14830 int
do_traverse(Traverse * traverse)14831 Allocation_expression::do_traverse(Traverse* traverse)
14832 {
14833 return Type::traverse(this->type_, traverse);
14834 }
14835
14836 Type*
do_type()14837 Allocation_expression::do_type()
14838 {
14839 return Type::make_pointer_type(this->type_);
14840 }
14841
14842 void
do_check_types(Gogo *)14843 Allocation_expression::do_check_types(Gogo*)
14844 {
14845 if (!this->type_->in_heap())
14846 go_error_at(this->location(), "cannot heap allocate go:notinheap type");
14847 }
14848
14849 // Make a copy of an allocation expression.
14850
14851 Expression*
do_copy()14852 Allocation_expression::do_copy()
14853 {
14854 Allocation_expression* alloc =
14855 new Allocation_expression(this->type_->copy_expressions(),
14856 this->location());
14857 if (this->allocate_on_stack_)
14858 alloc->set_allocate_on_stack();
14859 if (this->no_zero_)
14860 alloc->set_no_zero();
14861 return alloc;
14862 }
14863
14864 // Return the backend representation for an allocation expression.
14865
14866 Bexpression*
do_get_backend(Translate_context * context)14867 Allocation_expression::do_get_backend(Translate_context* context)
14868 {
14869 Gogo* gogo = context->gogo();
14870 Location loc = this->location();
14871 Btype* btype = this->type_->get_backend(gogo);
14872
14873 if (this->allocate_on_stack_)
14874 {
14875 int64_t size;
14876 bool ok = this->type_->backend_type_size(gogo, &size);
14877 if (!ok)
14878 {
14879 go_assert(saw_errors());
14880 return gogo->backend()->error_expression();
14881 }
14882 Bstatement* decl;
14883 Named_object* fn = context->function();
14884 go_assert(fn != NULL);
14885 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14886 Bexpression* init = (this->no_zero_
14887 ? NULL
14888 : gogo->backend()->zero_expression(btype));
14889 Bvariable* temp =
14890 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14891 init, true, loc, &decl);
14892 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
14893 ret = gogo->backend()->address_expression(ret, loc);
14894 ret = gogo->backend()->compound_expression(decl, ret, loc);
14895 return ret;
14896 }
14897
14898 Bexpression* space =
14899 gogo->allocate_memory(this->type_, loc)->get_backend(context);
14900 Btype* pbtype = gogo->backend()->pointer_type(btype);
14901 return gogo->backend()->convert_expression(pbtype, space, loc);
14902 }
14903
14904 // Dump ast representation for an allocation expression.
14905
14906 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14907 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14908 const
14909 {
14910 ast_dump_context->ostream() << "new(";
14911 ast_dump_context->dump_type(this->type_);
14912 ast_dump_context->ostream() << ")";
14913 }
14914
14915 // Make an allocation expression.
14916
14917 Expression*
make_allocation(Type * type,Location location)14918 Expression::make_allocation(Type* type, Location location)
14919 {
14920 return new Allocation_expression(type, location);
14921 }
14922
14923 // Class Ordered_value_list.
14924
14925 int
traverse_vals(Traverse * traverse)14926 Ordered_value_list::traverse_vals(Traverse* traverse)
14927 {
14928 if (this->vals_ != NULL)
14929 {
14930 if (this->traverse_order_ == NULL)
14931 {
14932 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
14933 return TRAVERSE_EXIT;
14934 }
14935 else
14936 {
14937 for (std::vector<unsigned long>::const_iterator p =
14938 this->traverse_order_->begin();
14939 p != this->traverse_order_->end();
14940 ++p)
14941 {
14942 if (Expression::traverse(&this->vals_->at(*p), traverse)
14943 == TRAVERSE_EXIT)
14944 return TRAVERSE_EXIT;
14945 }
14946 }
14947 }
14948 return TRAVERSE_CONTINUE;
14949 }
14950
14951 // Class Struct_construction_expression.
14952
14953 // Traversal.
14954
14955 int
do_traverse(Traverse * traverse)14956 Struct_construction_expression::do_traverse(Traverse* traverse)
14957 {
14958 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
14959 return TRAVERSE_EXIT;
14960 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14961 return TRAVERSE_EXIT;
14962 return TRAVERSE_CONTINUE;
14963 }
14964
14965 // Return whether this is a constant initializer.
14966
14967 bool
is_constant_struct() const14968 Struct_construction_expression::is_constant_struct() const
14969 {
14970 if (this->vals() == NULL)
14971 return true;
14972 for (Expression_list::const_iterator pv = this->vals()->begin();
14973 pv != this->vals()->end();
14974 ++pv)
14975 {
14976 if (*pv != NULL
14977 && !(*pv)->is_constant()
14978 && (!(*pv)->is_composite_literal()
14979 || (*pv)->is_nonconstant_composite_literal()))
14980 return false;
14981 }
14982
14983 const Struct_field_list* fields = this->type_->struct_type()->fields();
14984 for (Struct_field_list::const_iterator pf = fields->begin();
14985 pf != fields->end();
14986 ++pf)
14987 {
14988 // There are no constant constructors for interfaces.
14989 if (pf->type()->interface_type() != NULL)
14990 return false;
14991 }
14992
14993 return true;
14994 }
14995
14996 // Return whether this is a zero value.
14997
14998 bool
do_is_zero_value() const14999 Struct_construction_expression::do_is_zero_value() const
15000 {
15001 if (this->vals() == NULL)
15002 return true;
15003 for (Expression_list::const_iterator pv = this->vals()->begin();
15004 pv != this->vals()->end();
15005 ++pv)
15006 if (*pv != NULL && !(*pv)->is_zero_value())
15007 return false;
15008
15009 const Struct_field_list* fields = this->type_->struct_type()->fields();
15010 for (Struct_field_list::const_iterator pf = fields->begin();
15011 pf != fields->end();
15012 ++pf)
15013 {
15014 // Interface conversion may cause a zero value being converted
15015 // to a non-zero value, like interface{}(0). Be conservative.
15016 if (pf->type()->interface_type() != NULL)
15017 return false;
15018 }
15019
15020 return true;
15021 }
15022
15023 // Return whether this struct can be used as a constant initializer.
15024
15025 bool
do_is_static_initializer() const15026 Struct_construction_expression::do_is_static_initializer() const
15027 {
15028 if (this->vals() == NULL)
15029 return true;
15030 for (Expression_list::const_iterator pv = this->vals()->begin();
15031 pv != this->vals()->end();
15032 ++pv)
15033 {
15034 if (*pv != NULL && !(*pv)->is_static_initializer())
15035 return false;
15036 }
15037
15038 const Struct_field_list* fields = this->type_->struct_type()->fields();
15039 for (Struct_field_list::const_iterator pf = fields->begin();
15040 pf != fields->end();
15041 ++pf)
15042 {
15043 // There are no constant constructors for interfaces.
15044 if (pf->type()->interface_type() != NULL)
15045 return false;
15046 }
15047
15048 return true;
15049 }
15050
15051 // Final type determination.
15052
15053 void
do_determine_type(const Type_context *)15054 Struct_construction_expression::do_determine_type(const Type_context*)
15055 {
15056 if (this->vals() == NULL)
15057 return;
15058 const Struct_field_list* fields = this->type_->struct_type()->fields();
15059 Expression_list::const_iterator pv = this->vals()->begin();
15060 for (Struct_field_list::const_iterator pf = fields->begin();
15061 pf != fields->end();
15062 ++pf, ++pv)
15063 {
15064 if (pv == this->vals()->end())
15065 return;
15066 if (*pv != NULL)
15067 {
15068 Type_context subcontext(pf->type(), false);
15069 (*pv)->determine_type(&subcontext);
15070 }
15071 }
15072 // Extra values are an error we will report elsewhere; we still want
15073 // to determine the type to avoid knockon errors.
15074 for (; pv != this->vals()->end(); ++pv)
15075 (*pv)->determine_type_no_context();
15076 }
15077
15078 // Check types.
15079
15080 void
do_check_types(Gogo *)15081 Struct_construction_expression::do_check_types(Gogo*)
15082 {
15083 if (this->vals() == NULL)
15084 return;
15085
15086 Struct_type* st = this->type_->struct_type();
15087 if (this->vals()->size() > st->field_count())
15088 {
15089 this->report_error(_("too many expressions for struct"));
15090 return;
15091 }
15092
15093 const Struct_field_list* fields = st->fields();
15094 Expression_list::const_iterator pv = this->vals()->begin();
15095 int i = 0;
15096 for (Struct_field_list::const_iterator pf = fields->begin();
15097 pf != fields->end();
15098 ++pf, ++pv, ++i)
15099 {
15100 if (pv == this->vals()->end())
15101 {
15102 this->report_error(_("too few expressions for struct"));
15103 break;
15104 }
15105
15106 if (*pv == NULL)
15107 continue;
15108
15109 std::string reason;
15110 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
15111 {
15112 if (reason.empty())
15113 go_error_at((*pv)->location(),
15114 "incompatible type for field %d in struct construction",
15115 i + 1);
15116 else
15117 go_error_at((*pv)->location(),
15118 ("incompatible type for field %d in "
15119 "struct construction (%s)"),
15120 i + 1, reason.c_str());
15121 this->set_is_error();
15122 }
15123 }
15124 go_assert(pv == this->vals()->end());
15125 }
15126
15127 // Copy.
15128
15129 Expression*
do_copy()15130 Struct_construction_expression::do_copy()
15131 {
15132 Struct_construction_expression* ret =
15133 new Struct_construction_expression(this->type_->copy_expressions(),
15134 (this->vals() == NULL
15135 ? NULL
15136 : this->vals()->copy()),
15137 this->location());
15138 if (this->traverse_order() != NULL)
15139 ret->set_traverse_order(this->traverse_order());
15140 return ret;
15141 }
15142
15143 // Flatten a struct construction expression. Store the values into
15144 // temporaries if they may need interface conversion.
15145
15146 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15147 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
15148 Statement_inserter* inserter)
15149 {
15150 if (this->vals() == NULL)
15151 return this;
15152
15153 // If this is a constant struct, we don't need temporaries.
15154 if (this->is_constant_struct() || this->is_static_initializer())
15155 return this;
15156
15157 Location loc = this->location();
15158 const Struct_field_list* fields = this->type_->struct_type()->fields();
15159 Struct_field_list::const_iterator pf = fields->begin();
15160 for (Expression_list::iterator pv = this->vals()->begin();
15161 pv != this->vals()->end();
15162 ++pv, ++pf)
15163 {
15164 go_assert(pf != fields->end());
15165 if (*pv != NULL)
15166 {
15167 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15168 {
15169 go_assert(saw_errors());
15170 return Expression::make_error(loc);
15171 }
15172 if (pf->type()->interface_type() != NULL
15173 && !(*pv)->is_multi_eval_safe())
15174 {
15175 Temporary_statement* temp =
15176 Statement::make_temporary(NULL, *pv, loc);
15177 inserter->insert(temp);
15178 *pv = Expression::make_temporary_reference(temp, loc);
15179 }
15180 }
15181 }
15182 return this;
15183 }
15184
15185 // Make implicit type conversions explicit.
15186
15187 void
do_add_conversions()15188 Struct_construction_expression::do_add_conversions()
15189 {
15190 if (this->vals() == NULL)
15191 return;
15192
15193 Location loc = this->location();
15194 const Struct_field_list* fields = this->type_->struct_type()->fields();
15195 Expression_list::iterator pv = this->vals()->begin();
15196 for (Struct_field_list::const_iterator pf = fields->begin();
15197 pf != fields->end();
15198 ++pf, ++pv)
15199 {
15200 if (pv == this->vals()->end())
15201 break;
15202 if (*pv != NULL)
15203 {
15204 Type* ft = pf->type();
15205 if (!Type::are_identical(ft, (*pv)->type(), 0, NULL)
15206 && ft->interface_type() != NULL)
15207 *pv = Expression::make_cast(ft, *pv, loc);
15208 }
15209 }
15210 }
15211
15212 // Return the backend representation for constructing a struct.
15213
15214 Bexpression*
do_get_backend(Translate_context * context)15215 Struct_construction_expression::do_get_backend(Translate_context* context)
15216 {
15217 Gogo* gogo = context->gogo();
15218
15219 Btype* btype = this->type_->get_backend(gogo);
15220 if (this->vals() == NULL)
15221 return gogo->backend()->zero_expression(btype);
15222
15223 const Struct_field_list* fields = this->type_->struct_type()->fields();
15224 Expression_list::const_iterator pv = this->vals()->begin();
15225 std::vector<Bexpression*> init;
15226 for (Struct_field_list::const_iterator pf = fields->begin();
15227 pf != fields->end();
15228 ++pf)
15229 {
15230 Btype* fbtype = pf->type()->get_backend(gogo);
15231 if (pv == this->vals()->end())
15232 init.push_back(gogo->backend()->zero_expression(fbtype));
15233 else if (*pv == NULL)
15234 {
15235 init.push_back(gogo->backend()->zero_expression(fbtype));
15236 ++pv;
15237 }
15238 else
15239 {
15240 Expression* val =
15241 Expression::convert_for_assignment(gogo, pf->type(),
15242 *pv, this->location());
15243 init.push_back(val->get_backend(context));
15244 ++pv;
15245 }
15246 }
15247 if (this->type_->struct_type()->has_padding())
15248 {
15249 // Feed an extra value if there is a padding field.
15250 Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
15251 init.push_back(gogo->backend()->zero_expression(fbtype));
15252 }
15253 return gogo->backend()->constructor_expression(btype, init, this->location());
15254 }
15255
15256 // Export a struct construction.
15257
15258 void
do_export(Export_function_body * efb) const15259 Struct_construction_expression::do_export(Export_function_body* efb) const
15260 {
15261 efb->write_c_string("$convert(");
15262 efb->write_type(this->type_);
15263 for (Expression_list::const_iterator pv = this->vals()->begin();
15264 pv != this->vals()->end();
15265 ++pv)
15266 {
15267 efb->write_c_string(", ");
15268 if (*pv != NULL)
15269 (*pv)->export_expression(efb);
15270 }
15271 efb->write_c_string(")");
15272 }
15273
15274 // Dump ast representation of a struct construction expression.
15275
15276 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15277 Struct_construction_expression::do_dump_expression(
15278 Ast_dump_context* ast_dump_context) const
15279 {
15280 ast_dump_context->dump_type(this->type_);
15281 ast_dump_context->ostream() << "{";
15282 ast_dump_context->dump_expression_list(this->vals());
15283 ast_dump_context->ostream() << "}";
15284 }
15285
15286 // Make a struct composite literal. This used by the thunk code.
15287
15288 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)15289 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
15290 Location location)
15291 {
15292 go_assert(type->struct_type() != NULL);
15293 return new Struct_construction_expression(type, vals, location);
15294 }
15295
15296 // Class Array_construction_expression.
15297
15298 // Traversal.
15299
15300 int
do_traverse(Traverse * traverse)15301 Array_construction_expression::do_traverse(Traverse* traverse)
15302 {
15303 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
15304 return TRAVERSE_EXIT;
15305 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15306 return TRAVERSE_EXIT;
15307 return TRAVERSE_CONTINUE;
15308 }
15309
15310 // Return whether this is a constant initializer.
15311
15312 bool
is_constant_array() const15313 Array_construction_expression::is_constant_array() const
15314 {
15315 if (this->vals() == NULL)
15316 return true;
15317
15318 // There are no constant constructors for interfaces.
15319 if (this->type_->array_type()->element_type()->interface_type() != NULL)
15320 return false;
15321
15322 for (Expression_list::const_iterator pv = this->vals()->begin();
15323 pv != this->vals()->end();
15324 ++pv)
15325 {
15326 if (*pv != NULL
15327 && !(*pv)->is_constant()
15328 && (!(*pv)->is_composite_literal()
15329 || (*pv)->is_nonconstant_composite_literal()))
15330 return false;
15331 }
15332 return true;
15333 }
15334
15335 // Return whether this is a zero value.
15336
15337 bool
do_is_zero_value() const15338 Array_construction_expression::do_is_zero_value() const
15339 {
15340 if (this->vals() == NULL)
15341 return true;
15342
15343 // Interface conversion may cause a zero value being converted
15344 // to a non-zero value, like interface{}(0). Be conservative.
15345 if (this->type_->array_type()->element_type()->interface_type() != NULL)
15346 return false;
15347
15348 for (Expression_list::const_iterator pv = this->vals()->begin();
15349 pv != this->vals()->end();
15350 ++pv)
15351 if (*pv != NULL && !(*pv)->is_zero_value())
15352 return false;
15353
15354 return true;
15355 }
15356
15357 // Return whether this can be used a constant initializer.
15358
15359 bool
do_is_static_initializer() const15360 Array_construction_expression::do_is_static_initializer() const
15361 {
15362 if (this->vals() == NULL)
15363 return true;
15364
15365 // There are no constant constructors for interfaces.
15366 if (this->type_->array_type()->element_type()->interface_type() != NULL)
15367 return false;
15368
15369 for (Expression_list::const_iterator pv = this->vals()->begin();
15370 pv != this->vals()->end();
15371 ++pv)
15372 {
15373 if (*pv != NULL && !(*pv)->is_static_initializer())
15374 return false;
15375 }
15376 return true;
15377 }
15378
15379 // Final type determination.
15380
15381 void
do_determine_type(const Type_context *)15382 Array_construction_expression::do_determine_type(const Type_context*)
15383 {
15384 if (this->is_error_expression())
15385 {
15386 go_assert(saw_errors());
15387 return;
15388 }
15389
15390 if (this->vals() == NULL)
15391 return;
15392 Array_type* at = this->type_->array_type();
15393 if (at == NULL || at->is_error() || at->element_type()->is_error())
15394 {
15395 go_assert(saw_errors());
15396 this->set_is_error();
15397 return;
15398 }
15399 Type_context subcontext(at->element_type(), false);
15400 for (Expression_list::const_iterator pv = this->vals()->begin();
15401 pv != this->vals()->end();
15402 ++pv)
15403 {
15404 if (*pv != NULL)
15405 (*pv)->determine_type(&subcontext);
15406 }
15407 }
15408
15409 // Check types.
15410
15411 void
do_check_types(Gogo *)15412 Array_construction_expression::do_check_types(Gogo*)
15413 {
15414 if (this->is_error_expression())
15415 {
15416 go_assert(saw_errors());
15417 return;
15418 }
15419
15420 if (this->vals() == NULL)
15421 return;
15422
15423 Array_type* at = this->type_->array_type();
15424 if (at == NULL || at->is_error() || at->element_type()->is_error())
15425 {
15426 go_assert(saw_errors());
15427 this->set_is_error();
15428 return;
15429 }
15430 int i = 0;
15431 Type* element_type = at->element_type();
15432 for (Expression_list::const_iterator pv = this->vals()->begin();
15433 pv != this->vals()->end();
15434 ++pv, ++i)
15435 {
15436 if (*pv != NULL
15437 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
15438 {
15439 go_error_at((*pv)->location(),
15440 "incompatible type for element %d in composite literal",
15441 i + 1);
15442 this->set_is_error();
15443 }
15444 }
15445 }
15446
15447 // Flatten an array construction expression. Store the values into
15448 // temporaries if they may need interface conversion.
15449
15450 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15451 Array_construction_expression::do_flatten(Gogo*, Named_object*,
15452 Statement_inserter* inserter)
15453 {
15454 if (this->is_error_expression())
15455 {
15456 go_assert(saw_errors());
15457 return this;
15458 }
15459
15460 if (this->vals() == NULL)
15461 return this;
15462
15463 // If this is a constant array, we don't need temporaries.
15464 if (this->is_constant_array() || this->is_static_initializer())
15465 return this;
15466
15467 // If the array element type is not an interface type, we don't need
15468 // temporaries.
15469 if (this->type_->array_type()->element_type()->interface_type() == NULL)
15470 return this;
15471
15472 Location loc = this->location();
15473 for (Expression_list::iterator pv = this->vals()->begin();
15474 pv != this->vals()->end();
15475 ++pv)
15476 {
15477 if (*pv != NULL)
15478 {
15479 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
15480 {
15481 go_assert(saw_errors());
15482 return Expression::make_error(loc);
15483 }
15484 if (!(*pv)->is_multi_eval_safe())
15485 {
15486 Temporary_statement* temp =
15487 Statement::make_temporary(NULL, *pv, loc);
15488 inserter->insert(temp);
15489 *pv = Expression::make_temporary_reference(temp, loc);
15490 }
15491 }
15492 }
15493 return this;
15494 }
15495
15496 // Make implicit type conversions explicit.
15497
15498 void
do_add_conversions()15499 Array_construction_expression::do_add_conversions()
15500 {
15501 if (this->is_error_expression())
15502 {
15503 go_assert(saw_errors());
15504 return;
15505 }
15506
15507 if (this->vals() == NULL)
15508 return;
15509
15510 Type* et = this->type_->array_type()->element_type();
15511 if (et->interface_type() == NULL)
15512 return;
15513
15514 Location loc = this->location();
15515 for (Expression_list::iterator pv = this->vals()->begin();
15516 pv != this->vals()->end();
15517 ++pv)
15518 if (!Type::are_identical(et, (*pv)->type(), 0, NULL))
15519 *pv = Expression::make_cast(et, *pv, loc);
15520 }
15521
15522 // Get a constructor expression for the array values.
15523
15524 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)15525 Array_construction_expression::get_constructor(Translate_context* context,
15526 Btype* array_btype)
15527 {
15528 Type* element_type = this->type_->array_type()->element_type();
15529
15530 std::vector<unsigned long> indexes;
15531 std::vector<Bexpression*> vals;
15532 Gogo* gogo = context->gogo();
15533 if (this->vals() != NULL)
15534 {
15535 size_t i = 0;
15536 std::vector<unsigned long>::const_iterator pi;
15537 if (this->indexes_ != NULL)
15538 pi = this->indexes_->begin();
15539 for (Expression_list::const_iterator pv = this->vals()->begin();
15540 pv != this->vals()->end();
15541 ++pv, ++i)
15542 {
15543 if (this->indexes_ != NULL)
15544 go_assert(pi != this->indexes_->end());
15545
15546 if (this->indexes_ == NULL)
15547 indexes.push_back(i);
15548 else
15549 indexes.push_back(*pi);
15550 if (*pv == NULL)
15551 {
15552 Btype* ebtype = element_type->get_backend(gogo);
15553 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
15554 vals.push_back(zv);
15555 }
15556 else
15557 {
15558 Expression* val_expr =
15559 Expression::convert_for_assignment(gogo, element_type, *pv,
15560 this->location());
15561 vals.push_back(val_expr->get_backend(context));
15562 }
15563 if (this->indexes_ != NULL)
15564 ++pi;
15565 }
15566 if (this->indexes_ != NULL)
15567 go_assert(pi == this->indexes_->end());
15568 }
15569 return gogo->backend()->array_constructor_expression(array_btype, indexes,
15570 vals, this->location());
15571 }
15572
15573 // Export an array construction.
15574
15575 void
do_export(Export_function_body * efb) const15576 Array_construction_expression::do_export(Export_function_body* efb) const
15577 {
15578 efb->write_c_string("$convert(");
15579 efb->write_type(this->type_);
15580 if (this->vals() != NULL)
15581 {
15582 std::vector<unsigned long>::const_iterator pi;
15583 if (this->indexes_ != NULL)
15584 pi = this->indexes_->begin();
15585 for (Expression_list::const_iterator pv = this->vals()->begin();
15586 pv != this->vals()->end();
15587 ++pv)
15588 {
15589 efb->write_c_string(", ");
15590
15591 if (this->indexes_ != NULL)
15592 {
15593 char buf[100];
15594 snprintf(buf, sizeof buf, "%lu", *pi);
15595 efb->write_c_string(buf);
15596 efb->write_c_string(":");
15597 }
15598
15599 if (*pv != NULL)
15600 (*pv)->export_expression(efb);
15601
15602 if (this->indexes_ != NULL)
15603 ++pi;
15604 }
15605 }
15606 efb->write_c_string(")");
15607 }
15608
15609 // Dump ast representation of an array construction expression.
15610
15611 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15612 Array_construction_expression::do_dump_expression(
15613 Ast_dump_context* ast_dump_context) const
15614 {
15615 Expression* length = this->type_->array_type()->length();
15616
15617 ast_dump_context->ostream() << "[" ;
15618 if (length != NULL)
15619 {
15620 ast_dump_context->dump_expression(length);
15621 }
15622 ast_dump_context->ostream() << "]" ;
15623 ast_dump_context->dump_type(this->type_);
15624 this->dump_slice_storage_expression(ast_dump_context);
15625 ast_dump_context->ostream() << "{" ;
15626 if (this->indexes_ == NULL)
15627 ast_dump_context->dump_expression_list(this->vals());
15628 else
15629 {
15630 Expression_list::const_iterator pv = this->vals()->begin();
15631 for (std::vector<unsigned long>::const_iterator pi =
15632 this->indexes_->begin();
15633 pi != this->indexes_->end();
15634 ++pi, ++pv)
15635 {
15636 if (pi != this->indexes_->begin())
15637 ast_dump_context->ostream() << ", ";
15638 ast_dump_context->ostream() << *pi << ':';
15639 ast_dump_context->dump_expression(*pv);
15640 }
15641 }
15642 ast_dump_context->ostream() << "}" ;
15643
15644 }
15645
15646 // Class Fixed_array_construction_expression.
15647
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15648 Fixed_array_construction_expression::Fixed_array_construction_expression(
15649 Type* type, const std::vector<unsigned long>* indexes,
15650 Expression_list* vals, Location location)
15651 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
15652 type, indexes, vals, location)
15653 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
15654
15655
15656 // Copy.
15657
15658 Expression*
do_copy()15659 Fixed_array_construction_expression::do_copy()
15660 {
15661 Type* t = this->type()->copy_expressions();
15662 return new Fixed_array_construction_expression(t, this->indexes(),
15663 (this->vals() == NULL
15664 ? NULL
15665 : this->vals()->copy()),
15666 this->location());
15667 }
15668
15669 // Return the backend representation for constructing a fixed array.
15670
15671 Bexpression*
do_get_backend(Translate_context * context)15672 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
15673 {
15674 Type* type = this->type();
15675 Btype* btype = type->get_backend(context->gogo());
15676 return this->get_constructor(context, btype);
15677 }
15678
15679 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)15680 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
15681 Location location)
15682 {
15683 go_assert(type->array_type() != NULL && !type->is_slice_type());
15684 return new Fixed_array_construction_expression(type, NULL, vals, location);
15685 }
15686
15687 // Class Slice_construction_expression.
15688
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)15689 Slice_construction_expression::Slice_construction_expression(
15690 Type* type, const std::vector<unsigned long>* indexes,
15691 Expression_list* vals, Location location)
15692 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
15693 type, indexes, vals, location),
15694 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
15695 storage_escapes_(true)
15696 {
15697 go_assert(type->is_slice_type());
15698
15699 unsigned long lenval;
15700 Expression* length;
15701 if (vals == NULL || vals->empty())
15702 lenval = 0;
15703 else
15704 {
15705 if (this->indexes() == NULL)
15706 lenval = vals->size();
15707 else
15708 lenval = indexes->back() + 1;
15709 }
15710 Type* int_type = Type::lookup_integer_type("int");
15711 length = Expression::make_integer_ul(lenval, int_type, location);
15712 Type* element_type = type->array_type()->element_type();
15713 Array_type* array_type = Type::make_array_type(element_type, length);
15714 array_type->set_is_array_incomparable();
15715 this->valtype_ = array_type;
15716 }
15717
15718 // Traversal.
15719
15720 int
do_traverse(Traverse * traverse)15721 Slice_construction_expression::do_traverse(Traverse* traverse)
15722 {
15723 if (this->Array_construction_expression::do_traverse(traverse)
15724 == TRAVERSE_EXIT)
15725 return TRAVERSE_EXIT;
15726 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
15727 return TRAVERSE_EXIT;
15728 if (this->array_val_ != NULL
15729 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
15730 return TRAVERSE_EXIT;
15731 if (this->slice_storage_ != NULL
15732 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
15733 return TRAVERSE_EXIT;
15734 return TRAVERSE_CONTINUE;
15735 }
15736
15737 // Helper routine to create fixed array value underlying the slice literal.
15738 // May be called during flattening, or later during do_get_backend().
15739
15740 Expression*
create_array_val()15741 Slice_construction_expression::create_array_val()
15742 {
15743 Array_type* array_type = this->type()->array_type();
15744 if (array_type == NULL)
15745 {
15746 go_assert(this->type()->is_error());
15747 return NULL;
15748 }
15749
15750 Location loc = this->location();
15751 go_assert(this->valtype_ != NULL);
15752
15753 Expression_list* vals = this->vals();
15754 return new Fixed_array_construction_expression(
15755 this->valtype_, this->indexes(), vals, loc);
15756 }
15757
15758 // If we're previous established that the slice storage does not
15759 // escape, then create a separate array temp val here for it. We
15760 // need to do this as part of flattening so as to be able to insert
15761 // the new temp statement.
15762
15763 Expression*
do_flatten(Gogo * gogo,Named_object * no,Statement_inserter * inserter)15764 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
15765 Statement_inserter* inserter)
15766 {
15767 if (this->type()->array_type() == NULL)
15768 return NULL;
15769
15770 // Base class flattening first
15771 this->Array_construction_expression::do_flatten(gogo, no, inserter);
15772
15773 // Create a stack-allocated storage temp if storage won't escape
15774 if (!this->storage_escapes_
15775 && this->slice_storage_ == NULL
15776 && this->element_count() > 0)
15777 {
15778 Location loc = this->location();
15779 this->array_val_ = this->create_array_val();
15780 go_assert(this->array_val_);
15781 Temporary_statement* temp =
15782 Statement::make_temporary(this->valtype_, this->array_val_, loc);
15783 inserter->insert(temp);
15784 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
15785 }
15786 return this;
15787 }
15788
15789 // When dumping a slice construction expression that has an explicit
15790 // storeage temp, emit the temp here (if we don't do this the storage
15791 // temp appears unused in the AST dump).
15792
15793 void
15794 Slice_construction_expression::
dump_slice_storage_expression(Ast_dump_context * ast_dump_context) const15795 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
15796 {
15797 if (this->slice_storage_ == NULL)
15798 return;
15799 ast_dump_context->ostream() << "storage=" ;
15800 ast_dump_context->dump_expression(this->slice_storage_);
15801 }
15802
15803 // Copy.
15804
15805 Expression*
do_copy()15806 Slice_construction_expression::do_copy()
15807 {
15808 return new Slice_construction_expression(this->type()->copy_expressions(),
15809 this->indexes(),
15810 (this->vals() == NULL
15811 ? NULL
15812 : this->vals()->copy()),
15813 this->location());
15814 }
15815
15816 // Return the backend representation for constructing a slice.
15817
15818 Bexpression*
do_get_backend(Translate_context * context)15819 Slice_construction_expression::do_get_backend(Translate_context* context)
15820 {
15821 if (this->array_val_ == NULL)
15822 this->array_val_ = this->create_array_val();
15823 if (this->array_val_ == NULL)
15824 {
15825 go_assert(this->type()->is_error());
15826 return context->backend()->error_expression();
15827 }
15828
15829 Location loc = this->location();
15830
15831 bool is_static_initializer = this->array_val_->is_static_initializer();
15832
15833 // We have to copy the initial values into heap memory if we are in
15834 // a function or if the values are not constants.
15835 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
15836
15837 Expression* space;
15838
15839 if (this->slice_storage_ != NULL)
15840 {
15841 go_assert(!this->storage_escapes_);
15842 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
15843 }
15844 else if (!copy_to_heap)
15845 {
15846 // The initializer will only run once.
15847 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
15848 space->unary_expression()->set_is_slice_init();
15849 }
15850 else
15851 {
15852 go_assert(this->storage_escapes_ || this->element_count() == 0);
15853 space = Expression::make_heap_expression(this->array_val_, loc);
15854 }
15855 Array_type* at = this->valtype_->array_type();
15856 Type* et = at->element_type();
15857 space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
15858 space, loc);
15859
15860 // Build a constructor for the slice.
15861 Expression* len = at->length();
15862 Expression* slice_val =
15863 Expression::make_slice_value(this->type(), space, len, len, loc);
15864 return slice_val->get_backend(context);
15865 }
15866
15867 // Make a slice composite literal. This is used by the type
15868 // descriptor code.
15869
15870 Slice_construction_expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)15871 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
15872 Location location)
15873 {
15874 go_assert(type->is_slice_type());
15875 return new Slice_construction_expression(type, NULL, vals, location);
15876 }
15877
15878 // Class Map_construction_expression.
15879
15880 // Traversal.
15881
15882 int
do_traverse(Traverse * traverse)15883 Map_construction_expression::do_traverse(Traverse* traverse)
15884 {
15885 if (this->vals_ != NULL
15886 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
15887 return TRAVERSE_EXIT;
15888 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15889 return TRAVERSE_EXIT;
15890 return TRAVERSE_CONTINUE;
15891 }
15892
15893 // Flatten constructor initializer into a temporary variable since
15894 // we need to take its address for __go_construct_map.
15895
15896 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)15897 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
15898 Statement_inserter* inserter)
15899 {
15900 if (!this->is_error_expression()
15901 && this->vals_ != NULL
15902 && !this->vals_->empty()
15903 && this->constructor_temp_ == NULL)
15904 {
15905 Map_type* mt = this->type_->map_type();
15906 Type* key_type = mt->key_type();
15907 Type* val_type = mt->val_type();
15908 this->element_type_ = Type::make_builtin_struct_type(2,
15909 "__key", key_type,
15910 "__val", val_type);
15911
15912 Expression_list* value_pairs = new Expression_list();
15913 Location loc = this->location();
15914
15915 size_t i = 0;
15916 for (Expression_list::const_iterator pv = this->vals_->begin();
15917 pv != this->vals_->end();
15918 ++pv, ++i)
15919 {
15920 Expression_list* key_value_pair = new Expression_list();
15921 Expression* key = *pv;
15922 if (key->is_error_expression() || key->type()->is_error_type())
15923 {
15924 go_assert(saw_errors());
15925 return Expression::make_error(loc);
15926 }
15927 if (key->type()->interface_type() != NULL
15928 && !key->is_multi_eval_safe())
15929 {
15930 Temporary_statement* temp =
15931 Statement::make_temporary(NULL, key, loc);
15932 inserter->insert(temp);
15933 key = Expression::make_temporary_reference(temp, loc);
15934 }
15935 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
15936
15937 ++pv;
15938 Expression* val = *pv;
15939 if (val->is_error_expression() || val->type()->is_error_type())
15940 {
15941 go_assert(saw_errors());
15942 return Expression::make_error(loc);
15943 }
15944 if (val->type()->interface_type() != NULL
15945 && !val->is_multi_eval_safe())
15946 {
15947 Temporary_statement* temp =
15948 Statement::make_temporary(NULL, val, loc);
15949 inserter->insert(temp);
15950 val = Expression::make_temporary_reference(temp, loc);
15951 }
15952 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
15953
15954 key_value_pair->push_back(key);
15955 key_value_pair->push_back(val);
15956 value_pairs->push_back(
15957 Expression::make_struct_composite_literal(this->element_type_,
15958 key_value_pair, loc));
15959 }
15960
15961 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
15962 Array_type* ctor_type =
15963 Type::make_array_type(this->element_type_, element_count);
15964 ctor_type->set_is_array_incomparable();
15965 Expression* constructor =
15966 new Fixed_array_construction_expression(ctor_type, NULL,
15967 value_pairs, loc);
15968
15969 this->constructor_temp_ =
15970 Statement::make_temporary(NULL, constructor, loc);
15971 constructor->issue_nil_check();
15972 this->constructor_temp_->set_is_address_taken();
15973 inserter->insert(this->constructor_temp_);
15974 }
15975
15976 return this;
15977 }
15978
15979 // Final type determination.
15980
15981 void
do_determine_type(const Type_context *)15982 Map_construction_expression::do_determine_type(const Type_context*)
15983 {
15984 if (this->vals_ == NULL)
15985 return;
15986
15987 Map_type* mt = this->type_->map_type();
15988 Type_context key_context(mt->key_type(), false);
15989 Type_context val_context(mt->val_type(), false);
15990 for (Expression_list::const_iterator pv = this->vals_->begin();
15991 pv != this->vals_->end();
15992 ++pv)
15993 {
15994 (*pv)->determine_type(&key_context);
15995 ++pv;
15996 (*pv)->determine_type(&val_context);
15997 }
15998 }
15999
16000 // Check types.
16001
16002 void
do_check_types(Gogo *)16003 Map_construction_expression::do_check_types(Gogo*)
16004 {
16005 if (this->vals_ == NULL)
16006 return;
16007
16008 Map_type* mt = this->type_->map_type();
16009 int i = 0;
16010 Type* key_type = mt->key_type();
16011 Type* val_type = mt->val_type();
16012 for (Expression_list::const_iterator pv = this->vals_->begin();
16013 pv != this->vals_->end();
16014 ++pv, ++i)
16015 {
16016 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
16017 {
16018 go_error_at((*pv)->location(),
16019 "incompatible type for element %d key in map construction",
16020 i + 1);
16021 this->set_is_error();
16022 }
16023 ++pv;
16024 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
16025 {
16026 go_error_at((*pv)->location(),
16027 ("incompatible type for element %d value "
16028 "in map construction"),
16029 i + 1);
16030 this->set_is_error();
16031 }
16032 }
16033 }
16034
16035 // Copy.
16036
16037 Expression*
do_copy()16038 Map_construction_expression::do_copy()
16039 {
16040 return new Map_construction_expression(this->type_->copy_expressions(),
16041 (this->vals_ == NULL
16042 ? NULL
16043 : this->vals_->copy()),
16044 this->location());
16045 }
16046
16047 // Make implicit type conversions explicit.
16048
16049 void
do_add_conversions()16050 Map_construction_expression::do_add_conversions()
16051 {
16052 if (this->vals_ == NULL || this->vals_->empty())
16053 return;
16054
16055 Map_type* mt = this->type_->map_type();
16056 Type* kt = mt->key_type();
16057 Type* vt = mt->val_type();
16058 bool key_is_interface = (kt->interface_type() != NULL);
16059 bool val_is_interface = (vt->interface_type() != NULL);
16060 if (!key_is_interface && !val_is_interface)
16061 return;
16062
16063 Location loc = this->location();
16064 for (Expression_list::iterator pv = this->vals_->begin();
16065 pv != this->vals_->end();
16066 ++pv)
16067 {
16068 if (key_is_interface &&
16069 !Type::are_identical(kt, (*pv)->type(), 0, NULL))
16070 *pv = Expression::make_cast(kt, *pv, loc);
16071 ++pv;
16072 if (val_is_interface &&
16073 !Type::are_identical(vt, (*pv)->type(), 0, NULL))
16074 *pv = Expression::make_cast(vt, *pv, loc);
16075 }
16076 }
16077
16078 // Return the backend representation for constructing a map.
16079
16080 Bexpression*
do_get_backend(Translate_context * context)16081 Map_construction_expression::do_get_backend(Translate_context* context)
16082 {
16083 if (this->is_error_expression())
16084 return context->backend()->error_expression();
16085 Location loc = this->location();
16086
16087 size_t i = 0;
16088 Expression* ventries;
16089 if (this->vals_ == NULL || this->vals_->empty())
16090 ventries = Expression::make_nil(loc);
16091 else
16092 {
16093 go_assert(this->constructor_temp_ != NULL);
16094 i = this->vals_->size() / 2;
16095
16096 Expression* ctor_ref =
16097 Expression::make_temporary_reference(this->constructor_temp_, loc);
16098 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
16099 }
16100
16101 Map_type* mt = this->type_->map_type();
16102 if (this->element_type_ == NULL)
16103 this->element_type_ =
16104 Type::make_builtin_struct_type(2,
16105 "__key", mt->key_type(),
16106 "__val", mt->val_type());
16107 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
16108
16109 Type* uintptr_t = Type::lookup_integer_type("uintptr");
16110 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
16111
16112 Expression* entry_size =
16113 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
16114
16115 unsigned int field_index;
16116 const Struct_field* valfield =
16117 this->element_type_->find_local_field("__val", &field_index);
16118 Expression* val_offset =
16119 Expression::make_struct_field_offset(this->element_type_, valfield);
16120
16121 Expression* map_ctor =
16122 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
16123 entry_size, val_offset, ventries);
16124 return map_ctor->get_backend(context);
16125 }
16126
16127 // Export an array construction.
16128
16129 void
do_export(Export_function_body * efb) const16130 Map_construction_expression::do_export(Export_function_body* efb) const
16131 {
16132 efb->write_c_string("$convert(");
16133 efb->write_type(this->type_);
16134 for (Expression_list::const_iterator pv = this->vals_->begin();
16135 pv != this->vals_->end();
16136 ++pv)
16137 {
16138 efb->write_c_string(", ");
16139 (*pv)->export_expression(efb);
16140 }
16141 efb->write_c_string(")");
16142 }
16143
16144 // Dump ast representation for a map construction expression.
16145
16146 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16147 Map_construction_expression::do_dump_expression(
16148 Ast_dump_context* ast_dump_context) const
16149 {
16150 ast_dump_context->ostream() << "{" ;
16151 ast_dump_context->dump_expression_list(this->vals_, true);
16152 ast_dump_context->ostream() << "}";
16153 }
16154
16155 // A composite literal key. This is seen during parsing, but is not
16156 // resolved to a named_object in case this is a composite literal of
16157 // struct type.
16158
16159 class Composite_literal_key_expression : public Parser_expression
16160 {
16161 public:
Composite_literal_key_expression(const std::string & name,Location location)16162 Composite_literal_key_expression(const std::string& name, Location location)
16163 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL_KEY, location),
16164 name_(name)
16165 { }
16166
16167 const std::string&
name() const16168 name() const
16169 { return this->name_; }
16170
16171 protected:
16172 Expression*
16173 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
16174
16175 Expression*
do_copy()16176 do_copy()
16177 {
16178 return new Composite_literal_key_expression(this->name_, this->location());
16179 }
16180
16181 void
16182 do_dump_expression(Ast_dump_context*) const;
16183
16184 private:
16185 // The name.
16186 std::string name_;
16187 };
16188
16189 // Lower a composite literal key. We will never get here for keys in
16190 // composite literals of struct types, because that is prevented by
16191 // Composite_literal_expression::do_traverse. So if we do get here,
16192 // this must be a regular name reference after all.
16193
16194 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)16195 Composite_literal_key_expression::do_lower(Gogo* gogo, Named_object*,
16196 Statement_inserter*, int)
16197 {
16198 Named_object* no = gogo->lookup(this->name_, NULL);
16199 if (no == NULL)
16200 {
16201 // Gogo::lookup doesn't look in the global namespace, and names
16202 // used in composite literal keys aren't seen by
16203 // Gogo::define_global_names, so we have to look in the global
16204 // namespace ourselves.
16205 no = gogo->lookup_global(Gogo::unpack_hidden_name(this->name_).c_str());
16206 if (no == NULL)
16207 {
16208 go_error_at(this->location(), "reference to undefined name %qs",
16209 Gogo::message_name(this->name_).c_str());
16210 return Expression::make_error(this->location());
16211 }
16212 }
16213 return Expression::make_unknown_reference(no, this->location());
16214 }
16215
16216 // Dump a composite literal key.
16217
16218 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16219 Composite_literal_key_expression::do_dump_expression(
16220 Ast_dump_context* ast_dump_context) const
16221 {
16222 ast_dump_context->ostream() << "_UnknownName_(" << this->name_ << ")";
16223 }
16224
16225 // Make a composite literal key.
16226
16227 Expression*
make_composite_literal_key(const std::string & name,Location location)16228 Expression::make_composite_literal_key(const std::string& name,
16229 Location location)
16230 {
16231 return new Composite_literal_key_expression(name, location);
16232 }
16233
16234 // Class Composite_literal_expression.
16235
16236 // Traversal.
16237
16238 int
do_traverse(Traverse * traverse)16239 Composite_literal_expression::do_traverse(Traverse* traverse)
16240 {
16241 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
16242 return TRAVERSE_EXIT;
16243
16244 // If this is a struct composite literal with keys, then the keys
16245 // are field names, not expressions. We don't want to traverse them
16246 // in that case. If we do, we can give an erroneous error "variable
16247 // initializer refers to itself." See bug482.go in the testsuite.
16248 if (this->has_keys_ && this->vals_ != NULL)
16249 {
16250 // The type may not be resolvable at this point.
16251 Type* type = this->type_;
16252
16253 for (int depth = 0; depth < this->depth_; ++depth)
16254 {
16255 type = type->deref();
16256 if (type->array_type() != NULL)
16257 type = type->array_type()->element_type();
16258 else if (type->map_type() != NULL)
16259 {
16260 if (this->key_path_[depth])
16261 type = type->map_type()->key_type();
16262 else
16263 type = type->map_type()->val_type();
16264 }
16265 else
16266 {
16267 // This error will be reported during lowering.
16268 return TRAVERSE_CONTINUE;
16269 }
16270 }
16271 type = type->deref();
16272
16273 while (true)
16274 {
16275 if (type->classification() == Type::TYPE_NAMED)
16276 type = type->named_type()->real_type();
16277 else if (type->classification() == Type::TYPE_FORWARD)
16278 {
16279 Type* t = type->forwarded();
16280 if (t == type)
16281 break;
16282 type = t;
16283 }
16284 else
16285 break;
16286 }
16287
16288 if (type->classification() == Type::TYPE_STRUCT)
16289 {
16290 Expression_list::iterator p = this->vals_->begin();
16291 while (p != this->vals_->end())
16292 {
16293 // Skip key.
16294 ++p;
16295 go_assert(p != this->vals_->end());
16296 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16297 return TRAVERSE_EXIT;
16298 ++p;
16299 }
16300 return TRAVERSE_CONTINUE;
16301 }
16302 }
16303
16304 if (this->vals_ != NULL)
16305 return this->vals_->traverse(traverse);
16306
16307 return TRAVERSE_CONTINUE;
16308 }
16309
16310 // Lower a generic composite literal into a specific version based on
16311 // the type.
16312
16313 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)16314 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
16315 Statement_inserter* inserter, int)
16316 {
16317 Type* type = this->type_;
16318
16319 for (int depth = 0; depth < this->depth_; ++depth)
16320 {
16321 type = type->deref();
16322 if (type->array_type() != NULL)
16323 type = type->array_type()->element_type();
16324 else if (type->map_type() != NULL)
16325 {
16326 if (this->key_path_[depth])
16327 type = type->map_type()->key_type();
16328 else
16329 type = type->map_type()->val_type();
16330 }
16331 else
16332 {
16333 if (!type->is_error())
16334 go_error_at(this->location(),
16335 ("may only omit types within composite literals "
16336 "of slice, array, or map type"));
16337 return Expression::make_error(this->location());
16338 }
16339 }
16340
16341 Type *pt = type->points_to();
16342 bool is_pointer = false;
16343 if (pt != NULL)
16344 {
16345 is_pointer = true;
16346 type = pt;
16347 }
16348
16349 Expression* ret;
16350 if (type->is_error())
16351 return Expression::make_error(this->location());
16352 else if (type->struct_type() != NULL)
16353 ret = this->lower_struct(gogo, type);
16354 else if (type->array_type() != NULL)
16355 ret = this->lower_array(type);
16356 else if (type->map_type() != NULL)
16357 ret = this->lower_map(gogo, function, inserter, type);
16358 else
16359 {
16360 go_error_at(this->location(),
16361 ("expected struct, slice, array, or map type "
16362 "for composite literal"));
16363 return Expression::make_error(this->location());
16364 }
16365
16366 if (is_pointer)
16367 ret = Expression::make_heap_expression(ret, this->location());
16368
16369 return ret;
16370 }
16371
16372 // Lower a struct composite literal.
16373
16374 Expression*
lower_struct(Gogo * gogo,Type * type)16375 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
16376 {
16377 Location location = this->location();
16378 Struct_type* st = type->struct_type();
16379 if (this->vals_ == NULL || !this->has_keys_)
16380 {
16381 if (this->vals_ != NULL
16382 && !this->vals_->empty()
16383 && type->named_type() != NULL
16384 && type->named_type()->named_object()->package() != NULL)
16385 {
16386 for (Struct_field_list::const_iterator pf = st->fields()->begin();
16387 pf != st->fields()->end();
16388 ++pf)
16389 {
16390 if (Gogo::is_hidden_name(pf->field_name())
16391 || pf->is_embedded_builtin(gogo))
16392 go_error_at(this->location(),
16393 "assignment of unexported field %qs in %qs literal",
16394 Gogo::message_name(pf->field_name()).c_str(),
16395 type->named_type()->message_name().c_str());
16396 }
16397 }
16398
16399 return new Struct_construction_expression(type, this->vals_, location);
16400 }
16401
16402 size_t field_count = st->field_count();
16403 std::vector<Expression*> vals(field_count);
16404 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
16405 Expression_list::const_iterator p = this->vals_->begin();
16406 Expression* external_expr = NULL;
16407 const Named_object* external_no = NULL;
16408 while (p != this->vals_->end())
16409 {
16410 Expression* name_expr = *p;
16411
16412 ++p;
16413 go_assert(p != this->vals_->end());
16414 Expression* val = *p;
16415
16416 ++p;
16417
16418 if (name_expr == NULL)
16419 {
16420 go_error_at(val->location(),
16421 "mixture of field and value initializers");
16422 return Expression::make_error(location);
16423 }
16424
16425 bool bad_key = false;
16426 std::string name;
16427 const Named_object* no = NULL;
16428 switch (name_expr->classification())
16429 {
16430 case EXPRESSION_COMPOSITE_LITERAL_KEY:
16431 name =
16432 static_cast<Composite_literal_key_expression*>(name_expr)->name();
16433 break;
16434
16435 case EXPRESSION_UNKNOWN_REFERENCE:
16436 name = name_expr->unknown_expression()->name();
16437 if (type->named_type() != NULL)
16438 {
16439 // If the named object found for this field name comes from a
16440 // different package than the struct it is a part of, do not count
16441 // this incorrect lookup as a usage of the object's package.
16442 no = name_expr->unknown_expression()->named_object();
16443 if (no->package() != NULL
16444 && no->package() != type->named_type()->named_object()->package())
16445 no->package()->forget_usage(name_expr);
16446 }
16447 break;
16448
16449 case EXPRESSION_CONST_REFERENCE:
16450 no = static_cast<Const_expression*>(name_expr)->named_object();
16451 break;
16452
16453 case EXPRESSION_TYPE:
16454 {
16455 Type* t = name_expr->type();
16456 Named_type* nt = t->named_type();
16457 if (nt == NULL)
16458 bad_key = true;
16459 else
16460 no = nt->named_object();
16461 }
16462 break;
16463
16464 case EXPRESSION_VAR_REFERENCE:
16465 no = name_expr->var_expression()->named_object();
16466 break;
16467
16468 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
16469 no = name_expr->enclosed_var_expression()->variable();
16470 break;
16471
16472 case EXPRESSION_FUNC_REFERENCE:
16473 no = name_expr->func_expression()->named_object();
16474 break;
16475
16476 default:
16477 bad_key = true;
16478 break;
16479 }
16480 if (bad_key)
16481 {
16482 go_error_at(name_expr->location(), "expected struct field name");
16483 return Expression::make_error(location);
16484 }
16485
16486 if (no != NULL)
16487 {
16488 if (no->package() != NULL && external_expr == NULL)
16489 {
16490 external_expr = name_expr;
16491 external_no = no;
16492 }
16493
16494 name = no->name();
16495
16496 // A predefined name won't be packed. If it starts with a
16497 // lower case letter we need to check for that case, because
16498 // the field name will be packed. FIXME.
16499 if (!Gogo::is_hidden_name(name)
16500 && name[0] >= 'a'
16501 && name[0] <= 'z')
16502 {
16503 Named_object* gno = gogo->lookup_global(name.c_str());
16504 if (gno == no)
16505 name = gogo->pack_hidden_name(name, false);
16506 }
16507 }
16508
16509 unsigned int index;
16510 const Struct_field* sf = st->find_local_field(name, &index);
16511 if (sf == NULL)
16512 {
16513 go_error_at(name_expr->location(), "unknown field %qs in %qs",
16514 Gogo::message_name(name).c_str(),
16515 (type->named_type() != NULL
16516 ? type->named_type()->message_name().c_str()
16517 : "unnamed struct"));
16518 return Expression::make_error(location);
16519 }
16520 if (vals[index] != NULL)
16521 {
16522 go_error_at(name_expr->location(),
16523 "duplicate value for field %qs in %qs",
16524 Gogo::message_name(name).c_str(),
16525 (type->named_type() != NULL
16526 ? type->named_type()->message_name().c_str()
16527 : "unnamed struct"));
16528 return Expression::make_error(location);
16529 }
16530
16531 if (type->named_type() != NULL
16532 && type->named_type()->named_object()->package() != NULL
16533 && (Gogo::is_hidden_name(sf->field_name())
16534 || sf->is_embedded_builtin(gogo)))
16535 go_error_at(name_expr->location(),
16536 "assignment of unexported field %qs in %qs literal",
16537 Gogo::message_name(sf->field_name()).c_str(),
16538 type->named_type()->message_name().c_str());
16539
16540 vals[index] = val;
16541 traverse_order->push_back(static_cast<unsigned long>(index));
16542 }
16543
16544 if (!this->all_are_names_)
16545 {
16546 // This is a weird case like bug462 in the testsuite.
16547 if (external_expr == NULL)
16548 go_error_at(this->location(), "unknown field in %qs literal",
16549 (type->named_type() != NULL
16550 ? type->named_type()->message_name().c_str()
16551 : "unnamed struct"));
16552 else
16553 go_error_at(external_expr->location(), "unknown field %qs in %qs",
16554 external_no->message_name().c_str(),
16555 (type->named_type() != NULL
16556 ? type->named_type()->message_name().c_str()
16557 : "unnamed struct"));
16558 return Expression::make_error(location);
16559 }
16560
16561 Expression_list* list = new Expression_list;
16562 list->reserve(field_count);
16563 for (size_t i = 0; i < field_count; ++i)
16564 list->push_back(vals[i]);
16565
16566 Struct_construction_expression* ret =
16567 new Struct_construction_expression(type, list, location);
16568 ret->set_traverse_order(traverse_order);
16569 return ret;
16570 }
16571
16572 // Index/value/traversal-order triple.
16573
16574 struct IVT_triple {
16575 unsigned long index;
16576 unsigned long traversal_order;
16577 Expression* expr;
IVT_tripleIVT_triple16578 IVT_triple(unsigned long i, unsigned long to, Expression *e)
16579 : index(i), traversal_order(to), expr(e) { }
operator <IVT_triple16580 bool operator<(const IVT_triple& other) const
16581 { return this->index < other.index; }
16582 };
16583
16584 // Lower an array composite literal.
16585
16586 Expression*
lower_array(Type * type)16587 Composite_literal_expression::lower_array(Type* type)
16588 {
16589 Location location = this->location();
16590 if (this->vals_ == NULL || !this->has_keys_)
16591 return this->make_array(type, NULL, this->vals_);
16592
16593 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
16594 indexes->reserve(this->vals_->size());
16595 bool indexes_out_of_order = false;
16596 Expression_list* vals = new Expression_list();
16597 vals->reserve(this->vals_->size());
16598 unsigned long index = 0;
16599 Expression_list::const_iterator p = this->vals_->begin();
16600 while (p != this->vals_->end())
16601 {
16602 Expression* index_expr = *p;
16603
16604 ++p;
16605 go_assert(p != this->vals_->end());
16606 Expression* val = *p;
16607
16608 ++p;
16609
16610 if (index_expr == NULL)
16611 {
16612 if (std::find(indexes->begin(), indexes->end(), index)
16613 != indexes->end())
16614 {
16615 go_error_at(val->location(),
16616 "duplicate value for index %lu", index);
16617 return Expression::make_error(location);
16618 }
16619 if (!indexes->empty())
16620 indexes->push_back(index);
16621 }
16622 else
16623 {
16624 if (indexes->empty() && !vals->empty())
16625 {
16626 for (size_t i = 0; i < vals->size(); ++i)
16627 indexes->push_back(i);
16628 }
16629
16630 Numeric_constant nc;
16631 if (!index_expr->numeric_constant_value(&nc))
16632 {
16633 go_error_at(index_expr->location(),
16634 "index expression is not integer constant");
16635 return Expression::make_error(location);
16636 }
16637
16638 switch (nc.to_unsigned_long(&index))
16639 {
16640 case Numeric_constant::NC_UL_VALID:
16641 break;
16642 case Numeric_constant::NC_UL_NOTINT:
16643 go_error_at(index_expr->location(),
16644 "index expression is not integer constant");
16645 return Expression::make_error(location);
16646 case Numeric_constant::NC_UL_NEGATIVE:
16647 go_error_at(index_expr->location(),
16648 "index expression is negative");
16649 return Expression::make_error(location);
16650 case Numeric_constant::NC_UL_BIG:
16651 go_error_at(index_expr->location(), "index value overflow");
16652 return Expression::make_error(location);
16653 default:
16654 go_unreachable();
16655 }
16656
16657 Named_type* ntype = Type::lookup_integer_type("int");
16658 Integer_type* inttype = ntype->integer_type();
16659 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
16660 && index >> (inttype->bits() - 1) != 0)
16661 {
16662 go_error_at(index_expr->location(), "index value overflow");
16663 return Expression::make_error(location);
16664 }
16665
16666 if (std::find(indexes->begin(), indexes->end(), index)
16667 != indexes->end())
16668 {
16669 go_error_at(index_expr->location(),
16670 "duplicate value for index %lu",
16671 index);
16672 return Expression::make_error(location);
16673 }
16674
16675 if (!indexes->empty() && index < indexes->back())
16676 indexes_out_of_order = true;
16677
16678 indexes->push_back(index);
16679 }
16680
16681 vals->push_back(val);
16682
16683 ++index;
16684 }
16685
16686 if (indexes->empty())
16687 {
16688 delete indexes;
16689 indexes = NULL;
16690 }
16691
16692 std::vector<unsigned long>* traverse_order = NULL;
16693 if (indexes_out_of_order)
16694 {
16695 typedef std::vector<IVT_triple> V;
16696
16697 V v;
16698 v.reserve(indexes->size());
16699 std::vector<unsigned long>::const_iterator pi = indexes->begin();
16700 unsigned long torder = 0;
16701 for (Expression_list::const_iterator pe = vals->begin();
16702 pe != vals->end();
16703 ++pe, ++pi, ++torder)
16704 v.push_back(IVT_triple(*pi, torder, *pe));
16705
16706 std::sort(v.begin(), v.end());
16707
16708 delete indexes;
16709 delete vals;
16710
16711 indexes = new std::vector<unsigned long>();
16712 indexes->reserve(v.size());
16713 vals = new Expression_list();
16714 vals->reserve(v.size());
16715 traverse_order = new std::vector<unsigned long>();
16716 traverse_order->reserve(v.size());
16717
16718 for (V::const_iterator pv = v.begin(); pv != v.end(); ++pv)
16719 {
16720 indexes->push_back(pv->index);
16721 vals->push_back(pv->expr);
16722 traverse_order->push_back(pv->traversal_order);
16723 }
16724 }
16725
16726 Expression* ret = this->make_array(type, indexes, vals);
16727 Array_construction_expression* ace = ret->array_literal();
16728 if (ace != NULL && traverse_order != NULL)
16729 ace->set_traverse_order(traverse_order);
16730 return ret;
16731 }
16732
16733 // Actually build the array composite literal. This handles
16734 // [...]{...}.
16735
16736 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)16737 Composite_literal_expression::make_array(
16738 Type* type,
16739 const std::vector<unsigned long>* indexes,
16740 Expression_list* vals)
16741 {
16742 Location location = this->location();
16743 Array_type* at = type->array_type();
16744
16745 if (at->length() != NULL && at->length()->is_nil_expression())
16746 {
16747 size_t size;
16748 if (vals == NULL)
16749 size = 0;
16750 else if (indexes != NULL)
16751 size = indexes->back() + 1;
16752 else
16753 {
16754 size = vals->size();
16755 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
16756 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
16757 && size >> (it->bits() - 1) != 0)
16758 {
16759 go_error_at(location, "too many elements in composite literal");
16760 return Expression::make_error(location);
16761 }
16762 }
16763
16764 Expression* elen = Expression::make_integer_ul(size, NULL, location);
16765 at = Type::make_array_type(at->element_type(), elen);
16766 type = at;
16767 }
16768 else if (at->length() != NULL
16769 && !at->length()->is_error_expression()
16770 && this->vals_ != NULL)
16771 {
16772 Numeric_constant nc;
16773 unsigned long val;
16774 if (at->length()->numeric_constant_value(&nc)
16775 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
16776 {
16777 if (indexes == NULL)
16778 {
16779 if (this->vals_->size() > val)
16780 {
16781 go_error_at(location,
16782 "too many elements in composite literal");
16783 return Expression::make_error(location);
16784 }
16785 }
16786 else
16787 {
16788 unsigned long max = indexes->back();
16789 if (max >= val)
16790 {
16791 go_error_at(location,
16792 ("some element keys in composite literal "
16793 "are out of range"));
16794 return Expression::make_error(location);
16795 }
16796 }
16797 }
16798 }
16799
16800 if (at->length() != NULL)
16801 return new Fixed_array_construction_expression(type, indexes, vals,
16802 location);
16803 else
16804 return new Slice_construction_expression(type, indexes, vals, location);
16805 }
16806
16807 // Lower a map composite literal.
16808
16809 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)16810 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
16811 Statement_inserter* inserter,
16812 Type* type)
16813 {
16814 Location location = this->location();
16815 Unordered_map(unsigned int, std::vector<Expression*>) st;
16816 Unordered_map(unsigned int, std::vector<Expression*>) nt;
16817 if (this->vals_ != NULL)
16818 {
16819 if (!this->has_keys_)
16820 {
16821 go_error_at(location, "map composite literal must have keys");
16822 return Expression::make_error(location);
16823 }
16824
16825 for (Expression_list::iterator p = this->vals_->begin();
16826 p != this->vals_->end();
16827 p += 2)
16828 {
16829 if (*p == NULL)
16830 {
16831 ++p;
16832 go_error_at((*p)->location(),
16833 ("map composite literal must "
16834 "have keys for every value"));
16835 return Expression::make_error(location);
16836 }
16837 // Make sure we have lowered the key; it may not have been
16838 // lowered in order to handle keys for struct composite
16839 // literals. Lower it now to get the right error message.
16840 if ((*p)->unknown_expression() != NULL)
16841 {
16842 gogo->lower_expression(function, inserter, &*p);
16843 go_assert((*p)->is_error_expression());
16844 return Expression::make_error(location);
16845 }
16846 // Check if there are duplicate constant keys.
16847 if (!(*p)->is_constant())
16848 continue;
16849 std::string sval;
16850 Numeric_constant nval;
16851 if ((*p)->string_constant_value(&sval)) // Check string keys.
16852 {
16853 unsigned int h = Gogo::hash_string(sval, 0);
16854 // Search the index h in the hash map.
16855 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16856 mit = st.find(h);
16857 if (mit == st.end())
16858 {
16859 // No duplicate since h is a new index.
16860 // Create a new vector indexed by h and add it to the hash map.
16861 std::vector<Expression*> l;
16862 l.push_back(*p);
16863 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16864 st.insert(val);
16865 }
16866 else
16867 {
16868 // Do further check since index h already exists.
16869 for (std::vector<Expression*>::iterator lit =
16870 mit->second.begin();
16871 lit != mit->second.end();
16872 lit++)
16873 {
16874 std::string s;
16875 bool ok = (*lit)->string_constant_value(&s);
16876 go_assert(ok);
16877 if (s == sval)
16878 {
16879 go_error_at((*p)->location(), ("duplicate key "
16880 "in map literal"));
16881 return Expression::make_error(location);
16882 }
16883 }
16884 // Add this new string key to the vector indexed by h.
16885 mit->second.push_back(*p);
16886 }
16887 }
16888 else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
16889 {
16890 unsigned int h = nval.hash(0);
16891 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
16892 mit = nt.find(h);
16893 if (mit == nt.end())
16894 {
16895 // No duplicate since h is a new code.
16896 // Create a new vector indexed by h and add it to the hash map.
16897 std::vector<Expression*> l;
16898 l.push_back(*p);
16899 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
16900 nt.insert(val);
16901 }
16902 else
16903 {
16904 // Do further check since h already exists.
16905 for (std::vector<Expression*>::iterator lit =
16906 mit->second.begin();
16907 lit != mit->second.end();
16908 lit++)
16909 {
16910 Numeric_constant rval;
16911 bool ok = (*lit)->numeric_constant_value(&rval);
16912 go_assert(ok);
16913 if (nval.equals(rval))
16914 {
16915 go_error_at((*p)->location(),
16916 "duplicate key in map literal");
16917 return Expression::make_error(location);
16918 }
16919 }
16920 // Add this new numeric key to the vector indexed by h.
16921 mit->second.push_back(*p);
16922 }
16923 }
16924 }
16925 }
16926
16927 return new Map_construction_expression(type, this->vals_, location);
16928 }
16929
16930 // Copy.
16931
16932 Expression*
do_copy()16933 Composite_literal_expression::do_copy()
16934 {
16935 Composite_literal_expression* ret =
16936 new Composite_literal_expression(this->type_->copy_expressions(),
16937 this->depth_, this->has_keys_,
16938 (this->vals_ == NULL
16939 ? NULL
16940 : this->vals_->copy()),
16941 this->all_are_names_,
16942 this->location());
16943 ret->key_path_ = this->key_path_;
16944 return ret;
16945 }
16946
16947 // Dump ast representation for a composite literal expression.
16948
16949 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16950 Composite_literal_expression::do_dump_expression(
16951 Ast_dump_context* ast_dump_context) const
16952 {
16953 ast_dump_context->ostream() << "composite(";
16954 ast_dump_context->dump_type(this->type_);
16955 ast_dump_context->ostream() << ", {";
16956 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
16957 ast_dump_context->ostream() << "})";
16958 }
16959
16960 // Make a composite literal expression.
16961
16962 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)16963 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
16964 Expression_list* vals, bool all_are_names,
16965 Location location)
16966 {
16967 return new Composite_literal_expression(type, depth, has_keys, vals,
16968 all_are_names, location);
16969 }
16970
16971 // Return whether this expression is a composite literal.
16972
16973 bool
is_composite_literal() const16974 Expression::is_composite_literal() const
16975 {
16976 switch (this->classification_)
16977 {
16978 case EXPRESSION_COMPOSITE_LITERAL:
16979 case EXPRESSION_STRUCT_CONSTRUCTION:
16980 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
16981 case EXPRESSION_SLICE_CONSTRUCTION:
16982 case EXPRESSION_MAP_CONSTRUCTION:
16983 return true;
16984 default:
16985 return false;
16986 }
16987 }
16988
16989 // Return whether this expression is a composite literal which is not
16990 // constant.
16991
16992 bool
is_nonconstant_composite_literal() const16993 Expression::is_nonconstant_composite_literal() const
16994 {
16995 switch (this->classification_)
16996 {
16997 case EXPRESSION_STRUCT_CONSTRUCTION:
16998 {
16999 const Struct_construction_expression *psce =
17000 static_cast<const Struct_construction_expression*>(this);
17001 return !psce->is_constant_struct();
17002 }
17003 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
17004 {
17005 const Fixed_array_construction_expression *pace =
17006 static_cast<const Fixed_array_construction_expression*>(this);
17007 return !pace->is_constant_array();
17008 }
17009 case EXPRESSION_SLICE_CONSTRUCTION:
17010 {
17011 const Slice_construction_expression *pace =
17012 static_cast<const Slice_construction_expression*>(this);
17013 return !pace->is_constant_array();
17014 }
17015 case EXPRESSION_MAP_CONSTRUCTION:
17016 return true;
17017 default:
17018 return false;
17019 }
17020 }
17021
17022 // Return true if this is a variable or temporary_variable.
17023
17024 bool
is_variable() const17025 Expression::is_variable() const
17026 {
17027 switch (this->classification_)
17028 {
17029 case EXPRESSION_VAR_REFERENCE:
17030 case EXPRESSION_TEMPORARY_REFERENCE:
17031 case EXPRESSION_SET_AND_USE_TEMPORARY:
17032 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
17033 return true;
17034 default:
17035 return false;
17036 }
17037 }
17038
17039 // Return true if this is a reference to a local variable.
17040
17041 bool
is_local_variable() const17042 Expression::is_local_variable() const
17043 {
17044 const Var_expression* ve = this->var_expression();
17045 if (ve == NULL)
17046 return false;
17047 const Named_object* no = ve->named_object();
17048 return (no->is_result_variable()
17049 || (no->is_variable() && !no->var_value()->is_global()));
17050 }
17051
17052 // Return true if multiple evaluations are OK.
17053
17054 bool
is_multi_eval_safe()17055 Expression::is_multi_eval_safe()
17056 {
17057 switch (this->classification_)
17058 {
17059 case EXPRESSION_VAR_REFERENCE:
17060 {
17061 // A variable is a simple reference if not stored in the heap.
17062 const Named_object* no = this->var_expression()->named_object();
17063 if (no->is_variable())
17064 return !no->var_value()->is_in_heap();
17065 else if (no->is_result_variable())
17066 return !no->result_var_value()->is_in_heap();
17067 else
17068 go_unreachable();
17069 }
17070
17071 case EXPRESSION_TEMPORARY_REFERENCE:
17072 return true;
17073
17074 default:
17075 break;
17076 }
17077
17078 if (!this->is_constant())
17079 return false;
17080
17081 // Only numeric and boolean constants are really multi-evaluation
17082 // safe. We don't want multiple copies of string constants.
17083 Type* type = this->type();
17084 return type->is_numeric_type() || type->is_boolean_type();
17085 }
17086
17087 const Named_object*
named_constant() const17088 Expression::named_constant() const
17089 {
17090 if (this->classification() != EXPRESSION_CONST_REFERENCE)
17091 return NULL;
17092 const Const_expression* ce = static_cast<const Const_expression*>(this);
17093 return ce->named_object();
17094 }
17095
17096 // Class Type_guard_expression.
17097
17098 // Traversal.
17099
17100 int
do_traverse(Traverse * traverse)17101 Type_guard_expression::do_traverse(Traverse* traverse)
17102 {
17103 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
17104 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17105 return TRAVERSE_EXIT;
17106 return TRAVERSE_CONTINUE;
17107 }
17108
17109 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)17110 Type_guard_expression::do_flatten(Gogo*, Named_object*,
17111 Statement_inserter* inserter)
17112 {
17113 if (this->expr_->is_error_expression()
17114 || this->expr_->type()->is_error_type())
17115 {
17116 go_assert(saw_errors());
17117 return Expression::make_error(this->location());
17118 }
17119
17120 if (!this->expr_->is_multi_eval_safe())
17121 {
17122 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
17123 this->location());
17124 inserter->insert(temp);
17125 this->expr_ =
17126 Expression::make_temporary_reference(temp, this->location());
17127 }
17128 return this;
17129 }
17130
17131 // Check types of a type guard expression. The expression must have
17132 // an interface type, but the actual type conversion is checked at run
17133 // time.
17134
17135 void
do_check_types(Gogo *)17136 Type_guard_expression::do_check_types(Gogo*)
17137 {
17138 Type* expr_type = this->expr_->type();
17139 if (expr_type->interface_type() == NULL)
17140 {
17141 if (!expr_type->is_error() && !this->type_->is_error())
17142 this->report_error(_("type assertion only valid for interface types"));
17143 this->set_is_error();
17144 }
17145 else if (this->type_->interface_type() == NULL)
17146 {
17147 std::string reason;
17148 if (!expr_type->interface_type()->implements_interface(this->type_,
17149 &reason))
17150 {
17151 if (!this->type_->is_error())
17152 {
17153 if (reason.empty())
17154 this->report_error(_("impossible type assertion: "
17155 "type does not implement interface"));
17156 else
17157 go_error_at(this->location(),
17158 ("impossible type assertion: "
17159 "type does not implement interface (%s)"),
17160 reason.c_str());
17161 }
17162 this->set_is_error();
17163 }
17164 }
17165 }
17166
17167 // Copy.
17168
17169 Expression*
do_copy()17170 Type_guard_expression::do_copy()
17171 {
17172 return new Type_guard_expression(this->expr_->copy(),
17173 this->type_->copy_expressions(),
17174 this->location());
17175 }
17176
17177 // Return the backend representation for a type guard expression.
17178
17179 Bexpression*
do_get_backend(Translate_context * context)17180 Type_guard_expression::do_get_backend(Translate_context* context)
17181 {
17182 Expression* conversion;
17183 if (this->type_->interface_type() != NULL)
17184 conversion =
17185 Expression::convert_interface_to_interface(this->type_, this->expr_,
17186 true, this->location());
17187 else
17188 conversion =
17189 Expression::convert_for_assignment(context->gogo(), this->type_,
17190 this->expr_, this->location());
17191
17192 Gogo* gogo = context->gogo();
17193 Btype* bt = this->type_->get_backend(gogo);
17194 Bexpression* bexpr = conversion->get_backend(context);
17195 return gogo->backend()->convert_expression(bt, bexpr, this->location());
17196 }
17197
17198 // Dump ast representation for a type guard expression.
17199
17200 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17201 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
17202 const
17203 {
17204 this->expr_->dump_expression(ast_dump_context);
17205 ast_dump_context->ostream() << ".";
17206 ast_dump_context->dump_type(this->type_);
17207 }
17208
17209 // Make a type guard expression.
17210
17211 Expression*
make_type_guard(Expression * expr,Type * type,Location location)17212 Expression::make_type_guard(Expression* expr, Type* type,
17213 Location location)
17214 {
17215 return new Type_guard_expression(expr, type, location);
17216 }
17217
17218 // Class Heap_expression.
17219
17220 // Return the type of the expression stored on the heap.
17221
17222 Type*
do_type()17223 Heap_expression::do_type()
17224 { return Type::make_pointer_type(this->expr_->type()); }
17225
17226 // Return the backend representation for allocating an expression on the heap.
17227
17228 Bexpression*
do_get_backend(Translate_context * context)17229 Heap_expression::do_get_backend(Translate_context* context)
17230 {
17231 Type* etype = this->expr_->type();
17232 if (this->expr_->is_error_expression() || etype->is_error())
17233 return context->backend()->error_expression();
17234
17235 Location loc = this->location();
17236 Gogo* gogo = context->gogo();
17237 Btype* btype = this->type()->get_backend(gogo);
17238
17239 Expression* alloc = Expression::make_allocation(etype, loc);
17240 if (this->allocate_on_stack_)
17241 alloc->allocation_expression()->set_allocate_on_stack();
17242 Bexpression* space = alloc->get_backend(context);
17243
17244 Bstatement* decl;
17245 Named_object* fn = context->function();
17246 go_assert(fn != NULL);
17247 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
17248 Bvariable* space_temp =
17249 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
17250 space, true, loc, &decl);
17251 Btype* expr_btype = etype->get_backend(gogo);
17252
17253 Bexpression* bexpr = this->expr_->get_backend(context);
17254
17255 // If this assignment needs a write barrier, call typedmemmove. We
17256 // don't do this in the write barrier pass because in some cases
17257 // backend conversion can introduce new Heap_expression values.
17258 Bstatement* assn;
17259 if (!etype->has_pointer() || this->allocate_on_stack_)
17260 {
17261 space = gogo->backend()->var_expression(space_temp, loc);
17262 Bexpression* ref =
17263 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17264 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
17265 }
17266 else
17267 {
17268 Bstatement* edecl;
17269 Bvariable* btemp =
17270 gogo->backend()->temporary_variable(fndecl, context->bblock(),
17271 expr_btype, bexpr, true, loc,
17272 &edecl);
17273 Bexpression* btempref = gogo->backend()->var_expression(btemp,
17274 loc);
17275 space = gogo->backend()->var_expression(space_temp, loc);
17276 Type* etype_ptr = Type::make_pointer_type(etype);
17277 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
17278 Expression* erhs;
17279 Expression* call;
17280 if (etype->is_direct_iface_type())
17281 {
17282 // Single pointer.
17283 Type* uintptr_type = Type::lookup_integer_type("uintptr");
17284 erhs = Expression::make_backend(btempref, etype, loc);
17285 erhs = Expression::unpack_direct_iface(erhs, loc);
17286 erhs = Expression::make_unsafe_cast(uintptr_type, erhs, loc);
17287 call = Runtime::make_call(Runtime::GCWRITEBARRIER, loc, 2,
17288 elhs, erhs);
17289 }
17290 else
17291 {
17292 Expression* td = Expression::make_type_descriptor(etype, loc);
17293 Bexpression* addr =
17294 gogo->backend()->address_expression(btempref, loc);
17295 erhs = Expression::make_backend(addr, etype_ptr, loc);
17296 call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
17297 td, elhs, erhs);
17298 }
17299 Statement* cs = Statement::make_statement(call, false);
17300
17301 space = gogo->backend()->var_expression(space_temp, loc);
17302 Bexpression* ref =
17303 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
17304 Expression* eref = Expression::make_backend(ref, etype, loc);
17305 btempref = gogo->backend()->var_expression(btemp, loc);
17306 erhs = Expression::make_backend(btempref, etype, loc);
17307 Statement* as = Statement::make_assignment(eref, erhs, loc);
17308
17309 as = gogo->check_write_barrier(context->block(), as, cs);
17310 Bstatement* s = as->get_backend(context);
17311
17312 assn = gogo->backend()->compound_statement(edecl, s);
17313 }
17314 decl = gogo->backend()->compound_statement(decl, assn);
17315 space = gogo->backend()->var_expression(space_temp, loc);
17316 return gogo->backend()->compound_expression(decl, space, loc);
17317 }
17318
17319 // Dump ast representation for a heap expression.
17320
17321 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17322 Heap_expression::do_dump_expression(
17323 Ast_dump_context* ast_dump_context) const
17324 {
17325 ast_dump_context->ostream() << "&(";
17326 ast_dump_context->dump_expression(this->expr_);
17327 ast_dump_context->ostream() << ")";
17328 }
17329
17330 // Allocate an expression on the heap.
17331
17332 Expression*
make_heap_expression(Expression * expr,Location location)17333 Expression::make_heap_expression(Expression* expr, Location location)
17334 {
17335 return new Heap_expression(expr, location);
17336 }
17337
17338 // Class Receive_expression.
17339
17340 // Return the type of a receive expression.
17341
17342 Type*
do_type()17343 Receive_expression::do_type()
17344 {
17345 if (this->is_error_expression())
17346 return Type::make_error_type();
17347 Channel_type* channel_type = this->channel_->type()->channel_type();
17348 if (channel_type == NULL)
17349 {
17350 this->report_error(_("expected channel"));
17351 return Type::make_error_type();
17352 }
17353 return channel_type->element_type();
17354 }
17355
17356 // Check types for a receive expression.
17357
17358 void
do_check_types(Gogo *)17359 Receive_expression::do_check_types(Gogo*)
17360 {
17361 Type* type = this->channel_->type();
17362 if (type->is_error())
17363 {
17364 go_assert(saw_errors());
17365 this->set_is_error();
17366 return;
17367 }
17368 if (type->channel_type() == NULL)
17369 {
17370 this->report_error(_("expected channel"));
17371 return;
17372 }
17373 if (!type->channel_type()->may_receive())
17374 {
17375 this->report_error(_("invalid receive on send-only channel"));
17376 return;
17377 }
17378 }
17379
17380 // Flattening for receive expressions creates a temporary variable to store
17381 // received data in for receives.
17382
17383 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)17384 Receive_expression::do_flatten(Gogo*, Named_object*,
17385 Statement_inserter* inserter)
17386 {
17387 Channel_type* channel_type = this->channel_->type()->channel_type();
17388 if (channel_type == NULL)
17389 {
17390 go_assert(saw_errors());
17391 return this;
17392 }
17393 else if (this->channel_->is_error_expression())
17394 {
17395 go_assert(saw_errors());
17396 return Expression::make_error(this->location());
17397 }
17398
17399 Type* element_type = channel_type->element_type();
17400 if (this->temp_receiver_ == NULL)
17401 {
17402 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
17403 this->location());
17404 this->temp_receiver_->set_is_address_taken();
17405 inserter->insert(this->temp_receiver_);
17406 }
17407
17408 return this;
17409 }
17410
17411 // Get the backend representation for a receive expression.
17412
17413 Bexpression*
do_get_backend(Translate_context * context)17414 Receive_expression::do_get_backend(Translate_context* context)
17415 {
17416 Location loc = this->location();
17417
17418 Channel_type* channel_type = this->channel_->type()->channel_type();
17419 if (channel_type == NULL)
17420 {
17421 go_assert(this->channel_->type()->is_error());
17422 return context->backend()->error_expression();
17423 }
17424
17425 Expression* recv_ref =
17426 Expression::make_temporary_reference(this->temp_receiver_, loc);
17427 Expression* recv_addr =
17428 Expression::make_temporary_reference(this->temp_receiver_, loc);
17429 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
17430 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
17431 this->channel_, recv_addr);
17432 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
17433 }
17434
17435 // Export a receive expression.
17436
17437 void
do_export(Export_function_body * efb) const17438 Receive_expression::do_export(Export_function_body* efb) const
17439 {
17440 efb->write_c_string("<-");
17441 this->channel_->export_expression(efb);
17442 }
17443
17444 // Dump ast representation for a receive expression.
17445
17446 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17447 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
17448 {
17449 ast_dump_context->ostream() << " <- " ;
17450 ast_dump_context->dump_expression(channel_);
17451 }
17452
17453 // Import a receive expression.
17454
17455 Expression*
do_import(Import_expression * imp,Location loc)17456 Receive_expression::do_import(Import_expression* imp, Location loc)
17457 {
17458 imp->require_c_string("<-");
17459 Expression* expr = Expression::import_expression(imp, loc);
17460 return Expression::make_receive(expr, loc);
17461 }
17462
17463 // Make a receive expression.
17464
17465 Receive_expression*
make_receive(Expression * channel,Location location)17466 Expression::make_receive(Expression* channel, Location location)
17467 {
17468 return new Receive_expression(channel, location);
17469 }
17470
17471 // An expression which evaluates to a pointer to the type descriptor
17472 // of a type.
17473
17474 class Type_descriptor_expression : public Expression
17475 {
17476 public:
Type_descriptor_expression(Type * type,Location location)17477 Type_descriptor_expression(Type* type, Location location)
17478 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
17479 type_(type)
17480 { }
17481
17482 protected:
17483 int
17484 do_traverse(Traverse*);
17485
17486 Type*
do_type()17487 do_type()
17488 { return Type::make_type_descriptor_ptr_type(); }
17489
17490 bool
do_is_static_initializer() const17491 do_is_static_initializer() const
17492 { return true; }
17493
17494 void
do_determine_type(const Type_context *)17495 do_determine_type(const Type_context*)
17496 { }
17497
17498 Expression*
do_copy()17499 do_copy()
17500 { return this; }
17501
17502 Bexpression*
do_get_backend(Translate_context * context)17503 do_get_backend(Translate_context* context)
17504 {
17505 return this->type_->type_descriptor_pointer(context->gogo(),
17506 this->location());
17507 }
17508
17509 void
17510 do_dump_expression(Ast_dump_context*) const;
17511
17512 private:
17513 // The type for which this is the descriptor.
17514 Type* type_;
17515 };
17516
17517 int
do_traverse(Traverse * traverse)17518 Type_descriptor_expression::do_traverse(Traverse* traverse)
17519 {
17520 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
17521 return TRAVERSE_EXIT;
17522 return TRAVERSE_CONTINUE;
17523 }
17524
17525 // Dump ast representation for a type descriptor expression.
17526
17527 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17528 Type_descriptor_expression::do_dump_expression(
17529 Ast_dump_context* ast_dump_context) const
17530 {
17531 ast_dump_context->dump_type(this->type_);
17532 }
17533
17534 // Make a type descriptor expression.
17535
17536 Expression*
make_type_descriptor(Type * type,Location location)17537 Expression::make_type_descriptor(Type* type, Location location)
17538 {
17539 return new Type_descriptor_expression(type, location);
17540 }
17541
17542 // An expression which evaluates to a pointer to the Garbage Collection symbol
17543 // of a type.
17544
17545 class GC_symbol_expression : public Expression
17546 {
17547 public:
GC_symbol_expression(Type * type)17548 GC_symbol_expression(Type* type)
17549 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
17550 type_(type)
17551 {}
17552
17553 protected:
17554 Type*
do_type()17555 do_type()
17556 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17557
17558 bool
do_is_static_initializer() const17559 do_is_static_initializer() const
17560 { return true; }
17561
17562 void
do_determine_type(const Type_context *)17563 do_determine_type(const Type_context*)
17564 { }
17565
17566 Expression*
do_copy()17567 do_copy()
17568 { return this; }
17569
17570 Bexpression*
do_get_backend(Translate_context * context)17571 do_get_backend(Translate_context* context)
17572 { return this->type_->gc_symbol_pointer(context->gogo()); }
17573
17574 void
17575 do_dump_expression(Ast_dump_context*) const;
17576
17577 private:
17578 // The type which this gc symbol describes.
17579 Type* type_;
17580 };
17581
17582 // Dump ast representation for a gc symbol expression.
17583
17584 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17585 GC_symbol_expression::do_dump_expression(
17586 Ast_dump_context* ast_dump_context) const
17587 {
17588 ast_dump_context->ostream() << "gcdata(";
17589 ast_dump_context->dump_type(this->type_);
17590 ast_dump_context->ostream() << ")";
17591 }
17592
17593 // Make a gc symbol expression.
17594
17595 Expression*
make_gc_symbol(Type * type)17596 Expression::make_gc_symbol(Type* type)
17597 {
17598 return new GC_symbol_expression(type);
17599 }
17600
17601 // An expression that evaluates to a pointer to a symbol holding the
17602 // ptrmask data of a type.
17603
17604 class Ptrmask_symbol_expression : public Expression
17605 {
17606 public:
Ptrmask_symbol_expression(Type * type)17607 Ptrmask_symbol_expression(Type* type)
17608 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
17609 type_(type)
17610 {}
17611
17612 protected:
17613 Type*
do_type()17614 do_type()
17615 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
17616
17617 bool
do_is_static_initializer() const17618 do_is_static_initializer() const
17619 { return true; }
17620
17621 void
do_determine_type(const Type_context *)17622 do_determine_type(const Type_context*)
17623 { }
17624
17625 Expression*
do_copy()17626 do_copy()
17627 { return this; }
17628
17629 Bexpression*
17630 do_get_backend(Translate_context*);
17631
17632 void
17633 do_dump_expression(Ast_dump_context*) const;
17634
17635 private:
17636 // The type that this ptrmask symbol describes.
17637 Type* type_;
17638 };
17639
17640 // Return the ptrmask variable.
17641
17642 Bexpression*
do_get_backend(Translate_context * context)17643 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
17644 {
17645 Gogo* gogo = context->gogo();
17646
17647 // If this type does not need a gcprog, then we can use the standard
17648 // GC symbol.
17649 int64_t ptrsize, ptrdata;
17650 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
17651 return this->type_->gc_symbol_pointer(gogo);
17652
17653 // Otherwise we have to build a ptrmask variable, and return a
17654 // pointer to it.
17655
17656 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
17657 Location bloc = Linemap::predeclared_location();
17658 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
17659 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
17660
17661 Type* uint8_type = Type::lookup_integer_type("uint8");
17662 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
17663 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
17664 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
17665 }
17666
17667 // Dump AST for a ptrmask symbol expression.
17668
17669 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17670 Ptrmask_symbol_expression::do_dump_expression(
17671 Ast_dump_context* ast_dump_context) const
17672 {
17673 ast_dump_context->ostream() << "ptrmask(";
17674 ast_dump_context->dump_type(this->type_);
17675 ast_dump_context->ostream() << ")";
17676 }
17677
17678 // Make a ptrmask symbol expression.
17679
17680 Expression*
make_ptrmask_symbol(Type * type)17681 Expression::make_ptrmask_symbol(Type* type)
17682 {
17683 return new Ptrmask_symbol_expression(type);
17684 }
17685
17686 // An expression which evaluates to some characteristic of a type.
17687 // This is only used to initialize fields of a type descriptor. Using
17688 // a new expression class is slightly inefficient but gives us a good
17689 // separation between the frontend and the middle-end with regard to
17690 // how types are laid out.
17691
17692 class Type_info_expression : public Expression
17693 {
17694 public:
Type_info_expression(Type * type,Type_info type_info)17695 Type_info_expression(Type* type, Type_info type_info)
17696 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
17697 type_(type), type_info_(type_info)
17698 { }
17699
17700 protected:
17701 bool
do_is_static_initializer() const17702 do_is_static_initializer() const
17703 { return true; }
17704
17705 Type*
17706 do_type();
17707
17708 void
do_determine_type(const Type_context *)17709 do_determine_type(const Type_context*)
17710 { }
17711
17712 Expression*
do_copy()17713 do_copy()
17714 { return this; }
17715
17716 Bexpression*
17717 do_get_backend(Translate_context* context);
17718
17719 void
17720 do_dump_expression(Ast_dump_context*) const;
17721
17722 private:
17723 // The type for which we are getting information.
17724 Type* type_;
17725 // What information we want.
17726 Type_info type_info_;
17727 };
17728
17729 // The type is chosen to match what the type descriptor struct
17730 // expects.
17731
17732 Type*
do_type()17733 Type_info_expression::do_type()
17734 {
17735 switch (this->type_info_)
17736 {
17737 case TYPE_INFO_SIZE:
17738 case TYPE_INFO_BACKEND_PTRDATA:
17739 case TYPE_INFO_DESCRIPTOR_PTRDATA:
17740 return Type::lookup_integer_type("uintptr");
17741 case TYPE_INFO_ALIGNMENT:
17742 case TYPE_INFO_FIELD_ALIGNMENT:
17743 return Type::lookup_integer_type("uint8");
17744 default:
17745 go_unreachable();
17746 }
17747 }
17748
17749 // Return the backend representation for type information.
17750
17751 Bexpression*
do_get_backend(Translate_context * context)17752 Type_info_expression::do_get_backend(Translate_context* context)
17753 {
17754 Gogo* gogo = context->gogo();
17755 bool ok = true;
17756 int64_t val;
17757 switch (this->type_info_)
17758 {
17759 case TYPE_INFO_SIZE:
17760 ok = this->type_->backend_type_size(gogo, &val);
17761 break;
17762 case TYPE_INFO_ALIGNMENT:
17763 ok = this->type_->backend_type_align(gogo, &val);
17764 break;
17765 case TYPE_INFO_FIELD_ALIGNMENT:
17766 ok = this->type_->backend_type_field_align(gogo, &val);
17767 break;
17768 case TYPE_INFO_BACKEND_PTRDATA:
17769 ok = this->type_->backend_type_ptrdata(gogo, &val);
17770 break;
17771 case TYPE_INFO_DESCRIPTOR_PTRDATA:
17772 ok = this->type_->descriptor_ptrdata(gogo, &val);
17773 break;
17774 default:
17775 go_unreachable();
17776 }
17777 if (!ok)
17778 {
17779 go_assert(saw_errors());
17780 return gogo->backend()->error_expression();
17781 }
17782 Expression* e = Expression::make_integer_int64(val, this->type(),
17783 this->location());
17784 return e->get_backend(context);
17785 }
17786
17787 // Dump ast representation for a type info expression.
17788
17789 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17790 Type_info_expression::do_dump_expression(
17791 Ast_dump_context* ast_dump_context) const
17792 {
17793 ast_dump_context->ostream() << "typeinfo(";
17794 ast_dump_context->dump_type(this->type_);
17795 ast_dump_context->ostream() << ",";
17796 ast_dump_context->ostream() <<
17797 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
17798 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
17799 : this->type_info_ == TYPE_INFO_SIZE ? "size"
17800 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
17801 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
17802 : "unknown");
17803 ast_dump_context->ostream() << ")";
17804 }
17805
17806 // Make a type info expression.
17807
17808 Expression*
make_type_info(Type * type,Type_info type_info)17809 Expression::make_type_info(Type* type, Type_info type_info)
17810 {
17811 return new Type_info_expression(type, type_info);
17812 }
17813
17814 // An expression that evaluates to some characteristic of a slice.
17815 // This is used when indexing, bound-checking, or nil checking a slice.
17816
17817 class Slice_info_expression : public Expression
17818 {
17819 public:
Slice_info_expression(Expression * slice,Slice_info slice_info,Location location)17820 Slice_info_expression(Expression* slice, Slice_info slice_info,
17821 Location location)
17822 : Expression(EXPRESSION_SLICE_INFO, location),
17823 slice_(slice), slice_info_(slice_info)
17824 { }
17825
17826 protected:
17827 Type*
17828 do_type();
17829
17830 void
do_determine_type(const Type_context *)17831 do_determine_type(const Type_context*)
17832 { }
17833
17834 Expression*
do_copy()17835 do_copy()
17836 {
17837 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
17838 this->location());
17839 }
17840
17841 Bexpression*
17842 do_get_backend(Translate_context* context);
17843
17844 void
17845 do_dump_expression(Ast_dump_context*) const;
17846
17847 void
do_issue_nil_check()17848 do_issue_nil_check()
17849 { this->slice_->issue_nil_check(); }
17850
17851 private:
17852 // The slice for which we are getting information.
17853 Expression* slice_;
17854 // What information we want.
17855 Slice_info slice_info_;
17856 };
17857
17858 // Return the type of the slice info.
17859
17860 Type*
do_type()17861 Slice_info_expression::do_type()
17862 {
17863 switch (this->slice_info_)
17864 {
17865 case SLICE_INFO_VALUE_POINTER:
17866 return Type::make_pointer_type(
17867 this->slice_->type()->array_type()->element_type());
17868 case SLICE_INFO_LENGTH:
17869 case SLICE_INFO_CAPACITY:
17870 return Type::lookup_integer_type("int");
17871 default:
17872 go_unreachable();
17873 }
17874 }
17875
17876 // Return the backend information for slice information.
17877
17878 Bexpression*
do_get_backend(Translate_context * context)17879 Slice_info_expression::do_get_backend(Translate_context* context)
17880 {
17881 Gogo* gogo = context->gogo();
17882 Bexpression* bslice = this->slice_->get_backend(context);
17883 switch (this->slice_info_)
17884 {
17885 case SLICE_INFO_VALUE_POINTER:
17886 case SLICE_INFO_LENGTH:
17887 case SLICE_INFO_CAPACITY:
17888 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
17889 this->location());
17890 break;
17891 default:
17892 go_unreachable();
17893 }
17894 }
17895
17896 // Dump ast representation for a type info expression.
17897
17898 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17899 Slice_info_expression::do_dump_expression(
17900 Ast_dump_context* ast_dump_context) const
17901 {
17902 ast_dump_context->ostream() << "sliceinfo(";
17903 this->slice_->dump_expression(ast_dump_context);
17904 ast_dump_context->ostream() << ",";
17905 ast_dump_context->ostream() <<
17906 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
17907 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
17908 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
17909 : "unknown");
17910 ast_dump_context->ostream() << ")";
17911 }
17912
17913 // Make a slice info expression.
17914
17915 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)17916 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
17917 Location location)
17918 {
17919 return new Slice_info_expression(slice, slice_info, location);
17920 }
17921
17922 // Class Slice_value_expression.
17923
17924 int
do_traverse(Traverse * traverse)17925 Slice_value_expression::do_traverse(Traverse* traverse)
17926 {
17927 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
17928 || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
17929 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
17930 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
17931 return TRAVERSE_EXIT;
17932 return TRAVERSE_CONTINUE;
17933 }
17934
17935 Expression*
do_copy()17936 Slice_value_expression::do_copy()
17937 {
17938 return new Slice_value_expression(this->type_->copy_expressions(),
17939 this->valmem_->copy(),
17940 this->len_->copy(), this->cap_->copy(),
17941 this->location());
17942 }
17943
17944 Bexpression*
do_get_backend(Translate_context * context)17945 Slice_value_expression::do_get_backend(Translate_context* context)
17946 {
17947 std::vector<Bexpression*> vals(3);
17948 vals[0] = this->valmem_->get_backend(context);
17949 vals[1] = this->len_->get_backend(context);
17950 vals[2] = this->cap_->get_backend(context);
17951
17952 Gogo* gogo = context->gogo();
17953 Btype* btype = this->type_->get_backend(gogo);
17954 return gogo->backend()->constructor_expression(btype, vals, this->location());
17955 }
17956
17957 void
do_dump_expression(Ast_dump_context * ast_dump_context) const17958 Slice_value_expression::do_dump_expression(
17959 Ast_dump_context* ast_dump_context) const
17960 {
17961 ast_dump_context->ostream() << "slicevalue(";
17962 ast_dump_context->ostream() << "values: ";
17963 this->valmem_->dump_expression(ast_dump_context);
17964 ast_dump_context->ostream() << ", length: ";
17965 this->len_->dump_expression(ast_dump_context);
17966 ast_dump_context->ostream() << ", capacity: ";
17967 this->cap_->dump_expression(ast_dump_context);
17968 ast_dump_context->ostream() << ")";
17969 }
17970
17971 Expression*
make_slice_value(Type * at,Expression * valmem,Expression * len,Expression * cap,Location location)17972 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
17973 Expression* cap, Location location)
17974 {
17975 go_assert(at->is_slice_type());
17976 go_assert(valmem->is_nil_expression()
17977 || (at->array_type()->element_type()
17978 == valmem->type()->points_to()));
17979 return new Slice_value_expression(at, valmem, len, cap, location);
17980 }
17981
17982 // Look through the expression of a Slice_value_expression's valmem to
17983 // find an call to makeslice. If found, return the call expression and
17984 // the containing temporary statement (if any).
17985
17986 std::pair<Call_expression*, Temporary_statement*>
find_makeslice_call(Expression * expr)17987 Expression::find_makeslice_call(Expression* expr)
17988 {
17989 Unsafe_type_conversion_expression* utce =
17990 expr->unsafe_conversion_expression();
17991 if (utce != NULL)
17992 expr = utce->expr();
17993
17994 Slice_value_expression* sve = expr->slice_value_expression();
17995 if (sve == NULL)
17996 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
17997 expr = sve->valmem();
17998
17999 utce = expr->unsafe_conversion_expression();
18000 if (utce != NULL)
18001 expr = utce->expr();
18002
18003 Temporary_reference_expression* tre = expr->temporary_reference_expression();
18004 Temporary_statement* ts = (tre != NULL ? tre->statement() : NULL);
18005 if (ts != NULL && ts->init() != NULL && !ts->assigned()
18006 && !ts->is_address_taken())
18007 expr = ts->init();
18008
18009 Call_expression* call = expr->call_expression();
18010 if (call == NULL)
18011 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
18012
18013 Func_expression* fe = call->fn()->func_expression();
18014 if (fe != NULL
18015 && fe->runtime_code() == Runtime::MAKESLICE)
18016 return std::make_pair(call, ts);
18017
18018 return std::make_pair<Call_expression*, Temporary_statement*>(NULL, NULL);
18019 }
18020
18021 // An expression that evaluates to some characteristic of a non-empty interface.
18022 // This is used to access the method table or underlying object of an interface.
18023
18024 class Interface_info_expression : public Expression
18025 {
18026 public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)18027 Interface_info_expression(Expression* iface, Interface_info iface_info,
18028 Location location)
18029 : Expression(EXPRESSION_INTERFACE_INFO, location),
18030 iface_(iface), iface_info_(iface_info)
18031 { }
18032
18033 protected:
18034 Type*
18035 do_type();
18036
18037 void
do_determine_type(const Type_context *)18038 do_determine_type(const Type_context*)
18039 { }
18040
18041 Expression*
do_copy()18042 do_copy()
18043 {
18044 return new Interface_info_expression(this->iface_->copy(),
18045 this->iface_info_, this->location());
18046 }
18047
18048 Bexpression*
18049 do_get_backend(Translate_context* context);
18050
18051 void
18052 do_dump_expression(Ast_dump_context*) const;
18053
18054 void
do_issue_nil_check()18055 do_issue_nil_check()
18056 { this->iface_->issue_nil_check(); }
18057
18058 private:
18059 // The interface for which we are getting information.
18060 Expression* iface_;
18061 // What information we want.
18062 Interface_info iface_info_;
18063 };
18064
18065 // Return the type of the interface info.
18066
18067 Type*
do_type()18068 Interface_info_expression::do_type()
18069 {
18070 switch (this->iface_info_)
18071 {
18072 case INTERFACE_INFO_METHODS:
18073 {
18074 typedef Unordered_map(Interface_type*, Type*) Hashtable;
18075 static Hashtable result_types;
18076
18077 Interface_type* itype = this->iface_->type()->interface_type();
18078
18079 Hashtable::const_iterator pr = result_types.find(itype);
18080 if (pr != result_types.end())
18081 return pr->second;
18082
18083 Type* pdt = Type::make_type_descriptor_ptr_type();
18084 if (itype->is_empty())
18085 {
18086 result_types[itype] = pdt;
18087 return pdt;
18088 }
18089
18090 Location loc = this->location();
18091 Struct_field_list* sfl = new Struct_field_list();
18092 sfl->push_back(
18093 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
18094
18095 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
18096 p != itype->methods()->end();
18097 ++p)
18098 {
18099 Function_type* ft = p->type()->function_type();
18100 go_assert(ft->receiver() == NULL);
18101
18102 const Typed_identifier_list* params = ft->parameters();
18103 Typed_identifier_list* mparams = new Typed_identifier_list();
18104 if (params != NULL)
18105 mparams->reserve(params->size() + 1);
18106 Type* vt = Type::make_pointer_type(Type::make_void_type());
18107 mparams->push_back(Typed_identifier("", vt, ft->location()));
18108 if (params != NULL)
18109 {
18110 for (Typed_identifier_list::const_iterator pp = params->begin();
18111 pp != params->end();
18112 ++pp)
18113 mparams->push_back(*pp);
18114 }
18115
18116 Typed_identifier_list* mresults = (ft->results() == NULL
18117 ? NULL
18118 : ft->results()->copy());
18119 Backend_function_type* mft =
18120 Type::make_backend_function_type(NULL, mparams, mresults,
18121 ft->location());
18122
18123 std::string fname = Gogo::unpack_hidden_name(p->name());
18124 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
18125 }
18126
18127 Struct_type* st = Type::make_struct_type(sfl, loc);
18128 st->set_is_struct_incomparable();
18129 Pointer_type *pt = Type::make_pointer_type(st);
18130 result_types[itype] = pt;
18131 return pt;
18132 }
18133 case INTERFACE_INFO_OBJECT:
18134 return Type::make_pointer_type(Type::make_void_type());
18135 default:
18136 go_unreachable();
18137 }
18138 }
18139
18140 // Return the backend representation for interface information.
18141
18142 Bexpression*
do_get_backend(Translate_context * context)18143 Interface_info_expression::do_get_backend(Translate_context* context)
18144 {
18145 Gogo* gogo = context->gogo();
18146 Bexpression* biface = this->iface_->get_backend(context);
18147 switch (this->iface_info_)
18148 {
18149 case INTERFACE_INFO_METHODS:
18150 case INTERFACE_INFO_OBJECT:
18151 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
18152 this->location());
18153 break;
18154 default:
18155 go_unreachable();
18156 }
18157 }
18158
18159 // Dump ast representation for an interface info expression.
18160
18161 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18162 Interface_info_expression::do_dump_expression(
18163 Ast_dump_context* ast_dump_context) const
18164 {
18165 bool is_empty = this->iface_->type()->interface_type()->is_empty();
18166 ast_dump_context->ostream() << "interfaceinfo(";
18167 this->iface_->dump_expression(ast_dump_context);
18168 ast_dump_context->ostream() << ",";
18169 ast_dump_context->ostream() <<
18170 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
18171 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
18172 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
18173 : "unknown");
18174 ast_dump_context->ostream() << ")";
18175 }
18176
18177 // Make an interface info expression.
18178
18179 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)18180 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
18181 Location location)
18182 {
18183 return new Interface_info_expression(iface, iface_info, location);
18184 }
18185
18186 // An expression that represents an interface value. The first field is either
18187 // a type descriptor for an empty interface or a pointer to the interface method
18188 // table for a non-empty interface. The second field is always the object.
18189
18190 class Interface_value_expression : public Expression
18191 {
18192 public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)18193 Interface_value_expression(Type* type, Expression* first_field,
18194 Expression* obj, Location location)
18195 : Expression(EXPRESSION_INTERFACE_VALUE, location),
18196 type_(type), first_field_(first_field), obj_(obj)
18197 { }
18198
18199 protected:
18200 int
18201 do_traverse(Traverse*);
18202
18203 Type*
do_type()18204 do_type()
18205 { return this->type_; }
18206
18207 void
do_determine_type(const Type_context *)18208 do_determine_type(const Type_context*)
18209 { go_unreachable(); }
18210
18211 Expression*
do_copy()18212 do_copy()
18213 {
18214 return new Interface_value_expression(this->type_->copy_expressions(),
18215 this->first_field_->copy(),
18216 this->obj_->copy(), this->location());
18217 }
18218
18219 Bexpression*
18220 do_get_backend(Translate_context* context);
18221
18222 void
18223 do_dump_expression(Ast_dump_context*) const;
18224
18225 private:
18226 // The type of the interface value.
18227 Type* type_;
18228 // The first field of the interface (either a type descriptor or a pointer
18229 // to the method table.
18230 Expression* first_field_;
18231 // The underlying object of the interface.
18232 Expression* obj_;
18233 };
18234
18235 int
do_traverse(Traverse * traverse)18236 Interface_value_expression::do_traverse(Traverse* traverse)
18237 {
18238 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
18239 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
18240 return TRAVERSE_EXIT;
18241 return TRAVERSE_CONTINUE;
18242 }
18243
18244 Bexpression*
do_get_backend(Translate_context * context)18245 Interface_value_expression::do_get_backend(Translate_context* context)
18246 {
18247 std::vector<Bexpression*> vals(2);
18248 vals[0] = this->first_field_->get_backend(context);
18249 vals[1] = this->obj_->get_backend(context);
18250
18251 Gogo* gogo = context->gogo();
18252 Btype* btype = this->type_->get_backend(gogo);
18253 return gogo->backend()->constructor_expression(btype, vals, this->location());
18254 }
18255
18256 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18257 Interface_value_expression::do_dump_expression(
18258 Ast_dump_context* ast_dump_context) const
18259 {
18260 ast_dump_context->ostream() << "interfacevalue(";
18261 ast_dump_context->ostream() <<
18262 (this->type_->interface_type()->is_empty()
18263 ? "type_descriptor: "
18264 : "methods: ");
18265 this->first_field_->dump_expression(ast_dump_context);
18266 ast_dump_context->ostream() << ", object: ";
18267 this->obj_->dump_expression(ast_dump_context);
18268 ast_dump_context->ostream() << ")";
18269 }
18270
18271 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)18272 Expression::make_interface_value(Type* type, Expression* first_value,
18273 Expression* object, Location location)
18274 {
18275 return new Interface_value_expression(type, first_value, object, location);
18276 }
18277
18278 // An interface method table for a pair of types: an interface type and a type
18279 // that implements that interface.
18280
18281 class Interface_mtable_expression : public Expression
18282 {
18283 public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)18284 Interface_mtable_expression(Interface_type* itype, Type* type,
18285 bool is_pointer, Location location)
18286 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
18287 itype_(itype), type_(type), is_pointer_(is_pointer),
18288 method_table_type_(NULL), bvar_(NULL)
18289 { }
18290
18291 protected:
18292 int
18293 do_traverse(Traverse*);
18294
18295 Type*
18296 do_type();
18297
18298 bool
do_is_static_initializer() const18299 do_is_static_initializer() const
18300 { return true; }
18301
18302 void
do_determine_type(const Type_context *)18303 do_determine_type(const Type_context*)
18304 { go_unreachable(); }
18305
18306 Expression*
do_copy()18307 do_copy()
18308 {
18309 Interface_type* itype = this->itype_->copy_expressions()->interface_type();
18310 return new Interface_mtable_expression(itype,
18311 this->type_->copy_expressions(),
18312 this->is_pointer_, this->location());
18313 }
18314
18315 bool
do_is_addressable() const18316 do_is_addressable() const
18317 { return true; }
18318
18319 Bexpression*
18320 do_get_backend(Translate_context* context);
18321
18322 void
18323 do_dump_expression(Ast_dump_context*) const;
18324
18325 private:
18326 // The interface type for which the methods are defined.
18327 Interface_type* itype_;
18328 // The type to construct the interface method table for.
18329 Type* type_;
18330 // Whether this table contains the method set for the receiver type or the
18331 // pointer receiver type.
18332 bool is_pointer_;
18333 // The type of the method table.
18334 Type* method_table_type_;
18335 // The backend variable that refers to the interface method table.
18336 Bvariable* bvar_;
18337 };
18338
18339 int
do_traverse(Traverse * traverse)18340 Interface_mtable_expression::do_traverse(Traverse* traverse)
18341 {
18342 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
18343 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
18344 return TRAVERSE_EXIT;
18345 return TRAVERSE_CONTINUE;
18346 }
18347
18348 Type*
do_type()18349 Interface_mtable_expression::do_type()
18350 {
18351 if (this->method_table_type_ != NULL)
18352 return this->method_table_type_;
18353
18354 const Typed_identifier_list* interface_methods = this->itype_->methods();
18355 go_assert(!interface_methods->empty());
18356
18357 Struct_field_list* sfl = new Struct_field_list;
18358 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
18359 this->location());
18360 sfl->push_back(Struct_field(tid));
18361 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
18362 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18363 p != interface_methods->end();
18364 ++p)
18365 {
18366 // We want C function pointers here, not func descriptors; model
18367 // using void* pointers.
18368 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
18369 sfl->push_back(Struct_field(method));
18370 }
18371 Struct_type* st = Type::make_struct_type(sfl, this->location());
18372 st->set_is_struct_incomparable();
18373 this->method_table_type_ = st;
18374 return this->method_table_type_;
18375 }
18376
18377 Bexpression*
do_get_backend(Translate_context * context)18378 Interface_mtable_expression::do_get_backend(Translate_context* context)
18379 {
18380 Gogo* gogo = context->gogo();
18381 Location loc = Linemap::predeclared_location();
18382 if (this->bvar_ != NULL)
18383 return gogo->backend()->var_expression(this->bvar_, this->location());
18384
18385 const Typed_identifier_list* interface_methods = this->itype_->methods();
18386 go_assert(!interface_methods->empty());
18387
18388 std::string mangled_name =
18389 gogo->interface_method_table_name(this->itype_, this->type_,
18390 this->is_pointer_);
18391
18392 // Set is_public if we are converting a named type to an interface
18393 // type that is defined in the same package as the named type, and
18394 // the interface has hidden methods. In that case the interface
18395 // method table will be defined by the package that defines the
18396 // types.
18397 bool is_public = false;
18398 if (this->type_->named_type() != NULL
18399 && (this->type_->named_type()->named_object()->package()
18400 == this->itype_->package()))
18401 {
18402 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18403 p != interface_methods->end();
18404 ++p)
18405 {
18406 if (Gogo::is_hidden_name(p->name()))
18407 {
18408 is_public = true;
18409 break;
18410 }
18411 }
18412 }
18413
18414 if (is_public
18415 && this->type_->named_type()->named_object()->package() != NULL)
18416 {
18417 // The interface conversion table is defined elsewhere.
18418 Btype* btype = this->type()->get_backend(gogo);
18419 this->bvar_ =
18420 gogo->backend()->immutable_struct_reference(mangled_name, "",
18421 btype, loc);
18422 return gogo->backend()->var_expression(this->bvar_, this->location());
18423 }
18424
18425 // The first element is the type descriptor.
18426 Type* td_type;
18427 if (!this->is_pointer_)
18428 td_type = this->type_;
18429 else
18430 td_type = Type::make_pointer_type(this->type_);
18431
18432 std::vector<Backend::Btyped_identifier> bstructfields;
18433
18434 // Build an interface method table for a type: a type descriptor followed by a
18435 // list of function pointers, one for each interface method. This is used for
18436 // interfaces.
18437 Expression_list* svals = new Expression_list();
18438 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
18439 svals->push_back(tdescriptor);
18440
18441 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
18442 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
18443 bstructfields.push_back(btd);
18444
18445 Named_type* nt = this->type_->named_type();
18446 Struct_type* st = this->type_->struct_type();
18447 go_assert(nt != NULL || st != NULL);
18448
18449 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
18450 p != interface_methods->end();
18451 ++p)
18452 {
18453 bool is_ambiguous;
18454 Method* m;
18455 if (nt != NULL)
18456 m = nt->method_function(p->name(), &is_ambiguous);
18457 else
18458 m = st->method_function(p->name(), &is_ambiguous);
18459 go_assert(m != NULL);
18460 Named_object* no =
18461 (this->is_pointer_
18462 && this->type_->is_direct_iface_type()
18463 && m->is_value_method()
18464 ? m->iface_stub_object()
18465 : m->named_object());
18466
18467 go_assert(no->is_function() || no->is_function_declaration());
18468
18469 Function_type* fcn_type = (no->is_function()
18470 ? no->func_value()->type()
18471 : no->func_declaration_value()->type());
18472 Btype* fcn_btype = fcn_type->get_backend_fntype(gogo);
18473 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
18474 bstructfields.push_back(bmtype);
18475
18476 svals->push_back(Expression::make_func_code_reference(no, loc));
18477 }
18478
18479 Btype *btype = gogo->backend()->struct_type(bstructfields);
18480 std::vector<Bexpression*> ctor_bexprs;
18481 for (Expression_list::const_iterator pe = svals->begin();
18482 pe != svals->end();
18483 ++pe)
18484 {
18485 ctor_bexprs.push_back((*pe)->get_backend(context));
18486 }
18487 Bexpression* ctor =
18488 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
18489
18490 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, "", false,
18491 !is_public, btype, loc);
18492 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
18493 !is_public, btype, loc, ctor);
18494 return gogo->backend()->var_expression(this->bvar_, loc);
18495 }
18496
18497 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18498 Interface_mtable_expression::do_dump_expression(
18499 Ast_dump_context* ast_dump_context) const
18500 {
18501 ast_dump_context->ostream() << "__go_"
18502 << (this->is_pointer_ ? "pimt__" : "imt_");
18503 ast_dump_context->dump_type(this->itype_);
18504 ast_dump_context->ostream() << "__";
18505 ast_dump_context->dump_type(this->type_);
18506 }
18507
18508 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)18509 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
18510 bool is_pointer, Location location)
18511 {
18512 return new Interface_mtable_expression(itype, type, is_pointer, location);
18513 }
18514
18515 // An expression which evaluates to the offset of a field within a
18516 // struct. This, like Type_info_expression, q.v., is only used to
18517 // initialize fields of a type descriptor.
18518
18519 class Struct_field_offset_expression : public Expression
18520 {
18521 public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)18522 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
18523 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
18524 Linemap::predeclared_location()),
18525 type_(type), field_(field)
18526 { }
18527
18528 protected:
18529 bool
do_is_static_initializer() const18530 do_is_static_initializer() const
18531 { return true; }
18532
18533 Type*
do_type()18534 do_type()
18535 { return Type::lookup_integer_type("uintptr"); }
18536
18537 void
do_determine_type(const Type_context *)18538 do_determine_type(const Type_context*)
18539 { }
18540
18541 Expression*
do_copy()18542 do_copy()
18543 { return this; }
18544
18545 Bexpression*
18546 do_get_backend(Translate_context* context);
18547
18548 void
18549 do_dump_expression(Ast_dump_context*) const;
18550
18551 private:
18552 // The type of the struct.
18553 Struct_type* type_;
18554 // The field.
18555 const Struct_field* field_;
18556 };
18557
18558 // Return the backend representation for a struct field offset.
18559
18560 Bexpression*
do_get_backend(Translate_context * context)18561 Struct_field_offset_expression::do_get_backend(Translate_context* context)
18562 {
18563 const Struct_field_list* fields = this->type_->fields();
18564 Struct_field_list::const_iterator p;
18565 unsigned i = 0;
18566 for (p = fields->begin();
18567 p != fields->end();
18568 ++p, ++i)
18569 if (&*p == this->field_)
18570 break;
18571 go_assert(&*p == this->field_);
18572
18573 Gogo* gogo = context->gogo();
18574 Btype* btype = this->type_->get_backend(gogo);
18575
18576 int64_t offset = gogo->backend()->type_field_offset(btype, i);
18577 Type* uptr_type = Type::lookup_integer_type("uintptr");
18578 Expression* ret =
18579 Expression::make_integer_int64(offset, uptr_type,
18580 Linemap::predeclared_location());
18581 return ret->get_backend(context);
18582 }
18583
18584 // Dump ast representation for a struct field offset expression.
18585
18586 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18587 Struct_field_offset_expression::do_dump_expression(
18588 Ast_dump_context* ast_dump_context) const
18589 {
18590 ast_dump_context->ostream() << "unsafe.Offsetof(";
18591 ast_dump_context->dump_type(this->type_);
18592 ast_dump_context->ostream() << '.';
18593 ast_dump_context->ostream() <<
18594 Gogo::message_name(this->field_->field_name());
18595 ast_dump_context->ostream() << ")";
18596 }
18597
18598 // Make an expression for a struct field offset.
18599
18600 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)18601 Expression::make_struct_field_offset(Struct_type* type,
18602 const Struct_field* field)
18603 {
18604 return new Struct_field_offset_expression(type, field);
18605 }
18606
18607 // An expression which evaluates to the address of an unnamed label.
18608
18609 class Label_addr_expression : public Expression
18610 {
18611 public:
Label_addr_expression(Label * label,Location location)18612 Label_addr_expression(Label* label, Location location)
18613 : Expression(EXPRESSION_LABEL_ADDR, location),
18614 label_(label)
18615 { }
18616
18617 protected:
18618 Type*
do_type()18619 do_type()
18620 { return Type::make_pointer_type(Type::make_void_type()); }
18621
18622 void
do_determine_type(const Type_context *)18623 do_determine_type(const Type_context*)
18624 { }
18625
18626 Expression*
do_copy()18627 do_copy()
18628 { return new Label_addr_expression(this->label_, this->location()); }
18629
18630 Bexpression*
do_get_backend(Translate_context * context)18631 do_get_backend(Translate_context* context)
18632 { return this->label_->get_addr(context, this->location()); }
18633
18634 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18635 do_dump_expression(Ast_dump_context* ast_dump_context) const
18636 { ast_dump_context->ostream() << this->label_->name(); }
18637
18638 private:
18639 // The label whose address we are taking.
18640 Label* label_;
18641 };
18642
18643 // Make an expression for the address of an unnamed label.
18644
18645 Expression*
make_label_addr(Label * label,Location location)18646 Expression::make_label_addr(Label* label, Location location)
18647 {
18648 return new Label_addr_expression(label, location);
18649 }
18650
18651 // Class Conditional_expression.
18652
18653 // Traversal.
18654
18655 int
do_traverse(Traverse * traverse)18656 Conditional_expression::do_traverse(Traverse* traverse)
18657 {
18658 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
18659 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
18660 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
18661 return TRAVERSE_EXIT;
18662 return TRAVERSE_CONTINUE;
18663 }
18664
18665 // Return the type of the conditional expression.
18666
18667 Type*
do_type()18668 Conditional_expression::do_type()
18669 {
18670 Type* result_type = Type::make_void_type();
18671 if (Type::are_identical(this->then_->type(), this->else_->type(),
18672 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
18673 NULL))
18674 result_type = this->then_->type();
18675 else if (this->then_->is_nil_expression()
18676 || this->else_->is_nil_expression())
18677 result_type = (!this->then_->is_nil_expression()
18678 ? this->then_->type()
18679 : this->else_->type());
18680 return result_type;
18681 }
18682
18683 // Determine type for a conditional expression.
18684
18685 void
do_determine_type(const Type_context * context)18686 Conditional_expression::do_determine_type(const Type_context* context)
18687 {
18688 this->cond_->determine_type_no_context();
18689 this->then_->determine_type(context);
18690 this->else_->determine_type(context);
18691 }
18692
18693 // Get the backend representation of a conditional expression.
18694
18695 Bexpression*
do_get_backend(Translate_context * context)18696 Conditional_expression::do_get_backend(Translate_context* context)
18697 {
18698 Gogo* gogo = context->gogo();
18699 Btype* result_btype = this->type()->get_backend(gogo);
18700 Bexpression* cond = this->cond_->get_backend(context);
18701 Bexpression* then = this->then_->get_backend(context);
18702 Bexpression* belse = this->else_->get_backend(context);
18703 Bfunction* bfn = context->function()->func_value()->get_decl();
18704 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
18705 belse, this->location());
18706 }
18707
18708 // Dump ast representation of a conditional expression.
18709
18710 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18711 Conditional_expression::do_dump_expression(
18712 Ast_dump_context* ast_dump_context) const
18713 {
18714 ast_dump_context->ostream() << "(";
18715 ast_dump_context->dump_expression(this->cond_);
18716 ast_dump_context->ostream() << " ? ";
18717 ast_dump_context->dump_expression(this->then_);
18718 ast_dump_context->ostream() << " : ";
18719 ast_dump_context->dump_expression(this->else_);
18720 ast_dump_context->ostream() << ") ";
18721 }
18722
18723 // Make a conditional expression.
18724
18725 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)18726 Expression::make_conditional(Expression* cond, Expression* then,
18727 Expression* else_expr, Location location)
18728 {
18729 return new Conditional_expression(cond, then, else_expr, location);
18730 }
18731
18732 // Class Compound_expression.
18733
18734 // Traversal.
18735
18736 int
do_traverse(Traverse * traverse)18737 Compound_expression::do_traverse(Traverse* traverse)
18738 {
18739 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
18740 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
18741 return TRAVERSE_EXIT;
18742 return TRAVERSE_CONTINUE;
18743 }
18744
18745 // Return the type of the compound expression.
18746
18747 Type*
do_type()18748 Compound_expression::do_type()
18749 {
18750 return this->expr_->type();
18751 }
18752
18753 // Determine type for a compound expression.
18754
18755 void
do_determine_type(const Type_context * context)18756 Compound_expression::do_determine_type(const Type_context* context)
18757 {
18758 this->init_->determine_type_no_context();
18759 this->expr_->determine_type(context);
18760 }
18761
18762 // Get the backend representation of a compound expression.
18763
18764 Bexpression*
do_get_backend(Translate_context * context)18765 Compound_expression::do_get_backend(Translate_context* context)
18766 {
18767 Gogo* gogo = context->gogo();
18768 Bexpression* binit = this->init_->get_backend(context);
18769 Bfunction* bfunction = context->function()->func_value()->get_decl();
18770 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
18771 binit);
18772 Bexpression* bexpr = this->expr_->get_backend(context);
18773 return gogo->backend()->compound_expression(init_stmt, bexpr,
18774 this->location());
18775 }
18776
18777 // Dump ast representation of a conditional expression.
18778
18779 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18780 Compound_expression::do_dump_expression(
18781 Ast_dump_context* ast_dump_context) const
18782 {
18783 ast_dump_context->ostream() << "(";
18784 ast_dump_context->dump_expression(this->init_);
18785 ast_dump_context->ostream() << ",";
18786 ast_dump_context->dump_expression(this->expr_);
18787 ast_dump_context->ostream() << ") ";
18788 }
18789
18790 // Make a compound expression.
18791
18792 Expression*
make_compound(Expression * init,Expression * expr,Location location)18793 Expression::make_compound(Expression* init, Expression* expr, Location location)
18794 {
18795 return new Compound_expression(init, expr, location);
18796 }
18797
18798 // Class Backend_expression.
18799
18800 int
do_traverse(Traverse *)18801 Backend_expression::do_traverse(Traverse*)
18802 {
18803 return TRAVERSE_CONTINUE;
18804 }
18805
18806 Expression*
do_copy()18807 Backend_expression::do_copy()
18808 {
18809 return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
18810 this->location());
18811 }
18812
18813 void
do_dump_expression(Ast_dump_context * ast_dump_context) const18814 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
18815 {
18816 ast_dump_context->ostream() << "backend_expression<";
18817 ast_dump_context->dump_type(this->type_);
18818 ast_dump_context->ostream() << ">";
18819 }
18820
18821 Expression*
make_backend(Bexpression * bexpr,Type * type,Location location)18822 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
18823 {
18824 return new Backend_expression(bexpr, type, location);
18825 }
18826
18827 // Import an expression. This comes at the end in order to see the
18828 // various class definitions.
18829
18830 Expression*
import_expression(Import_expression * imp,Location loc)18831 Expression::import_expression(Import_expression* imp, Location loc)
18832 {
18833 Expression* expr = Expression::import_expression_without_suffix(imp, loc);
18834 while (true)
18835 {
18836 if (imp->match_c_string("("))
18837 {
18838 imp->advance(1);
18839 Expression_list* args = new Expression_list();
18840 bool is_varargs = false;
18841 while (!imp->match_c_string(")"))
18842 {
18843 Expression* arg = Expression::import_expression(imp, loc);
18844 if (arg->is_error_expression())
18845 return arg;
18846 args->push_back(arg);
18847 if (imp->match_c_string(")"))
18848 break;
18849 else if (imp->match_c_string("...)"))
18850 {
18851 imp->advance(3);
18852 is_varargs = true;
18853 break;
18854 }
18855 imp->require_c_string(", ");
18856 }
18857 imp->require_c_string(")");
18858 expr = Expression::make_call(expr, args, is_varargs, loc);
18859 expr->call_expression()->set_varargs_are_lowered();
18860 }
18861 else if (imp->match_c_string("["))
18862 {
18863 imp->advance(1);
18864 Expression* start = Expression::import_expression(imp, loc);
18865 Expression* end = NULL;
18866 Expression* cap = NULL;
18867 if (imp->match_c_string(":"))
18868 {
18869 imp->advance(1);
18870 int c = imp->peek_char();
18871 if (c == ':' || c == ']')
18872 end = Expression::make_nil(loc);
18873 else
18874 end = Expression::import_expression(imp, loc);
18875 if (imp->match_c_string(":"))
18876 {
18877 imp->advance(1);
18878 cap = Expression::import_expression(imp, loc);
18879 }
18880 }
18881 imp->require_c_string("]");
18882 expr = Expression::make_index(expr, start, end, cap, loc);
18883 }
18884 else
18885 break;
18886 }
18887
18888 return expr;
18889 }
18890
18891 // Import an expression without considering a suffix (function
18892 // arguments, index operations, etc.).
18893
18894 Expression*
import_expression_without_suffix(Import_expression * imp,Location loc)18895 Expression::import_expression_without_suffix(Import_expression* imp,
18896 Location loc)
18897 {
18898 int c = imp->peek_char();
18899 if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
18900 return Unary_expression::do_import(imp, loc);
18901 else if (c == '(')
18902 return Binary_expression::do_import(imp, loc);
18903 else if (imp->match_c_string("$true")
18904 || imp->match_c_string("$false")
18905 || (imp->version() < EXPORT_FORMAT_V3
18906 && (imp->match_c_string("true")
18907 || imp->match_c_string("false"))))
18908 return Boolean_expression::do_import(imp, loc);
18909 else if (c == '"')
18910 return String_expression::do_import(imp, loc);
18911 else if (c == '-' || (c >= '0' && c <= '9'))
18912 {
18913 // This handles integers, floats and complex constants.
18914 return Integer_expression::do_import(imp, loc);
18915 }
18916 else if (imp->match_c_string("<-"))
18917 return Receive_expression::do_import(imp, loc);
18918 else if (imp->match_c_string("$nil")
18919 || (imp->version() < EXPORT_FORMAT_V3
18920 && imp->match_c_string("nil")))
18921 return Nil_expression::do_import(imp, loc);
18922 else if (imp->match_c_string("$convert")
18923 || (imp->version() < EXPORT_FORMAT_V3
18924 && imp->match_c_string("convert")))
18925 return Type_conversion_expression::do_import(imp, loc);
18926
18927 Import_function_body* ifb = imp->ifb();
18928 if (ifb == NULL)
18929 {
18930 go_error_at(imp->location(), "import error: expected expression");
18931 return Expression::make_error(loc);
18932 }
18933 if (ifb->saw_error())
18934 return Expression::make_error(loc);
18935
18936 if (ifb->match_c_string("$t"))
18937 return Temporary_reference_expression::do_import(ifb, loc);
18938
18939 return Expression::import_identifier(ifb, loc);
18940 }
18941
18942 // Import an identifier in an expression. This is a reference to a
18943 // variable or function.
18944
18945 Expression*
import_identifier(Import_function_body * ifb,Location loc)18946 Expression::import_identifier(Import_function_body* ifb, Location loc)
18947 {
18948 std::string id;
18949 Package* pkg;
18950 bool is_exported;
18951 if (!Import::read_qualified_identifier(ifb, &id, &pkg, &is_exported))
18952 {
18953 if (!ifb->saw_error())
18954 go_error_at(ifb->location(),
18955 "import error for %qs: bad qualified identifier at %lu",
18956 ifb->name().c_str(),
18957 static_cast<unsigned long>(ifb->off()));
18958 ifb->set_saw_error();
18959 return Expression::make_error(loc);
18960 }
18961
18962 Named_object* no = NULL;
18963 if (pkg == NULL && is_exported)
18964 no = ifb->block()->bindings()->lookup(id);
18965 if (no == NULL)
18966 {
18967 const Package* ipkg = pkg;
18968 if (ipkg == NULL)
18969 ipkg = ifb->function()->package();
18970 if (!is_exported)
18971 id = '.' + ipkg->pkgpath() + '.' + id;
18972 no = ipkg->bindings()->lookup(id);
18973 }
18974 if (no == NULL)
18975 no = ifb->gogo()->lookup_global(id.c_str());
18976
18977 if (no == NULL)
18978 {
18979 if (!ifb->saw_error())
18980 go_error_at(ifb->location(),
18981 "import error for %qs: lookup of %qs failed",
18982 ifb->name().c_str(), id.c_str());
18983 ifb->set_saw_error();
18984 return Expression::make_error(loc);
18985 }
18986
18987 if (no->is_variable() || no->is_result_variable())
18988 return Expression::make_var_reference(no, loc);
18989 else if (no->is_function() || no->is_function_declaration())
18990 return Expression::make_func_reference(no, NULL, loc);
18991 else
18992 {
18993 if (!ifb->saw_error())
18994 go_error_at(ifb->location(),
18995 ("import error for %qs: "
18996 "unexpected type of identifier %qs (%d)"),
18997 ifb->name().c_str(),
18998 id.c_str(), no->classification());
18999 ifb->set_saw_error();
19000 return Expression::make_error(loc);
19001 }
19002 }
19003
19004 // Class Expression_list.
19005
19006 // Traverse the list.
19007
19008 int
traverse(Traverse * traverse)19009 Expression_list::traverse(Traverse* traverse)
19010 {
19011 for (Expression_list::iterator p = this->begin();
19012 p != this->end();
19013 ++p)
19014 {
19015 if (*p != NULL)
19016 {
19017 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
19018 return TRAVERSE_EXIT;
19019 }
19020 }
19021 return TRAVERSE_CONTINUE;
19022 }
19023
19024 // Copy the list.
19025
19026 Expression_list*
copy()19027 Expression_list::copy()
19028 {
19029 Expression_list* ret = new Expression_list();
19030 for (Expression_list::iterator p = this->begin();
19031 p != this->end();
19032 ++p)
19033 {
19034 if (*p == NULL)
19035 ret->push_back(NULL);
19036 else
19037 ret->push_back((*p)->copy());
19038 }
19039 return ret;
19040 }
19041
19042 // Return whether an expression list has an error expression.
19043
19044 bool
contains_error() const19045 Expression_list::contains_error() const
19046 {
19047 for (Expression_list::const_iterator p = this->begin();
19048 p != this->end();
19049 ++p)
19050 if (*p != NULL && (*p)->is_error_expression())
19051 return true;
19052 return false;
19053 }
19054
19055 // Class Numeric_constant.
19056
19057 // Destructor.
19058
~Numeric_constant()19059 Numeric_constant::~Numeric_constant()
19060 {
19061 this->clear();
19062 }
19063
19064 // Copy constructor.
19065
Numeric_constant(const Numeric_constant & a)19066 Numeric_constant::Numeric_constant(const Numeric_constant& a)
19067 : classification_(a.classification_), type_(a.type_)
19068 {
19069 switch (a.classification_)
19070 {
19071 case NC_INVALID:
19072 break;
19073 case NC_INT:
19074 case NC_RUNE:
19075 mpz_init_set(this->u_.int_val, a.u_.int_val);
19076 break;
19077 case NC_FLOAT:
19078 mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
19079 break;
19080 case NC_COMPLEX:
19081 mpc_init2(this->u_.complex_val, mpc_precision);
19082 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
19083 break;
19084 default:
19085 go_unreachable();
19086 }
19087 }
19088
19089 // Assignment operator.
19090
19091 Numeric_constant&
operator =(const Numeric_constant & a)19092 Numeric_constant::operator=(const Numeric_constant& a)
19093 {
19094 this->clear();
19095 this->classification_ = a.classification_;
19096 this->type_ = a.type_;
19097 switch (a.classification_)
19098 {
19099 case NC_INVALID:
19100 break;
19101 case NC_INT:
19102 case NC_RUNE:
19103 mpz_init_set(this->u_.int_val, a.u_.int_val);
19104 break;
19105 case NC_FLOAT:
19106 mpfr_init_set(this->u_.float_val, a.u_.float_val, MPFR_RNDN);
19107 break;
19108 case NC_COMPLEX:
19109 mpc_init2(this->u_.complex_val, mpc_precision);
19110 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
19111 break;
19112 default:
19113 go_unreachable();
19114 }
19115 return *this;
19116 }
19117
19118 // Check equality with another numeric constant.
19119
19120 bool
equals(const Numeric_constant & a) const19121 Numeric_constant::equals(const Numeric_constant& a) const
19122 {
19123 if (this->classification_ != a.classification_)
19124 return false;
19125
19126 if (this->type_ != NULL && a.type_ != NULL
19127 && !Type::are_identical(this->type_, a.type_,
19128 Type::COMPARE_ALIASES, NULL))
19129 return false;
19130
19131 switch (a.classification_)
19132 {
19133 case NC_INVALID:
19134 break;
19135 case NC_INT:
19136 case NC_RUNE:
19137 return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
19138 case NC_FLOAT:
19139 return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
19140 case NC_COMPLEX:
19141 return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
19142 default:
19143 go_unreachable();
19144 }
19145 return false;
19146 }
19147
19148 // Clear the contents.
19149
19150 void
clear()19151 Numeric_constant::clear()
19152 {
19153 switch (this->classification_)
19154 {
19155 case NC_INVALID:
19156 break;
19157 case NC_INT:
19158 case NC_RUNE:
19159 mpz_clear(this->u_.int_val);
19160 break;
19161 case NC_FLOAT:
19162 mpfr_clear(this->u_.float_val);
19163 break;
19164 case NC_COMPLEX:
19165 mpc_clear(this->u_.complex_val);
19166 break;
19167 default:
19168 go_unreachable();
19169 }
19170 this->classification_ = NC_INVALID;
19171 }
19172
19173 // Set to an unsigned long value.
19174
19175 void
set_unsigned_long(Type * type,unsigned long val)19176 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
19177 {
19178 this->clear();
19179 this->classification_ = NC_INT;
19180 this->type_ = type;
19181 mpz_init_set_ui(this->u_.int_val, val);
19182 }
19183
19184 // Set to an integer value.
19185
19186 void
set_int(Type * type,const mpz_t val)19187 Numeric_constant::set_int(Type* type, const mpz_t val)
19188 {
19189 this->clear();
19190 this->classification_ = NC_INT;
19191 this->type_ = type;
19192 mpz_init_set(this->u_.int_val, val);
19193 }
19194
19195 // Set to a rune value.
19196
19197 void
set_rune(Type * type,const mpz_t val)19198 Numeric_constant::set_rune(Type* type, const mpz_t val)
19199 {
19200 this->clear();
19201 this->classification_ = NC_RUNE;
19202 this->type_ = type;
19203 mpz_init_set(this->u_.int_val, val);
19204 }
19205
19206 // Set to a floating point value.
19207
19208 void
set_float(Type * type,const mpfr_t val)19209 Numeric_constant::set_float(Type* type, const mpfr_t val)
19210 {
19211 this->clear();
19212 this->classification_ = NC_FLOAT;
19213 this->type_ = type;
19214
19215 // Numeric constants do not have negative zero values, so remove
19216 // them here. They also don't have infinity or NaN values, but we
19217 // should never see them here.
19218 int bits = 0;
19219 if (type != NULL
19220 && type->float_type() != NULL
19221 && !type->float_type()->is_abstract())
19222 bits = type->float_type()->bits();
19223 if (Numeric_constant::is_float_neg_zero(val, bits))
19224 mpfr_init_set_ui(this->u_.float_val, 0, MPFR_RNDN);
19225 else
19226 mpfr_init_set(this->u_.float_val, val, MPFR_RNDN);
19227 }
19228
19229 // Set to a complex value.
19230
19231 void
set_complex(Type * type,const mpc_t val)19232 Numeric_constant::set_complex(Type* type, const mpc_t val)
19233 {
19234 this->clear();
19235 this->classification_ = NC_COMPLEX;
19236 this->type_ = type;
19237
19238 // Avoid negative zero as in set_float.
19239 int bits = 0;
19240 if (type != NULL
19241 && type->complex_type() != NULL
19242 && !type->complex_type()->is_abstract())
19243 bits = type->complex_type()->bits() / 2;
19244
19245 mpfr_t real;
19246 mpfr_init_set(real, mpc_realref(val), MPFR_RNDN);
19247 if (Numeric_constant::is_float_neg_zero(real, bits))
19248 mpfr_set_ui(real, 0, MPFR_RNDN);
19249
19250 mpfr_t imag;
19251 mpfr_init_set(imag, mpc_imagref(val), MPFR_RNDN);
19252 if (Numeric_constant::is_float_neg_zero(imag, bits))
19253 mpfr_set_ui(imag, 0, MPFR_RNDN);
19254
19255 mpc_init2(this->u_.complex_val, mpc_precision);
19256 mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
19257
19258 mpfr_clear(real);
19259 mpfr_clear(imag);
19260 }
19261
19262 // Return whether VAL, at a precision of BITS, is a negative zero.
19263 // BITS may be zero in which case it is ignored.
19264
19265 bool
is_float_neg_zero(const mpfr_t val,int bits)19266 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
19267 {
19268 if (!mpfr_signbit(val))
19269 return false;
19270 if (mpfr_zero_p(val))
19271 return true;
19272 mpfr_exp_t min_exp;
19273 switch (bits)
19274 {
19275 case 0:
19276 return false;
19277 case 32:
19278 // In a denormalized float32 the exponent is -126, and there are
19279 // 24 bits of which at least the last must be 1, so the smallest
19280 // representable non-zero exponent is -126 - (24 - 1) == -149.
19281 min_exp = -149;
19282 break;
19283 case 64:
19284 // Minimum exponent is -1022, there are 53 bits.
19285 min_exp = -1074;
19286 break;
19287 default:
19288 go_unreachable();
19289 }
19290 return mpfr_get_exp(val) < min_exp;
19291 }
19292
19293 // Get an int value.
19294
19295 void
get_int(mpz_t * val) const19296 Numeric_constant::get_int(mpz_t* val) const
19297 {
19298 go_assert(this->is_int());
19299 mpz_init_set(*val, this->u_.int_val);
19300 }
19301
19302 // Get a rune value.
19303
19304 void
get_rune(mpz_t * val) const19305 Numeric_constant::get_rune(mpz_t* val) const
19306 {
19307 go_assert(this->is_rune());
19308 mpz_init_set(*val, this->u_.int_val);
19309 }
19310
19311 // Get a floating point value.
19312
19313 void
get_float(mpfr_t * val) const19314 Numeric_constant::get_float(mpfr_t* val) const
19315 {
19316 go_assert(this->is_float());
19317 mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19318 }
19319
19320 // Get a complex value.
19321
19322 void
get_complex(mpc_t * val) const19323 Numeric_constant::get_complex(mpc_t* val) const
19324 {
19325 go_assert(this->is_complex());
19326 mpc_init2(*val, mpc_precision);
19327 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19328 }
19329
19330 // Express value as unsigned long if possible.
19331
19332 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const19333 Numeric_constant::to_unsigned_long(unsigned long* val) const
19334 {
19335 switch (this->classification_)
19336 {
19337 case NC_INT:
19338 case NC_RUNE:
19339 return this->mpz_to_unsigned_long(this->u_.int_val, val);
19340 case NC_FLOAT:
19341 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
19342 case NC_COMPLEX:
19343 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19344 return NC_UL_NOTINT;
19345 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
19346 val);
19347 default:
19348 go_unreachable();
19349 }
19350 }
19351
19352 // Express integer value as unsigned long if possible.
19353
19354 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const19355 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
19356 unsigned long *val) const
19357 {
19358 if (mpz_sgn(ival) < 0)
19359 return NC_UL_NEGATIVE;
19360 unsigned long ui = mpz_get_ui(ival);
19361 if (mpz_cmp_ui(ival, ui) != 0)
19362 return NC_UL_BIG;
19363 *val = ui;
19364 return NC_UL_VALID;
19365 }
19366
19367 // Express floating point value as unsigned long if possible.
19368
19369 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const19370 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
19371 unsigned long *val) const
19372 {
19373 if (!mpfr_integer_p(fval))
19374 return NC_UL_NOTINT;
19375 mpz_t ival;
19376 mpz_init(ival);
19377 mpfr_get_z(ival, fval, MPFR_RNDN);
19378 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
19379 mpz_clear(ival);
19380 return ret;
19381 }
19382
19383 // Express value as memory size if possible.
19384
19385 bool
to_memory_size(int64_t * val) const19386 Numeric_constant::to_memory_size(int64_t* val) const
19387 {
19388 switch (this->classification_)
19389 {
19390 case NC_INT:
19391 case NC_RUNE:
19392 return this->mpz_to_memory_size(this->u_.int_val, val);
19393 case NC_FLOAT:
19394 return this->mpfr_to_memory_size(this->u_.float_val, val);
19395 case NC_COMPLEX:
19396 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19397 return false;
19398 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
19399 default:
19400 go_unreachable();
19401 }
19402 }
19403
19404 // Express integer as memory size if possible.
19405
19406 bool
mpz_to_memory_size(const mpz_t ival,int64_t * val) const19407 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
19408 {
19409 if (mpz_sgn(ival) < 0)
19410 return false;
19411 if (mpz_fits_slong_p(ival))
19412 {
19413 *val = static_cast<int64_t>(mpz_get_si(ival));
19414 return true;
19415 }
19416
19417 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
19418 // positive value.
19419 if (mpz_sizeinbase(ival, 2) >= 64)
19420 return false;
19421
19422 mpz_t q, r;
19423 mpz_init(q);
19424 mpz_init(r);
19425 mpz_tdiv_q_2exp(q, ival, 32);
19426 mpz_tdiv_r_2exp(r, ival, 32);
19427 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
19428 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
19429 + static_cast<int64_t>(mpz_get_ui(r)));
19430 mpz_clear(r);
19431 mpz_clear(q);
19432 return true;
19433 }
19434
19435 // Express floating point value as memory size if possible.
19436
19437 bool
mpfr_to_memory_size(const mpfr_t fval,int64_t * val) const19438 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
19439 {
19440 if (!mpfr_integer_p(fval))
19441 return false;
19442 mpz_t ival;
19443 mpz_init(ival);
19444 mpfr_get_z(ival, fval, MPFR_RNDN);
19445 bool ret = this->mpz_to_memory_size(ival, val);
19446 mpz_clear(ival);
19447 return ret;
19448 }
19449
19450 // Convert value to integer if possible.
19451
19452 bool
to_int(mpz_t * val) const19453 Numeric_constant::to_int(mpz_t* val) const
19454 {
19455 switch (this->classification_)
19456 {
19457 case NC_INT:
19458 case NC_RUNE:
19459 mpz_init_set(*val, this->u_.int_val);
19460 return true;
19461 case NC_FLOAT:
19462 if (!mpfr_integer_p(this->u_.float_val))
19463 return false;
19464 mpz_init(*val);
19465 mpfr_get_z(*val, this->u_.float_val, MPFR_RNDN);
19466 return true;
19467 case NC_COMPLEX:
19468 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
19469 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
19470 return false;
19471 mpz_init(*val);
19472 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19473 return true;
19474 default:
19475 go_unreachable();
19476 }
19477 }
19478
19479 // Convert value to floating point if possible.
19480
19481 bool
to_float(mpfr_t * val) const19482 Numeric_constant::to_float(mpfr_t* val) const
19483 {
19484 switch (this->classification_)
19485 {
19486 case NC_INT:
19487 case NC_RUNE:
19488 mpfr_init_set_z(*val, this->u_.int_val, MPFR_RNDN);
19489 return true;
19490 case NC_FLOAT:
19491 mpfr_init_set(*val, this->u_.float_val, MPFR_RNDN);
19492 return true;
19493 case NC_COMPLEX:
19494 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19495 return false;
19496 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19497 return true;
19498 default:
19499 go_unreachable();
19500 }
19501 }
19502
19503 // Convert value to complex.
19504
19505 bool
to_complex(mpc_t * val) const19506 Numeric_constant::to_complex(mpc_t* val) const
19507 {
19508 mpc_init2(*val, mpc_precision);
19509 switch (this->classification_)
19510 {
19511 case NC_INT:
19512 case NC_RUNE:
19513 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
19514 return true;
19515 case NC_FLOAT:
19516 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
19517 return true;
19518 case NC_COMPLEX:
19519 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
19520 return true;
19521 default:
19522 go_unreachable();
19523 }
19524 }
19525
19526 // Get the type.
19527
19528 Type*
type() const19529 Numeric_constant::type() const
19530 {
19531 if (this->type_ != NULL)
19532 return this->type_;
19533 switch (this->classification_)
19534 {
19535 case NC_INT:
19536 return Type::make_abstract_integer_type();
19537 case NC_RUNE:
19538 return Type::make_abstract_character_type();
19539 case NC_FLOAT:
19540 return Type::make_abstract_float_type();
19541 case NC_COMPLEX:
19542 return Type::make_abstract_complex_type();
19543 default:
19544 go_unreachable();
19545 }
19546 }
19547
19548 // If the constant can be expressed in TYPE, then set the type of the
19549 // constant to TYPE and return true. Otherwise return false, and, if
19550 // ISSUE_ERROR is true, report an appropriate error message.
19551
19552 bool
set_type(Type * type,bool issue_error,Location loc)19553 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
19554 {
19555 bool ret;
19556 if (type == NULL || type->is_error())
19557 ret = true;
19558 else if (type->integer_type() != NULL)
19559 ret = this->check_int_type(type->integer_type(), issue_error, loc);
19560 else if (type->float_type() != NULL)
19561 ret = this->check_float_type(type->float_type(), issue_error, loc);
19562 else if (type->complex_type() != NULL)
19563 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
19564 else
19565 {
19566 ret = false;
19567 if (issue_error)
19568 go_assert(saw_errors());
19569 }
19570 if (ret)
19571 this->type_ = type;
19572 return ret;
19573 }
19574
19575 // Check whether the constant can be expressed in an integer type.
19576
19577 bool
check_int_type(Integer_type * type,bool issue_error,Location location)19578 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
19579 Location location)
19580 {
19581 mpz_t val;
19582 switch (this->classification_)
19583 {
19584 case NC_INT:
19585 case NC_RUNE:
19586 mpz_init_set(val, this->u_.int_val);
19587 break;
19588
19589 case NC_FLOAT:
19590 if (!mpfr_integer_p(this->u_.float_val))
19591 {
19592 if (issue_error)
19593 {
19594 go_error_at(location,
19595 "floating-point constant truncated to integer");
19596 this->set_invalid();
19597 }
19598 return false;
19599 }
19600 mpz_init(val);
19601 mpfr_get_z(val, this->u_.float_val, MPFR_RNDN);
19602 break;
19603
19604 case NC_COMPLEX:
19605 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
19606 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19607 {
19608 if (issue_error)
19609 {
19610 go_error_at(location, "complex constant truncated to integer");
19611 this->set_invalid();
19612 }
19613 return false;
19614 }
19615 mpz_init(val);
19616 mpfr_get_z(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19617 break;
19618
19619 default:
19620 go_unreachable();
19621 }
19622
19623 bool ret;
19624 if (type->is_abstract())
19625 ret = true;
19626 else
19627 {
19628 int bits = mpz_sizeinbase(val, 2);
19629 if (type->is_unsigned())
19630 {
19631 // For an unsigned type we can only accept a nonnegative
19632 // number, and we must be able to represents at least BITS.
19633 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
19634 }
19635 else
19636 {
19637 // For a signed type we need an extra bit to indicate the
19638 // sign. We have to handle the most negative integer
19639 // specially.
19640 ret = (bits + 1 <= type->bits()
19641 || (bits <= type->bits()
19642 && mpz_sgn(val) < 0
19643 && (mpz_scan1(val, 0)
19644 == static_cast<unsigned long>(type->bits() - 1))
19645 && mpz_scan0(val, type->bits()) == ULONG_MAX));
19646 }
19647 }
19648
19649 if (!ret && issue_error)
19650 {
19651 go_error_at(location, "integer constant overflow");
19652 this->set_invalid();
19653 }
19654
19655 return ret;
19656 }
19657
19658 // Check whether the constant can be expressed in a floating point
19659 // type.
19660
19661 bool
check_float_type(Float_type * type,bool issue_error,Location location)19662 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
19663 Location location)
19664 {
19665 mpfr_t val;
19666 switch (this->classification_)
19667 {
19668 case NC_INT:
19669 case NC_RUNE:
19670 mpfr_init_set_z(val, this->u_.int_val, MPFR_RNDN);
19671 break;
19672
19673 case NC_FLOAT:
19674 mpfr_init_set(val, this->u_.float_val, MPFR_RNDN);
19675 break;
19676
19677 case NC_COMPLEX:
19678 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
19679 {
19680 if (issue_error)
19681 {
19682 this->set_invalid();
19683 go_error_at(location,
19684 "complex constant truncated to floating-point");
19685 }
19686 return false;
19687 }
19688 mpfr_init_set(val, mpc_realref(this->u_.complex_val), MPFR_RNDN);
19689 break;
19690
19691 default:
19692 go_unreachable();
19693 }
19694
19695 bool ret;
19696 if (type->is_abstract())
19697 ret = true;
19698 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
19699 {
19700 // A NaN or Infinity always fits in the range of the type.
19701 ret = true;
19702 }
19703 else
19704 {
19705 mpfr_exp_t exp = mpfr_get_exp(val);
19706 mpfr_exp_t max_exp;
19707 switch (type->bits())
19708 {
19709 case 32:
19710 max_exp = 128;
19711 break;
19712 case 64:
19713 max_exp = 1024;
19714 break;
19715 default:
19716 go_unreachable();
19717 }
19718
19719 ret = exp <= max_exp;
19720
19721 if (ret)
19722 {
19723 // Round the constant to the desired type.
19724 mpfr_t t;
19725 mpfr_init(t);
19726 switch (type->bits())
19727 {
19728 case 32:
19729 mpfr_set_prec(t, 24);
19730 break;
19731 case 64:
19732 mpfr_set_prec(t, 53);
19733 break;
19734 default:
19735 go_unreachable();
19736 }
19737 mpfr_set(t, val, MPFR_RNDN);
19738 mpfr_set(val, t, MPFR_RNDN);
19739 mpfr_clear(t);
19740
19741 this->set_float(type, val);
19742 }
19743 }
19744
19745 mpfr_clear(val);
19746
19747 if (!ret && issue_error)
19748 {
19749 go_error_at(location, "floating-point constant overflow");
19750 this->set_invalid();
19751 }
19752
19753 return ret;
19754 }
19755
19756 // Check whether the constant can be expressed in a complex type.
19757
19758 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)19759 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
19760 Location location)
19761 {
19762 if (type->is_abstract())
19763 return true;
19764
19765 mpfr_exp_t max_exp;
19766 switch (type->bits())
19767 {
19768 case 64:
19769 max_exp = 128;
19770 break;
19771 case 128:
19772 max_exp = 1024;
19773 break;
19774 default:
19775 go_unreachable();
19776 }
19777
19778 mpc_t val;
19779 mpc_init2(val, mpc_precision);
19780 switch (this->classification_)
19781 {
19782 case NC_INT:
19783 case NC_RUNE:
19784 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
19785 break;
19786
19787 case NC_FLOAT:
19788 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
19789 break;
19790
19791 case NC_COMPLEX:
19792 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
19793 break;
19794
19795 default:
19796 go_unreachable();
19797 }
19798
19799 bool ret = true;
19800 if (!mpfr_nan_p(mpc_realref(val))
19801 && !mpfr_inf_p(mpc_realref(val))
19802 && !mpfr_zero_p(mpc_realref(val))
19803 && mpfr_get_exp(mpc_realref(val)) > max_exp)
19804 {
19805 if (issue_error)
19806 {
19807 go_error_at(location, "complex real part overflow");
19808 this->set_invalid();
19809 }
19810 ret = false;
19811 }
19812
19813 if (!mpfr_nan_p(mpc_imagref(val))
19814 && !mpfr_inf_p(mpc_imagref(val))
19815 && !mpfr_zero_p(mpc_imagref(val))
19816 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
19817 {
19818 if (issue_error)
19819 {
19820 go_error_at(location, "complex imaginary part overflow");
19821 this->set_invalid();
19822 }
19823 ret = false;
19824 }
19825
19826 if (ret)
19827 {
19828 // Round the constant to the desired type.
19829 mpc_t t;
19830 switch (type->bits())
19831 {
19832 case 64:
19833 mpc_init2(t, 24);
19834 break;
19835 case 128:
19836 mpc_init2(t, 53);
19837 break;
19838 default:
19839 go_unreachable();
19840 }
19841 mpc_set(t, val, MPC_RNDNN);
19842 mpc_set(val, t, MPC_RNDNN);
19843 mpc_clear(t);
19844
19845 this->set_complex(type, val);
19846 }
19847
19848 mpc_clear(val);
19849
19850 return ret;
19851 }
19852
19853 // Return an Expression for this value.
19854
19855 Expression*
expression(Location loc) const19856 Numeric_constant::expression(Location loc) const
19857 {
19858 switch (this->classification_)
19859 {
19860 case NC_INT:
19861 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
19862 case NC_RUNE:
19863 return Expression::make_character(&this->u_.int_val, this->type_, loc);
19864 case NC_FLOAT:
19865 return Expression::make_float(&this->u_.float_val, this->type_, loc);
19866 case NC_COMPLEX:
19867 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
19868 case NC_INVALID:
19869 go_assert(saw_errors());
19870 return Expression::make_error(loc);
19871 default:
19872 go_unreachable();
19873 }
19874 }
19875
19876 // Calculate a hash code with a given seed.
19877
19878 unsigned int
hash(unsigned int seed) const19879 Numeric_constant::hash(unsigned int seed) const
19880 {
19881 unsigned long val;
19882 const unsigned int PRIME = 97;
19883 long e = 0;
19884 double f = 1.0;
19885 mpfr_t m;
19886
19887 switch (this->classification_)
19888 {
19889 case NC_INVALID:
19890 return PRIME;
19891 case NC_INT:
19892 case NC_RUNE:
19893 val = mpz_get_ui(this->u_.int_val);
19894 break;
19895 case NC_COMPLEX:
19896 mpfr_init(m);
19897 mpc_abs(m, this->u_.complex_val, MPFR_RNDN);
19898 val = mpfr_get_ui(m, MPFR_RNDN);
19899 mpfr_clear(m);
19900 break;
19901 case NC_FLOAT:
19902 f = mpfr_get_d_2exp(&e, this->u_.float_val, MPFR_RNDN) * 4294967295.0;
19903 val = static_cast<unsigned long>(e + static_cast<long>(f));
19904 break;
19905 default:
19906 go_unreachable();
19907 }
19908
19909 return (static_cast<unsigned int>(val) + seed) * PRIME;
19910 }
19911