]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
* class.c (declared_access): Split out from handle_using_decl.
[thirdparty/gcc.git] / gcc / go / gofrontend / expressions.cc
CommitLineData
e440a328 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
ffe743ca 9#include <algorithm>
10
e440a328 11#include "go-c.h"
12#include "gogo.h"
631d5788 13#include "go-diagnostics.h"
e440a328 14#include "types.h"
15#include "export.h"
16#include "import.h"
17#include "statements.h"
18#include "lex.h"
a9182619 19#include "runtime.h"
6e193e6f 20#include "backend.h"
e440a328 21#include "expressions.h"
d751bb78 22#include "ast-dump.h"
e440a328 23
24// Class Expression.
25
26Expression::Expression(Expression_classification classification,
b13c66cd 27 Location location)
e440a328 28 : classification_(classification), location_(location)
29{
30}
31
32Expression::~Expression()
33{
34}
35
e440a328 36// Traverse the expressions.
37
38int
39Expression::traverse(Expression** pexpr, Traverse* traverse)
40{
41 Expression* expr = *pexpr;
42 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
43 {
44 int t = traverse->expression(pexpr);
45 if (t == TRAVERSE_EXIT)
46 return TRAVERSE_EXIT;
47 else if (t == TRAVERSE_SKIP_COMPONENTS)
48 return TRAVERSE_CONTINUE;
49 }
50 return expr->do_traverse(traverse);
51}
52
53// Traverse subexpressions of this expression.
54
55int
56Expression::traverse_subexpressions(Traverse* traverse)
57{
58 return this->do_traverse(traverse);
59}
60
61// Default implementation for do_traverse for child classes.
62
63int
64Expression::do_traverse(Traverse*)
65{
66 return TRAVERSE_CONTINUE;
67}
68
69// This virtual function is called by the parser if the value of this
a7549a6a 70// expression is being discarded. By default, we give an error.
71// Expressions with side effects override.
e440a328 72
4f2138d7 73bool
e440a328 74Expression::do_discarding_value()
75{
a7549a6a 76 this->unused_value_error();
4f2138d7 77 return false;
e440a328 78}
79
80// This virtual function is called to export expressions. This will
81// only be used by expressions which may be constant.
82
83void
84Expression::do_export(Export*) const
85{
c3e6f413 86 go_unreachable();
e440a328 87}
88
a7549a6a 89// Give an error saying that the value of the expression is not used.
e440a328 90
91void
a7549a6a 92Expression::unused_value_error()
e440a328 93{
4f2138d7 94 this->report_error(_("value computed is not used"));
e440a328 95}
96
97// Note that this expression is an error. This is called by children
98// when they discover an error.
99
100void
101Expression::set_is_error()
102{
103 this->classification_ = EXPRESSION_ERROR;
104}
105
106// For children to call to report an error conveniently.
107
108void
109Expression::report_error(const char* msg)
110{
631d5788 111 go_error_at(this->location_, "%s", msg);
e440a328 112 this->set_is_error();
113}
114
115// Set types of variables and constants. This is implemented by the
116// child class.
117
118void
119Expression::determine_type(const Type_context* context)
120{
121 this->do_determine_type(context);
122}
123
124// Set types when there is no context.
125
126void
127Expression::determine_type_no_context()
128{
129 Type_context context;
130 this->do_determine_type(&context);
131}
132
2c809f8f 133// Return an expression handling any conversions which must be done during
e440a328 134// assignment.
135
2c809f8f 136Expression*
b4a33049 137Expression::convert_for_assignment(Gogo*, Type* lhs_type,
2c809f8f 138 Expression* rhs, Location location)
e440a328 139{
2c809f8f 140 Type* rhs_type = rhs->type();
141 if (lhs_type->is_error()
142 || rhs_type->is_error()
143 || rhs->is_error_expression())
144 return Expression::make_error(location);
e440a328 145
54211955 146 if (lhs_type->forwarded() != rhs_type->forwarded()
147 && lhs_type->interface_type() != NULL)
e440a328 148 {
149 if (rhs_type->interface_type() == NULL)
2c809f8f 150 return Expression::convert_type_to_interface(lhs_type, rhs, location);
e440a328 151 else
2c809f8f 152 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
153 location);
e440a328 154 }
54211955 155 else if (lhs_type->forwarded() != rhs_type->forwarded()
156 && rhs_type->interface_type() != NULL)
2c809f8f 157 return Expression::convert_interface_to_type(lhs_type, rhs, location);
411eb89e 158 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
e440a328 159 {
2c809f8f 160 // Assigning nil to a slice.
2c809f8f 161 Expression* nil = Expression::make_nil(location);
e67508fa 162 Expression* zero = Expression::make_integer_ul(0, NULL, location);
2c809f8f 163 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
e440a328 164 }
165 else if (rhs_type->is_nil_type())
2c809f8f 166 return Expression::make_nil(location);
167 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
e440a328 168 {
169 // No conversion is needed.
2c809f8f 170 return rhs;
171 }
172 else if (lhs_type->points_to() != NULL)
173 return Expression::make_unsafe_cast(lhs_type, rhs, location);
174 else if (lhs_type->is_numeric_type())
175 return Expression::make_cast(lhs_type, rhs, location);
176 else if ((lhs_type->struct_type() != NULL
177 && rhs_type->struct_type() != NULL)
178 || (lhs_type->array_type() != NULL
179 && rhs_type->array_type() != NULL))
e440a328 180 {
181 // This conversion must be permitted by Go, or we wouldn't have
182 // gotten here.
2c809f8f 183 return Expression::make_unsafe_cast(lhs_type, rhs, location);
e440a328 184 }
185 else
2c809f8f 186 return rhs;
e440a328 187}
188
2c809f8f 189// Return an expression for a conversion from a non-interface type to an
e440a328 190// interface type.
191
2c809f8f 192Expression*
193Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
194 Location location)
e440a328 195{
e440a328 196 Interface_type* lhs_interface_type = lhs_type->interface_type();
197 bool lhs_is_empty = lhs_interface_type->is_empty();
198
199 // Since RHS_TYPE is a static type, we can create the interface
200 // method table at compile time.
201
202 // When setting an interface to nil, we just set both fields to
203 // NULL.
2c809f8f 204 Type* rhs_type = rhs->type();
e440a328 205 if (rhs_type->is_nil_type())
63697958 206 {
2c809f8f 207 Expression* nil = Expression::make_nil(location);
208 return Expression::make_interface_value(lhs_type, nil, nil, location);
63697958 209 }
e440a328 210
211 // This should have been checked already.
c484d925 212 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
e440a328 213
e440a328 214 // An interface is a tuple. If LHS_TYPE is an empty interface type,
215 // then the first field is the type descriptor for RHS_TYPE.
216 // Otherwise it is the interface method table for RHS_TYPE.
2c809f8f 217 Expression* first_field;
e440a328 218 if (lhs_is_empty)
2c809f8f 219 first_field = Expression::make_type_descriptor(rhs_type, location);
e440a328 220 else
221 {
222 // Build the interface method table for this interface and this
223 // object type: a list of function pointers for each interface
224 // method.
225 Named_type* rhs_named_type = rhs_type->named_type();
c0cab2ec 226 Struct_type* rhs_struct_type = rhs_type->struct_type();
e440a328 227 bool is_pointer = false;
c0cab2ec 228 if (rhs_named_type == NULL && rhs_struct_type == NULL)
e440a328 229 {
230 rhs_named_type = rhs_type->deref()->named_type();
c0cab2ec 231 rhs_struct_type = rhs_type->deref()->struct_type();
e440a328 232 is_pointer = true;
233 }
c0cab2ec 234 if (rhs_named_type != NULL)
2c809f8f 235 first_field =
236 rhs_named_type->interface_method_table(lhs_interface_type,
237 is_pointer);
c0cab2ec 238 else if (rhs_struct_type != NULL)
2c809f8f 239 first_field =
240 rhs_struct_type->interface_method_table(lhs_interface_type,
241 is_pointer);
c0cab2ec 242 else
2c809f8f 243 first_field = Expression::make_nil(location);
e440a328 244 }
e440a328 245
2c809f8f 246 Expression* obj;
e440a328 247 if (rhs_type->points_to() != NULL)
248 {
2c809f8f 249 // We are assigning a pointer to the interface; the interface
e440a328 250 // holds the pointer itself.
2c809f8f 251 obj = rhs;
252 }
253 else
254 {
255 // We are assigning a non-pointer value to the interface; the
45ff893b 256 // interface gets a copy of the value in the heap if it escapes.
257 // TODO(cmang): Associate escape state state of RHS with newly
258 // created OBJ.
2c809f8f 259 obj = Expression::make_heap_expression(rhs, location);
e440a328 260 }
261
2c809f8f 262 return Expression::make_interface_value(lhs_type, first_field, obj, location);
263}
e440a328 264
2c809f8f 265// Return an expression for the type descriptor of RHS.
e440a328 266
2c809f8f 267Expression*
268Expression::get_interface_type_descriptor(Expression* rhs)
269{
270 go_assert(rhs->type()->interface_type() != NULL);
271 Location location = rhs->location();
e440a328 272
2c809f8f 273 // The type descriptor is the first field of an empty interface.
274 if (rhs->type()->interface_type()->is_empty())
275 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
276 location);
277
278 Expression* mtable =
279 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
e440a328 280
2c809f8f 281 Expression* descriptor =
282 Expression::make_unary(OPERATOR_MULT, mtable, location);
283 descriptor = Expression::make_field_reference(descriptor, 0, location);
284 Expression* nil = Expression::make_nil(location);
e440a328 285
2c809f8f 286 Expression* eq =
287 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
288 return Expression::make_conditional(eq, nil, descriptor, location);
e440a328 289}
290
2c809f8f 291// Return an expression for the conversion of an interface type to an
e440a328 292// interface type.
293
2c809f8f 294Expression*
295Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
296 bool for_type_guard,
297 Location location)
e440a328 298{
8ba8cc87 299 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
300 return rhs;
301
e440a328 302 Interface_type* lhs_interface_type = lhs_type->interface_type();
303 bool lhs_is_empty = lhs_interface_type->is_empty();
304
e440a328 305 // In the general case this requires runtime examination of the type
306 // method table to match it up with the interface methods.
307
308 // FIXME: If all of the methods in the right hand side interface
309 // also appear in the left hand side interface, then we don't need
310 // to do a runtime check, although we still need to build a new
311 // method table.
312
8ba8cc87 313 // We are going to evaluate RHS multiple times.
314 go_assert(rhs->is_variable());
315
e440a328 316 // Get the type descriptor for the right hand side. This will be
317 // NULL for a nil interface.
2c809f8f 318 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
319 Expression* lhs_type_expr =
320 Expression::make_type_descriptor(lhs_type, location);
e440a328 321
2c809f8f 322 Expression* first_field;
e440a328 323 if (for_type_guard)
324 {
325 // A type assertion fails when converting a nil interface.
6098d6cb 326 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
327 lhs_type_expr, rhs_type_expr);
e440a328 328 }
329 else if (lhs_is_empty)
330 {
2c809f8f 331 // A conversion to an empty interface always succeeds, and the
e440a328 332 // first field is just the type descriptor of the object.
2c809f8f 333 first_field = rhs_type_expr;
e440a328 334 }
335 else
336 {
337 // A conversion to a non-empty interface may fail, but unlike a
338 // type assertion converting nil will always succeed.
6098d6cb 339 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
340 lhs_type_expr, rhs_type_expr);
e440a328 341 }
342
343 // The second field is simply the object pointer.
2c809f8f 344 Expression* obj =
345 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
346 return Expression::make_interface_value(lhs_type, first_field, obj, location);
e440a328 347}
348
2c809f8f 349// Return an expression for the conversion of an interface type to a
e440a328 350// non-interface type.
351
2c809f8f 352Expression*
353Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
354 Location location)
e440a328 355{
8ba8cc87 356 // We are going to evaluate RHS multiple times.
357 go_assert(rhs->is_variable());
358
e440a328 359 // Call a function to check that the type is valid. The function
360 // will panic with an appropriate runtime type error if the type is
361 // not valid.
2c809f8f 362 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
363 location);
364 Expression* rhs_descriptor =
365 Expression::get_interface_type_descriptor(rhs);
366
367 Type* rhs_type = rhs->type();
368 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
369 location);
370
6098d6cb 371 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
2c809f8f 372 location, 3, lhs_type_expr,
373 rhs_descriptor, rhs_inter_expr);
e440a328 374
375 // If the call succeeds, pull out the value.
2c809f8f 376 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
377 location);
e440a328 378
379 // If the value is a pointer, then it is the value we want.
380 // Otherwise it points to the value.
381 if (lhs_type->points_to() == NULL)
382 {
2c809f8f 383 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
384 location);
385 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
e440a328 386 }
2c809f8f 387 return Expression::make_compound(check_iface, obj, location);
e440a328 388}
389
ea664253 390// Convert an expression to its backend representation. This is implemented by
391// the child class. Not that it is not in general safe to call this multiple
e440a328 392// times for a single expression, but that we don't catch such errors.
393
ea664253 394Bexpression*
395Expression::get_backend(Translate_context* context)
e440a328 396{
397 // The child may have marked this expression as having an error.
398 if (this->classification_ == EXPRESSION_ERROR)
ea664253 399 return context->backend()->error_expression();
e440a328 400
ea664253 401 return this->do_get_backend(context);
e440a328 402}
403
48c2a53a 404// Return a backend expression for VAL.
405Bexpression*
406Expression::backend_numeric_constant_expression(Translate_context* context,
407 Numeric_constant* val)
e440a328 408{
48c2a53a 409 Gogo* gogo = context->gogo();
410 Type* type = val->type();
411 if (type == NULL)
412 return gogo->backend()->error_expression();
e440a328 413
48c2a53a 414 Btype* btype = type->get_backend(gogo);
415 Bexpression* ret;
416 if (type->integer_type() != NULL)
e440a328 417 {
418 mpz_t ival;
48c2a53a 419 if (!val->to_int(&ival))
420 {
421 go_assert(saw_errors());
422 return gogo->backend()->error_expression();
423 }
424 ret = gogo->backend()->integer_constant_expression(btype, ival);
e440a328 425 mpz_clear(ival);
e440a328 426 }
48c2a53a 427 else if (type->float_type() != NULL)
e440a328 428 {
48c2a53a 429 mpfr_t fval;
430 if (!val->to_float(&fval))
431 {
432 go_assert(saw_errors());
433 return gogo->backend()->error_expression();
434 }
435 ret = gogo->backend()->float_constant_expression(btype, fval);
436 mpfr_clear(fval);
e440a328 437 }
48c2a53a 438 else if (type->complex_type() != NULL)
e440a328 439 {
fcbea5e4 440 mpc_t cval;
441 if (!val->to_complex(&cval))
48c2a53a 442 {
443 go_assert(saw_errors());
444 return gogo->backend()->error_expression();
445 }
fcbea5e4 446 ret = gogo->backend()->complex_constant_expression(btype, cval);
447 mpc_clear(cval);
e440a328 448 }
449 else
c3e6f413 450 go_unreachable();
e440a328 451
48c2a53a 452 return ret;
e440a328 453}
454
2c809f8f 455// Return an expression which evaluates to true if VAL, of arbitrary integer
456// type, is negative or is more than the maximum value of the Go type "int".
e440a328 457
2c809f8f 458Expression*
459Expression::check_bounds(Expression* val, Location loc)
e440a328 460{
2c809f8f 461 Type* val_type = val->type();
462 Type* bound_type = Type::lookup_integer_type("int");
463
464 int val_type_size;
465 bool val_is_unsigned = false;
466 if (val_type->integer_type() != NULL)
467 {
468 val_type_size = val_type->integer_type()->bits();
469 val_is_unsigned = val_type->integer_type()->is_unsigned();
470 }
471 else
472 {
473 if (!val_type->is_numeric_type()
474 || !Type::are_convertible(bound_type, val_type, NULL))
475 {
476 go_assert(saw_errors());
477 return Expression::make_boolean(true, loc);
478 }
e440a328 479
2c809f8f 480 if (val_type->complex_type() != NULL)
481 val_type_size = val_type->complex_type()->bits();
482 else
483 val_type_size = val_type->float_type()->bits();
484 }
485
486 Expression* negative_index = Expression::make_boolean(false, loc);
487 Expression* index_overflows = Expression::make_boolean(false, loc);
488 if (!val_is_unsigned)
e440a328 489 {
e67508fa 490 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
2c809f8f 491 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
e440a328 492 }
493
2c809f8f 494 int bound_type_size = bound_type->integer_type()->bits();
c3068ac0 495 if (val_type_size > bound_type_size
496 || (val_type_size == bound_type_size
2c809f8f 497 && val_is_unsigned))
498 {
499 mpz_t one;
500 mpz_init_set_ui(one, 1UL);
501
502 // maxval = 2^(bound_type_size - 1) - 1
503 mpz_t maxval;
504 mpz_init(maxval);
505 mpz_mul_2exp(maxval, one, bound_type_size - 1);
506 mpz_sub_ui(maxval, maxval, 1);
e67508fa 507 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
2c809f8f 508 mpz_clear(one);
509 mpz_clear(maxval);
510
511 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
e440a328 512 }
513
2c809f8f 514 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
515 loc);
e440a328 516}
517
d751bb78 518void
519Expression::dump_expression(Ast_dump_context* ast_dump_context) const
520{
521 this->do_dump_expression(ast_dump_context);
522}
523
e440a328 524// Error expressions. This are used to avoid cascading errors.
525
526class Error_expression : public Expression
527{
528 public:
b13c66cd 529 Error_expression(Location location)
e440a328 530 : Expression(EXPRESSION_ERROR, location)
531 { }
532
533 protected:
534 bool
535 do_is_constant() const
536 { return true; }
537
0e168074 538 bool
539 do_is_immutable() const
540 { return true; }
541
e440a328 542 bool
0c77715b 543 do_numeric_constant_value(Numeric_constant* nc) const
e440a328 544 {
0c77715b 545 nc->set_unsigned_long(NULL, 0);
e440a328 546 return true;
547 }
548
4f2138d7 549 bool
e440a328 550 do_discarding_value()
4f2138d7 551 { return true; }
e440a328 552
553 Type*
554 do_type()
555 { return Type::make_error_type(); }
556
557 void
558 do_determine_type(const Type_context*)
559 { }
560
561 Expression*
562 do_copy()
563 { return this; }
564
565 bool
566 do_is_addressable() const
567 { return true; }
568
ea664253 569 Bexpression*
570 do_get_backend(Translate_context* context)
571 { return context->backend()->error_expression(); }
d751bb78 572
573 void
574 do_dump_expression(Ast_dump_context*) const;
e440a328 575};
576
d751bb78 577// Dump the ast representation for an error expression to a dump context.
578
579void
580Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
581{
582 ast_dump_context->ostream() << "_Error_" ;
583}
584
e440a328 585Expression*
b13c66cd 586Expression::make_error(Location location)
e440a328 587{
588 return new Error_expression(location);
589}
590
591// An expression which is really a type. This is used during parsing.
592// It is an error if these survive after lowering.
593
594class
595Type_expression : public Expression
596{
597 public:
b13c66cd 598 Type_expression(Type* type, Location location)
e440a328 599 : Expression(EXPRESSION_TYPE, location),
600 type_(type)
601 { }
602
603 protected:
604 int
605 do_traverse(Traverse* traverse)
606 { return Type::traverse(this->type_, traverse); }
607
608 Type*
609 do_type()
610 { return this->type_; }
611
612 void
613 do_determine_type(const Type_context*)
614 { }
615
616 void
617 do_check_types(Gogo*)
618 { this->report_error(_("invalid use of type")); }
619
620 Expression*
621 do_copy()
622 { return this; }
623
ea664253 624 Bexpression*
625 do_get_backend(Translate_context*)
c3e6f413 626 { go_unreachable(); }
e440a328 627
d751bb78 628 void do_dump_expression(Ast_dump_context*) const;
629
e440a328 630 private:
631 // The type which we are representing as an expression.
632 Type* type_;
633};
634
d751bb78 635void
636Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
637{
638 ast_dump_context->dump_type(this->type_);
639}
640
e440a328 641Expression*
b13c66cd 642Expression::make_type(Type* type, Location location)
e440a328 643{
644 return new Type_expression(type, location);
645}
646
e03bdf36 647// Class Parser_expression.
648
649Type*
650Parser_expression::do_type()
651{
652 // We should never really ask for the type of a Parser_expression.
653 // However, it can happen, at least when we have an invalid const
654 // whose initializer refers to the const itself. In that case we
655 // may ask for the type when lowering the const itself.
c484d925 656 go_assert(saw_errors());
e03bdf36 657 return Type::make_error_type();
658}
659
e440a328 660// Class Var_expression.
661
662// Lower a variable expression. Here we just make sure that the
663// initialization expression of the variable has been lowered. This
664// ensures that we will be able to determine the type of the variable
665// if necessary.
666
667Expression*
ceeb4318 668Var_expression::do_lower(Gogo* gogo, Named_object* function,
669 Statement_inserter* inserter, int)
e440a328 670{
671 if (this->variable_->is_variable())
672 {
673 Variable* var = this->variable_->var_value();
674 // This is either a local variable or a global variable. A
675 // reference to a variable which is local to an enclosing
676 // function will be a reference to a field in a closure.
677 if (var->is_global())
ceeb4318 678 {
679 function = NULL;
680 inserter = NULL;
681 }
682 var->lower_init_expression(gogo, function, inserter);
e440a328 683 }
684 return this;
685}
686
e440a328 687// Return the type of a reference to a variable.
688
689Type*
690Var_expression::do_type()
691{
692 if (this->variable_->is_variable())
693 return this->variable_->var_value()->type();
694 else if (this->variable_->is_result_variable())
695 return this->variable_->result_var_value()->type();
696 else
c3e6f413 697 go_unreachable();
e440a328 698}
699
0ab09e06 700// Determine the type of a reference to a variable.
701
702void
703Var_expression::do_determine_type(const Type_context*)
704{
705 if (this->variable_->is_variable())
706 this->variable_->var_value()->determine_type();
707}
708
e440a328 709// Something takes the address of this variable. This means that we
710// may want to move the variable onto the heap.
711
712void
713Var_expression::do_address_taken(bool escapes)
714{
715 if (!escapes)
f325319b 716 {
717 if (this->variable_->is_variable())
718 this->variable_->var_value()->set_non_escaping_address_taken();
719 else if (this->variable_->is_result_variable())
720 this->variable_->result_var_value()->set_non_escaping_address_taken();
721 else
722 go_unreachable();
723 }
e440a328 724 else
f325319b 725 {
726 if (this->variable_->is_variable())
727 this->variable_->var_value()->set_address_taken();
728 else if (this->variable_->is_result_variable())
729 this->variable_->result_var_value()->set_address_taken();
730 else
731 go_unreachable();
732 }
45ff893b 733
734 if (this->variable_->is_variable()
735 && this->variable_->var_value()->is_in_heap())
736 {
737 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
738 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
739 }
e440a328 740}
741
ea664253 742// Get the backend representation for a reference to a variable.
e440a328 743
ea664253 744Bexpression*
745Var_expression::do_get_backend(Translate_context* context)
e440a328 746{
fe2f84cf 747 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
748 context->function());
fe2f84cf 749 bool is_in_heap;
c6777780 750 Location loc = this->location();
9b27b43c 751 Btype* btype;
752 Gogo* gogo = context->gogo();
fe2f84cf 753 if (this->variable_->is_variable())
9b27b43c 754 {
755 is_in_heap = this->variable_->var_value()->is_in_heap();
756 btype = this->variable_->var_value()->type()->get_backend(gogo);
757 }
fe2f84cf 758 else if (this->variable_->is_result_variable())
9b27b43c 759 {
760 is_in_heap = this->variable_->result_var_value()->is_in_heap();
761 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
762 }
fe2f84cf 763 else
c3e6f413 764 go_unreachable();
c6777780 765
766 Bexpression* ret = context->backend()->var_expression(bvar, loc);
fe2f84cf 767 if (is_in_heap)
9b27b43c 768 ret = context->backend()->indirect_expression(btype, ret, true, loc);
ea664253 769 return ret;
e440a328 770}
771
d751bb78 772// Ast dump for variable expression.
773
774void
775Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
776{
777 ast_dump_context->ostream() << this->variable_->name() ;
778}
779
e440a328 780// Make a reference to a variable in an expression.
781
782Expression*
b13c66cd 783Expression::make_var_reference(Named_object* var, Location location)
e440a328 784{
785 if (var->is_sink())
786 return Expression::make_sink(location);
787
788 // FIXME: Creating a new object for each reference to a variable is
789 // wasteful.
790 return new Var_expression(var, location);
791}
792
b0c09712 793// Class Enclosed_var_expression.
794
795int
796Enclosed_var_expression::do_traverse(Traverse*)
797{
798 return TRAVERSE_CONTINUE;
799}
800
801// Lower the reference to the enclosed variable.
802
803Expression*
804Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
805 Statement_inserter* inserter, int)
806{
807 gogo->lower_expression(function, inserter, &this->reference_);
808 return this;
809}
810
811// Flatten the reference to the enclosed variable.
812
813Expression*
814Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
815 Statement_inserter* inserter)
816{
817 gogo->flatten_expression(function, inserter, &this->reference_);
818 return this;
819}
820
821void
822Enclosed_var_expression::do_address_taken(bool escapes)
823{
824 if (!escapes)
825 {
826 if (this->variable_->is_variable())
827 this->variable_->var_value()->set_non_escaping_address_taken();
828 else if (this->variable_->is_result_variable())
829 this->variable_->result_var_value()->set_non_escaping_address_taken();
830 else
831 go_unreachable();
832 }
833 else
834 {
835 if (this->variable_->is_variable())
836 this->variable_->var_value()->set_address_taken();
837 else if (this->variable_->is_result_variable())
838 this->variable_->result_var_value()->set_address_taken();
839 else
840 go_unreachable();
841 }
45ff893b 842
843 if (this->variable_->is_variable()
844 && this->variable_->var_value()->is_in_heap())
845 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
b0c09712 846}
847
848// Ast dump for enclosed variable expression.
849
850void
851Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
852{
853 adc->ostream() << this->variable_->name();
854}
855
856// Make a reference to a variable within an enclosing function.
857
858Expression*
859Expression::make_enclosing_var_reference(Expression* reference,
860 Named_object* var, Location location)
861{
862 return new Enclosed_var_expression(reference, var, location);
863}
864
e440a328 865// Class Temporary_reference_expression.
866
867// The type.
868
869Type*
870Temporary_reference_expression::do_type()
871{
872 return this->statement_->type();
873}
874
875// Called if something takes the address of this temporary variable.
876// We never have to move temporary variables to the heap, but we do
877// need to know that they must live in the stack rather than in a
878// register.
879
880void
881Temporary_reference_expression::do_address_taken(bool)
882{
883 this->statement_->set_is_address_taken();
884}
885
ea664253 886// Get a backend expression referring to the variable.
e440a328 887
ea664253 888Bexpression*
889Temporary_reference_expression::do_get_backend(Translate_context* context)
e440a328 890{
cd440cff 891 Gogo* gogo = context->gogo();
eefc1ed3 892 Bvariable* bvar = this->statement_->get_backend_variable(context);
cd440cff 893 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
eefc1ed3 894
cd440cff 895 // The backend can't always represent the same set of recursive types
eefc1ed3 896 // that the Go frontend can. In some cases this means that a
897 // temporary variable won't have the right backend type. Correct
898 // that here by adding a type cast. We need to use base() to push
899 // the circularity down one level.
cd440cff 900 Type* stype = this->statement_->type();
ceeb4318 901 if (!this->is_lvalue_
cd440cff 902 && stype->has_pointer()
903 && stype->deref()->is_void_type())
eefc1ed3 904 {
cd440cff 905 Btype* btype = this->type()->base()->get_backend(gogo);
906 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 907 }
ea664253 908 return ret;
e440a328 909}
910
d751bb78 911// Ast dump for temporary reference.
912
913void
914Temporary_reference_expression::do_dump_expression(
915 Ast_dump_context* ast_dump_context) const
916{
917 ast_dump_context->dump_temp_variable_name(this->statement_);
918}
919
e440a328 920// Make a reference to a temporary variable.
921
ceeb4318 922Temporary_reference_expression*
e440a328 923Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 924 Location location)
e440a328 925{
926 return new Temporary_reference_expression(statement, location);
927}
928
e9d3367e 929// Class Set_and_use_temporary_expression.
930
931// Return the type.
932
933Type*
934Set_and_use_temporary_expression::do_type()
935{
936 return this->statement_->type();
937}
938
0afbb937 939// Determine the type of the expression.
940
941void
942Set_and_use_temporary_expression::do_determine_type(
943 const Type_context* context)
944{
945 this->expr_->determine_type(context);
946}
947
e9d3367e 948// Take the address.
949
950void
951Set_and_use_temporary_expression::do_address_taken(bool)
952{
953 this->statement_->set_is_address_taken();
954}
955
956// Return the backend representation.
957
ea664253 958Bexpression*
959Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
e9d3367e 960{
e9d3367e 961 Location loc = this->location();
a302c105 962 Gogo* gogo = context->gogo();
963 Bvariable* bvar = this->statement_->get_backend_variable(context);
964 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
965
ea664253 966 Bexpression* bexpr = this->expr_->get_backend(context);
a302c105 967 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
968 var_ref = gogo->backend()->var_expression(bvar, loc);
969 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
ea664253 970 return ret;
e9d3367e 971}
972
973// Dump.
974
975void
976Set_and_use_temporary_expression::do_dump_expression(
977 Ast_dump_context* ast_dump_context) const
978{
979 ast_dump_context->ostream() << '(';
980 ast_dump_context->dump_temp_variable_name(this->statement_);
981 ast_dump_context->ostream() << " = ";
982 this->expr_->dump_expression(ast_dump_context);
983 ast_dump_context->ostream() << ')';
984}
985
986// Make a set-and-use temporary.
987
988Set_and_use_temporary_expression*
989Expression::make_set_and_use_temporary(Temporary_statement* statement,
990 Expression* expr, Location location)
991{
992 return new Set_and_use_temporary_expression(statement, expr, location);
993}
994
e440a328 995// A sink expression--a use of the blank identifier _.
996
997class Sink_expression : public Expression
998{
999 public:
b13c66cd 1000 Sink_expression(Location location)
e440a328 1001 : Expression(EXPRESSION_SINK, location),
aa93217a 1002 type_(NULL), bvar_(NULL)
e440a328 1003 { }
1004
1005 protected:
4f2138d7 1006 bool
e440a328 1007 do_discarding_value()
4f2138d7 1008 { return true; }
e440a328 1009
1010 Type*
1011 do_type();
1012
1013 void
1014 do_determine_type(const Type_context*);
1015
1016 Expression*
1017 do_copy()
1018 { return new Sink_expression(this->location()); }
1019
ea664253 1020 Bexpression*
1021 do_get_backend(Translate_context*);
e440a328 1022
d751bb78 1023 void
1024 do_dump_expression(Ast_dump_context*) const;
1025
e440a328 1026 private:
1027 // The type of this sink variable.
1028 Type* type_;
1029 // The temporary variable we generate.
aa93217a 1030 Bvariable* bvar_;
e440a328 1031};
1032
1033// Return the type of a sink expression.
1034
1035Type*
1036Sink_expression::do_type()
1037{
1038 if (this->type_ == NULL)
1039 return Type::make_sink_type();
1040 return this->type_;
1041}
1042
1043// Determine the type of a sink expression.
1044
1045void
1046Sink_expression::do_determine_type(const Type_context* context)
1047{
1048 if (context->type != NULL)
1049 this->type_ = context->type;
1050}
1051
1052// Return a temporary variable for a sink expression. This will
1053// presumably be a write-only variable which the middle-end will drop.
1054
ea664253 1055Bexpression*
1056Sink_expression::do_get_backend(Translate_context* context)
e440a328 1057{
aa93217a 1058 Location loc = this->location();
1059 Gogo* gogo = context->gogo();
1060 if (this->bvar_ == NULL)
e440a328 1061 {
c484d925 1062 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
aa93217a 1063 Named_object* fn = context->function();
1064 go_assert(fn != NULL);
1065 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
9f0e0513 1066 Btype* bt = this->type_->get_backend(context->gogo());
aa93217a 1067 Bstatement* decl;
1068 this->bvar_ =
1069 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1070 false, loc, &decl);
1071 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
1072 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
ea664253 1073 return var_ref;
e440a328 1074 }
ea664253 1075 return gogo->backend()->var_expression(this->bvar_, loc);
e440a328 1076}
1077
d751bb78 1078// Ast dump for sink expression.
1079
1080void
1081Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1082{
1083 ast_dump_context->ostream() << "_" ;
1084}
1085
e440a328 1086// Make a sink expression.
1087
1088Expression*
b13c66cd 1089Expression::make_sink(Location location)
e440a328 1090{
1091 return new Sink_expression(location);
1092}
1093
1094// Class Func_expression.
1095
1096// FIXME: Can a function expression appear in a constant expression?
1097// The value is unchanging. Initializing a constant to the address of
1098// a function seems like it could work, though there might be little
1099// point to it.
1100
e440a328 1101// Traversal.
1102
1103int
1104Func_expression::do_traverse(Traverse* traverse)
1105{
1106 return (this->closure_ == NULL
1107 ? TRAVERSE_CONTINUE
1108 : Expression::traverse(&this->closure_, traverse));
1109}
1110
1111// Return the type of a function expression.
1112
1113Type*
1114Func_expression::do_type()
1115{
1116 if (this->function_->is_function())
1117 return this->function_->func_value()->type();
1118 else if (this->function_->is_function_declaration())
1119 return this->function_->func_declaration_value()->type();
1120 else
c3e6f413 1121 go_unreachable();
e440a328 1122}
1123
ea664253 1124// Get the backend representation for the code of a function expression.
e440a328 1125
97267c39 1126Bexpression*
8381eda7 1127Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1128{
1129 Function_type* fntype;
8381eda7 1130 if (no->is_function())
1131 fntype = no->func_value()->type();
1132 else if (no->is_function_declaration())
1133 fntype = no->func_declaration_value()->type();
e440a328 1134 else
c3e6f413 1135 go_unreachable();
e440a328 1136
1137 // Builtin functions are handled specially by Call_expression. We
1138 // can't take their address.
1139 if (fntype->is_builtin())
1140 {
631d5788 1141 go_error_at(loc,
1142 "invalid use of special builtin function %qs; must be called",
1143 no->message_name().c_str());
97267c39 1144 return gogo->backend()->error_expression();
e440a328 1145 }
1146
97267c39 1147 Bfunction* fndecl;
e440a328 1148 if (no->is_function())
cf3cae55 1149 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1150 else if (no->is_function_declaration())
cf3cae55 1151 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1152 else
c3e6f413 1153 go_unreachable();
e440a328 1154
97267c39 1155 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1156}
1157
ea664253 1158// Get the backend representation for a function expression. This is used when
1159// we take the address of a function rather than simply calling it. A func
8381eda7 1160// value is represented as a pointer to a block of memory. The first
1161// word of that memory is a pointer to the function code. The
1162// remaining parts of that memory are the addresses of variables that
1163// the function closes over.
e440a328 1164
ea664253 1165Bexpression*
1166Func_expression::do_get_backend(Translate_context* context)
e440a328 1167{
8381eda7 1168 // If there is no closure, just use the function descriptor.
2010c17a 1169 if (this->closure_ == NULL)
8381eda7 1170 {
1171 Gogo* gogo = context->gogo();
1172 Named_object* no = this->function_;
1173 Expression* descriptor;
1174 if (no->is_function())
1175 descriptor = no->func_value()->descriptor(gogo, no);
1176 else if (no->is_function_declaration())
1177 {
1178 if (no->func_declaration_value()->type()->is_builtin())
1179 {
631d5788 1180 go_error_at(this->location(),
1181 ("invalid use of special builtin function %qs; "
1182 "must be called"),
1183 no->message_name().c_str());
ea664253 1184 return gogo->backend()->error_expression();
8381eda7 1185 }
1186 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1187 }
1188 else
1189 go_unreachable();
2010c17a 1190
ea664253 1191 Bexpression* bdesc = descriptor->get_backend(context);
1192 return gogo->backend()->address_expression(bdesc, this->location());
8381eda7 1193 }
e440a328 1194
8381eda7 1195 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1196
8381eda7 1197 // If there is a closure, then the closure is itself the function
1198 // expression. It is a pointer to a struct whose first field points
1199 // to the function code and whose remaining fields are the addresses
1200 // of the closed-over variables.
ea664253 1201 return this->closure_->get_backend(context);
e440a328 1202}
1203
d751bb78 1204// Ast dump for function.
1205
1206void
1207Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1208{
8b1c301d 1209 ast_dump_context->ostream() << this->function_->name();
1210 if (this->closure_ != NULL)
1211 {
1212 ast_dump_context->ostream() << " {closure = ";
1213 this->closure_->dump_expression(ast_dump_context);
1214 ast_dump_context->ostream() << "}";
1215 }
d751bb78 1216}
1217
e440a328 1218// Make a reference to a function in an expression.
1219
1220Expression*
1221Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1222 Location location)
e440a328 1223{
b1d7ecfa 1224 Func_expression* fe = new Func_expression(function, closure, location);
1225
1226 // Detect references to builtin functions and set the runtime code if
1227 // appropriate.
1228 if (function->is_function_declaration())
1229 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1230 return fe;
e440a328 1231}
1232
c6837989 1233// Class Func_descriptor_expression.
8381eda7 1234
c6837989 1235// Constructor.
8381eda7 1236
c6837989 1237Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1238 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1239 fn_(fn), dvar_(NULL)
c6837989 1240{
1241 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1242}
8381eda7 1243
c6837989 1244// Traversal.
8381eda7 1245
c6837989 1246int
1247Func_descriptor_expression::do_traverse(Traverse*)
1248{
1249 return TRAVERSE_CONTINUE;
1250}
8381eda7 1251
1252// All function descriptors have the same type.
1253
1254Type* Func_descriptor_expression::descriptor_type;
1255
1256void
1257Func_descriptor_expression::make_func_descriptor_type()
1258{
1259 if (Func_descriptor_expression::descriptor_type != NULL)
1260 return;
1261 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1262 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1263 Func_descriptor_expression::descriptor_type =
1264 Type::make_builtin_named_type("functionDescriptor", struct_type);
1265}
1266
1267Type*
1268Func_descriptor_expression::do_type()
1269{
1270 Func_descriptor_expression::make_func_descriptor_type();
1271 return Func_descriptor_expression::descriptor_type;
1272}
1273
ea664253 1274// The backend representation for a function descriptor.
8381eda7 1275
ea664253 1276Bexpression*
1277Func_descriptor_expression::do_get_backend(Translate_context* context)
8381eda7 1278{
8381eda7 1279 Named_object* no = this->fn_;
1280 Location loc = no->location();
ea664253 1281 if (this->dvar_ != NULL)
1282 return context->backend()->var_expression(this->dvar_, loc);
8381eda7 1283
ea664253 1284 Gogo* gogo = context->gogo();
8381eda7 1285 std::string var_name;
09e57698 1286 bool is_descriptor = false;
1287 if (no->is_function_declaration()
1288 && !no->func_declaration_value()->asm_name().empty()
1289 && Linemap::is_predeclared_location(no->location()))
1290 {
6098d6cb 1291 if (no->func_declaration_value()->asm_name().substr(0, 8) != "runtime.")
1292 var_name = no->func_declaration_value()->asm_name() + "_descriptor";
1293 else
1294 var_name = no->func_declaration_value()->asm_name() + "$descriptor";
09e57698 1295 is_descriptor = true;
1296 }
8381eda7 1297 else
09e57698 1298 {
1299 if (no->package() == NULL)
1300 var_name = gogo->pkgpath_symbol();
1301 else
1302 var_name = no->package()->pkgpath_symbol();
1303 var_name.push_back('.');
1304 var_name.append(Gogo::unpack_hidden_name(no->name()));
1305 var_name.append("$descriptor");
1306 }
8381eda7 1307
1308 Btype* btype = this->type()->get_backend(gogo);
1309
1310 Bvariable* bvar;
09e57698 1311 if (no->package() != NULL || is_descriptor)
f8bdf81a 1312 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1313 loc);
8381eda7 1314 else
1315 {
1316 Location bloc = Linemap::predeclared_location();
1317 bool is_hidden = ((no->is_function()
1318 && no->func_value()->enclosing() != NULL)
1319 || Gogo::is_thunk(no));
1320 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1321 btype, bloc);
1322 Expression_list* vals = new Expression_list();
f8bdf81a 1323 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1324 Expression* init =
1325 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1326 Translate_context bcontext(gogo, NULL, NULL, NULL);
1327 bcontext.set_is_const();
ea664253 1328 Bexpression* binit = init->get_backend(&bcontext);
8381eda7 1329 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1330 false, btype, bloc, binit);
1331 }
1332
1333 this->dvar_ = bvar;
ea664253 1334 return gogo->backend()->var_expression(bvar, loc);
8381eda7 1335}
1336
c6837989 1337// Print a function descriptor expression.
1338
1339void
1340Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1341{
1342 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1343}
1344
8381eda7 1345// Make a function descriptor expression.
1346
c6837989 1347Func_descriptor_expression*
1348Expression::make_func_descriptor(Named_object* fn)
8381eda7 1349{
c6837989 1350 return new Func_descriptor_expression(fn);
8381eda7 1351}
1352
1353// Make the function descriptor type, so that it can be converted.
1354
1355void
1356Expression::make_func_descriptor_type()
1357{
1358 Func_descriptor_expression::make_func_descriptor_type();
1359}
1360
1361// A reference to just the code of a function.
1362
1363class Func_code_reference_expression : public Expression
1364{
1365 public:
1366 Func_code_reference_expression(Named_object* function, Location location)
1367 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1368 function_(function)
1369 { }
1370
1371 protected:
1372 int
1373 do_traverse(Traverse*)
1374 { return TRAVERSE_CONTINUE; }
1375
f9ca30f9 1376 bool
1377 do_is_immutable() const
1378 { return true; }
1379
8381eda7 1380 Type*
1381 do_type()
1382 { return Type::make_pointer_type(Type::make_void_type()); }
1383
1384 void
1385 do_determine_type(const Type_context*)
1386 { }
1387
1388 Expression*
1389 do_copy()
1390 {
1391 return Expression::make_func_code_reference(this->function_,
1392 this->location());
1393 }
1394
ea664253 1395 Bexpression*
1396 do_get_backend(Translate_context*);
8381eda7 1397
1398 void
1399 do_dump_expression(Ast_dump_context* context) const
1400 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1401
1402 private:
1403 // The function.
1404 Named_object* function_;
1405};
1406
ea664253 1407// Get the backend representation for a reference to function code.
8381eda7 1408
ea664253 1409Bexpression*
1410Func_code_reference_expression::do_get_backend(Translate_context* context)
8381eda7 1411{
ea664253 1412 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1413 this->location());
8381eda7 1414}
1415
1416// Make a reference to the code of a function.
1417
1418Expression*
1419Expression::make_func_code_reference(Named_object* function, Location location)
1420{
1421 return new Func_code_reference_expression(function, location);
1422}
1423
e440a328 1424// Class Unknown_expression.
1425
1426// Return the name of an unknown expression.
1427
1428const std::string&
1429Unknown_expression::name() const
1430{
1431 return this->named_object_->name();
1432}
1433
1434// Lower a reference to an unknown name.
1435
1436Expression*
ceeb4318 1437Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1438{
b13c66cd 1439 Location location = this->location();
e440a328 1440 Named_object* no = this->named_object_;
deded542 1441 Named_object* real;
1442 if (!no->is_unknown())
1443 real = no;
1444 else
e440a328 1445 {
deded542 1446 real = no->unknown_value()->real_named_object();
1447 if (real == NULL)
1448 {
1449 if (this->is_composite_literal_key_)
1450 return this;
acf8e158 1451 if (!this->no_error_message_)
631d5788 1452 go_error_at(location, "reference to undefined name %qs",
1453 this->named_object_->message_name().c_str());
deded542 1454 return Expression::make_error(location);
1455 }
e440a328 1456 }
1457 switch (real->classification())
1458 {
1459 case Named_object::NAMED_OBJECT_CONST:
1460 return Expression::make_const_reference(real, location);
1461 case Named_object::NAMED_OBJECT_TYPE:
1462 return Expression::make_type(real->type_value(), location);
1463 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1464 if (this->is_composite_literal_key_)
1465 return this;
acf8e158 1466 if (!this->no_error_message_)
631d5788 1467 go_error_at(location, "reference to undefined type %qs",
1468 real->message_name().c_str());
e440a328 1469 return Expression::make_error(location);
1470 case Named_object::NAMED_OBJECT_VAR:
7d834090 1471 real->var_value()->set_is_used();
e440a328 1472 return Expression::make_var_reference(real, location);
1473 case Named_object::NAMED_OBJECT_FUNC:
1474 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1475 return Expression::make_func_reference(real, NULL, location);
1476 case Named_object::NAMED_OBJECT_PACKAGE:
1477 if (this->is_composite_literal_key_)
1478 return this;
acf8e158 1479 if (!this->no_error_message_)
631d5788 1480 go_error_at(location, "unexpected reference to package");
e440a328 1481 return Expression::make_error(location);
1482 default:
c3e6f413 1483 go_unreachable();
e440a328 1484 }
1485}
1486
d751bb78 1487// Dump the ast representation for an unknown expression to a dump context.
1488
1489void
1490Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1491{
1492 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1493 << ")";
d751bb78 1494}
1495
e440a328 1496// Make a reference to an unknown name.
1497
acf8e158 1498Unknown_expression*
b13c66cd 1499Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1500{
e440a328 1501 return new Unknown_expression(no, location);
1502}
1503
1504// A boolean expression.
1505
1506class Boolean_expression : public Expression
1507{
1508 public:
b13c66cd 1509 Boolean_expression(bool val, Location location)
e440a328 1510 : Expression(EXPRESSION_BOOLEAN, location),
1511 val_(val), type_(NULL)
1512 { }
1513
1514 static Expression*
1515 do_import(Import*);
1516
1517 protected:
1518 bool
1519 do_is_constant() const
1520 { return true; }
1521
0e168074 1522 bool
1523 do_is_immutable() const
1524 { return true; }
1525
e440a328 1526 Type*
1527 do_type();
1528
1529 void
1530 do_determine_type(const Type_context*);
1531
1532 Expression*
1533 do_copy()
1534 { return this; }
1535
ea664253 1536 Bexpression*
1537 do_get_backend(Translate_context* context)
1538 { return context->backend()->boolean_constant_expression(this->val_); }
e440a328 1539
1540 void
1541 do_export(Export* exp) const
1542 { exp->write_c_string(this->val_ ? "true" : "false"); }
1543
d751bb78 1544 void
1545 do_dump_expression(Ast_dump_context* ast_dump_context) const
1546 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1547
e440a328 1548 private:
1549 // The constant.
1550 bool val_;
1551 // The type as determined by context.
1552 Type* type_;
1553};
1554
1555// Get the type.
1556
1557Type*
1558Boolean_expression::do_type()
1559{
1560 if (this->type_ == NULL)
1561 this->type_ = Type::make_boolean_type();
1562 return this->type_;
1563}
1564
1565// Set the type from the context.
1566
1567void
1568Boolean_expression::do_determine_type(const Type_context* context)
1569{
1570 if (this->type_ != NULL && !this->type_->is_abstract())
1571 ;
1572 else if (context->type != NULL && context->type->is_boolean_type())
1573 this->type_ = context->type;
1574 else if (!context->may_be_abstract)
1575 this->type_ = Type::lookup_bool_type();
1576}
1577
1578// Import a boolean constant.
1579
1580Expression*
1581Boolean_expression::do_import(Import* imp)
1582{
1583 if (imp->peek_char() == 't')
1584 {
1585 imp->require_c_string("true");
1586 return Expression::make_boolean(true, imp->location());
1587 }
1588 else
1589 {
1590 imp->require_c_string("false");
1591 return Expression::make_boolean(false, imp->location());
1592 }
1593}
1594
1595// Make a boolean expression.
1596
1597Expression*
b13c66cd 1598Expression::make_boolean(bool val, Location location)
e440a328 1599{
1600 return new Boolean_expression(val, location);
1601}
1602
1603// Class String_expression.
1604
1605// Get the type.
1606
1607Type*
1608String_expression::do_type()
1609{
1610 if (this->type_ == NULL)
1611 this->type_ = Type::make_string_type();
1612 return this->type_;
1613}
1614
1615// Set the type from the context.
1616
1617void
1618String_expression::do_determine_type(const Type_context* context)
1619{
1620 if (this->type_ != NULL && !this->type_->is_abstract())
1621 ;
1622 else if (context->type != NULL && context->type->is_string_type())
1623 this->type_ = context->type;
1624 else if (!context->may_be_abstract)
1625 this->type_ = Type::lookup_string_type();
1626}
1627
1628// Build a string constant.
1629
ea664253 1630Bexpression*
1631String_expression::do_get_backend(Translate_context* context)
e440a328 1632{
2c809f8f 1633 Gogo* gogo = context->gogo();
1634 Btype* btype = Type::make_string_type()->get_backend(gogo);
1635
1636 Location loc = this->location();
1637 std::vector<Bexpression*> init(2);
1638 Bexpression* str_cst =
1639 gogo->backend()->string_constant_expression(this->val_);
1640 init[0] = gogo->backend()->address_expression(str_cst, loc);
1641
1642 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1643 mpz_t lenval;
1644 mpz_init_set_ui(lenval, this->val_.length());
1645 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1646 mpz_clear(lenval);
1647
ea664253 1648 return gogo->backend()->constructor_expression(btype, init, loc);
e440a328 1649}
1650
8b1c301d 1651 // Write string literal to string dump.
e440a328 1652
1653void
8b1c301d 1654String_expression::export_string(String_dump* exp,
1655 const String_expression* str)
e440a328 1656{
1657 std::string s;
8b1c301d 1658 s.reserve(str->val_.length() * 4 + 2);
e440a328 1659 s += '"';
8b1c301d 1660 for (std::string::const_iterator p = str->val_.begin();
1661 p != str->val_.end();
e440a328 1662 ++p)
1663 {
1664 if (*p == '\\' || *p == '"')
1665 {
1666 s += '\\';
1667 s += *p;
1668 }
1669 else if (*p >= 0x20 && *p < 0x7f)
1670 s += *p;
1671 else if (*p == '\n')
1672 s += "\\n";
1673 else if (*p == '\t')
1674 s += "\\t";
1675 else
1676 {
1677 s += "\\x";
1678 unsigned char c = *p;
1679 unsigned int dig = c >> 4;
1680 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1681 dig = c & 0xf;
1682 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1683 }
1684 }
1685 s += '"';
1686 exp->write_string(s);
1687}
1688
8b1c301d 1689// Export a string expression.
1690
1691void
1692String_expression::do_export(Export* exp) const
1693{
1694 String_expression::export_string(exp, this);
1695}
1696
e440a328 1697// Import a string expression.
1698
1699Expression*
1700String_expression::do_import(Import* imp)
1701{
1702 imp->require_c_string("\"");
1703 std::string val;
1704 while (true)
1705 {
1706 int c = imp->get_char();
1707 if (c == '"' || c == -1)
1708 break;
1709 if (c != '\\')
1710 val += static_cast<char>(c);
1711 else
1712 {
1713 c = imp->get_char();
1714 if (c == '\\' || c == '"')
1715 val += static_cast<char>(c);
1716 else if (c == 'n')
1717 val += '\n';
1718 else if (c == 't')
1719 val += '\t';
1720 else if (c == 'x')
1721 {
1722 c = imp->get_char();
1723 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1724 c = imp->get_char();
1725 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1726 char v = (vh << 4) | vl;
1727 val += v;
1728 }
1729 else
1730 {
631d5788 1731 go_error_at(imp->location(), "bad string constant");
e440a328 1732 return Expression::make_error(imp->location());
1733 }
1734 }
1735 }
1736 return Expression::make_string(val, imp->location());
1737}
1738
d751bb78 1739// Ast dump for string expression.
1740
1741void
1742String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1743{
8b1c301d 1744 String_expression::export_string(ast_dump_context, this);
d751bb78 1745}
1746
e440a328 1747// Make a string expression.
1748
1749Expression*
b13c66cd 1750Expression::make_string(const std::string& val, Location location)
e440a328 1751{
1752 return new String_expression(val, location);
1753}
1754
2c809f8f 1755// An expression that evaluates to some characteristic of a string.
1756// This is used when indexing, bound-checking, or nil checking a string.
1757
1758class String_info_expression : public Expression
1759{
1760 public:
1761 String_info_expression(Expression* string, String_info string_info,
1762 Location location)
1763 : Expression(EXPRESSION_STRING_INFO, location),
1764 string_(string), string_info_(string_info)
1765 { }
1766
1767 protected:
1768 Type*
1769 do_type();
1770
1771 void
1772 do_determine_type(const Type_context*)
1773 { go_unreachable(); }
1774
1775 Expression*
1776 do_copy()
1777 {
1778 return new String_info_expression(this->string_->copy(), this->string_info_,
1779 this->location());
1780 }
1781
ea664253 1782 Bexpression*
1783 do_get_backend(Translate_context* context);
2c809f8f 1784
1785 void
1786 do_dump_expression(Ast_dump_context*) const;
1787
1788 void
1789 do_issue_nil_check()
1790 { this->string_->issue_nil_check(); }
1791
1792 private:
1793 // The string for which we are getting information.
1794 Expression* string_;
1795 // What information we want.
1796 String_info string_info_;
1797};
1798
1799// Return the type of the string info.
1800
1801Type*
1802String_info_expression::do_type()
1803{
1804 switch (this->string_info_)
1805 {
1806 case STRING_INFO_DATA:
1807 {
1808 Type* byte_type = Type::lookup_integer_type("uint8");
1809 return Type::make_pointer_type(byte_type);
1810 }
1811 case STRING_INFO_LENGTH:
1812 return Type::lookup_integer_type("int");
1813 default:
1814 go_unreachable();
1815 }
1816}
1817
1818// Return string information in GENERIC.
1819
ea664253 1820Bexpression*
1821String_info_expression::do_get_backend(Translate_context* context)
2c809f8f 1822{
1823 Gogo* gogo = context->gogo();
1824
ea664253 1825 Bexpression* bstring = this->string_->get_backend(context);
2c809f8f 1826 switch (this->string_info_)
1827 {
1828 case STRING_INFO_DATA:
1829 case STRING_INFO_LENGTH:
ea664253 1830 return gogo->backend()->struct_field_expression(bstring,
1831 this->string_info_,
1832 this->location());
2c809f8f 1833 break;
1834 default:
1835 go_unreachable();
1836 }
2c809f8f 1837}
1838
1839// Dump ast representation for a type info expression.
1840
1841void
1842String_info_expression::do_dump_expression(
1843 Ast_dump_context* ast_dump_context) const
1844{
1845 ast_dump_context->ostream() << "stringinfo(";
1846 this->string_->dump_expression(ast_dump_context);
1847 ast_dump_context->ostream() << ",";
1848 ast_dump_context->ostream() <<
1849 (this->string_info_ == STRING_INFO_DATA ? "data"
1850 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1851 : "unknown");
1852 ast_dump_context->ostream() << ")";
1853}
1854
1855// Make a string info expression.
1856
1857Expression*
1858Expression::make_string_info(Expression* string, String_info string_info,
1859 Location location)
1860{
1861 return new String_info_expression(string, string_info, location);
1862}
1863
e440a328 1864// Make an integer expression.
1865
1866class Integer_expression : public Expression
1867{
1868 public:
5d4b8566 1869 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1870 Location location)
e440a328 1871 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1872 type_(type), is_character_constant_(is_character_constant)
e440a328 1873 { mpz_init_set(this->val_, *val); }
1874
1875 static Expression*
1876 do_import(Import*);
1877
8b1c301d 1878 // Write VAL to string dump.
e440a328 1879 static void
8b1c301d 1880 export_integer(String_dump* exp, const mpz_t val);
e440a328 1881
d751bb78 1882 // Write VAL to dump context.
1883 static void
1884 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1885
e440a328 1886 protected:
1887 bool
1888 do_is_constant() const
1889 { return true; }
1890
0e168074 1891 bool
1892 do_is_immutable() const
1893 { return true; }
1894
e440a328 1895 bool
0c77715b 1896 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1897
1898 Type*
1899 do_type();
1900
1901 void
1902 do_determine_type(const Type_context* context);
1903
1904 void
1905 do_check_types(Gogo*);
1906
ea664253 1907 Bexpression*
1908 do_get_backend(Translate_context*);
e440a328 1909
1910 Expression*
1911 do_copy()
5d4b8566 1912 {
1913 if (this->is_character_constant_)
1914 return Expression::make_character(&this->val_, this->type_,
1915 this->location());
1916 else
e67508fa 1917 return Expression::make_integer_z(&this->val_, this->type_,
1918 this->location());
5d4b8566 1919 }
e440a328 1920
1921 void
1922 do_export(Export*) const;
1923
d751bb78 1924 void
1925 do_dump_expression(Ast_dump_context*) const;
1926
e440a328 1927 private:
1928 // The integer value.
1929 mpz_t val_;
1930 // The type so far.
1931 Type* type_;
5d4b8566 1932 // Whether this is a character constant.
1933 bool is_character_constant_;
e440a328 1934};
1935
0c77715b 1936// Return a numeric constant for this expression. We have to mark
1937// this as a character when appropriate.
e440a328 1938
1939bool
0c77715b 1940Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1941{
0c77715b 1942 if (this->is_character_constant_)
1943 nc->set_rune(this->type_, this->val_);
1944 else
1945 nc->set_int(this->type_, this->val_);
e440a328 1946 return true;
1947}
1948
1949// Return the current type. If we haven't set the type yet, we return
1950// an abstract integer type.
1951
1952Type*
1953Integer_expression::do_type()
1954{
1955 if (this->type_ == NULL)
5d4b8566 1956 {
1957 if (this->is_character_constant_)
1958 this->type_ = Type::make_abstract_character_type();
1959 else
1960 this->type_ = Type::make_abstract_integer_type();
1961 }
e440a328 1962 return this->type_;
1963}
1964
1965// Set the type of the integer value. Here we may switch from an
1966// abstract type to a real type.
1967
1968void
1969Integer_expression::do_determine_type(const Type_context* context)
1970{
1971 if (this->type_ != NULL && !this->type_->is_abstract())
1972 ;
0c77715b 1973 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1974 this->type_ = context->type;
1975 else if (!context->may_be_abstract)
5d4b8566 1976 {
1977 if (this->is_character_constant_)
1978 this->type_ = Type::lookup_integer_type("int32");
1979 else
1980 this->type_ = Type::lookup_integer_type("int");
1981 }
e440a328 1982}
1983
e440a328 1984// Check the type of an integer constant.
1985
1986void
1987Integer_expression::do_check_types(Gogo*)
1988{
0c77715b 1989 Type* type = this->type_;
1990 if (type == NULL)
e440a328 1991 return;
0c77715b 1992 Numeric_constant nc;
1993 if (this->is_character_constant_)
1994 nc.set_rune(NULL, this->val_);
1995 else
1996 nc.set_int(NULL, this->val_);
1997 if (!nc.set_type(type, true, this->location()))
e440a328 1998 this->set_is_error();
1999}
2000
ea664253 2001// Get the backend representation for an integer constant.
e440a328 2002
ea664253 2003Bexpression*
2004Integer_expression::do_get_backend(Translate_context* context)
e440a328 2005{
12373dd5 2006 if (this->is_error_expression()
2007 || (this->type_ != NULL && this->type_->is_error_type()))
2008 {
2009 go_assert(saw_errors());
2010 return context->gogo()->backend()->error_expression();
2011 }
2012
48c2a53a 2013 Type* resolved_type = NULL;
e440a328 2014 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2015 resolved_type = this->type_;
e440a328 2016 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2017 {
2018 // We are converting to an abstract floating point type.
48c2a53a 2019 resolved_type = Type::lookup_float_type("float64");
e440a328 2020 }
2021 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2022 {
2023 // We are converting to an abstract complex type.
48c2a53a 2024 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2025 }
2026 else
2027 {
2028 // If we still have an abstract type here, then this is being
2029 // used in a constant expression which didn't get reduced for
2030 // some reason. Use a type which will fit the value. We use <,
2031 // not <=, because we need an extra bit for the sign bit.
2032 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 2033 Type* int_type = Type::lookup_integer_type("int");
2034 if (bits < int_type->integer_type()->bits())
48c2a53a 2035 resolved_type = int_type;
e440a328 2036 else if (bits < 64)
48c2a53a 2037 resolved_type = Type::lookup_integer_type("int64");
e440a328 2038 else
48c2a53a 2039 {
2040 if (!saw_errors())
631d5788 2041 go_error_at(this->location(),
2042 "unknown type for large integer constant");
ea664253 2043 return context->gogo()->backend()->error_expression();
48c2a53a 2044 }
e440a328 2045 }
48c2a53a 2046 Numeric_constant nc;
2047 nc.set_int(resolved_type, this->val_);
ea664253 2048 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2049}
2050
2051// Write VAL to export data.
2052
2053void
8b1c301d 2054Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 2055{
2056 char* s = mpz_get_str(NULL, 10, val);
2057 exp->write_c_string(s);
2058 free(s);
2059}
2060
2061// Export an integer in a constant expression.
2062
2063void
2064Integer_expression::do_export(Export* exp) const
2065{
2066 Integer_expression::export_integer(exp, this->val_);
5d4b8566 2067 if (this->is_character_constant_)
2068 exp->write_c_string("'");
e440a328 2069 // A trailing space lets us reliably identify the end of the number.
2070 exp->write_c_string(" ");
2071}
2072
2073// Import an integer, floating point, or complex value. This handles
2074// all these types because they all start with digits.
2075
2076Expression*
2077Integer_expression::do_import(Import* imp)
2078{
2079 std::string num = imp->read_identifier();
2080 imp->require_c_string(" ");
2081 if (!num.empty() && num[num.length() - 1] == 'i')
2082 {
2083 mpfr_t real;
2084 size_t plus_pos = num.find('+', 1);
2085 size_t minus_pos = num.find('-', 1);
2086 size_t pos;
2087 if (plus_pos == std::string::npos)
2088 pos = minus_pos;
2089 else if (minus_pos == std::string::npos)
2090 pos = plus_pos;
2091 else
2092 {
631d5788 2093 go_error_at(imp->location(), "bad number in import data: %qs",
2094 num.c_str());
e440a328 2095 return Expression::make_error(imp->location());
2096 }
2097 if (pos == std::string::npos)
2098 mpfr_set_ui(real, 0, GMP_RNDN);
2099 else
2100 {
2101 std::string real_str = num.substr(0, pos);
2102 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2103 {
631d5788 2104 go_error_at(imp->location(), "bad number in import data: %qs",
2105 real_str.c_str());
e440a328 2106 return Expression::make_error(imp->location());
2107 }
2108 }
2109
2110 std::string imag_str;
2111 if (pos == std::string::npos)
2112 imag_str = num;
2113 else
2114 imag_str = num.substr(pos);
2115 imag_str = imag_str.substr(0, imag_str.size() - 1);
2116 mpfr_t imag;
2117 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2118 {
631d5788 2119 go_error_at(imp->location(), "bad number in import data: %qs",
2120 imag_str.c_str());
e440a328 2121 return Expression::make_error(imp->location());
2122 }
fcbea5e4 2123 mpc_t cval;
2124 mpc_init2(cval, mpc_precision);
2125 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
e440a328 2126 mpfr_clear(real);
2127 mpfr_clear(imag);
fcbea5e4 2128 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2129 mpc_clear(cval);
e440a328 2130 return ret;
2131 }
2132 else if (num.find('.') == std::string::npos
2133 && num.find('E') == std::string::npos)
2134 {
5d4b8566 2135 bool is_character_constant = (!num.empty()
2136 && num[num.length() - 1] == '\'');
2137 if (is_character_constant)
2138 num = num.substr(0, num.length() - 1);
e440a328 2139 mpz_t val;
2140 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2141 {
631d5788 2142 go_error_at(imp->location(), "bad number in import data: %qs",
2143 num.c_str());
e440a328 2144 return Expression::make_error(imp->location());
2145 }
5d4b8566 2146 Expression* ret;
2147 if (is_character_constant)
2148 ret = Expression::make_character(&val, NULL, imp->location());
2149 else
e67508fa 2150 ret = Expression::make_integer_z(&val, NULL, imp->location());
e440a328 2151 mpz_clear(val);
2152 return ret;
2153 }
2154 else
2155 {
2156 mpfr_t val;
2157 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2158 {
631d5788 2159 go_error_at(imp->location(), "bad number in import data: %qs",
2160 num.c_str());
e440a328 2161 return Expression::make_error(imp->location());
2162 }
2163 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2164 mpfr_clear(val);
2165 return ret;
2166 }
2167}
d751bb78 2168// Ast dump for integer expression.
2169
2170void
2171Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2172{
5d4b8566 2173 if (this->is_character_constant_)
2174 ast_dump_context->ostream() << '\'';
8b1c301d 2175 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2176 if (this->is_character_constant_)
2177 ast_dump_context->ostream() << '\'';
d751bb78 2178}
2179
e67508fa 2180// Build a new integer value from a multi-precision integer.
e440a328 2181
2182Expression*
e67508fa 2183Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
5d4b8566 2184{
2185 return new Integer_expression(val, type, false, location);
2186}
2187
e67508fa 2188// Build a new integer value from an unsigned long.
2189
2190Expression*
2191Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2192{
2193 mpz_t zval;
2194 mpz_init_set_ui(zval, val);
2195 Expression* ret = Expression::make_integer_z(&zval, type, location);
2196 mpz_clear(zval);
2197 return ret;
2198}
2199
2200// Build a new integer value from a signed long.
2201
2202Expression*
2203Expression::make_integer_sl(long val, Type *type, Location location)
2204{
2205 mpz_t zval;
2206 mpz_init_set_si(zval, val);
2207 Expression* ret = Expression::make_integer_z(&zval, type, location);
2208 mpz_clear(zval);
2209 return ret;
2210}
2211
3f378015 2212// Store an int64_t in an uninitialized mpz_t.
2213
2214static void
2215set_mpz_from_int64(mpz_t* zval, int64_t val)
2216{
2217 if (val >= 0)
2218 {
2219 unsigned long ul = static_cast<unsigned long>(val);
2220 if (static_cast<int64_t>(ul) == val)
2221 {
2222 mpz_init_set_ui(*zval, ul);
2223 return;
2224 }
2225 }
2226 uint64_t uv;
2227 if (val >= 0)
2228 uv = static_cast<uint64_t>(val);
2229 else
2230 uv = static_cast<uint64_t>(- val);
2231 unsigned long ul = uv & 0xffffffffUL;
2232 mpz_init_set_ui(*zval, ul);
2233 mpz_t hval;
2234 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2235 mpz_mul_2exp(hval, hval, 32);
2236 mpz_add(*zval, *zval, hval);
2237 mpz_clear(hval);
2238 if (val < 0)
2239 mpz_neg(*zval, *zval);
2240}
2241
2242// Build a new integer value from an int64_t.
2243
2244Expression*
2245Expression::make_integer_int64(int64_t val, Type* type, Location location)
2246{
2247 mpz_t zval;
2248 set_mpz_from_int64(&zval, val);
2249 Expression* ret = Expression::make_integer_z(&zval, type, location);
2250 mpz_clear(zval);
2251 return ret;
2252}
2253
5d4b8566 2254// Build a new character constant value.
2255
2256Expression*
2257Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2258{
5d4b8566 2259 return new Integer_expression(val, type, true, location);
e440a328 2260}
2261
2262// Floats.
2263
2264class Float_expression : public Expression
2265{
2266 public:
b13c66cd 2267 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2268 : Expression(EXPRESSION_FLOAT, location),
2269 type_(type)
2270 {
2271 mpfr_init_set(this->val_, *val, GMP_RNDN);
2272 }
2273
e440a328 2274 // Write VAL to export data.
2275 static void
8b1c301d 2276 export_float(String_dump* exp, const mpfr_t val);
2277
d751bb78 2278 // Write VAL to dump file.
2279 static void
2280 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2281
2282 protected:
2283 bool
2284 do_is_constant() const
2285 { return true; }
2286
0e168074 2287 bool
2288 do_is_immutable() const
2289 { return true; }
2290
e440a328 2291 bool
0c77715b 2292 do_numeric_constant_value(Numeric_constant* nc) const
2293 {
2294 nc->set_float(this->type_, this->val_);
2295 return true;
2296 }
e440a328 2297
2298 Type*
2299 do_type();
2300
2301 void
2302 do_determine_type(const Type_context*);
2303
2304 void
2305 do_check_types(Gogo*);
2306
2307 Expression*
2308 do_copy()
2309 { return Expression::make_float(&this->val_, this->type_,
2310 this->location()); }
2311
ea664253 2312 Bexpression*
2313 do_get_backend(Translate_context*);
e440a328 2314
2315 void
2316 do_export(Export*) const;
2317
d751bb78 2318 void
2319 do_dump_expression(Ast_dump_context*) const;
2320
e440a328 2321 private:
2322 // The floating point value.
2323 mpfr_t val_;
2324 // The type so far.
2325 Type* type_;
2326};
2327
e440a328 2328// Return the current type. If we haven't set the type yet, we return
2329// an abstract float type.
2330
2331Type*
2332Float_expression::do_type()
2333{
2334 if (this->type_ == NULL)
2335 this->type_ = Type::make_abstract_float_type();
2336 return this->type_;
2337}
2338
2339// Set the type of the float value. Here we may switch from an
2340// abstract type to a real type.
2341
2342void
2343Float_expression::do_determine_type(const Type_context* context)
2344{
2345 if (this->type_ != NULL && !this->type_->is_abstract())
2346 ;
2347 else if (context->type != NULL
2348 && (context->type->integer_type() != NULL
2349 || context->type->float_type() != NULL
2350 || context->type->complex_type() != NULL))
2351 this->type_ = context->type;
2352 else if (!context->may_be_abstract)
48080209 2353 this->type_ = Type::lookup_float_type("float64");
e440a328 2354}
2355
e440a328 2356// Check the type of a float value.
2357
2358void
2359Float_expression::do_check_types(Gogo*)
2360{
0c77715b 2361 Type* type = this->type_;
2362 if (type == NULL)
e440a328 2363 return;
0c77715b 2364 Numeric_constant nc;
2365 nc.set_float(NULL, this->val_);
2366 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2367 this->set_is_error();
e440a328 2368}
2369
ea664253 2370// Get the backend representation for a float constant.
e440a328 2371
ea664253 2372Bexpression*
2373Float_expression::do_get_backend(Translate_context* context)
e440a328 2374{
12373dd5 2375 if (this->is_error_expression()
2376 || (this->type_ != NULL && this->type_->is_error_type()))
2377 {
2378 go_assert(saw_errors());
2379 return context->gogo()->backend()->error_expression();
2380 }
2381
48c2a53a 2382 Type* resolved_type;
e440a328 2383 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2384 resolved_type = this->type_;
e440a328 2385 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2386 {
2387 // We have an abstract integer type. We just hope for the best.
48c2a53a 2388 resolved_type = Type::lookup_integer_type("int");
2389 }
2390 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2391 {
2392 // We are converting to an abstract complex type.
2393 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2394 }
2395 else
2396 {
2397 // If we still have an abstract type here, then this is being
2398 // used in a constant expression which didn't get reduced. We
2399 // just use float64 and hope for the best.
48c2a53a 2400 resolved_type = Type::lookup_float_type("float64");
e440a328 2401 }
48c2a53a 2402
2403 Numeric_constant nc;
2404 nc.set_float(resolved_type, this->val_);
ea664253 2405 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2406}
2407
8b1c301d 2408// Write a floating point number to a string dump.
e440a328 2409
2410void
8b1c301d 2411Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2412{
2413 mp_exp_t exponent;
2414 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2415 if (*s == '-')
2416 exp->write_c_string("-");
2417 exp->write_c_string("0.");
2418 exp->write_c_string(*s == '-' ? s + 1 : s);
2419 mpfr_free_str(s);
2420 char buf[30];
2421 snprintf(buf, sizeof buf, "E%ld", exponent);
2422 exp->write_c_string(buf);
2423}
2424
2425// Export a floating point number in a constant expression.
2426
2427void
2428Float_expression::do_export(Export* exp) const
2429{
2430 Float_expression::export_float(exp, this->val_);
2431 // A trailing space lets us reliably identify the end of the number.
2432 exp->write_c_string(" ");
2433}
2434
d751bb78 2435// Dump a floating point number to the dump file.
2436
2437void
2438Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2439{
8b1c301d 2440 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2441}
2442
e440a328 2443// Make a float expression.
2444
2445Expression*
b13c66cd 2446Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2447{
2448 return new Float_expression(val, type, location);
2449}
2450
2451// Complex numbers.
2452
2453class Complex_expression : public Expression
2454{
2455 public:
fcbea5e4 2456 Complex_expression(const mpc_t* val, Type* type, Location location)
e440a328 2457 : Expression(EXPRESSION_COMPLEX, location),
2458 type_(type)
2459 {
fcbea5e4 2460 mpc_init2(this->val_, mpc_precision);
2461 mpc_set(this->val_, *val, MPC_RNDNN);
e440a328 2462 }
2463
fcbea5e4 2464 // Write VAL to string dump.
e440a328 2465 static void
fcbea5e4 2466 export_complex(String_dump* exp, const mpc_t val);
e440a328 2467
d751bb78 2468 // Write REAL/IMAG to dump context.
2469 static void
fcbea5e4 2470 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
d751bb78 2471
e440a328 2472 protected:
2473 bool
2474 do_is_constant() const
2475 { return true; }
2476
0e168074 2477 bool
2478 do_is_immutable() const
2479 { return true; }
2480
e440a328 2481 bool
0c77715b 2482 do_numeric_constant_value(Numeric_constant* nc) const
2483 {
fcbea5e4 2484 nc->set_complex(this->type_, this->val_);
0c77715b 2485 return true;
2486 }
e440a328 2487
2488 Type*
2489 do_type();
2490
2491 void
2492 do_determine_type(const Type_context*);
2493
2494 void
2495 do_check_types(Gogo*);
2496
2497 Expression*
2498 do_copy()
2499 {
fcbea5e4 2500 return Expression::make_complex(&this->val_, this->type_,
e440a328 2501 this->location());
2502 }
2503
ea664253 2504 Bexpression*
2505 do_get_backend(Translate_context*);
e440a328 2506
2507 void
2508 do_export(Export*) const;
2509
d751bb78 2510 void
2511 do_dump_expression(Ast_dump_context*) const;
abd26de0 2512
e440a328 2513 private:
fcbea5e4 2514 // The complex value.
2515 mpc_t val_;
e440a328 2516 // The type if known.
2517 Type* type_;
2518};
2519
e440a328 2520// Return the current type. If we haven't set the type yet, we return
2521// an abstract complex type.
2522
2523Type*
2524Complex_expression::do_type()
2525{
2526 if (this->type_ == NULL)
2527 this->type_ = Type::make_abstract_complex_type();
2528 return this->type_;
2529}
2530
2531// Set the type of the complex value. Here we may switch from an
2532// abstract type to a real type.
2533
2534void
2535Complex_expression::do_determine_type(const Type_context* context)
2536{
2537 if (this->type_ != NULL && !this->type_->is_abstract())
2538 ;
abd26de0 2539 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 2540 this->type_ = context->type;
2541 else if (!context->may_be_abstract)
48080209 2542 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2543}
2544
e440a328 2545// Check the type of a complex value.
2546
2547void
2548Complex_expression::do_check_types(Gogo*)
2549{
0c77715b 2550 Type* type = this->type_;
2551 if (type == NULL)
e440a328 2552 return;
0c77715b 2553 Numeric_constant nc;
fcbea5e4 2554 nc.set_complex(NULL, this->val_);
0c77715b 2555 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2556 this->set_is_error();
2557}
2558
ea664253 2559// Get the backend representation for a complex constant.
e440a328 2560
ea664253 2561Bexpression*
2562Complex_expression::do_get_backend(Translate_context* context)
e440a328 2563{
12373dd5 2564 if (this->is_error_expression()
2565 || (this->type_ != NULL && this->type_->is_error_type()))
2566 {
2567 go_assert(saw_errors());
2568 return context->gogo()->backend()->error_expression();
2569 }
2570
48c2a53a 2571 Type* resolved_type;
e440a328 2572 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2573 resolved_type = this->type_;
2574 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2575 {
2576 // We are converting to an abstract integer type.
2577 resolved_type = Type::lookup_integer_type("int");
2578 }
2579 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2580 {
2581 // We are converting to an abstract float type.
2582 resolved_type = Type::lookup_float_type("float64");
2583 }
e440a328 2584 else
2585 {
47ae02b7 2586 // If we still have an abstract type here, this is being
e440a328 2587 // used in a constant expression which didn't get reduced. We
2588 // just use complex128 and hope for the best.
48c2a53a 2589 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2590 }
48c2a53a 2591
2592 Numeric_constant nc;
fcbea5e4 2593 nc.set_complex(resolved_type, this->val_);
ea664253 2594 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2595}
2596
2597// Write REAL/IMAG to export data.
2598
2599void
fcbea5e4 2600Complex_expression::export_complex(String_dump* exp, const mpc_t val)
e440a328 2601{
fcbea5e4 2602 if (!mpfr_zero_p(mpc_realref(val)))
e440a328 2603 {
fcbea5e4 2604 Float_expression::export_float(exp, mpc_realref(val));
d1db782d 2605 if (mpfr_sgn(mpc_imagref(val)) >= 0)
e440a328 2606 exp->write_c_string("+");
2607 }
fcbea5e4 2608 Float_expression::export_float(exp, mpc_imagref(val));
e440a328 2609 exp->write_c_string("i");
2610}
2611
2612// Export a complex number in a constant expression.
2613
2614void
2615Complex_expression::do_export(Export* exp) const
2616{
fcbea5e4 2617 Complex_expression::export_complex(exp, this->val_);
e440a328 2618 // A trailing space lets us reliably identify the end of the number.
2619 exp->write_c_string(" ");
2620}
2621
d751bb78 2622// Dump a complex expression to the dump file.
2623
2624void
2625Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2626{
fcbea5e4 2627 Complex_expression::export_complex(ast_dump_context, this->val_);
d751bb78 2628}
2629
e440a328 2630// Make a complex expression.
2631
2632Expression*
fcbea5e4 2633Expression::make_complex(const mpc_t* val, Type* type, Location location)
e440a328 2634{
fcbea5e4 2635 return new Complex_expression(val, type, location);
e440a328 2636}
2637
d5b605df 2638// Find a named object in an expression.
2639
2640class Find_named_object : public Traverse
2641{
2642 public:
2643 Find_named_object(Named_object* no)
2644 : Traverse(traverse_expressions),
2645 no_(no), found_(false)
2646 { }
2647
2648 // Whether we found the object.
2649 bool
2650 found() const
2651 { return this->found_; }
2652
2653 protected:
2654 int
2655 expression(Expression**);
2656
2657 private:
2658 // The object we are looking for.
2659 Named_object* no_;
2660 // Whether we found it.
2661 bool found_;
2662};
2663
e440a328 2664// A reference to a const in an expression.
2665
2666class Const_expression : public Expression
2667{
2668 public:
b13c66cd 2669 Const_expression(Named_object* constant, Location location)
e440a328 2670 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2671 constant_(constant), type_(NULL), seen_(false)
e440a328 2672 { }
2673
d5b605df 2674 Named_object*
2675 named_object()
2676 { return this->constant_; }
2677
a7f064d5 2678 // Check that the initializer does not refer to the constant itself.
2679 void
2680 check_for_init_loop();
2681
e440a328 2682 protected:
ba4aedd4 2683 int
2684 do_traverse(Traverse*);
2685
e440a328 2686 Expression*
ceeb4318 2687 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2688
2689 bool
2690 do_is_constant() const
2691 { return true; }
2692
0e168074 2693 bool
2694 do_is_immutable() const
2695 { return true; }
2696
e440a328 2697 bool
0c77715b 2698 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2699
2700 bool
af6b489a 2701 do_string_constant_value(std::string* val) const;
e440a328 2702
2703 Type*
2704 do_type();
2705
2706 // The type of a const is set by the declaration, not the use.
2707 void
2708 do_determine_type(const Type_context*);
2709
2710 void
2711 do_check_types(Gogo*);
2712
2713 Expression*
2714 do_copy()
2715 { return this; }
2716
ea664253 2717 Bexpression*
2718 do_get_backend(Translate_context* context);
e440a328 2719
2720 // When exporting a reference to a const as part of a const
2721 // expression, we export the value. We ignore the fact that it has
2722 // a name.
2723 void
2724 do_export(Export* exp) const
2725 { this->constant_->const_value()->expr()->export_expression(exp); }
2726
d751bb78 2727 void
2728 do_dump_expression(Ast_dump_context*) const;
2729
e440a328 2730 private:
2731 // The constant.
2732 Named_object* constant_;
2733 // The type of this reference. This is used if the constant has an
2734 // abstract type.
2735 Type* type_;
13e818f5 2736 // Used to prevent infinite recursion when a constant incorrectly
2737 // refers to itself.
2738 mutable bool seen_;
e440a328 2739};
2740
ba4aedd4 2741// Traversal.
2742
2743int
2744Const_expression::do_traverse(Traverse* traverse)
2745{
2746 if (this->type_ != NULL)
2747 return Type::traverse(this->type_, traverse);
2748 return TRAVERSE_CONTINUE;
2749}
2750
e440a328 2751// Lower a constant expression. This is where we convert the
2752// predeclared constant iota into an integer value.
2753
2754Expression*
ceeb4318 2755Const_expression::do_lower(Gogo* gogo, Named_object*,
2756 Statement_inserter*, int iota_value)
e440a328 2757{
2758 if (this->constant_->const_value()->expr()->classification()
2759 == EXPRESSION_IOTA)
2760 {
2761 if (iota_value == -1)
2762 {
631d5788 2763 go_error_at(this->location(),
2764 "iota is only defined in const declarations");
e440a328 2765 iota_value = 0;
2766 }
e67508fa 2767 return Expression::make_integer_ul(iota_value, NULL, this->location());
e440a328 2768 }
2769
2770 // Make sure that the constant itself has been lowered.
2771 gogo->lower_constant(this->constant_);
2772
2773 return this;
2774}
2775
0c77715b 2776// Return a numeric constant value.
e440a328 2777
2778bool
0c77715b 2779Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2780{
13e818f5 2781 if (this->seen_)
2782 return false;
2783
e440a328 2784 Expression* e = this->constant_->const_value()->expr();
0c77715b 2785
13e818f5 2786 this->seen_ = true;
2787
0c77715b 2788 bool r = e->numeric_constant_value(nc);
e440a328 2789
13e818f5 2790 this->seen_ = false;
2791
e440a328 2792 Type* ctype;
2793 if (this->type_ != NULL)
2794 ctype = this->type_;
2795 else
2796 ctype = this->constant_->const_value()->type();
e440a328 2797 if (r && ctype != NULL)
2798 {
0c77715b 2799 if (!nc->set_type(ctype, false, this->location()))
e440a328 2800 return false;
e440a328 2801 }
e440a328 2802
e440a328 2803 return r;
2804}
2805
af6b489a 2806bool
2807Const_expression::do_string_constant_value(std::string* val) const
2808{
2809 if (this->seen_)
2810 return false;
2811
2812 Expression* e = this->constant_->const_value()->expr();
2813
2814 this->seen_ = true;
2815 bool ok = e->string_constant_value(val);
2816 this->seen_ = false;
2817
2818 return ok;
2819}
2820
e440a328 2821// Return the type of the const reference.
2822
2823Type*
2824Const_expression::do_type()
2825{
2826 if (this->type_ != NULL)
2827 return this->type_;
13e818f5 2828
2f78f012 2829 Named_constant* nc = this->constant_->const_value();
2830
2831 if (this->seen_ || nc->lowering())
13e818f5 2832 {
2833 this->report_error(_("constant refers to itself"));
2834 this->type_ = Type::make_error_type();
2835 return this->type_;
2836 }
2837
2838 this->seen_ = true;
2839
e440a328 2840 Type* ret = nc->type();
13e818f5 2841
e440a328 2842 if (ret != NULL)
13e818f5 2843 {
2844 this->seen_ = false;
2845 return ret;
2846 }
2847
e440a328 2848 // During parsing, a named constant may have a NULL type, but we
2849 // must not return a NULL type here.
13e818f5 2850 ret = nc->expr()->type();
2851
2852 this->seen_ = false;
2853
2854 return ret;
e440a328 2855}
2856
2857// Set the type of the const reference.
2858
2859void
2860Const_expression::do_determine_type(const Type_context* context)
2861{
2862 Type* ctype = this->constant_->const_value()->type();
2863 Type* cetype = (ctype != NULL
2864 ? ctype
2865 : this->constant_->const_value()->expr()->type());
2866 if (ctype != NULL && !ctype->is_abstract())
2867 ;
2868 else if (context->type != NULL
0c77715b 2869 && context->type->is_numeric_type()
2870 && cetype->is_numeric_type())
e440a328 2871 this->type_ = context->type;
2872 else if (context->type != NULL
2873 && context->type->is_string_type()
2874 && cetype->is_string_type())
2875 this->type_ = context->type;
2876 else if (context->type != NULL
2877 && context->type->is_boolean_type()
2878 && cetype->is_boolean_type())
2879 this->type_ = context->type;
2880 else if (!context->may_be_abstract)
2881 {
2882 if (cetype->is_abstract())
2883 cetype = cetype->make_non_abstract_type();
2884 this->type_ = cetype;
2885 }
2886}
2887
a7f064d5 2888// Check for a loop in which the initializer of a constant refers to
2889// the constant itself.
e440a328 2890
2891void
a7f064d5 2892Const_expression::check_for_init_loop()
e440a328 2893{
5c13bd80 2894 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2895 return;
2896
a7f064d5 2897 if (this->seen_)
2898 {
2899 this->report_error(_("constant refers to itself"));
2900 this->type_ = Type::make_error_type();
2901 return;
2902 }
2903
d5b605df 2904 Expression* init = this->constant_->const_value()->expr();
2905 Find_named_object find_named_object(this->constant_);
a7f064d5 2906
2907 this->seen_ = true;
d5b605df 2908 Expression::traverse(&init, &find_named_object);
a7f064d5 2909 this->seen_ = false;
2910
d5b605df 2911 if (find_named_object.found())
2912 {
5c13bd80 2913 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2914 {
2915 this->report_error(_("constant refers to itself"));
2916 this->type_ = Type::make_error_type();
2917 }
d5b605df 2918 return;
2919 }
a7f064d5 2920}
2921
2922// Check types of a const reference.
2923
2924void
2925Const_expression::do_check_types(Gogo*)
2926{
5c13bd80 2927 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2928 return;
2929
2930 this->check_for_init_loop();
d5b605df 2931
0c77715b 2932 // Check that numeric constant fits in type.
2933 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2934 {
0c77715b 2935 Numeric_constant nc;
2936 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2937 {
0c77715b 2938 if (!nc.set_type(this->type_, true, this->location()))
2939 this->set_is_error();
e440a328 2940 }
e440a328 2941 }
2942}
2943
ea664253 2944// Return the backend representation for a const reference.
e440a328 2945
ea664253 2946Bexpression*
2947Const_expression::do_get_backend(Translate_context* context)
e440a328 2948{
12373dd5 2949 if (this->is_error_expression()
2950 || (this->type_ != NULL && this->type_->is_error()))
2951 {
2952 go_assert(saw_errors());
2953 return context->backend()->error_expression();
2954 }
e440a328 2955
2956 // If the type has been set for this expression, but the underlying
2957 // object is an abstract int or float, we try to get the abstract
2958 // value. Otherwise we may lose something in the conversion.
f2de4532 2959 Expression* expr = this->constant_->const_value()->expr();
e440a328 2960 if (this->type_ != NULL
0c77715b 2961 && this->type_->is_numeric_type()
a68492b4 2962 && (this->constant_->const_value()->type() == NULL
2963 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2964 {
0c77715b 2965 Numeric_constant nc;
2966 if (expr->numeric_constant_value(&nc)
2967 && nc.set_type(this->type_, false, this->location()))
e440a328 2968 {
0c77715b 2969 Expression* e = nc.expression(this->location());
ea664253 2970 return e->get_backend(context);
e440a328 2971 }
e440a328 2972 }
2973
2c809f8f 2974 if (this->type_ != NULL)
f2de4532 2975 expr = Expression::make_cast(this->type_, expr, this->location());
ea664253 2976 return expr->get_backend(context);
e440a328 2977}
2978
d751bb78 2979// Dump ast representation for constant expression.
2980
2981void
2982Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2983{
2984 ast_dump_context->ostream() << this->constant_->name();
2985}
2986
e440a328 2987// Make a reference to a constant in an expression.
2988
2989Expression*
2990Expression::make_const_reference(Named_object* constant,
b13c66cd 2991 Location location)
e440a328 2992{
2993 return new Const_expression(constant, location);
2994}
2995
d5b605df 2996// Find a named object in an expression.
2997
2998int
2999Find_named_object::expression(Expression** pexpr)
3000{
3001 switch ((*pexpr)->classification())
3002 {
3003 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 3004 {
3005 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3006 if (ce->named_object() == this->no_)
3007 break;
3008
3009 // We need to check a constant initializer explicitly, as
3010 // loops here will not be caught by the loop checking for
3011 // variable initializers.
3012 ce->check_for_init_loop();
3013
3014 return TRAVERSE_CONTINUE;
3015 }
3016
d5b605df 3017 case Expression::EXPRESSION_VAR_REFERENCE:
3018 if ((*pexpr)->var_expression()->named_object() == this->no_)
3019 break;
3020 return TRAVERSE_CONTINUE;
3021 case Expression::EXPRESSION_FUNC_REFERENCE:
3022 if ((*pexpr)->func_expression()->named_object() == this->no_)
3023 break;
3024 return TRAVERSE_CONTINUE;
3025 default:
3026 return TRAVERSE_CONTINUE;
3027 }
3028 this->found_ = true;
3029 return TRAVERSE_EXIT;
3030}
3031
e440a328 3032// The nil value.
3033
3034class Nil_expression : public Expression
3035{
3036 public:
b13c66cd 3037 Nil_expression(Location location)
e440a328 3038 : Expression(EXPRESSION_NIL, location)
3039 { }
3040
3041 static Expression*
3042 do_import(Import*);
3043
3044 protected:
3045 bool
3046 do_is_constant() const
3047 { return true; }
3048
f9ca30f9 3049 bool
3050 do_is_immutable() const
3051 { return true; }
3052
e440a328 3053 Type*
3054 do_type()
3055 { return Type::make_nil_type(); }
3056
3057 void
3058 do_determine_type(const Type_context*)
3059 { }
3060
3061 Expression*
3062 do_copy()
3063 { return this; }
3064
ea664253 3065 Bexpression*
3066 do_get_backend(Translate_context* context)
3067 { return context->backend()->nil_pointer_expression(); }
e440a328 3068
3069 void
3070 do_export(Export* exp) const
3071 { exp->write_c_string("nil"); }
d751bb78 3072
3073 void
3074 do_dump_expression(Ast_dump_context* ast_dump_context) const
3075 { ast_dump_context->ostream() << "nil"; }
e440a328 3076};
3077
3078// Import a nil expression.
3079
3080Expression*
3081Nil_expression::do_import(Import* imp)
3082{
3083 imp->require_c_string("nil");
3084 return Expression::make_nil(imp->location());
3085}
3086
3087// Make a nil expression.
3088
3089Expression*
b13c66cd 3090Expression::make_nil(Location location)
e440a328 3091{
3092 return new Nil_expression(location);
3093}
3094
3095// The value of the predeclared constant iota. This is little more
3096// than a marker. This will be lowered to an integer in
3097// Const_expression::do_lower, which is where we know the value that
3098// it should have.
3099
3100class Iota_expression : public Parser_expression
3101{
3102 public:
b13c66cd 3103 Iota_expression(Location location)
e440a328 3104 : Parser_expression(EXPRESSION_IOTA, location)
3105 { }
3106
3107 protected:
3108 Expression*
ceeb4318 3109 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 3110 { go_unreachable(); }
e440a328 3111
3112 // There should only ever be one of these.
3113 Expression*
3114 do_copy()
c3e6f413 3115 { go_unreachable(); }
d751bb78 3116
3117 void
3118 do_dump_expression(Ast_dump_context* ast_dump_context) const
3119 { ast_dump_context->ostream() << "iota"; }
e440a328 3120};
3121
3122// Make an iota expression. This is only called for one case: the
3123// value of the predeclared constant iota.
3124
3125Expression*
3126Expression::make_iota()
3127{
b13c66cd 3128 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 3129 return &iota_expression;
3130}
3131
da244e59 3132// Class Type_conversion_expression.
e440a328 3133
3134// Traversal.
3135
3136int
3137Type_conversion_expression::do_traverse(Traverse* traverse)
3138{
3139 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3140 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3141 return TRAVERSE_EXIT;
3142 return TRAVERSE_CONTINUE;
3143}
3144
3145// Convert to a constant at lowering time.
3146
3147Expression*
ceeb4318 3148Type_conversion_expression::do_lower(Gogo*, Named_object*,
3149 Statement_inserter*, int)
e440a328 3150{
3151 Type* type = this->type_;
3152 Expression* val = this->expr_;
b13c66cd 3153 Location location = this->location();
e440a328 3154
0c77715b 3155 if (type->is_numeric_type())
e440a328 3156 {
0c77715b 3157 Numeric_constant nc;
3158 if (val->numeric_constant_value(&nc))
e440a328 3159 {
0c77715b 3160 if (!nc.set_type(type, true, location))
3161 return Expression::make_error(location);
3162 return nc.expression(location);
e440a328 3163 }
e440a328 3164 }
3165
d7739c9a 3166 // According to the language specification on string conversions
3167 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3168 // When converting an integer into a string, the string will be a UTF-8
3169 // representation of the integer and integers "outside the range of valid
3170 // Unicode code points are converted to '\uFFFD'."
3171 if (type->is_string_type())
3172 {
3173 Numeric_constant nc;
3174 if (val->numeric_constant_value(&nc) && nc.is_int())
3175 {
3176 // An integer value doesn't fit in the Unicode code point range if it
3177 // overflows the Go "int" type or is negative.
3178 unsigned long ul;
3179 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3180 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3181 return Expression::make_string("\ufffd", location);
3182 }
3183 }
3184
55072f2b 3185 if (type->is_slice_type())
e440a328 3186 {
3187 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3188 bool is_byte = (element_type->integer_type() != NULL
3189 && element_type->integer_type()->is_byte());
3190 bool is_rune = (element_type->integer_type() != NULL
3191 && element_type->integer_type()->is_rune());
3192 if (is_byte || is_rune)
e440a328 3193 {
3194 std::string s;
3195 if (val->string_constant_value(&s))
3196 {
3197 Expression_list* vals = new Expression_list();
3198 if (is_byte)
3199 {
3200 for (std::string::const_iterator p = s.begin();
3201 p != s.end();
3202 p++)
3203 {
e67508fa 3204 unsigned char c = static_cast<unsigned char>(*p);
3205 vals->push_back(Expression::make_integer_ul(c,
3206 element_type,
3207 location));
e440a328 3208 }
3209 }
3210 else
3211 {
3212 const char *p = s.data();
3213 const char *pend = s.data() + s.length();
3214 while (p < pend)
3215 {
3216 unsigned int c;
3217 int adv = Lex::fetch_char(p, &c);
3218 if (adv == 0)
3219 {
631d5788 3220 go_warning_at(this->location(), 0,
e440a328 3221 "invalid UTF-8 encoding");
3222 adv = 1;
3223 }
3224 p += adv;
e67508fa 3225 vals->push_back(Expression::make_integer_ul(c,
3226 element_type,
3227 location));
e440a328 3228 }
3229 }
3230
3231 return Expression::make_slice_composite_literal(type, vals,
3232 location);
3233 }
3234 }
3235 }
3236
3237 return this;
3238}
3239
35a54f17 3240// Flatten a type conversion by using a temporary variable for the slice
3241// in slice to string conversions.
3242
3243Expression*
3244Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3245 Statement_inserter* inserter)
3246{
5bf8be8b 3247 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3248 {
3249 go_assert(saw_errors());
3250 return Expression::make_error(this->location());
3251 }
3252
2c809f8f 3253 if (((this->type()->is_string_type()
3254 && this->expr_->type()->is_slice_type())
8ba8cc87 3255 || this->expr_->type()->interface_type() != NULL)
35a54f17 3256 && !this->expr_->is_variable())
3257 {
3258 Temporary_statement* temp =
3259 Statement::make_temporary(NULL, this->expr_, this->location());
3260 inserter->insert(temp);
3261 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3262 }
3263 return this;
3264}
3265
1ca01a59 3266// Return whether a type conversion is a constant.
3267
3268bool
3269Type_conversion_expression::do_is_constant() const
3270{
3271 if (!this->expr_->is_constant())
3272 return false;
3273
3274 // A conversion to a type that may not be used as a constant is not
3275 // a constant. For example, []byte(nil).
3276 Type* type = this->type_;
3277 if (type->integer_type() == NULL
3278 && type->float_type() == NULL
3279 && type->complex_type() == NULL
3280 && !type->is_boolean_type()
3281 && !type->is_string_type())
3282 return false;
3283
3284 return true;
3285}
3286
0e168074 3287// Return whether a type conversion is immutable.
3288
3289bool
3290Type_conversion_expression::do_is_immutable() const
3291{
3292 Type* type = this->type_;
3293 Type* expr_type = this->expr_->type();
3294
3295 if (type->interface_type() != NULL
3296 || expr_type->interface_type() != NULL)
3297 return false;
3298
3299 if (!this->expr_->is_immutable())
3300 return false;
3301
3302 if (Type::are_identical(type, expr_type, false, NULL))
3303 return true;
3304
3305 return type->is_basic_type() && expr_type->is_basic_type();
3306}
3307
0c77715b 3308// Return the constant numeric value if there is one.
e440a328 3309
3310bool
0c77715b 3311Type_conversion_expression::do_numeric_constant_value(
3312 Numeric_constant* nc) const
e440a328 3313{
0c77715b 3314 if (!this->type_->is_numeric_type())
e440a328 3315 return false;
0c77715b 3316 if (!this->expr_->numeric_constant_value(nc))
e440a328 3317 return false;
0c77715b 3318 return nc->set_type(this->type_, false, this->location());
e440a328 3319}
3320
3321// Return the constant string value if there is one.
3322
3323bool
3324Type_conversion_expression::do_string_constant_value(std::string* val) const
3325{
3326 if (this->type_->is_string_type()
3327 && this->expr_->type()->integer_type() != NULL)
3328 {
0c77715b 3329 Numeric_constant nc;
3330 if (this->expr_->numeric_constant_value(&nc))
e440a328 3331 {
0c77715b 3332 unsigned long ival;
3333 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3334 {
0c77715b 3335 val->clear();
3336 Lex::append_char(ival, true, val, this->location());
e440a328 3337 return true;
3338 }
3339 }
e440a328 3340 }
3341
3342 // FIXME: Could handle conversion from const []int here.
3343
3344 return false;
3345}
3346
da244e59 3347// Determine the resulting type of the conversion.
3348
3349void
3350Type_conversion_expression::do_determine_type(const Type_context*)
3351{
3352 Type_context subcontext(this->type_, false);
3353 this->expr_->determine_type(&subcontext);
3354}
3355
e440a328 3356// Check that types are convertible.
3357
3358void
3359Type_conversion_expression::do_check_types(Gogo*)
3360{
3361 Type* type = this->type_;
3362 Type* expr_type = this->expr_->type();
3363 std::string reason;
3364
5c13bd80 3365 if (type->is_error() || expr_type->is_error())
842f6425 3366 {
842f6425 3367 this->set_is_error();
3368 return;
3369 }
3370
e440a328 3371 if (this->may_convert_function_types_
3372 && type->function_type() != NULL
3373 && expr_type->function_type() != NULL)
3374 return;
3375
3376 if (Type::are_convertible(type, expr_type, &reason))
3377 return;
3378
631d5788 3379 go_error_at(this->location(), "%s", reason.c_str());
e440a328 3380 this->set_is_error();
3381}
3382
ea664253 3383// Get the backend representation for a type conversion.
e440a328 3384
ea664253 3385Bexpression*
3386Type_conversion_expression::do_get_backend(Translate_context* context)
e440a328 3387{
e440a328 3388 Type* type = this->type_;
3389 Type* expr_type = this->expr_->type();
2c809f8f 3390
3391 Gogo* gogo = context->gogo();
3392 Btype* btype = type->get_backend(gogo);
ea664253 3393 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3394 Location loc = this->location();
3395
3396 if (Type::are_identical(type, expr_type, false, NULL))
ea664253 3397 return gogo->backend()->convert_expression(btype, bexpr, loc);
2c809f8f 3398 else if (type->interface_type() != NULL
3399 || expr_type->interface_type() != NULL)
e440a328 3400 {
2c809f8f 3401 Expression* conversion =
3402 Expression::convert_for_assignment(gogo, type, this->expr_,
3403 this->location());
ea664253 3404 return conversion->get_backend(context);
e440a328 3405 }
3406 else if (type->is_string_type()
3407 && expr_type->integer_type() != NULL)
3408 {
2c809f8f 3409 mpz_t intval;
3410 Numeric_constant nc;
3411 if (this->expr_->numeric_constant_value(&nc)
3412 && nc.to_int(&intval)
3413 && mpz_fits_ushort_p(intval))
e440a328 3414 {
e440a328 3415 std::string s;
2c809f8f 3416 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3417 mpz_clear(intval);
3418 Expression* se = Expression::make_string(s, loc);
ea664253 3419 return se->get_backend(context);
e440a328 3420 }
3421
f16ab008 3422 Expression* i2s_expr =
736a16ba 3423 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3424 Expression::make_nil(loc), this->expr_);
ea664253 3425 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
e440a328 3426 }
55072f2b 3427 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3428 {
55072f2b 3429 Array_type* a = expr_type->array_type();
e440a328 3430 Type* e = a->element_type()->forwarded();
c484d925 3431 go_assert(e->integer_type() != NULL);
35a54f17 3432 go_assert(this->expr_->is_variable());
3433
3434 Runtime::Function code;
60963afd 3435 if (e->integer_type()->is_byte())
736a16ba 3436 code = Runtime::SLICEBYTETOSTRING;
e440a328 3437 else
35a54f17 3438 {
3439 go_assert(e->integer_type()->is_rune());
736a16ba 3440 code = Runtime::SLICERUNETOSTRING;
35a54f17 3441 }
736a16ba 3442 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3443 this->expr_)->get_backend(context);
e440a328 3444 }
411eb89e 3445 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3446 {
3447 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3448 go_assert(e->integer_type() != NULL);
6c252e42 3449
2c809f8f 3450 Runtime::Function code;
60963afd 3451 if (e->integer_type()->is_byte())
736a16ba 3452 code = Runtime::STRINGTOSLICEBYTE;
e440a328 3453 else
3454 {
60963afd 3455 go_assert(e->integer_type()->is_rune());
736a16ba 3456 code = Runtime::STRINGTOSLICERUNE;
e440a328 3457 }
736a16ba 3458 Expression* s2a = Runtime::make_call(code, loc, 2,
3459 Expression::make_nil(loc),
3460 this->expr_);
ea664253 3461 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
2c809f8f 3462 }
3463 else if (type->is_numeric_type())
3464 {
3465 go_assert(Type::are_convertible(type, expr_type, NULL));
ea664253 3466 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3467 }
3468 else if ((type->is_unsafe_pointer_type()
2c809f8f 3469 && (expr_type->points_to() != NULL
3470 || expr_type->integer_type()))
3471 || (expr_type->is_unsafe_pointer_type()
3472 && type->points_to() != NULL)
3473 || (this->may_convert_function_types_
3474 && type->function_type() != NULL
3475 && expr_type->function_type() != NULL))
ea664253 3476 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3477 else
2c809f8f 3478 {
3479 Expression* conversion =
3480 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
ea664253 3481 return conversion->get_backend(context);
2c809f8f 3482 }
e440a328 3483}
3484
3485// Output a type conversion in a constant expression.
3486
3487void
3488Type_conversion_expression::do_export(Export* exp) const
3489{
3490 exp->write_c_string("convert(");
3491 exp->write_type(this->type_);
3492 exp->write_c_string(", ");
3493 this->expr_->export_expression(exp);
3494 exp->write_c_string(")");
3495}
3496
3497// Import a type conversion or a struct construction.
3498
3499Expression*
3500Type_conversion_expression::do_import(Import* imp)
3501{
3502 imp->require_c_string("convert(");
3503 Type* type = imp->read_type();
3504 imp->require_c_string(", ");
3505 Expression* val = Expression::import_expression(imp);
3506 imp->require_c_string(")");
3507 return Expression::make_cast(type, val, imp->location());
3508}
3509
d751bb78 3510// Dump ast representation for a type conversion expression.
3511
3512void
3513Type_conversion_expression::do_dump_expression(
3514 Ast_dump_context* ast_dump_context) const
3515{
3516 ast_dump_context->dump_type(this->type_);
3517 ast_dump_context->ostream() << "(";
3518 ast_dump_context->dump_expression(this->expr_);
3519 ast_dump_context->ostream() << ") ";
3520}
3521
e440a328 3522// Make a type cast expression.
3523
3524Expression*
b13c66cd 3525Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3526{
3527 if (type->is_error_type() || val->is_error_expression())
3528 return Expression::make_error(location);
3529 return new Type_conversion_expression(type, val, location);
3530}
3531
98f62f7a 3532// Class Unsafe_type_conversion_expression.
9581e91d 3533
3534// Traversal.
3535
3536int
3537Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3538{
3539 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3540 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3541 return TRAVERSE_EXIT;
3542 return TRAVERSE_CONTINUE;
3543}
3544
aa5ae575 3545// Return whether an unsafe type conversion is immutable.
3546
3547bool
3548Unsafe_type_conversion_expression::do_is_immutable() const
3549{
3550 Type* type = this->type_;
3551 Type* expr_type = this->expr_->type();
3552
3553 if (type->interface_type() != NULL
3554 || expr_type->interface_type() != NULL)
3555 return false;
3556
3557 if (!this->expr_->is_immutable())
3558 return false;
3559
3560 if (Type::are_convertible(type, expr_type, NULL))
3561 return true;
3562
3563 return type->is_basic_type() && expr_type->is_basic_type();
3564}
3565
9581e91d 3566// Convert to backend representation.
3567
ea664253 3568Bexpression*
3569Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
9581e91d 3570{
3571 // We are only called for a limited number of cases.
3572
3573 Type* t = this->type_;
3574 Type* et = this->expr_->type();
5c4802f1 3575
3576 if (t->is_error_type()
3577 || this->expr_->is_error_expression()
3578 || et->is_error_type())
3579 {
3580 go_assert(saw_errors());
3581 return context->backend()->error_expression();
3582 }
3583
2c809f8f 3584 if (t->array_type() != NULL)
3585 go_assert(et->array_type() != NULL
3586 && t->is_slice_type() == et->is_slice_type());
3587 else if (t->struct_type() != NULL)
9581e91d 3588 {
2c809f8f 3589 if (t->named_type() != NULL
3590 && et->named_type() != NULL
3591 && !Type::are_convertible(t, et, NULL))
3592 {
3593 go_assert(saw_errors());
ea664253 3594 return context->backend()->error_expression();
2c809f8f 3595 }
3596
3597 go_assert(et->struct_type() != NULL
3598 && Type::are_convertible(t, et, NULL));
3599 }
3600 else if (t->map_type() != NULL)
c484d925 3601 go_assert(et->map_type() != NULL);
9581e91d 3602 else if (t->channel_type() != NULL)
c484d925 3603 go_assert(et->channel_type() != NULL);
09ea332d 3604 else if (t->points_to() != NULL)
2c809f8f 3605 go_assert(et->points_to() != NULL
3606 || et->channel_type() != NULL
3607 || et->map_type() != NULL
3608 || et->function_type() != NULL
132ed071 3609 || et->integer_type() != NULL
2c809f8f 3610 || et->is_nil_type());
9581e91d 3611 else if (et->is_unsafe_pointer_type())
c484d925 3612 go_assert(t->points_to() != NULL);
2c809f8f 3613 else if (t->interface_type() != NULL)
9581e91d 3614 {
2c809f8f 3615 bool empty_iface = t->interface_type()->is_empty();
c484d925 3616 go_assert(et->interface_type() != NULL
2c809f8f 3617 && et->interface_type()->is_empty() == empty_iface);
9581e91d 3618 }
588e3cf9 3619 else if (t->integer_type() != NULL)
2c809f8f 3620 go_assert(et->is_boolean_type()
3621 || et->integer_type() != NULL
3622 || et->function_type() != NULL
3623 || et->points_to() != NULL
3624 || et->map_type() != NULL
8ba8cc87 3625 || et->channel_type() != NULL
3626 || et->is_nil_type());
cd39797e 3627 else if (t->function_type() != NULL)
3628 go_assert(et->points_to() != NULL);
9581e91d 3629 else
c3e6f413 3630 go_unreachable();
9581e91d 3631
2c809f8f 3632 Gogo* gogo = context->gogo();
3633 Btype* btype = t->get_backend(gogo);
ea664253 3634 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3635 Location loc = this->location();
ea664253 3636 return gogo->backend()->convert_expression(btype, bexpr, loc);
9581e91d 3637}
3638
d751bb78 3639// Dump ast representation for an unsafe type conversion expression.
3640
3641void
3642Unsafe_type_conversion_expression::do_dump_expression(
3643 Ast_dump_context* ast_dump_context) const
3644{
3645 ast_dump_context->dump_type(this->type_);
3646 ast_dump_context->ostream() << "(";
3647 ast_dump_context->dump_expression(this->expr_);
3648 ast_dump_context->ostream() << ") ";
3649}
3650
9581e91d 3651// Make an unsafe type conversion expression.
3652
3653Expression*
3654Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3655 Location location)
9581e91d 3656{
3657 return new Unsafe_type_conversion_expression(type, expr, location);
3658}
3659
76f85fd6 3660// Class Unary_expression.
e440a328 3661
3662// If we are taking the address of a composite literal, and the
2c809f8f 3663// contents are not constant, then we want to make a heap expression
e440a328 3664// instead.
3665
3666Expression*
ceeb4318 3667Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3668{
b13c66cd 3669 Location loc = this->location();
e440a328 3670 Operator op = this->op_;
3671 Expression* expr = this->expr_;
3672
3673 if (op == OPERATOR_MULT && expr->is_type_expression())
3674 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3675
3676 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3677 // moving x to the heap. FIXME: Is it worth doing a real escape
3678 // analysis here? This case is found in math/unsafe.go and is
3679 // therefore worth special casing.
3680 if (op == OPERATOR_MULT)
3681 {
3682 Expression* e = expr;
3683 while (e->classification() == EXPRESSION_CONVERSION)
3684 {
3685 Type_conversion_expression* te
3686 = static_cast<Type_conversion_expression*>(e);
3687 e = te->expr();
3688 }
3689
3690 if (e->classification() == EXPRESSION_UNARY)
3691 {
3692 Unary_expression* ue = static_cast<Unary_expression*>(e);
3693 if (ue->op_ == OPERATOR_AND)
3694 {
3695 if (e == expr)
3696 {
3697 // *&x == x.
f4dea966 3698 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3699 {
631d5788 3700 go_error_at(ue->location(),
3701 "invalid operand for unary %<&%>");
f4dea966 3702 this->set_is_error();
3703 }
e440a328 3704 return ue->expr_;
3705 }
3706 ue->set_does_not_escape();
3707 }
3708 }
3709 }
3710
55661ce9 3711 // Catching an invalid indirection of unsafe.Pointer here avoid
3712 // having to deal with TYPE_VOID in other places.
3713 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3714 {
631d5788 3715 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
55661ce9 3716 return Expression::make_error(this->location());
3717 }
3718
d9f3743a 3719 // Check for an invalid pointer dereference. We need to do this
3720 // here because Unary_expression::do_type will return an error type
3721 // in this case. That can cause code to appear erroneous, and
3722 // therefore disappear at lowering time, without any error message.
3723 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3724 {
3725 this->report_error(_("expected pointer"));
3726 return Expression::make_error(this->location());
3727 }
3728
59a401fe 3729 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3730 {
0c77715b 3731 Numeric_constant nc;
3732 if (expr->numeric_constant_value(&nc))
e440a328 3733 {
0c77715b 3734 Numeric_constant result;
3735 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3736 return result.expression(loc);
e440a328 3737 }
3738 }
3739
3740 return this;
3741}
3742
f9ca30f9 3743// Flatten expression if a nil check must be performed and create temporary
3744// variables if necessary.
3745
3746Expression*
3747Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3748 Statement_inserter* inserter)
3749{
5bf8be8b 3750 if (this->is_error_expression()
3751 || this->expr_->is_error_expression()
3752 || this->expr_->type()->is_error_type())
3753 {
3754 go_assert(saw_errors());
3755 return Expression::make_error(this->location());
3756 }
f4dea966 3757
f9ca30f9 3758 Location location = this->location();
3759 if (this->op_ == OPERATOR_MULT
3760 && !this->expr_->is_variable())
3761 {
3762 go_assert(this->expr_->type()->points_to() != NULL);
3763 Type* ptype = this->expr_->type()->points_to();
3764 if (!ptype->is_void_type())
3765 {
2a305b85 3766 int64_t s;
3767 bool ok = ptype->backend_type_size(gogo, &s);
3768 if (!ok)
3769 {
3770 go_assert(saw_errors());
3771 return Expression::make_error(this->location());
3772 }
f9ca30f9 3773 if (s >= 4096 || this->issue_nil_check_)
3774 {
3775 Temporary_statement* temp =
3776 Statement::make_temporary(NULL, this->expr_, location);
3777 inserter->insert(temp);
3778 this->expr_ =
3779 Expression::make_temporary_reference(temp, location);
3780 }
3781 }
3782 }
3783
da244e59 3784 if (this->op_ == OPERATOR_AND)
3785 {
8ff995b5 3786 // If this->escapes_ is false at this point, then it was set to
3787 // false by an explicit call to set_does_not_escape, and the
3788 // value does not escape. If this->escapes_ is true, we may be
3789 // able to set it to false if taking the address of a variable
3790 // that does not escape.
45ff893b 3791 Node* n = Node::make_node(this);
3792 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3793 this->escapes_ = false;
3794
0dad6de4 3795 // When compiling the runtime, the address operator does not
3796 // cause local variables to escapes. When escape analysis
3797 // becomes the default, this should be changed to make it an
3798 // error if we have an address operator that escapes.
3799 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3800 this->escapes_ = false;
3801
45ff893b 3802 Named_object* var = NULL;
3803 if (this->expr_->var_expression() != NULL)
3804 var = this->expr_->var_expression()->named_object();
3805 else if (this->expr_->enclosed_var_expression() != NULL)
3806 var = this->expr_->enclosed_var_expression()->variable();
3807
3808 if (this->escapes_ && var != NULL)
da244e59 3809 {
da244e59 3810 if (var->is_variable())
3811 this->escapes_ = var->var_value()->escapes();
3812 if (var->is_result_variable())
3813 this->escapes_ = var->result_var_value()->escapes();
3814 }
3815 this->expr_->address_taken(this->escapes_);
3816 }
3817
f9ca30f9 3818 if (this->create_temp_ && !this->expr_->is_variable())
3819 {
3820 Temporary_statement* temp =
3821 Statement::make_temporary(NULL, this->expr_, location);
3822 inserter->insert(temp);
3823 this->expr_ = Expression::make_temporary_reference(temp, location);
3824 }
3825
3826 return this;
3827}
3828
e440a328 3829// Return whether a unary expression is a constant.
3830
3831bool
3832Unary_expression::do_is_constant() const
3833{
3834 if (this->op_ == OPERATOR_MULT)
3835 {
3836 // Indirecting through a pointer is only constant if the object
3837 // to which the expression points is constant, but we currently
3838 // have no way to determine that.
3839 return false;
3840 }
3841 else if (this->op_ == OPERATOR_AND)
3842 {
3843 // Taking the address of a variable is constant if it is a
f9ca30f9 3844 // global variable, not constant otherwise. In other cases taking the
3845 // address is probably not a constant.
e440a328 3846 Var_expression* ve = this->expr_->var_expression();
3847 if (ve != NULL)
3848 {
3849 Named_object* no = ve->named_object();
3850 return no->is_variable() && no->var_value()->is_global();
3851 }
3852 return false;
3853 }
3854 else
3855 return this->expr_->is_constant();
3856}
3857
0c77715b 3858// Apply unary opcode OP to UNC, setting NC. Return true if this
3859// could be done, false if not. Issue errors for overflow.
e440a328 3860
3861bool
0c77715b 3862Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3863 Location location, Numeric_constant* nc)
e440a328 3864{
3865 switch (op)
3866 {
3867 case OPERATOR_PLUS:
0c77715b 3868 *nc = *unc;
e440a328 3869 return true;
0c77715b 3870
e440a328 3871 case OPERATOR_MINUS:
0c77715b 3872 if (unc->is_int() || unc->is_rune())
3873 break;
3874 else if (unc->is_float())
3875 {
3876 mpfr_t uval;
3877 unc->get_float(&uval);
3878 mpfr_t val;
3879 mpfr_init(val);
3880 mpfr_neg(val, uval, GMP_RNDN);
3881 nc->set_float(unc->type(), val);
3882 mpfr_clear(uval);
3883 mpfr_clear(val);
3884 return true;
3885 }
3886 else if (unc->is_complex())
3887 {
fcbea5e4 3888 mpc_t uval;
3889 unc->get_complex(&uval);
3890 mpc_t val;
3891 mpc_init2(val, mpc_precision);
3892 mpc_neg(val, uval, MPC_RNDNN);
3893 nc->set_complex(unc->type(), val);
3894 mpc_clear(uval);
3895 mpc_clear(val);
0c77715b 3896 return true;
3897 }
e440a328 3898 else
0c77715b 3899 go_unreachable();
e440a328 3900
0c77715b 3901 case OPERATOR_XOR:
3902 break;
68448d53 3903
59a401fe 3904 case OPERATOR_NOT:
e440a328 3905 case OPERATOR_AND:
3906 case OPERATOR_MULT:
3907 return false;
0c77715b 3908
e440a328 3909 default:
c3e6f413 3910 go_unreachable();
e440a328 3911 }
e440a328 3912
0c77715b 3913 if (!unc->is_int() && !unc->is_rune())
3914 return false;
3915
3916 mpz_t uval;
8387e1df 3917 if (unc->is_rune())
3918 unc->get_rune(&uval);
3919 else
3920 unc->get_int(&uval);
0c77715b 3921 mpz_t val;
3922 mpz_init(val);
e440a328 3923
e440a328 3924 switch (op)
3925 {
e440a328 3926 case OPERATOR_MINUS:
0c77715b 3927 mpz_neg(val, uval);
3928 break;
3929
e440a328 3930 case OPERATOR_NOT:
0c77715b 3931 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3932 break;
3933
e440a328 3934 case OPERATOR_XOR:
0c77715b 3935 {
3936 Type* utype = unc->type();
3937 if (utype->integer_type() == NULL
3938 || utype->integer_type()->is_abstract())
3939 mpz_com(val, uval);
3940 else
3941 {
3942 // The number of HOST_WIDE_INTs that it takes to represent
3943 // UVAL.
3944 size_t count = ((mpz_sizeinbase(uval, 2)
3945 + HOST_BITS_PER_WIDE_INT
3946 - 1)
3947 / HOST_BITS_PER_WIDE_INT);
e440a328 3948
0c77715b 3949 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3950 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3951
3952 size_t obits = utype->integer_type()->bits();
3953
3954 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3955 {
3956 mpz_t adj;
3957 mpz_init_set_ui(adj, 1);
3958 mpz_mul_2exp(adj, adj, obits);
3959 mpz_add(uval, uval, adj);
3960 mpz_clear(adj);
3961 }
3962
3963 size_t ecount;
3964 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3965 go_assert(ecount <= count);
3966
3967 // Trim down to the number of words required by the type.
3968 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3969 / HOST_BITS_PER_WIDE_INT);
3970 go_assert(ocount <= count);
3971
3972 for (size_t i = 0; i < ocount; ++i)
3973 phwi[i] = ~phwi[i];
3974
3975 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3976 if (clearbits != 0)
3977 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3978 >> clearbits);
3979
3980 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3981
3982 if (!utype->integer_type()->is_unsigned()
3983 && mpz_tstbit(val, obits - 1))
3984 {
3985 mpz_t adj;
3986 mpz_init_set_ui(adj, 1);
3987 mpz_mul_2exp(adj, adj, obits);
3988 mpz_sub(val, val, adj);
3989 mpz_clear(adj);
3990 }
3991
3992 delete[] phwi;
3993 }
3994 }
3995 break;
e440a328 3996
e440a328 3997 default:
c3e6f413 3998 go_unreachable();
e440a328 3999 }
e440a328 4000
0c77715b 4001 if (unc->is_rune())
4002 nc->set_rune(NULL, val);
e440a328 4003 else
0c77715b 4004 nc->set_int(NULL, val);
e440a328 4005
0c77715b 4006 mpz_clear(uval);
4007 mpz_clear(val);
e440a328 4008
0c77715b 4009 return nc->set_type(unc->type(), true, location);
e440a328 4010}
4011
0c77715b 4012// Return the integral constant value of a unary expression, if it has one.
e440a328 4013
4014bool
0c77715b 4015Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 4016{
0c77715b 4017 Numeric_constant unc;
4018 if (!this->expr_->numeric_constant_value(&unc))
4019 return false;
4020 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4021 nc);
e440a328 4022}
4023
4024// Return the type of a unary expression.
4025
4026Type*
4027Unary_expression::do_type()
4028{
4029 switch (this->op_)
4030 {
4031 case OPERATOR_PLUS:
4032 case OPERATOR_MINUS:
4033 case OPERATOR_NOT:
4034 case OPERATOR_XOR:
4035 return this->expr_->type();
4036
4037 case OPERATOR_AND:
4038 return Type::make_pointer_type(this->expr_->type());
4039
4040 case OPERATOR_MULT:
4041 {
4042 Type* subtype = this->expr_->type();
4043 Type* points_to = subtype->points_to();
4044 if (points_to == NULL)
4045 return Type::make_error_type();
4046 return points_to;
4047 }
4048
4049 default:
c3e6f413 4050 go_unreachable();
e440a328 4051 }
4052}
4053
4054// Determine abstract types for a unary expression.
4055
4056void
4057Unary_expression::do_determine_type(const Type_context* context)
4058{
4059 switch (this->op_)
4060 {
4061 case OPERATOR_PLUS:
4062 case OPERATOR_MINUS:
4063 case OPERATOR_NOT:
4064 case OPERATOR_XOR:
4065 this->expr_->determine_type(context);
4066 break;
4067
4068 case OPERATOR_AND:
4069 // Taking the address of something.
4070 {
4071 Type* subtype = (context->type == NULL
4072 ? NULL
4073 : context->type->points_to());
4074 Type_context subcontext(subtype, false);
4075 this->expr_->determine_type(&subcontext);
4076 }
4077 break;
4078
4079 case OPERATOR_MULT:
4080 // Indirecting through a pointer.
4081 {
4082 Type* subtype = (context->type == NULL
4083 ? NULL
4084 : Type::make_pointer_type(context->type));
4085 Type_context subcontext(subtype, false);
4086 this->expr_->determine_type(&subcontext);
4087 }
4088 break;
4089
4090 default:
c3e6f413 4091 go_unreachable();
e440a328 4092 }
4093}
4094
4095// Check types for a unary expression.
4096
4097void
4098Unary_expression::do_check_types(Gogo*)
4099{
9fe897ef 4100 Type* type = this->expr_->type();
5c13bd80 4101 if (type->is_error())
9fe897ef 4102 {
4103 this->set_is_error();
4104 return;
4105 }
4106
e440a328 4107 switch (this->op_)
4108 {
4109 case OPERATOR_PLUS:
4110 case OPERATOR_MINUS:
9fe897ef 4111 if (type->integer_type() == NULL
4112 && type->float_type() == NULL
4113 && type->complex_type() == NULL)
4114 this->report_error(_("expected numeric type"));
e440a328 4115 break;
4116
4117 case OPERATOR_NOT:
59a401fe 4118 if (!type->is_boolean_type())
4119 this->report_error(_("expected boolean type"));
4120 break;
4121
e440a328 4122 case OPERATOR_XOR:
b3b1474e 4123 if (type->integer_type() == NULL)
4124 this->report_error(_("expected integer"));
e440a328 4125 break;
4126
4127 case OPERATOR_AND:
4128 if (!this->expr_->is_addressable())
09ea332d 4129 {
4130 if (!this->create_temp_)
f4dea966 4131 {
631d5788 4132 go_error_at(this->location(), "invalid operand for unary %<&%>");
f4dea966 4133 this->set_is_error();
4134 }
09ea332d 4135 }
e440a328 4136 else
da244e59 4137 this->expr_->issue_nil_check();
e440a328 4138 break;
4139
4140 case OPERATOR_MULT:
4141 // Indirecting through a pointer.
9fe897ef 4142 if (type->points_to() == NULL)
4143 this->report_error(_("expected pointer"));
7661d702 4144 if (type->points_to()->is_error())
4145 this->set_is_error();
e440a328 4146 break;
4147
4148 default:
c3e6f413 4149 go_unreachable();
e440a328 4150 }
4151}
4152
ea664253 4153// Get the backend representation for a unary expression.
e440a328 4154
ea664253 4155Bexpression*
4156Unary_expression::do_get_backend(Translate_context* context)
e440a328 4157{
1b1f2abf 4158 Gogo* gogo = context->gogo();
e9d3367e 4159 Location loc = this->location();
4160
4161 // Taking the address of a set-and-use-temporary expression requires
4162 // setting the temporary and then taking the address.
4163 if (this->op_ == OPERATOR_AND)
4164 {
4165 Set_and_use_temporary_expression* sut =
4166 this->expr_->set_and_use_temporary_expression();
4167 if (sut != NULL)
4168 {
4169 Temporary_statement* temp = sut->temporary();
4170 Bvariable* bvar = temp->get_backend_variable(context);
f9ca30f9 4171 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
ea664253 4172 Bexpression* bval = sut->expression()->get_backend(context);
f9ca30f9 4173
4174 Bstatement* bassign =
4175 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4176 Bexpression* bvar_addr =
4177 gogo->backend()->address_expression(bvar_expr, loc);
ea664253 4178 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
e9d3367e 4179 }
4180 }
4181
f9ca30f9 4182 Bexpression* ret;
ea664253 4183 Bexpression* bexpr = this->expr_->get_backend(context);
f9ca30f9 4184 Btype* btype = this->expr_->type()->get_backend(gogo);
e440a328 4185 switch (this->op_)
4186 {
4187 case OPERATOR_PLUS:
f9ca30f9 4188 ret = bexpr;
4189 break;
e440a328 4190
4191 case OPERATOR_MINUS:
f9ca30f9 4192 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4193 ret = gogo->backend()->convert_expression(btype, ret, loc);
4194 break;
e440a328 4195
4196 case OPERATOR_NOT:
e440a328 4197 case OPERATOR_XOR:
f9ca30f9 4198 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4199 break;
e440a328 4200
4201 case OPERATOR_AND:
09ea332d 4202 if (!this->create_temp_)
4203 {
4204 // We should not see a non-constant constructor here; cases
4205 // where we would see one should have been moved onto the
4206 // heap at parse time. Taking the address of a nonconstant
4207 // constructor will not do what the programmer expects.
f9ca30f9 4208
4209 go_assert(!this->expr_->is_composite_literal()
4210 || this->expr_->is_immutable());
24060bf9 4211 if (this->expr_->classification() == EXPRESSION_UNARY)
4212 {
4213 Unary_expression* ue =
4214 static_cast<Unary_expression*>(this->expr_);
4215 go_assert(ue->op() != OPERATOR_AND);
4216 }
09ea332d 4217 }
e440a328 4218
f23d7786 4219 static unsigned int counter;
4220 char buf[100];
4221 if (this->is_gc_root_ || this->is_slice_init_)
76f85fd6 4222 {
f23d7786 4223 bool copy_to_heap = false;
4224 if (this->is_gc_root_)
4225 {
4226 // Build a decl for a GC root variable. GC roots are mutable, so
4227 // they cannot be represented as an immutable_struct in the
4228 // backend.
4229 static unsigned int root_counter;
4230 snprintf(buf, sizeof buf, "gc%u", root_counter);
4231 ++root_counter;
4232 }
4233 else
4234 {
4235 // Build a decl for a slice value initializer. An immutable slice
4236 // value initializer may have to be copied to the heap if it
4237 // contains pointers in a non-constant context.
4238 snprintf(buf, sizeof buf, "C%u", counter);
4239 ++counter;
4240
4241 Array_type* at = this->expr_->type()->array_type();
4242 go_assert(at != NULL);
4243
4244 // If we are not copying the value to the heap, we will only
4245 // initialize the value once, so we can use this directly
4246 // rather than copying it. In that case we can't make it
4247 // read-only, because the program is permitted to change it.
4248 copy_to_heap = (at->element_type()->has_pointer()
4249 && !context->is_const());
4250 }
4251 Bvariable* implicit =
aa5ae575 4252 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
5892f89f 4253 false, 0);
aa5ae575 4254 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4255 true, copy_to_heap, false,
4256 bexpr);
f23d7786 4257 bexpr = gogo->backend()->var_expression(implicit, loc);
76f85fd6 4258 }
4259 else if ((this->expr_->is_composite_literal()
f9ca30f9 4260 || this->expr_->string_expression() != NULL)
4261 && this->expr_->is_immutable())
4262 {
76f85fd6 4263 // Build a decl for a constant constructor.
f9ca30f9 4264 snprintf(buf, sizeof buf, "C%u", counter);
4265 ++counter;
4266
4267 Bvariable* decl =
4268 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4269 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4270 btype, loc, bexpr);
4271 bexpr = gogo->backend()->var_expression(decl, loc);
4272 }
09ea332d 4273
f9ca30f9 4274 go_assert(!this->create_temp_ || this->expr_->is_variable());
4275 ret = gogo->backend()->address_expression(bexpr, loc);
4276 break;
e440a328 4277
4278 case OPERATOR_MULT:
4279 {
f9ca30f9 4280 go_assert(this->expr_->type()->points_to() != NULL);
e440a328 4281
4282 // If we are dereferencing the pointer to a large struct, we
4283 // need to check for nil. We don't bother to check for small
4284 // structs because we expect the system to crash on a nil
56080003 4285 // pointer dereference. However, if we know the address of this
4286 // expression is being taken, we must always check for nil.
f9ca30f9 4287
4288 Type* ptype = this->expr_->type()->points_to();
4289 Btype* pbtype = ptype->get_backend(gogo);
4290 if (!ptype->is_void_type())
e440a328 4291 {
2a305b85 4292 int64_t s;
4293 bool ok = ptype->backend_type_size(gogo, &s);
4294 if (!ok)
4295 {
4296 go_assert(saw_errors());
4297 return gogo->backend()->error_expression();
4298 }
f9ca30f9 4299 if (s >= 4096 || this->issue_nil_check_)
19b4f09b 4300 {
f9ca30f9 4301 go_assert(this->expr_->is_variable());
ea664253 4302 Bexpression* nil =
4303 Expression::make_nil(loc)->get_backend(context);
f9ca30f9 4304 Bexpression* compare =
4305 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4306 nil, loc);
f9ca30f9 4307 Bexpression* crash =
ea664253 4308 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4309 loc)->get_backend(context);
f9ca30f9 4310 bexpr = gogo->backend()->conditional_expression(btype, compare,
4311 crash, bexpr,
4312 loc);
4313
19b4f09b 4314 }
e440a328 4315 }
9b27b43c 4316 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
e440a328 4317 }
f9ca30f9 4318 break;
e440a328 4319
4320 default:
c3e6f413 4321 go_unreachable();
e440a328 4322 }
f9ca30f9 4323
ea664253 4324 return ret;
e440a328 4325}
4326
4327// Export a unary expression.
4328
4329void
4330Unary_expression::do_export(Export* exp) const
4331{
4332 switch (this->op_)
4333 {
4334 case OPERATOR_PLUS:
4335 exp->write_c_string("+ ");
4336 break;
4337 case OPERATOR_MINUS:
4338 exp->write_c_string("- ");
4339 break;
4340 case OPERATOR_NOT:
4341 exp->write_c_string("! ");
4342 break;
4343 case OPERATOR_XOR:
4344 exp->write_c_string("^ ");
4345 break;
4346 case OPERATOR_AND:
4347 case OPERATOR_MULT:
4348 default:
c3e6f413 4349 go_unreachable();
e440a328 4350 }
4351 this->expr_->export_expression(exp);
4352}
4353
4354// Import a unary expression.
4355
4356Expression*
4357Unary_expression::do_import(Import* imp)
4358{
4359 Operator op;
4360 switch (imp->get_char())
4361 {
4362 case '+':
4363 op = OPERATOR_PLUS;
4364 break;
4365 case '-':
4366 op = OPERATOR_MINUS;
4367 break;
4368 case '!':
4369 op = OPERATOR_NOT;
4370 break;
4371 case '^':
4372 op = OPERATOR_XOR;
4373 break;
4374 default:
c3e6f413 4375 go_unreachable();
e440a328 4376 }
4377 imp->require_c_string(" ");
4378 Expression* expr = Expression::import_expression(imp);
4379 return Expression::make_unary(op, expr, imp->location());
4380}
4381
d751bb78 4382// Dump ast representation of an unary expression.
4383
4384void
4385Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4386{
4387 ast_dump_context->dump_operator(this->op_);
4388 ast_dump_context->ostream() << "(";
4389 ast_dump_context->dump_expression(this->expr_);
4390 ast_dump_context->ostream() << ") ";
4391}
4392
e440a328 4393// Make a unary expression.
4394
4395Expression*
b13c66cd 4396Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4397{
4398 return new Unary_expression(op, expr, location);
4399}
4400
4401// If this is an indirection through a pointer, return the expression
4402// being pointed through. Otherwise return this.
4403
4404Expression*
4405Expression::deref()
4406{
4407 if (this->classification_ == EXPRESSION_UNARY)
4408 {
4409 Unary_expression* ue = static_cast<Unary_expression*>(this);
4410 if (ue->op() == OPERATOR_MULT)
4411 return ue->operand();
4412 }
4413 return this;
4414}
4415
4416// Class Binary_expression.
4417
4418// Traversal.
4419
4420int
4421Binary_expression::do_traverse(Traverse* traverse)
4422{
4423 int t = Expression::traverse(&this->left_, traverse);
4424 if (t == TRAVERSE_EXIT)
4425 return TRAVERSE_EXIT;
4426 return Expression::traverse(&this->right_, traverse);
4427}
4428
0c77715b 4429// Return the type to use for a binary operation on operands of
4430// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4431// such may be NULL or abstract.
4432
4433bool
4434Binary_expression::operation_type(Operator op, Type* left_type,
4435 Type* right_type, Type** result_type)
4436{
4437 if (left_type != right_type
4438 && !left_type->is_abstract()
4439 && !right_type->is_abstract()
4440 && left_type->base() != right_type->base()
4441 && op != OPERATOR_LSHIFT
4442 && op != OPERATOR_RSHIFT)
4443 {
4444 // May be a type error--let it be diagnosed elsewhere.
4445 return false;
4446 }
4447
4448 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4449 {
4450 if (left_type->integer_type() != NULL)
4451 *result_type = left_type;
4452 else
4453 *result_type = Type::make_abstract_integer_type();
4454 }
4455 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4456 *result_type = left_type;
4457 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4458 *result_type = right_type;
4459 else if (!left_type->is_abstract())
4460 *result_type = left_type;
4461 else if (!right_type->is_abstract())
4462 *result_type = right_type;
4463 else if (left_type->complex_type() != NULL)
4464 *result_type = left_type;
4465 else if (right_type->complex_type() != NULL)
4466 *result_type = right_type;
4467 else if (left_type->float_type() != NULL)
4468 *result_type = left_type;
4469 else if (right_type->float_type() != NULL)
4470 *result_type = right_type;
4471 else if (left_type->integer_type() != NULL
4472 && left_type->integer_type()->is_rune())
4473 *result_type = left_type;
4474 else if (right_type->integer_type() != NULL
4475 && right_type->integer_type()->is_rune())
4476 *result_type = right_type;
4477 else
4478 *result_type = left_type;
4479
4480 return true;
4481}
4482
4483// Convert an integer comparison code and an operator to a boolean
4484// value.
e440a328 4485
4486bool
0c77715b 4487Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4488{
e440a328 4489 switch (op)
4490 {
4491 case OPERATOR_EQEQ:
0c77715b 4492 return cmp == 0;
4493 break;
e440a328 4494 case OPERATOR_NOTEQ:
0c77715b 4495 return cmp != 0;
4496 break;
e440a328 4497 case OPERATOR_LT:
0c77715b 4498 return cmp < 0;
4499 break;
e440a328 4500 case OPERATOR_LE:
0c77715b 4501 return cmp <= 0;
e440a328 4502 case OPERATOR_GT:
0c77715b 4503 return cmp > 0;
e440a328 4504 case OPERATOR_GE:
0c77715b 4505 return cmp >= 0;
e440a328 4506 default:
c3e6f413 4507 go_unreachable();
e440a328 4508 }
4509}
4510
0c77715b 4511// Compare constants according to OP.
e440a328 4512
4513bool
0c77715b 4514Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4515 Numeric_constant* right_nc,
4516 Location location, bool* result)
e440a328 4517{
0c77715b 4518 Type* left_type = left_nc->type();
4519 Type* right_type = right_nc->type();
4520
4521 Type* type;
4522 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4523 return false;
4524
4525 // When comparing an untyped operand to a typed operand, we are
4526 // effectively coercing the untyped operand to the other operand's
4527 // type, so make sure that is valid.
4528 if (!left_nc->set_type(type, true, location)
4529 || !right_nc->set_type(type, true, location))
4530 return false;
4531
4532 bool ret;
4533 int cmp;
4534 if (type->complex_type() != NULL)
4535 {
4536 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4537 return false;
4538 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4539 }
4540 else if (type->float_type() != NULL)
4541 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4542 else
0c77715b 4543 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4544
4545 if (ret)
4546 *result = Binary_expression::cmp_to_bool(op, cmp);
4547
4548 return ret;
4549}
4550
4551// Compare integer constants.
4552
4553bool
4554Binary_expression::compare_integer(const Numeric_constant* left_nc,
4555 const Numeric_constant* right_nc,
4556 int* cmp)
4557{
4558 mpz_t left_val;
4559 if (!left_nc->to_int(&left_val))
4560 return false;
4561 mpz_t right_val;
4562 if (!right_nc->to_int(&right_val))
e440a328 4563 {
0c77715b 4564 mpz_clear(left_val);
4565 return false;
e440a328 4566 }
0c77715b 4567
4568 *cmp = mpz_cmp(left_val, right_val);
4569
4570 mpz_clear(left_val);
4571 mpz_clear(right_val);
4572
4573 return true;
4574}
4575
4576// Compare floating point constants.
4577
4578bool
4579Binary_expression::compare_float(const Numeric_constant* left_nc,
4580 const Numeric_constant* right_nc,
4581 int* cmp)
4582{
4583 mpfr_t left_val;
4584 if (!left_nc->to_float(&left_val))
4585 return false;
4586 mpfr_t right_val;
4587 if (!right_nc->to_float(&right_val))
e440a328 4588 {
0c77715b 4589 mpfr_clear(left_val);
4590 return false;
4591 }
4592
4593 // We already coerced both operands to the same type. If that type
4594 // is not an abstract type, we need to round the values accordingly.
4595 Type* type = left_nc->type();
4596 if (!type->is_abstract() && type->float_type() != NULL)
4597 {
4598 int bits = type->float_type()->bits();
4599 mpfr_prec_round(left_val, bits, GMP_RNDN);
4600 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4601 }
0c77715b 4602
4603 *cmp = mpfr_cmp(left_val, right_val);
4604
4605 mpfr_clear(left_val);
4606 mpfr_clear(right_val);
4607
4608 return true;
e440a328 4609}
4610
0c77715b 4611// Compare complex constants. Complex numbers may only be compared
4612// for equality.
e440a328 4613
4614bool
0c77715b 4615Binary_expression::compare_complex(const Numeric_constant* left_nc,
4616 const Numeric_constant* right_nc,
4617 int* cmp)
e440a328 4618{
fcbea5e4 4619 mpc_t left_val;
4620 if (!left_nc->to_complex(&left_val))
0c77715b 4621 return false;
fcbea5e4 4622 mpc_t right_val;
4623 if (!right_nc->to_complex(&right_val))
e440a328 4624 {
fcbea5e4 4625 mpc_clear(left_val);
0c77715b 4626 return false;
e440a328 4627 }
0c77715b 4628
4629 // We already coerced both operands to the same type. If that type
4630 // is not an abstract type, we need to round the values accordingly.
4631 Type* type = left_nc->type();
4632 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4633 {
0c77715b 4634 int bits = type->complex_type()->bits();
fcbea5e4 4635 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4636 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4637 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4638 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
e440a328 4639 }
0c77715b 4640
fcbea5e4 4641 *cmp = mpc_cmp(left_val, right_val) != 0;
0c77715b 4642
fcbea5e4 4643 mpc_clear(left_val);
4644 mpc_clear(right_val);
0c77715b 4645
4646 return true;
e440a328 4647}
4648
0c77715b 4649// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4650// true if this could be done, false if not. Issue errors at LOCATION
4651// as appropriate.
e440a328 4652
4653bool
0c77715b 4654Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4655 Numeric_constant* right_nc,
4656 Location location, Numeric_constant* nc)
e440a328 4657{
e440a328 4658 switch (op)
4659 {
4660 case OPERATOR_OROR:
4661 case OPERATOR_ANDAND:
4662 case OPERATOR_EQEQ:
4663 case OPERATOR_NOTEQ:
4664 case OPERATOR_LT:
4665 case OPERATOR_LE:
4666 case OPERATOR_GT:
4667 case OPERATOR_GE:
9767e2d3 4668 // These return boolean values, not numeric.
4669 return false;
0c77715b 4670 default:
4671 break;
4672 }
4673
4674 Type* left_type = left_nc->type();
4675 Type* right_type = right_nc->type();
4676
4677 Type* type;
4678 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4679 return false;
4680
4681 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4682
4683 // When combining an untyped operand with a typed operand, we are
4684 // effectively coercing the untyped operand to the other operand's
4685 // type, so make sure that is valid.
4686 if (!left_nc->set_type(type, true, location))
4687 return false;
4688 if (!is_shift && !right_nc->set_type(type, true, location))
4689 return false;
85334a21 4690 if (is_shift
4691 && ((left_type->integer_type() == NULL
4692 && !left_type->is_abstract())
4693 || (right_type->integer_type() == NULL
4694 && !right_type->is_abstract())))
4695 return false;
0c77715b 4696
4697 bool r;
4698 if (type->complex_type() != NULL)
4699 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4700 else if (type->float_type() != NULL)
4701 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4702 else
4703 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4704
4705 if (r)
4706 r = nc->set_type(type, true, location);
4707
4708 return r;
4709}
4710
4711// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4712// integer operations. Return true if this could be done, false if
4713// not.
4714
4715bool
4716Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4717 const Numeric_constant* right_nc,
4718 Location location, Numeric_constant* nc)
4719{
4720 mpz_t left_val;
4721 if (!left_nc->to_int(&left_val))
4722 return false;
4723 mpz_t right_val;
4724 if (!right_nc->to_int(&right_val))
4725 {
4726 mpz_clear(left_val);
e440a328 4727 return false;
0c77715b 4728 }
4729
4730 mpz_t val;
4731 mpz_init(val);
4732
4733 switch (op)
4734 {
e440a328 4735 case OPERATOR_PLUS:
4736 mpz_add(val, left_val, right_val);
2c809f8f 4737 if (mpz_sizeinbase(val, 2) > 0x100000)
4738 {
631d5788 4739 go_error_at(location, "constant addition overflow");
71a45216 4740 nc->set_invalid();
2c809f8f 4741 mpz_set_ui(val, 1);
4742 }
e440a328 4743 break;
4744 case OPERATOR_MINUS:
4745 mpz_sub(val, left_val, right_val);
2c809f8f 4746 if (mpz_sizeinbase(val, 2) > 0x100000)
4747 {
631d5788 4748 go_error_at(location, "constant subtraction overflow");
71a45216 4749 nc->set_invalid();
2c809f8f 4750 mpz_set_ui(val, 1);
4751 }
e440a328 4752 break;
4753 case OPERATOR_OR:
4754 mpz_ior(val, left_val, right_val);
4755 break;
4756 case OPERATOR_XOR:
4757 mpz_xor(val, left_val, right_val);
4758 break;
4759 case OPERATOR_MULT:
4760 mpz_mul(val, left_val, right_val);
2c809f8f 4761 if (mpz_sizeinbase(val, 2) > 0x100000)
4762 {
631d5788 4763 go_error_at(location, "constant multiplication overflow");
71a45216 4764 nc->set_invalid();
2c809f8f 4765 mpz_set_ui(val, 1);
4766 }
e440a328 4767 break;
4768 case OPERATOR_DIV:
4769 if (mpz_sgn(right_val) != 0)
4770 mpz_tdiv_q(val, left_val, right_val);
4771 else
4772 {
631d5788 4773 go_error_at(location, "division by zero");
71a45216 4774 nc->set_invalid();
e440a328 4775 mpz_set_ui(val, 0);
e440a328 4776 }
4777 break;
4778 case OPERATOR_MOD:
4779 if (mpz_sgn(right_val) != 0)
4780 mpz_tdiv_r(val, left_val, right_val);
4781 else
4782 {
631d5788 4783 go_error_at(location, "division by zero");
71a45216 4784 nc->set_invalid();
e440a328 4785 mpz_set_ui(val, 0);
e440a328 4786 }
4787 break;
4788 case OPERATOR_LSHIFT:
4789 {
4790 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4791 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4792 mpz_mul_2exp(val, left_val, shift);
4793 else
e440a328 4794 {
631d5788 4795 go_error_at(location, "shift count overflow");
71a45216 4796 nc->set_invalid();
2c809f8f 4797 mpz_set_ui(val, 1);
e440a328 4798 }
e440a328 4799 break;
4800 }
4801 break;
4802 case OPERATOR_RSHIFT:
4803 {
4804 unsigned long shift = mpz_get_ui(right_val);
4805 if (mpz_cmp_ui(right_val, shift) != 0)
4806 {
631d5788 4807 go_error_at(location, "shift count overflow");
71a45216 4808 nc->set_invalid();
2c809f8f 4809 mpz_set_ui(val, 1);
e440a328 4810 }
e440a328 4811 else
0c77715b 4812 {
4813 if (mpz_cmp_ui(left_val, 0) >= 0)
4814 mpz_tdiv_q_2exp(val, left_val, shift);
4815 else
4816 mpz_fdiv_q_2exp(val, left_val, shift);
4817 }
e440a328 4818 break;
4819 }
4820 break;
4821 case OPERATOR_AND:
4822 mpz_and(val, left_val, right_val);
4823 break;
4824 case OPERATOR_BITCLEAR:
4825 {
4826 mpz_t tval;
4827 mpz_init(tval);
4828 mpz_com(tval, right_val);
4829 mpz_and(val, left_val, tval);
4830 mpz_clear(tval);
4831 }
4832 break;
4833 default:
c3e6f413 4834 go_unreachable();
e440a328 4835 }
4836
0c77715b 4837 mpz_clear(left_val);
4838 mpz_clear(right_val);
e440a328 4839
0c77715b 4840 if (left_nc->is_rune()
4841 || (op != OPERATOR_LSHIFT
4842 && op != OPERATOR_RSHIFT
4843 && right_nc->is_rune()))
4844 nc->set_rune(NULL, val);
4845 else
4846 nc->set_int(NULL, val);
4847
4848 mpz_clear(val);
e440a328 4849
4850 return true;
4851}
4852
0c77715b 4853// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4854// floating point operations. Return true if this could be done,
4855// false if not.
e440a328 4856
4857bool
0c77715b 4858Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4859 const Numeric_constant* right_nc,
4860 Location location, Numeric_constant* nc)
e440a328 4861{
0c77715b 4862 mpfr_t left_val;
4863 if (!left_nc->to_float(&left_val))
4864 return false;
4865 mpfr_t right_val;
4866 if (!right_nc->to_float(&right_val))
e440a328 4867 {
0c77715b 4868 mpfr_clear(left_val);
e440a328 4869 return false;
0c77715b 4870 }
4871
4872 mpfr_t val;
4873 mpfr_init(val);
4874
4875 bool ret = true;
4876 switch (op)
4877 {
e440a328 4878 case OPERATOR_PLUS:
4879 mpfr_add(val, left_val, right_val, GMP_RNDN);
4880 break;
4881 case OPERATOR_MINUS:
4882 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4883 break;
4884 case OPERATOR_OR:
4885 case OPERATOR_XOR:
4886 case OPERATOR_AND:
4887 case OPERATOR_BITCLEAR:
0c77715b 4888 case OPERATOR_MOD:
4889 case OPERATOR_LSHIFT:
4890 case OPERATOR_RSHIFT:
4891 mpfr_set_ui(val, 0, GMP_RNDN);
4892 ret = false;
4893 break;
e440a328 4894 case OPERATOR_MULT:
4895 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4896 break;
4897 case OPERATOR_DIV:
0c77715b 4898 if (!mpfr_zero_p(right_val))
4899 mpfr_div(val, left_val, right_val, GMP_RNDN);
4900 else
4901 {
631d5788 4902 go_error_at(location, "division by zero");
71a45216 4903 nc->set_invalid();
0c77715b 4904 mpfr_set_ui(val, 0, GMP_RNDN);
4905 }
e440a328 4906 break;
e440a328 4907 default:
c3e6f413 4908 go_unreachable();
e440a328 4909 }
4910
0c77715b 4911 mpfr_clear(left_val);
4912 mpfr_clear(right_val);
e440a328 4913
0c77715b 4914 nc->set_float(NULL, val);
4915 mpfr_clear(val);
e440a328 4916
0c77715b 4917 return ret;
e440a328 4918}
4919
0c77715b 4920// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4921// complex operations. Return true if this could be done, false if
4922// not.
e440a328 4923
4924bool
0c77715b 4925Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4926 const Numeric_constant* right_nc,
4927 Location location, Numeric_constant* nc)
e440a328 4928{
fcbea5e4 4929 mpc_t left_val;
4930 if (!left_nc->to_complex(&left_val))
0c77715b 4931 return false;
fcbea5e4 4932 mpc_t right_val;
4933 if (!right_nc->to_complex(&right_val))
e440a328 4934 {
fcbea5e4 4935 mpc_clear(left_val);
e440a328 4936 return false;
0c77715b 4937 }
4938
fcbea5e4 4939 mpc_t val;
4940 mpc_init2(val, mpc_precision);
0c77715b 4941
4942 bool ret = true;
4943 switch (op)
4944 {
e440a328 4945 case OPERATOR_PLUS:
fcbea5e4 4946 mpc_add(val, left_val, right_val, MPC_RNDNN);
e440a328 4947 break;
4948 case OPERATOR_MINUS:
fcbea5e4 4949 mpc_sub(val, left_val, right_val, MPC_RNDNN);
e440a328 4950 break;
4951 case OPERATOR_OR:
4952 case OPERATOR_XOR:
4953 case OPERATOR_AND:
4954 case OPERATOR_BITCLEAR:
0c77715b 4955 case OPERATOR_MOD:
4956 case OPERATOR_LSHIFT:
4957 case OPERATOR_RSHIFT:
fcbea5e4 4958 mpc_set_ui(val, 0, MPC_RNDNN);
0c77715b 4959 ret = false;
4960 break;
e440a328 4961 case OPERATOR_MULT:
fcbea5e4 4962 mpc_mul(val, left_val, right_val, MPC_RNDNN);
e440a328 4963 break;
4964 case OPERATOR_DIV:
fcbea5e4 4965 if (mpc_cmp_si(right_val, 0) == 0)
4966 {
631d5788 4967 go_error_at(location, "division by zero");
71a45216 4968 nc->set_invalid();
fcbea5e4 4969 mpc_set_ui(val, 0, MPC_RNDNN);
4970 break;
4971 }
4972 mpc_div(val, left_val, right_val, MPC_RNDNN);
e440a328 4973 break;
e440a328 4974 default:
c3e6f413 4975 go_unreachable();
e440a328 4976 }
4977
fcbea5e4 4978 mpc_clear(left_val);
4979 mpc_clear(right_val);
e440a328 4980
fcbea5e4 4981 nc->set_complex(NULL, val);
4982 mpc_clear(val);
e440a328 4983
0c77715b 4984 return ret;
e440a328 4985}
4986
4987// Lower a binary expression. We have to evaluate constant
4988// expressions now, in order to implement Go's unlimited precision
4989// constants.
4990
4991Expression*
e9d3367e 4992Binary_expression::do_lower(Gogo* gogo, Named_object*,
4993 Statement_inserter* inserter, int)
e440a328 4994{
b13c66cd 4995 Location location = this->location();
e440a328 4996 Operator op = this->op_;
4997 Expression* left = this->left_;
4998 Expression* right = this->right_;
4999
5000 const bool is_comparison = (op == OPERATOR_EQEQ
5001 || op == OPERATOR_NOTEQ
5002 || op == OPERATOR_LT
5003 || op == OPERATOR_LE
5004 || op == OPERATOR_GT
5005 || op == OPERATOR_GE);
5006
0c77715b 5007 // Numeric constant expressions.
e440a328 5008 {
0c77715b 5009 Numeric_constant left_nc;
5010 Numeric_constant right_nc;
5011 if (left->numeric_constant_value(&left_nc)
5012 && right->numeric_constant_value(&right_nc))
e440a328 5013 {
0c77715b 5014 if (is_comparison)
e440a328 5015 {
0c77715b 5016 bool result;
5017 if (!Binary_expression::compare_constant(op, &left_nc,
5018 &right_nc, location,
5019 &result))
5020 return this;
e90c9dfc 5021 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 5022 Expression::make_boolean(result,
5023 location),
5024 location);
e440a328 5025 }
5026 else
5027 {
0c77715b 5028 Numeric_constant nc;
5029 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5030 location, &nc))
71a45216 5031 return this;
0c77715b 5032 return nc.expression(location);
e440a328 5033 }
5034 }
e440a328 5035 }
5036
5037 // String constant expressions.
315fa98d 5038 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 5039 {
5040 std::string left_string;
5041 std::string right_string;
5042 if (left->string_constant_value(&left_string)
5043 && right->string_constant_value(&right_string))
315fa98d 5044 {
5045 if (op == OPERATOR_PLUS)
5046 return Expression::make_string(left_string + right_string,
5047 location);
5048 else if (is_comparison)
5049 {
5050 int cmp = left_string.compare(right_string);
0c77715b 5051 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 5052 return Expression::make_boolean(r, location);
b40dc774 5053 }
5054 }
b40dc774 5055 }
5056
ceeb12d7 5057 // Lower struct, array, and some interface comparisons.
e9d3367e 5058 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5059 {
b79832ca 5060 if (left->type()->struct_type() != NULL
5061 && right->type()->struct_type() != NULL)
e9d3367e 5062 return this->lower_struct_comparison(gogo, inserter);
5063 else if (left->type()->array_type() != NULL
b79832ca 5064 && !left->type()->is_slice_type()
5065 && right->type()->array_type() != NULL
5066 && !right->type()->is_slice_type())
e9d3367e 5067 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 5068 else if ((left->type()->interface_type() != NULL
5069 && right->type()->interface_type() == NULL)
5070 || (left->type()->interface_type() == NULL
5071 && right->type()->interface_type() != NULL))
5072 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 5073 }
5074
736a16ba 5075 // Lower string concatenation to String_concat_expression, so that
5076 // we can group sequences of string additions.
5077 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5078 {
5079 Expression_list* exprs;
5080 String_concat_expression* left_sce =
5081 this->left_->string_concat_expression();
5082 if (left_sce != NULL)
5083 exprs = left_sce->exprs();
5084 else
5085 {
5086 exprs = new Expression_list();
5087 exprs->push_back(this->left_);
5088 }
5089
5090 String_concat_expression* right_sce =
5091 this->right_->string_concat_expression();
5092 if (right_sce != NULL)
5093 exprs->append(right_sce->exprs());
5094 else
5095 exprs->push_back(this->right_);
5096
5097 return Expression::make_string_concat(exprs);
5098 }
5099
e440a328 5100 return this;
5101}
5102
e9d3367e 5103// Lower a struct comparison.
5104
5105Expression*
5106Binary_expression::lower_struct_comparison(Gogo* gogo,
5107 Statement_inserter* inserter)
5108{
5109 Struct_type* st = this->left_->type()->struct_type();
5110 Struct_type* st2 = this->right_->type()->struct_type();
5111 if (st2 == NULL)
5112 return this;
5113 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5114 return this;
5115 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5116 this->right_->type(), NULL))
5117 return this;
5118
5119 // See if we can compare using memcmp. As a heuristic, we use
5120 // memcmp rather than field references and comparisons if there are
5121 // more than two fields.
113ef6a5 5122 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 5123 return this->lower_compare_to_memcmp(gogo, inserter);
5124
5125 Location loc = this->location();
5126
5127 Expression* left = this->left_;
5128 Temporary_statement* left_temp = NULL;
5129 if (left->var_expression() == NULL
5130 && left->temporary_reference_expression() == NULL)
5131 {
5132 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5133 inserter->insert(left_temp);
5134 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5135 }
5136
5137 Expression* right = this->right_;
5138 Temporary_statement* right_temp = NULL;
5139 if (right->var_expression() == NULL
5140 && right->temporary_reference_expression() == NULL)
5141 {
5142 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5143 inserter->insert(right_temp);
5144 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5145 }
5146
5147 Expression* ret = Expression::make_boolean(true, loc);
5148 const Struct_field_list* fields = st->fields();
5149 unsigned int field_index = 0;
5150 for (Struct_field_list::const_iterator pf = fields->begin();
5151 pf != fields->end();
5152 ++pf, ++field_index)
5153 {
f5165c05 5154 if (Gogo::is_sink_name(pf->field_name()))
5155 continue;
5156
e9d3367e 5157 if (field_index > 0)
5158 {
5159 if (left_temp == NULL)
5160 left = left->copy();
5161 else
5162 left = Expression::make_temporary_reference(left_temp, loc);
5163 if (right_temp == NULL)
5164 right = right->copy();
5165 else
5166 right = Expression::make_temporary_reference(right_temp, loc);
5167 }
5168 Expression* f1 = Expression::make_field_reference(left, field_index,
5169 loc);
5170 Expression* f2 = Expression::make_field_reference(right, field_index,
5171 loc);
5172 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5173 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5174 }
5175
5176 if (this->op_ == OPERATOR_NOTEQ)
5177 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5178
5179 return ret;
5180}
5181
5182// Lower an array comparison.
5183
5184Expression*
5185Binary_expression::lower_array_comparison(Gogo* gogo,
5186 Statement_inserter* inserter)
5187{
5188 Array_type* at = this->left_->type()->array_type();
5189 Array_type* at2 = this->right_->type()->array_type();
5190 if (at2 == NULL)
5191 return this;
5192 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5193 return this;
5194 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5195 this->right_->type(), NULL))
5196 return this;
5197
5198 // Call memcmp directly if possible. This may let the middle-end
5199 // optimize the call.
113ef6a5 5200 if (at->compare_is_identity(gogo))
e9d3367e 5201 return this->lower_compare_to_memcmp(gogo, inserter);
5202
5203 // Call the array comparison function.
5204 Named_object* hash_fn;
5205 Named_object* equal_fn;
5206 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5207 &hash_fn, &equal_fn);
5208
5209 Location loc = this->location();
5210
5211 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5212
5213 Expression_list* args = new Expression_list();
5214 args->push_back(this->operand_address(inserter, this->left_));
5215 args->push_back(this->operand_address(inserter, this->right_));
5216 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5217
5218 Expression* ret = Expression::make_call(func, args, false, loc);
5219
5220 if (this->op_ == OPERATOR_NOTEQ)
5221 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5222
5223 return ret;
5224}
5225
ceeb12d7 5226// Lower an interface to value comparison.
5227
5228Expression*
5229Binary_expression::lower_interface_value_comparison(Gogo*,
5230 Statement_inserter* inserter)
5231{
5232 Type* left_type = this->left_->type();
5233 Type* right_type = this->right_->type();
5234 Interface_type* ift;
5235 if (left_type->interface_type() != NULL)
5236 {
5237 ift = left_type->interface_type();
5238 if (!ift->implements_interface(right_type, NULL))
5239 return this;
5240 }
5241 else
5242 {
5243 ift = right_type->interface_type();
5244 if (!ift->implements_interface(left_type, NULL))
5245 return this;
5246 }
5247 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5248 return this;
5249
5250 Location loc = this->location();
5251
5252 if (left_type->interface_type() == NULL
5253 && left_type->points_to() == NULL
5254 && !this->left_->is_addressable())
5255 {
5256 Temporary_statement* temp =
5257 Statement::make_temporary(left_type, NULL, loc);
5258 inserter->insert(temp);
5259 this->left_ =
5260 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5261 }
5262
5263 if (right_type->interface_type() == NULL
5264 && right_type->points_to() == NULL
5265 && !this->right_->is_addressable())
5266 {
5267 Temporary_statement* temp =
5268 Statement::make_temporary(right_type, NULL, loc);
5269 inserter->insert(temp);
5270 this->right_ =
5271 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5272 }
5273
5274 return this;
5275}
5276
e9d3367e 5277// Lower a struct or array comparison to a call to memcmp.
5278
5279Expression*
5280Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5281{
5282 Location loc = this->location();
5283
5284 Expression* a1 = this->operand_address(inserter, this->left_);
5285 Expression* a2 = this->operand_address(inserter, this->right_);
5286 Expression* len = Expression::make_type_info(this->left_->type(),
5287 TYPE_INFO_SIZE);
5288
5289 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
e67508fa 5290 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
e9d3367e 5291 return Expression::make_binary(this->op_, call, zero, loc);
5292}
5293
a32698ee 5294Expression*
5c3f3470 5295Binary_expression::do_flatten(Gogo* gogo, Named_object*,
a32698ee 5296 Statement_inserter* inserter)
5297{
5298 Location loc = this->location();
5bf8be8b 5299 if (this->left_->type()->is_error_type()
5300 || this->right_->type()->is_error_type()
5301 || this->left_->is_error_expression()
5302 || this->right_->is_error_expression())
5303 {
5304 go_assert(saw_errors());
5305 return Expression::make_error(loc);
5306 }
5307
a32698ee 5308 Temporary_statement* temp;
a32698ee 5309
5310 Type* left_type = this->left_->type();
5311 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5312 || this->op_ == OPERATOR_RSHIFT);
5313 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5314 left_type->integer_type() != NULL)
5315 || this->op_ == OPERATOR_MOD);
5316
a32698ee 5317 if (is_shift_op
5c3f3470 5318 || (is_idiv_op
5319 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
a32698ee 5320 {
545ab43b 5321 if (!this->left_->is_variable() && !this->left_->is_constant())
a32698ee 5322 {
5323 temp = Statement::make_temporary(NULL, this->left_, loc);
5324 inserter->insert(temp);
5325 this->left_ = Expression::make_temporary_reference(temp, loc);
5326 }
545ab43b 5327 if (!this->right_->is_variable() && !this->right_->is_constant())
a32698ee 5328 {
5329 temp =
5330 Statement::make_temporary(NULL, this->right_, loc);
5331 this->right_ = Expression::make_temporary_reference(temp, loc);
5332 inserter->insert(temp);
5333 }
5334 }
5335 return this;
5336}
5337
5338
e9d3367e 5339// Return the address of EXPR, cast to unsafe.Pointer.
5340
5341Expression*
5342Binary_expression::operand_address(Statement_inserter* inserter,
5343 Expression* expr)
5344{
5345 Location loc = this->location();
5346
5347 if (!expr->is_addressable())
5348 {
5349 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5350 loc);
5351 inserter->insert(temp);
5352 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5353 }
5354 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5355 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5356 Type* void_type = Type::make_void_type();
5357 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5358 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5359}
5360
0c77715b 5361// Return the numeric constant value, if it has one.
e440a328 5362
5363bool
0c77715b 5364Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5365{
0c77715b 5366 Numeric_constant left_nc;
5367 if (!this->left_->numeric_constant_value(&left_nc))
5368 return false;
5369 Numeric_constant right_nc;
5370 if (!this->right_->numeric_constant_value(&right_nc))
5371 return false;
9767e2d3 5372 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5373 this->location(), nc);
e440a328 5374}
5375
5376// Note that the value is being discarded.
5377
4f2138d7 5378bool
e440a328 5379Binary_expression::do_discarding_value()
5380{
5381 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5382 return this->right_->discarding_value();
e440a328 5383 else
4f2138d7 5384 {
5385 this->unused_value_error();
5386 return false;
5387 }
e440a328 5388}
5389
5390// Get type.
5391
5392Type*
5393Binary_expression::do_type()
5394{
5f5fea79 5395 if (this->classification() == EXPRESSION_ERROR)
5396 return Type::make_error_type();
5397
e440a328 5398 switch (this->op_)
5399 {
e440a328 5400 case OPERATOR_EQEQ:
5401 case OPERATOR_NOTEQ:
5402 case OPERATOR_LT:
5403 case OPERATOR_LE:
5404 case OPERATOR_GT:
5405 case OPERATOR_GE:
e90c9dfc 5406 if (this->type_ == NULL)
5407 this->type_ = Type::make_boolean_type();
5408 return this->type_;
e440a328 5409
5410 case OPERATOR_PLUS:
5411 case OPERATOR_MINUS:
5412 case OPERATOR_OR:
5413 case OPERATOR_XOR:
5414 case OPERATOR_MULT:
5415 case OPERATOR_DIV:
5416 case OPERATOR_MOD:
5417 case OPERATOR_AND:
5418 case OPERATOR_BITCLEAR:
e90c9dfc 5419 case OPERATOR_OROR:
5420 case OPERATOR_ANDAND:
e440a328 5421 {
0c77715b 5422 Type* type;
5423 if (!Binary_expression::operation_type(this->op_,
5424 this->left_->type(),
5425 this->right_->type(),
5426 &type))
5427 return Type::make_error_type();
5428 return type;
e440a328 5429 }
5430
5431 case OPERATOR_LSHIFT:
5432 case OPERATOR_RSHIFT:
5433 return this->left_->type();
5434
5435 default:
c3e6f413 5436 go_unreachable();
e440a328 5437 }
5438}
5439
5440// Set type for a binary expression.
5441
5442void
5443Binary_expression::do_determine_type(const Type_context* context)
5444{
5445 Type* tleft = this->left_->type();
5446 Type* tright = this->right_->type();
5447
5448 // Both sides should have the same type, except for the shift
5449 // operations. For a comparison, we should ignore the incoming
5450 // type.
5451
5452 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5453 || this->op_ == OPERATOR_RSHIFT);
5454
5455 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5456 || this->op_ == OPERATOR_NOTEQ
5457 || this->op_ == OPERATOR_LT
5458 || this->op_ == OPERATOR_LE
5459 || this->op_ == OPERATOR_GT
5460 || this->op_ == OPERATOR_GE);
5461
c999c2a7 5462 // For constant expressions, the context of the result is not useful in
5463 // determining the types of the operands. It is only legal to use abstract
5464 // boolean, numeric, and string constants as operands where it is legal to
5465 // use non-abstract boolean, numeric, and string constants, respectively.
5466 // Any issues with the operation will be resolved in the check_types pass.
5467 bool is_constant_expr = (this->left_->is_constant()
5468 && this->right_->is_constant());
5469
e440a328 5470 Type_context subcontext(*context);
5471
5472 if (is_comparison)
5473 {
5474 // In a comparison, the context does not determine the types of
5475 // the operands.
5476 subcontext.type = NULL;
5477 }
5478
5479 // Set the context for the left hand operand.
5480 if (is_shift_op)
5481 {
b40dc774 5482 // The right hand operand of a shift plays no role in
5483 // determining the type of the left hand operand.
e440a328 5484 }
5485 else if (!tleft->is_abstract())
5486 subcontext.type = tleft;
5487 else if (!tright->is_abstract())
5488 subcontext.type = tright;
5489 else if (subcontext.type == NULL)
5490 {
5491 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5492 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5493 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5494 {
5495 // Both sides have an abstract integer, abstract float, or
5496 // abstract complex type. Just let CONTEXT determine
5497 // whether they may remain abstract or not.
5498 }
5499 else if (tleft->complex_type() != NULL)
5500 subcontext.type = tleft;
5501 else if (tright->complex_type() != NULL)
5502 subcontext.type = tright;
5503 else if (tleft->float_type() != NULL)
5504 subcontext.type = tleft;
5505 else if (tright->float_type() != NULL)
5506 subcontext.type = tright;
5507 else
5508 subcontext.type = tleft;
f58a23ae 5509
5510 if (subcontext.type != NULL && !context->may_be_abstract)
5511 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5512 }
5513
c999c2a7 5514 if (!is_constant_expr)
5515 this->left_->determine_type(&subcontext);
e440a328 5516
e440a328 5517 if (is_shift_op)
5518 {
b40dc774 5519 // We may have inherited an unusable type for the shift operand.
5520 // Give a useful error if that happened.
5521 if (tleft->is_abstract()
5522 && subcontext.type != NULL
8ab6effb 5523 && !subcontext.may_be_abstract
f6bc81e6 5524 && subcontext.type->interface_type() == NULL
8ab6effb 5525 && subcontext.type->integer_type() == NULL)
b40dc774 5526 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5527 "for left operand of shift"));
b40dc774 5528
5529 // The context for the right hand operand is the same as for the
5530 // left hand operand, except for a shift operator.
e440a328 5531 subcontext.type = Type::lookup_integer_type("uint");
5532 subcontext.may_be_abstract = false;
5533 }
5534
c999c2a7 5535 if (!is_constant_expr)
5536 this->right_->determine_type(&subcontext);
e90c9dfc 5537
5538 if (is_comparison)
5539 {
5540 if (this->type_ != NULL && !this->type_->is_abstract())
5541 ;
5542 else if (context->type != NULL && context->type->is_boolean_type())
5543 this->type_ = context->type;
5544 else if (!context->may_be_abstract)
5545 this->type_ = Type::lookup_bool_type();
5546 }
e440a328 5547}
5548
5549// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5550// OTYPE is the type of the other operand. Return whether the
5551// operation is OK. This should not be used for shift.
e440a328 5552
5553bool
be8b5eee 5554Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5555 Location location)
e440a328 5556{
5557 switch (op)
5558 {
5559 case OPERATOR_OROR:
5560 case OPERATOR_ANDAND:
c999c2a7 5561 if (!type->is_boolean_type()
5562 || !otype->is_boolean_type())
e440a328 5563 {
631d5788 5564 go_error_at(location, "expected boolean type");
e440a328 5565 return false;
5566 }
5567 break;
5568
5569 case OPERATOR_EQEQ:
5570 case OPERATOR_NOTEQ:
e9d3367e 5571 {
5572 std::string reason;
5573 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5574 {
631d5788 5575 go_error_at(location, "%s", reason.c_str());
e9d3367e 5576 return false;
5577 }
5578 }
e440a328 5579 break;
5580
5581 case OPERATOR_LT:
5582 case OPERATOR_LE:
5583 case OPERATOR_GT:
5584 case OPERATOR_GE:
e9d3367e 5585 {
5586 std::string reason;
5587 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5588 {
631d5788 5589 go_error_at(location, "%s", reason.c_str());
e9d3367e 5590 return false;
5591 }
5592 }
e440a328 5593 break;
5594
5595 case OPERATOR_PLUS:
5596 case OPERATOR_PLUSEQ:
c999c2a7 5597 if ((!type->is_numeric_type() && !type->is_string_type())
5598 || (!otype->is_numeric_type() && !otype->is_string_type()))
e440a328 5599 {
631d5788 5600 go_error_at(location,
e440a328 5601 "expected integer, floating, complex, or string type");
5602 return false;
5603 }
5604 break;
5605
5606 case OPERATOR_MINUS:
5607 case OPERATOR_MINUSEQ:
5608 case OPERATOR_MULT:
5609 case OPERATOR_MULTEQ:
5610 case OPERATOR_DIV:
5611 case OPERATOR_DIVEQ:
c999c2a7 5612 if (!type->is_numeric_type() || !otype->is_numeric_type())
e440a328 5613 {
631d5788 5614 go_error_at(location, "expected integer, floating, or complex type");
e440a328 5615 return false;
5616 }
5617 break;
5618
5619 case OPERATOR_MOD:
5620 case OPERATOR_MODEQ:
5621 case OPERATOR_OR:
5622 case OPERATOR_OREQ:
5623 case OPERATOR_AND:
5624 case OPERATOR_ANDEQ:
5625 case OPERATOR_XOR:
5626 case OPERATOR_XOREQ:
5627 case OPERATOR_BITCLEAR:
5628 case OPERATOR_BITCLEAREQ:
c999c2a7 5629 if (type->integer_type() == NULL || otype->integer_type() == NULL)
e440a328 5630 {
631d5788 5631 go_error_at(location, "expected integer type");
e440a328 5632 return false;
5633 }
5634 break;
5635
5636 default:
c3e6f413 5637 go_unreachable();
e440a328 5638 }
5639
5640 return true;
5641}
5642
5643// Check types.
5644
5645void
5646Binary_expression::do_check_types(Gogo*)
5647{
5f5fea79 5648 if (this->classification() == EXPRESSION_ERROR)
5649 return;
5650
e440a328 5651 Type* left_type = this->left_->type();
5652 Type* right_type = this->right_->type();
5c13bd80 5653 if (left_type->is_error() || right_type->is_error())
9fe897ef 5654 {
5655 this->set_is_error();
5656 return;
5657 }
e440a328 5658
5659 if (this->op_ == OPERATOR_EQEQ
5660 || this->op_ == OPERATOR_NOTEQ
5661 || this->op_ == OPERATOR_LT
5662 || this->op_ == OPERATOR_LE
5663 || this->op_ == OPERATOR_GT
5664 || this->op_ == OPERATOR_GE)
5665 {
907c5ecd 5666 if (left_type->is_nil_type() && right_type->is_nil_type())
5667 {
5668 this->report_error(_("invalid comparison of nil with nil"));
5669 return;
5670 }
e440a328 5671 if (!Type::are_assignable(left_type, right_type, NULL)
5672 && !Type::are_assignable(right_type, left_type, NULL))
5673 {
5674 this->report_error(_("incompatible types in binary expression"));
5675 return;
5676 }
5677 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5678 right_type,
e440a328 5679 this->location())
5680 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5681 left_type,
e440a328 5682 this->location()))
5683 {
5684 this->set_is_error();
5685 return;
5686 }
5687 }
5688 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5689 {
5690 if (!Type::are_compatible_for_binop(left_type, right_type))
5691 {
5692 this->report_error(_("incompatible types in binary expression"));
5693 return;
5694 }
5695 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5696 right_type,
e440a328 5697 this->location()))
5698 {
5699 this->set_is_error();
5700 return;
5701 }
5c65b19d 5702 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5703 {
5704 // Division by a zero integer constant is an error.
5705 Numeric_constant rconst;
5706 unsigned long rval;
5707 if (left_type->integer_type() != NULL
5708 && this->right_->numeric_constant_value(&rconst)
5709 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5710 && rval == 0)
5711 {
5712 this->report_error(_("integer division by zero"));
5713 return;
5714 }
5715 }
e440a328 5716 }
5717 else
5718 {
5719 if (left_type->integer_type() == NULL)
5720 this->report_error(_("shift of non-integer operand"));
5721
6b5e0fac 5722 if (right_type->is_string_type())
5723 this->report_error(_("shift count not unsigned integer"));
5724 else if (!right_type->is_abstract()
e440a328 5725 && (right_type->integer_type() == NULL
5726 || !right_type->integer_type()->is_unsigned()))
5727 this->report_error(_("shift count not unsigned integer"));
5728 else
5729 {
0c77715b 5730 Numeric_constant nc;
5731 if (this->right_->numeric_constant_value(&nc))
e440a328 5732 {
0c77715b 5733 mpz_t val;
5734 if (!nc.to_int(&val))
5735 this->report_error(_("shift count not unsigned integer"));
5736 else
a4eba91b 5737 {
0c77715b 5738 if (mpz_sgn(val) < 0)
5739 {
5740 this->report_error(_("negative shift count"));
0c77715b 5741 Location rloc = this->right_->location();
e67508fa 5742 this->right_ = Expression::make_integer_ul(0, right_type,
5743 rloc);
0c77715b 5744 }
5745 mpz_clear(val);
a4eba91b 5746 }
e440a328 5747 }
e440a328 5748 }
5749 }
5750}
5751
ea664253 5752// Get the backend representation for a binary expression.
e440a328 5753
ea664253 5754Bexpression*
5755Binary_expression::do_get_backend(Translate_context* context)
e440a328 5756{
1b1f2abf 5757 Gogo* gogo = context->gogo();
a32698ee 5758 Location loc = this->location();
5759 Type* left_type = this->left_->type();
5760 Type* right_type = this->right_->type();
1b1f2abf 5761
e440a328 5762 bool use_left_type = true;
5763 bool is_shift_op = false;
29a2d1d8 5764 bool is_idiv_op = false;
e440a328 5765 switch (this->op_)
5766 {
5767 case OPERATOR_EQEQ:
5768 case OPERATOR_NOTEQ:
5769 case OPERATOR_LT:
5770 case OPERATOR_LE:
5771 case OPERATOR_GT:
5772 case OPERATOR_GE:
ea664253 5773 return Expression::comparison(context, this->type_, this->op_,
5774 this->left_, this->right_, loc);
e440a328 5775
5776 case OPERATOR_OROR:
e440a328 5777 case OPERATOR_ANDAND:
e440a328 5778 use_left_type = false;
5779 break;
5780 case OPERATOR_PLUS:
e440a328 5781 case OPERATOR_MINUS:
e440a328 5782 case OPERATOR_OR:
e440a328 5783 case OPERATOR_XOR:
e440a328 5784 case OPERATOR_MULT:
e440a328 5785 break;
5786 case OPERATOR_DIV:
a32698ee 5787 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5788 break;
729f8831 5789 // Fall through.
e440a328 5790 case OPERATOR_MOD:
29a2d1d8 5791 is_idiv_op = true;
e440a328 5792 break;
5793 case OPERATOR_LSHIFT:
e440a328 5794 case OPERATOR_RSHIFT:
e440a328 5795 is_shift_op = true;
5796 break;
e440a328 5797 case OPERATOR_BITCLEAR:
a32698ee 5798 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5799 case OPERATOR_AND:
e440a328 5800 break;
5801 default:
c3e6f413 5802 go_unreachable();
e440a328 5803 }
5804
736a16ba 5805 // The only binary operation for string is +, and that should have
5806 // been converted to a String_concat_expression in do_lower.
5807 go_assert(!left_type->is_string_type());
a32698ee 5808
5809 // For complex division Go might want slightly different results than the
5810 // backend implementation provides, so we have our own runtime routine.
1850e20c 5811 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5812 {
a32698ee 5813 Runtime::Function complex_code;
1850e20c 5814 switch (this->left_->type()->complex_type()->bits())
5815 {
5816 case 64:
a32698ee 5817 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 5818 break;
5819 case 128:
a32698ee 5820 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 5821 break;
5822 default:
5823 go_unreachable();
5824 }
a32698ee 5825 Expression* complex_div =
5826 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
ea664253 5827 return complex_div->get_backend(context);
1850e20c 5828 }
5829
ea664253 5830 Bexpression* left = this->left_->get_backend(context);
5831 Bexpression* right = this->right_->get_backend(context);
e440a328 5832
a32698ee 5833 Type* type = use_left_type ? left_type : right_type;
5834 Btype* btype = type->get_backend(gogo);
5835
5836 Bexpression* ret =
5837 gogo->backend()->binary_expression(this->op_, left, right, loc);
5838 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 5839
a32698ee 5840 // Initialize overflow constants.
5841 Bexpression* overflow;
5842 mpz_t zero;
5843 mpz_init_set_ui(zero, 0UL);
5844 mpz_t one;
5845 mpz_init_set_ui(one, 1UL);
5846 mpz_t neg_one;
5847 mpz_init_set_si(neg_one, -1);
e440a328 5848
a32698ee 5849 Btype* left_btype = left_type->get_backend(gogo);
5850 Btype* right_btype = right_type->get_backend(gogo);
e440a328 5851
5852 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 5853 // This is not true in C, so we need to insert a conditional.
e440a328 5854 if (is_shift_op)
5855 {
a32698ee 5856 go_assert(left_type->integer_type() != NULL);
e440a328 5857
a32698ee 5858 mpz_t bitsval;
5859 int bits = left_type->integer_type()->bits();
5860 mpz_init_set_ui(bitsval, bits);
5861 Bexpression* bits_expr =
5862 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5863 Bexpression* compare =
5864 gogo->backend()->binary_expression(OPERATOR_LT,
5865 right, bits_expr, loc);
e440a328 5866
a32698ee 5867 Bexpression* zero_expr =
5868 gogo->backend()->integer_constant_expression(left_btype, zero);
5869 overflow = zero_expr;
e440a328 5870 if (this->op_ == OPERATOR_RSHIFT
a32698ee 5871 && !left_type->integer_type()->is_unsigned())
e440a328 5872 {
a32698ee 5873 Bexpression* neg_expr =
5874 gogo->backend()->binary_expression(OPERATOR_LT, left,
5875 zero_expr, loc);
5876 Bexpression* neg_one_expr =
5877 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5878 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5879 neg_one_expr,
5880 zero_expr, loc);
29a2d1d8 5881 }
a32698ee 5882 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5883 overflow, loc);
5884 mpz_clear(bitsval);
29a2d1d8 5885 }
5886
5887 // Add checks for division by zero and division overflow as needed.
5888 if (is_idiv_op)
5889 {
5c3f3470 5890 if (gogo->check_divide_by_zero())
29a2d1d8 5891 {
5892 // right == 0
a32698ee 5893 Bexpression* zero_expr =
5894 gogo->backend()->integer_constant_expression(right_btype, zero);
5895 Bexpression* check =
5896 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5897 right, zero_expr, loc);
29a2d1d8 5898
a32698ee 5899 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 5900 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
ea664253 5901 Bexpression* crash = gogo->runtime_error(errcode,
5902 loc)->get_backend(context);
29a2d1d8 5903
5904 // right == 0 ? (__go_runtime_error(...), 0) : ret
ea664253 5905 ret = gogo->backend()->conditional_expression(btype, check, crash,
5906 ret, loc);
b13c66cd 5907 }
5908
5c3f3470 5909 if (gogo->check_divide_overflow())
29a2d1d8 5910 {
5911 // right == -1
5912 // FIXME: It would be nice to say that this test is expected
5913 // to return false.
a32698ee 5914
5915 Bexpression* neg_one_expr =
5916 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5917 Bexpression* check =
5918 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5919 right, neg_one_expr, loc);
5920
5921 Bexpression* zero_expr =
5922 gogo->backend()->integer_constant_expression(btype, zero);
5923 Bexpression* one_expr =
5924 gogo->backend()->integer_constant_expression(btype, one);
5925
5926 if (type->integer_type()->is_unsigned())
29a2d1d8 5927 {
5928 // An unsigned -1 is the largest possible number, so
5929 // dividing is always 1 or 0.
a32698ee 5930
5931 Bexpression* cmp =
5932 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5933 left, right, loc);
29a2d1d8 5934 if (this->op_ == OPERATOR_DIV)
a32698ee 5935 overflow =
5936 gogo->backend()->conditional_expression(btype, cmp,
5937 one_expr, zero_expr,
5938 loc);
29a2d1d8 5939 else
a32698ee 5940 overflow =
5941 gogo->backend()->conditional_expression(btype, cmp,
5942 zero_expr, left,
5943 loc);
29a2d1d8 5944 }
5945 else
5946 {
5947 // Computing left / -1 is the same as computing - left,
5948 // which does not overflow since Go sets -fwrapv.
5949 if (this->op_ == OPERATOR_DIV)
a32698ee 5950 {
5951 Expression* negate_expr =
5952 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
ea664253 5953 overflow = negate_expr->get_backend(context);
a32698ee 5954 }
29a2d1d8 5955 else
a32698ee 5956 overflow = zero_expr;
29a2d1d8 5957 }
a32698ee 5958 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 5959
5960 // right == -1 ? - left : ret
a32698ee 5961 ret = gogo->backend()->conditional_expression(btype, check, overflow,
5962 ret, loc);
29a2d1d8 5963 }
e440a328 5964 }
5965
a32698ee 5966 mpz_clear(zero);
5967 mpz_clear(one);
5968 mpz_clear(neg_one);
ea664253 5969 return ret;
e440a328 5970}
5971
5972// Export a binary expression.
5973
5974void
5975Binary_expression::do_export(Export* exp) const
5976{
5977 exp->write_c_string("(");
5978 this->left_->export_expression(exp);
5979 switch (this->op_)
5980 {
5981 case OPERATOR_OROR:
5982 exp->write_c_string(" || ");
5983 break;
5984 case OPERATOR_ANDAND:
5985 exp->write_c_string(" && ");
5986 break;
5987 case OPERATOR_EQEQ:
5988 exp->write_c_string(" == ");
5989 break;
5990 case OPERATOR_NOTEQ:
5991 exp->write_c_string(" != ");
5992 break;
5993 case OPERATOR_LT:
5994 exp->write_c_string(" < ");
5995 break;
5996 case OPERATOR_LE:
5997 exp->write_c_string(" <= ");
5998 break;
5999 case OPERATOR_GT:
6000 exp->write_c_string(" > ");
6001 break;
6002 case OPERATOR_GE:
6003 exp->write_c_string(" >= ");
6004 break;
6005 case OPERATOR_PLUS:
6006 exp->write_c_string(" + ");
6007 break;
6008 case OPERATOR_MINUS:
6009 exp->write_c_string(" - ");
6010 break;
6011 case OPERATOR_OR:
6012 exp->write_c_string(" | ");
6013 break;
6014 case OPERATOR_XOR:
6015 exp->write_c_string(" ^ ");
6016 break;
6017 case OPERATOR_MULT:
6018 exp->write_c_string(" * ");
6019 break;
6020 case OPERATOR_DIV:
6021 exp->write_c_string(" / ");
6022 break;
6023 case OPERATOR_MOD:
6024 exp->write_c_string(" % ");
6025 break;
6026 case OPERATOR_LSHIFT:
6027 exp->write_c_string(" << ");
6028 break;
6029 case OPERATOR_RSHIFT:
6030 exp->write_c_string(" >> ");
6031 break;
6032 case OPERATOR_AND:
6033 exp->write_c_string(" & ");
6034 break;
6035 case OPERATOR_BITCLEAR:
6036 exp->write_c_string(" &^ ");
6037 break;
6038 default:
c3e6f413 6039 go_unreachable();
e440a328 6040 }
6041 this->right_->export_expression(exp);
6042 exp->write_c_string(")");
6043}
6044
6045// Import a binary expression.
6046
6047Expression*
6048Binary_expression::do_import(Import* imp)
6049{
6050 imp->require_c_string("(");
6051
6052 Expression* left = Expression::import_expression(imp);
6053
6054 Operator op;
6055 if (imp->match_c_string(" || "))
6056 {
6057 op = OPERATOR_OROR;
6058 imp->advance(4);
6059 }
6060 else if (imp->match_c_string(" && "))
6061 {
6062 op = OPERATOR_ANDAND;
6063 imp->advance(4);
6064 }
6065 else if (imp->match_c_string(" == "))
6066 {
6067 op = OPERATOR_EQEQ;
6068 imp->advance(4);
6069 }
6070 else if (imp->match_c_string(" != "))
6071 {
6072 op = OPERATOR_NOTEQ;
6073 imp->advance(4);
6074 }
6075 else if (imp->match_c_string(" < "))
6076 {
6077 op = OPERATOR_LT;
6078 imp->advance(3);
6079 }
6080 else if (imp->match_c_string(" <= "))
6081 {
6082 op = OPERATOR_LE;
6083 imp->advance(4);
6084 }
6085 else if (imp->match_c_string(" > "))
6086 {
6087 op = OPERATOR_GT;
6088 imp->advance(3);
6089 }
6090 else if (imp->match_c_string(" >= "))
6091 {
6092 op = OPERATOR_GE;
6093 imp->advance(4);
6094 }
6095 else if (imp->match_c_string(" + "))
6096 {
6097 op = OPERATOR_PLUS;
6098 imp->advance(3);
6099 }
6100 else if (imp->match_c_string(" - "))
6101 {
6102 op = OPERATOR_MINUS;
6103 imp->advance(3);
6104 }
6105 else if (imp->match_c_string(" | "))
6106 {
6107 op = OPERATOR_OR;
6108 imp->advance(3);
6109 }
6110 else if (imp->match_c_string(" ^ "))
6111 {
6112 op = OPERATOR_XOR;
6113 imp->advance(3);
6114 }
6115 else if (imp->match_c_string(" * "))
6116 {
6117 op = OPERATOR_MULT;
6118 imp->advance(3);
6119 }
6120 else if (imp->match_c_string(" / "))
6121 {
6122 op = OPERATOR_DIV;
6123 imp->advance(3);
6124 }
6125 else if (imp->match_c_string(" % "))
6126 {
6127 op = OPERATOR_MOD;
6128 imp->advance(3);
6129 }
6130 else if (imp->match_c_string(" << "))
6131 {
6132 op = OPERATOR_LSHIFT;
6133 imp->advance(4);
6134 }
6135 else if (imp->match_c_string(" >> "))
6136 {
6137 op = OPERATOR_RSHIFT;
6138 imp->advance(4);
6139 }
6140 else if (imp->match_c_string(" & "))
6141 {
6142 op = OPERATOR_AND;
6143 imp->advance(3);
6144 }
6145 else if (imp->match_c_string(" &^ "))
6146 {
6147 op = OPERATOR_BITCLEAR;
6148 imp->advance(4);
6149 }
6150 else
6151 {
631d5788 6152 go_error_at(imp->location(), "unrecognized binary operator");
e440a328 6153 return Expression::make_error(imp->location());
6154 }
6155
6156 Expression* right = Expression::import_expression(imp);
6157
6158 imp->require_c_string(")");
6159
6160 return Expression::make_binary(op, left, right, imp->location());
6161}
6162
d751bb78 6163// Dump ast representation of a binary expression.
6164
6165void
6166Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6167{
6168 ast_dump_context->ostream() << "(";
6169 ast_dump_context->dump_expression(this->left_);
6170 ast_dump_context->ostream() << " ";
6171 ast_dump_context->dump_operator(this->op_);
6172 ast_dump_context->ostream() << " ";
6173 ast_dump_context->dump_expression(this->right_);
6174 ast_dump_context->ostream() << ") ";
6175}
6176
e440a328 6177// Make a binary expression.
6178
6179Expression*
6180Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6181 Location location)
e440a328 6182{
6183 return new Binary_expression(op, left, right, location);
6184}
6185
6186// Implement a comparison.
6187
a32698ee 6188Bexpression*
6189Expression::comparison(Translate_context* context, Type* result_type,
6190 Operator op, Expression* left, Expression* right,
6191 Location location)
e440a328 6192{
2387f644 6193 Type* left_type = left->type();
6194 Type* right_type = right->type();
ceeb12d7 6195
e67508fa 6196 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
1b1f2abf 6197
15c67ee2 6198 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6199 {
6098d6cb 6200 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6201 {
6202 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6203 left, right);
6204 right = Expression::make_boolean(true, location);
6205 }
6206 else
6207 {
6208 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6209 left, right);
6210 right = zexpr;
6211 }
e440a328 6212 }
15c67ee2 6213 else if ((left_type->interface_type() != NULL
6214 && right_type->interface_type() == NULL
6215 && !right_type->is_nil_type())
6216 || (left_type->interface_type() == NULL
6217 && !left_type->is_nil_type()
6218 && right_type->interface_type() != NULL))
e440a328 6219 {
6220 // Comparing an interface value to a non-interface value.
6221 if (left_type->interface_type() == NULL)
6222 {
6223 std::swap(left_type, right_type);
2387f644 6224 std::swap(left, right);
e440a328 6225 }
6226
6227 // The right operand is not an interface. We need to take its
6228 // address if it is not a pointer.
ceeb12d7 6229 Expression* pointer_arg = NULL;
e440a328 6230 if (right_type->points_to() != NULL)
2387f644 6231 pointer_arg = right;
e440a328 6232 else
6233 {
2387f644 6234 go_assert(right->is_addressable());
6235 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6236 location);
e440a328 6237 }
e440a328 6238
2387f644 6239 Expression* descriptor =
6240 Expression::make_type_descriptor(right_type, location);
6241 left =
ceeb12d7 6242 Runtime::make_call((left_type->interface_type()->is_empty()
6098d6cb 6243 ? Runtime::EFACEVALEQ
6244 : Runtime::IFACEVALEQ),
2387f644 6245 location, 3, left, descriptor,
ceeb12d7 6246 pointer_arg);
6098d6cb 6247 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6248 right = Expression::make_boolean(true, location);
e440a328 6249 }
6250 else if (left_type->interface_type() != NULL
6251 && right_type->interface_type() != NULL)
6252 {
ceeb12d7 6253 Runtime::Function compare_function;
739bad04 6254 if (left_type->interface_type()->is_empty()
6255 && right_type->interface_type()->is_empty())
6098d6cb 6256 compare_function = Runtime::EFACEEQ;
739bad04 6257 else if (!left_type->interface_type()->is_empty()
6258 && !right_type->interface_type()->is_empty())
6098d6cb 6259 compare_function = Runtime::IFACEEQ;
739bad04 6260 else
6261 {
6262 if (left_type->interface_type()->is_empty())
6263 {
739bad04 6264 std::swap(left_type, right_type);
2387f644 6265 std::swap(left, right);
739bad04 6266 }
c484d925 6267 go_assert(!left_type->interface_type()->is_empty());
6268 go_assert(right_type->interface_type()->is_empty());
6098d6cb 6269 compare_function = Runtime::IFACEEFACEEQ;
739bad04 6270 }
6271
2387f644 6272 left = Runtime::make_call(compare_function, location, 2, left, right);
6098d6cb 6273 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6274 right = Expression::make_boolean(true, location);
e440a328 6275 }
6276
6277 if (left_type->is_nil_type()
6278 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6279 {
6280 std::swap(left_type, right_type);
2387f644 6281 std::swap(left, right);
e440a328 6282 }
6283
6284 if (right_type->is_nil_type())
6285 {
2387f644 6286 right = Expression::make_nil(location);
e440a328 6287 if (left_type->array_type() != NULL
6288 && left_type->array_type()->length() == NULL)
6289 {
6290 Array_type* at = left_type->array_type();
2387f644 6291 left = at->get_value_pointer(context->gogo(), left);
e440a328 6292 }
6293 else if (left_type->interface_type() != NULL)
6294 {
6295 // An interface is nil if the first field is nil.
2387f644 6296 left = Expression::make_field_reference(left, 0, location);
e440a328 6297 }
6298 }
6299
ea664253 6300 Bexpression* left_bexpr = left->get_backend(context);
6301 Bexpression* right_bexpr = right->get_backend(context);
e90c9dfc 6302
a32698ee 6303 Gogo* gogo = context->gogo();
6304 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6305 right_bexpr, location);
6306 if (result_type != NULL)
6307 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6308 ret, location);
e440a328 6309 return ret;
6310}
6311
736a16ba 6312// Class String_concat_expression.
6313
6314bool
6315String_concat_expression::do_is_constant() const
6316{
6317 for (Expression_list::const_iterator pe = this->exprs_->begin();
6318 pe != this->exprs_->end();
6319 ++pe)
6320 {
6321 if (!(*pe)->is_constant())
6322 return false;
6323 }
6324 return true;
6325}
6326
6327bool
6328String_concat_expression::do_is_immutable() const
6329{
6330 for (Expression_list::const_iterator pe = this->exprs_->begin();
6331 pe != this->exprs_->end();
6332 ++pe)
6333 {
6334 if (!(*pe)->is_immutable())
6335 return false;
6336 }
6337 return true;
6338}
6339
6340Type*
6341String_concat_expression::do_type()
6342{
6343 Type* t = this->exprs_->front()->type();
6344 Expression_list::iterator pe = this->exprs_->begin();
6345 ++pe;
6346 for (; pe != this->exprs_->end(); ++pe)
6347 {
6348 Type* t1;
6349 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6350 (*pe)->type(),
6351 &t1))
6352 return Type::make_error_type();
6353 t = t1;
6354 }
6355 return t;
6356}
6357
6358void
6359String_concat_expression::do_determine_type(const Type_context* context)
6360{
6361 Type_context subcontext(*context);
6362 for (Expression_list::iterator pe = this->exprs_->begin();
6363 pe != this->exprs_->end();
6364 ++pe)
6365 {
6366 Type* t = (*pe)->type();
6367 if (!t->is_abstract())
6368 {
6369 subcontext.type = t;
6370 break;
6371 }
6372 }
6373 if (subcontext.type == NULL)
6374 subcontext.type = this->exprs_->front()->type();
6375 for (Expression_list::iterator pe = this->exprs_->begin();
6376 pe != this->exprs_->end();
6377 ++pe)
6378 (*pe)->determine_type(&subcontext);
6379}
6380
6381void
6382String_concat_expression::do_check_types(Gogo*)
6383{
6384 if (this->is_error_expression())
6385 return;
6386 Type* t = this->exprs_->front()->type();
6387 if (t->is_error())
6388 {
6389 this->set_is_error();
6390 return;
6391 }
6392 Expression_list::iterator pe = this->exprs_->begin();
6393 ++pe;
6394 for (; pe != this->exprs_->end(); ++pe)
6395 {
6396 Type* t1 = (*pe)->type();
6397 if (!Type::are_compatible_for_binop(t, t1))
6398 {
6399 this->report_error("incompatible types in binary expression");
6400 return;
6401 }
6402 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6403 this->location()))
6404 {
6405 this->set_is_error();
6406 return;
6407 }
6408 }
6409}
6410
6411Expression*
6412String_concat_expression::do_flatten(Gogo*, Named_object*,
6413 Statement_inserter*)
6414{
6415 if (this->is_error_expression())
6416 return this;
6417 Location loc = this->location();
6418 Type* type = this->type();
6419 Expression* nil_arg = Expression::make_nil(loc);
6420 Expression* call;
6421 switch (this->exprs_->size())
6422 {
6423 case 0: case 1:
6424 go_unreachable();
6425
6426 case 2: case 3: case 4: case 5:
6427 {
6428 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6429 NULL, loc);
6430 Array_type* arg_type = Type::make_array_type(type, len);
6431 arg_type->set_is_array_incomparable();
6432 Expression* arg =
6433 Expression::make_array_composite_literal(arg_type, this->exprs_,
6434 loc);
6435 Runtime::Function code;
6436 switch (this->exprs_->size())
6437 {
6438 default:
6439 go_unreachable();
6440 case 2:
6441 code = Runtime::CONCATSTRING2;
6442 break;
6443 case 3:
6444 code = Runtime::CONCATSTRING3;
6445 break;
6446 case 4:
6447 code = Runtime::CONCATSTRING4;
6448 break;
6449 case 5:
6450 code = Runtime::CONCATSTRING5;
6451 break;
6452 }
6453 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6454 }
6455 break;
6456
6457 default:
6458 {
6459 Type* arg_type = Type::make_array_type(type, NULL);
6460 Slice_construction_expression* sce =
6461 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6462 loc);
6463 sce->set_storage_does_not_escape();
6464 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6465 sce);
6466 }
6467 break;
6468 }
6469
6470 return Expression::make_cast(type, call, loc);
6471}
6472
6473void
6474String_concat_expression::do_dump_expression(
6475 Ast_dump_context* ast_dump_context) const
6476{
6477 ast_dump_context->ostream() << "concat(";
6478 ast_dump_context->dump_expression_list(this->exprs_, false);
6479 ast_dump_context->ostream() << ")";
6480}
6481
6482Expression*
6483Expression::make_string_concat(Expression_list* exprs)
6484{
6485 return new String_concat_expression(exprs);
6486}
6487
e440a328 6488// Class Bound_method_expression.
6489
6490// Traversal.
6491
6492int
6493Bound_method_expression::do_traverse(Traverse* traverse)
6494{
e0659c9e 6495 return Expression::traverse(&this->expr_, traverse);
e440a328 6496}
6497
6498// Return the type of a bound method expression. The type of this
0afbb937 6499// object is simply the type of the method with no receiver.
e440a328 6500
6501Type*
6502Bound_method_expression::do_type()
6503{
0afbb937 6504 Named_object* fn = this->method_->named_object();
6505 Function_type* fntype;
6506 if (fn->is_function())
6507 fntype = fn->func_value()->type();
6508 else if (fn->is_function_declaration())
6509 fntype = fn->func_declaration_value()->type();
e0659c9e 6510 else
6511 return Type::make_error_type();
0afbb937 6512 return fntype->copy_without_receiver();
e440a328 6513}
6514
6515// Determine the types of a method expression.
6516
6517void
6518Bound_method_expression::do_determine_type(const Type_context*)
6519{
0afbb937 6520 Named_object* fn = this->method_->named_object();
6521 Function_type* fntype;
6522 if (fn->is_function())
6523 fntype = fn->func_value()->type();
6524 else if (fn->is_function_declaration())
6525 fntype = fn->func_declaration_value()->type();
6526 else
6527 fntype = NULL;
e440a328 6528 if (fntype == NULL || !fntype->is_method())
6529 this->expr_->determine_type_no_context();
6530 else
6531 {
6532 Type_context subcontext(fntype->receiver()->type(), false);
6533 this->expr_->determine_type(&subcontext);
6534 }
6535}
6536
6537// Check the types of a method expression.
6538
6539void
6540Bound_method_expression::do_check_types(Gogo*)
6541{
0afbb937 6542 Named_object* fn = this->method_->named_object();
6543 if (!fn->is_function() && !fn->is_function_declaration())
6544 {
6545 this->report_error(_("object is not a method"));
6546 return;
6547 }
6548
6549 Function_type* fntype;
6550 if (fn->is_function())
6551 fntype = fn->func_value()->type();
6552 else if (fn->is_function_declaration())
6553 fntype = fn->func_declaration_value()->type();
e440a328 6554 else
0afbb937 6555 go_unreachable();
6556 Type* rtype = fntype->receiver()->type()->deref();
6557 Type* etype = (this->expr_type_ != NULL
6558 ? this->expr_type_
6559 : this->expr_->type());
6560 etype = etype->deref();
6561 if (!Type::are_identical(rtype, etype, true, NULL))
6562 this->report_error(_("method type does not match object type"));
6563}
6564
6565// If a bound method expression is not simply called, then it is
6566// represented as a closure. The closure will hold a single variable,
6567// the receiver to pass to the method. The function will be a simple
6568// thunk that pulls that value from the closure and calls the method
6569// with the remaining arguments.
6570//
6571// Because method values are not common, we don't build all thunks for
6572// every methods, but instead only build them as we need them. In
6573// particular, we even build them on demand for methods defined in
6574// other packages.
6575
6576Bound_method_expression::Method_value_thunks
6577 Bound_method_expression::method_value_thunks;
6578
6579// Find or create the thunk for METHOD.
6580
6581Named_object*
6582Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6583 Named_object* fn)
6584{
6585 std::pair<Named_object*, Named_object*> val(fn, NULL);
6586 std::pair<Method_value_thunks::iterator, bool> ins =
6587 Bound_method_expression::method_value_thunks.insert(val);
6588 if (!ins.second)
6589 {
6590 // We have seen this method before.
6591 go_assert(ins.first->second != NULL);
6592 return ins.first->second;
6593 }
6594
6595 Location loc = fn->location();
6596
6597 Function_type* orig_fntype;
6598 if (fn->is_function())
6599 orig_fntype = fn->func_value()->type();
6600 else if (fn->is_function_declaration())
6601 orig_fntype = fn->func_declaration_value()->type();
6602 else
6603 orig_fntype = NULL;
6604
6605 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6606 {
0afbb937 6607 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6608 return ins.first->second;
e440a328 6609 }
0afbb937 6610
6611 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6612 // The type here is wrong--it should be the C function type. But it
6613 // doesn't really matter.
0afbb937 6614 Type* vt = Type::make_pointer_type(Type::make_void_type());
6615 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6616 sfl->push_back(Struct_field(Typed_identifier("val.1",
6617 orig_fntype->receiver()->type(),
6618 loc)));
6619 Type* closure_type = Type::make_struct_type(sfl, loc);
6620 closure_type = Type::make_pointer_type(closure_type);
6621
f8bdf81a 6622 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6623
da244e59 6624 std::string thunk_name = Gogo::thunk_name();
6625 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
0afbb937 6626 false, loc);
6627
f8bdf81a 6628 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6629 cvar->set_is_used();
1ecc6157 6630 cvar->set_is_closure();
da244e59 6631 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6632 NULL, cvar);
f8bdf81a 6633 new_no->func_value()->set_closure_var(cp);
0afbb937 6634
f8bdf81a 6635 gogo->start_block(loc);
0afbb937 6636
6637 // Field 0 of the closure is the function code pointer, field 1 is
6638 // the value on which to invoke the method.
6639 Expression* arg = Expression::make_var_reference(cp, loc);
6640 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6641 arg = Expression::make_field_reference(arg, 1, loc);
6642
6643 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6644
6645 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6646 Expression_list* args;
6647 if (orig_params == NULL || orig_params->empty())
6648 args = NULL;
6649 else
6650 {
6651 const Typed_identifier_list* new_params = new_fntype->parameters();
6652 args = new Expression_list();
6653 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6654 p != new_params->end();
0afbb937 6655 ++p)
6656 {
6657 Named_object* p_no = gogo->lookup(p->name(), NULL);
6658 go_assert(p_no != NULL
6659 && p_no->is_variable()
6660 && p_no->var_value()->is_parameter());
6661 args->push_back(Expression::make_var_reference(p_no, loc));
6662 }
6663 }
6664
6665 Call_expression* call = Expression::make_call(bme, args,
6666 orig_fntype->is_varargs(),
6667 loc);
6668 call->set_varargs_are_lowered();
6669
6670 Statement* s = Statement::make_return_from_call(call, loc);
6671 gogo->add_statement(s);
6672 Block* b = gogo->finish_block(loc);
6673 gogo->add_block(b, loc);
6674 gogo->lower_block(new_no, b);
a32698ee 6675 gogo->flatten_block(new_no, b);
0afbb937 6676 gogo->finish_function(loc);
6677
6678 ins.first->second = new_no;
6679 return new_no;
6680}
6681
6682// Return an expression to check *REF for nil while dereferencing
6683// according to FIELD_INDEXES. Update *REF to build up the field
6684// reference. This is a static function so that we don't have to
6685// worry about declaring Field_indexes in expressions.h.
6686
6687static Expression*
6688bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6689 Expression** ref)
6690{
6691 if (field_indexes == NULL)
6692 return Expression::make_boolean(false, loc);
6693 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6694 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6695 go_assert(stype != NULL
6696 && field_indexes->field_index < stype->field_count());
6697 if ((*ref)->type()->struct_type() == NULL)
6698 {
6699 go_assert((*ref)->type()->points_to() != NULL);
6700 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6701 Expression::make_nil(loc),
6702 loc);
6703 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6704 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6705 go_assert((*ref)->type()->struct_type() == stype);
6706 }
6707 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6708 loc);
6709 return cond;
e440a328 6710}
6711
cd39797e 6712// Flatten a method value into a struct with nil checks. We can't do
6713// this in the lowering phase, because if the method value is called
6714// directly we don't need a thunk. That case will have been handled
6715// by Call_expression::do_lower, so if we get here then we do need a
6716// thunk.
e440a328 6717
cd39797e 6718Expression*
6719Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6720 Statement_inserter* inserter)
e440a328 6721{
cd39797e 6722 Location loc = this->location();
6723
6724 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
0afbb937 6725 this->method_,
6726 this->function_);
6727 if (thunk->is_erroneous())
6728 {
6729 go_assert(saw_errors());
cd39797e 6730 return Expression::make_error(loc);
0afbb937 6731 }
6732
cd39797e 6733 // Force the expression into a variable. This is only necessary if
6734 // we are going to do nil checks below, but it's easy enough to
6735 // always do it.
6736 Expression* expr = this->expr_;
6737 if (!expr->is_variable())
6738 {
6739 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6740 inserter->insert(etemp);
6741 expr = Expression::make_temporary_reference(etemp, loc);
6742 }
0afbb937 6743
6744 // If the method expects a value, and we have a pointer, we need to
6745 // dereference the pointer.
6746
6747 Named_object* fn = this->method_->named_object();
cd39797e 6748 Function_type *fntype;
0afbb937 6749 if (fn->is_function())
6750 fntype = fn->func_value()->type();
6751 else if (fn->is_function_declaration())
6752 fntype = fn->func_declaration_value()->type();
6753 else
6754 go_unreachable();
6755
cd39797e 6756 Expression* val = expr;
0afbb937 6757 if (fntype->receiver()->type()->points_to() == NULL
6758 && val->type()->points_to() != NULL)
6759 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6760
6761 // Note that we are ignoring this->expr_type_ here. The thunk will
6762 // expect a closure whose second field has type this->expr_type_ (if
6763 // that is not NULL). We are going to pass it a closure whose
6764 // second field has type this->expr_->type(). Since
6765 // this->expr_type_ is only not-NULL for pointer types, we can get
6766 // away with this.
6767
6768 Struct_field_list* fields = new Struct_field_list();
6769 fields->push_back(Struct_field(Typed_identifier("fn.0",
6770 thunk->func_value()->type(),
6771 loc)));
6772 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6773 Struct_type* st = Type::make_struct_type(fields, loc);
6774
6775 Expression_list* vals = new Expression_list();
6776 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6777 vals->push_back(val);
6778
6779 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
0afbb937 6780
cd39797e 6781 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
6782 ret = Expression::make_heap_expression(ret, loc);
6783 else
6784 {
6785 // When compiling the runtime, method closures do not escape.
6786 // When escape analysis becomes the default, and applies to
6787 // method closures, this should be changed to make it an error
6788 // if a method closure escapes.
6789 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
6790 inserter->insert(ctemp);
6791 ret = Expression::make_temporary_reference(ctemp, loc);
6792 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
6793 ret->unary_expression()->set_does_not_escape();
6794 }
6795
6796 // If necessary, check whether the expression or any embedded
6797 // pointers are nil.
0afbb937 6798
df7ef1fd 6799 Expression* nil_check = NULL;
0afbb937 6800 if (this->method_->field_indexes() != NULL)
6801 {
0afbb937 6802 Expression* ref = expr;
6803 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6804 expr = ref;
6805 }
6806
6807 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6808 {
6809 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6810 Expression::make_nil(loc),
6811 loc);
6812 if (nil_check == NULL)
6813 nil_check = n;
6814 else
6815 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6816 }
6817
6818 if (nil_check != NULL)
6819 {
cd39797e 6820 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6821 loc);
6822 // Fix the type of the conditional expression by pretending to
6823 // evaluate to RET either way through the conditional.
6824 crash = Expression::make_compound(crash, ret, loc);
6825 ret = Expression::make_conditional(nil_check, crash, ret, loc);
6826 }
6827
6828 // RET is a pointer to a struct, but we want a function type.
6829 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
6830
6831 return ret;
e440a328 6832}
6833
d751bb78 6834// Dump ast representation of a bound method expression.
6835
6836void
6837Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6838 const
6839{
6840 if (this->expr_type_ != NULL)
6841 ast_dump_context->ostream() << "(";
6842 ast_dump_context->dump_expression(this->expr_);
6843 if (this->expr_type_ != NULL)
6844 {
6845 ast_dump_context->ostream() << ":";
6846 ast_dump_context->dump_type(this->expr_type_);
6847 ast_dump_context->ostream() << ")";
6848 }
6849
0afbb937 6850 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6851}
6852
e440a328 6853// Make a method expression.
6854
6855Bound_method_expression*
0afbb937 6856Expression::make_bound_method(Expression* expr, const Method* method,
6857 Named_object* function, Location location)
e440a328 6858{
0afbb937 6859 return new Bound_method_expression(expr, method, function, location);
e440a328 6860}
6861
6862// Class Builtin_call_expression. This is used for a call to a
6863// builtin function.
6864
6865class Builtin_call_expression : public Call_expression
6866{
6867 public:
6868 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6869 bool is_varargs, Location location);
e440a328 6870
6871 protected:
6872 // This overrides Call_expression::do_lower.
6873 Expression*
ceeb4318 6874 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6875
35a54f17 6876 Expression*
6877 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6878
e440a328 6879 bool
6880 do_is_constant() const;
6881
6882 bool
0c77715b 6883 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6884
4f2138d7 6885 bool
a7549a6a 6886 do_discarding_value();
6887
e440a328 6888 Type*
6889 do_type();
6890
6891 void
6892 do_determine_type(const Type_context*);
6893
6894 void
6895 do_check_types(Gogo*);
6896
6897 Expression*
72666aed 6898 do_copy();
e440a328 6899
ea664253 6900 Bexpression*
6901 do_get_backend(Translate_context*);
e440a328 6902
6903 void
6904 do_export(Export*) const;
6905
6906 virtual bool
6907 do_is_recover_call() const;
6908
6909 virtual void
6910 do_set_recover_arg(Expression*);
6911
6912 private:
6913 // The builtin functions.
6914 enum Builtin_function_code
6915 {
6916 BUILTIN_INVALID,
6917
6918 // Predeclared builtin functions.
6919 BUILTIN_APPEND,
6920 BUILTIN_CAP,
6921 BUILTIN_CLOSE,
48080209 6922 BUILTIN_COMPLEX,
e440a328 6923 BUILTIN_COPY,
1cce762f 6924 BUILTIN_DELETE,
e440a328 6925 BUILTIN_IMAG,
6926 BUILTIN_LEN,
6927 BUILTIN_MAKE,
6928 BUILTIN_NEW,
6929 BUILTIN_PANIC,
6930 BUILTIN_PRINT,
6931 BUILTIN_PRINTLN,
6932 BUILTIN_REAL,
6933 BUILTIN_RECOVER,
6934
6935 // Builtin functions from the unsafe package.
6936 BUILTIN_ALIGNOF,
6937 BUILTIN_OFFSETOF,
6938 BUILTIN_SIZEOF
6939 };
6940
6941 Expression*
6942 one_arg() const;
6943
6944 bool
6945 check_one_arg();
6946
6947 static Type*
6948 real_imag_type(Type*);
6949
6950 static Type*
48080209 6951 complex_type(Type*);
e440a328 6952
a9182619 6953 Expression*
321e5ad2 6954 lower_make(Statement_inserter*);
6955
6956 Expression* flatten_append(Gogo*, Named_object*, Statement_inserter*);
a9182619 6957
6958 bool
1ad00fd4 6959 check_int_value(Expression*, bool is_length);
a9182619 6960
e440a328 6961 // A pointer back to the general IR structure. This avoids a global
6962 // variable, or passing it around everywhere.
6963 Gogo* gogo_;
6964 // The builtin function being called.
6965 Builtin_function_code code_;
0f914071 6966 // Used to stop endless loops when the length of an array uses len
6967 // or cap of the array itself.
6968 mutable bool seen_;
6334270b 6969 // Whether the argument is set for calls to BUILTIN_RECOVER.
6970 bool recover_arg_is_set_;
e440a328 6971};
6972
6973Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6974 Expression* fn,
6975 Expression_list* args,
6976 bool is_varargs,
b13c66cd 6977 Location location)
e440a328 6978 : Call_expression(fn, args, is_varargs, location),
6334270b 6979 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
6980 recover_arg_is_set_(false)
e440a328 6981{
6982 Func_expression* fnexp = this->fn()->func_expression();
79651b1f 6983 if (fnexp == NULL)
6984 {
6985 this->code_ = BUILTIN_INVALID;
6986 return;
6987 }
e440a328 6988 const std::string& name(fnexp->named_object()->name());
6989 if (name == "append")
6990 this->code_ = BUILTIN_APPEND;
6991 else if (name == "cap")
6992 this->code_ = BUILTIN_CAP;
6993 else if (name == "close")
6994 this->code_ = BUILTIN_CLOSE;
48080209 6995 else if (name == "complex")
6996 this->code_ = BUILTIN_COMPLEX;
e440a328 6997 else if (name == "copy")
6998 this->code_ = BUILTIN_COPY;
1cce762f 6999 else if (name == "delete")
7000 this->code_ = BUILTIN_DELETE;
e440a328 7001 else if (name == "imag")
7002 this->code_ = BUILTIN_IMAG;
7003 else if (name == "len")
7004 this->code_ = BUILTIN_LEN;
7005 else if (name == "make")
7006 this->code_ = BUILTIN_MAKE;
7007 else if (name == "new")
7008 this->code_ = BUILTIN_NEW;
7009 else if (name == "panic")
7010 this->code_ = BUILTIN_PANIC;
7011 else if (name == "print")
7012 this->code_ = BUILTIN_PRINT;
7013 else if (name == "println")
7014 this->code_ = BUILTIN_PRINTLN;
7015 else if (name == "real")
7016 this->code_ = BUILTIN_REAL;
7017 else if (name == "recover")
7018 this->code_ = BUILTIN_RECOVER;
7019 else if (name == "Alignof")
7020 this->code_ = BUILTIN_ALIGNOF;
7021 else if (name == "Offsetof")
7022 this->code_ = BUILTIN_OFFSETOF;
7023 else if (name == "Sizeof")
7024 this->code_ = BUILTIN_SIZEOF;
7025 else
c3e6f413 7026 go_unreachable();
e440a328 7027}
7028
7029// Return whether this is a call to recover. This is a virtual
7030// function called from the parent class.
7031
7032bool
7033Builtin_call_expression::do_is_recover_call() const
7034{
7035 if (this->classification() == EXPRESSION_ERROR)
7036 return false;
7037 return this->code_ == BUILTIN_RECOVER;
7038}
7039
7040// Set the argument for a call to recover.
7041
7042void
7043Builtin_call_expression::do_set_recover_arg(Expression* arg)
7044{
7045 const Expression_list* args = this->args();
c484d925 7046 go_assert(args == NULL || args->empty());
e440a328 7047 Expression_list* new_args = new Expression_list();
7048 new_args->push_back(arg);
7049 this->set_args(new_args);
6334270b 7050 this->recover_arg_is_set_ = true;
e440a328 7051}
7052
e440a328 7053// Lower a builtin call expression. This turns new and make into
7054// specific expressions. We also convert to a constant if we can.
7055
7056Expression*
321e5ad2 7057Builtin_call_expression::do_lower(Gogo*, Named_object* function,
ceeb4318 7058 Statement_inserter* inserter, int)
e440a328 7059{
79651b1f 7060 if (this->is_error_expression())
a9182619 7061 return this;
7062
b13c66cd 7063 Location loc = this->location();
1cce762f 7064
a8725655 7065 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7066 {
7067 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 7068 return Expression::make_error(loc);
a8725655 7069 }
7070
393ba00b 7071 if (this->code_ == BUILTIN_OFFSETOF)
7072 {
7073 Expression* arg = this->one_arg();
12e69faa 7074
7075 if (arg->bound_method_expression() != NULL
7076 || arg->interface_field_reference_expression() != NULL)
7077 {
7078 this->report_error(_("invalid use of method value as argument "
7079 "of Offsetof"));
7080 return this;
7081 }
7082
393ba00b 7083 Field_reference_expression* farg = arg->field_reference_expression();
7084 while (farg != NULL)
7085 {
7086 if (!farg->implicit())
7087 break;
7088 // When the selector refers to an embedded field,
7089 // it must not be reached through pointer indirections.
7090 if (farg->expr()->deref() != farg->expr())
7091 {
12e69faa 7092 this->report_error(_("argument of Offsetof implies "
7093 "indirection of an embedded field"));
393ba00b 7094 return this;
7095 }
7096 // Go up until we reach the original base.
7097 farg = farg->expr()->field_reference_expression();
7098 }
7099 }
7100
1cce762f 7101 if (this->is_constant())
e440a328 7102 {
0c77715b 7103 Numeric_constant nc;
7104 if (this->numeric_constant_value(&nc))
7105 return nc.expression(loc);
e440a328 7106 }
1cce762f 7107
7108 switch (this->code_)
e440a328 7109 {
1cce762f 7110 default:
7111 break;
7112
7113 case BUILTIN_NEW:
7114 {
7115 const Expression_list* args = this->args();
7116 if (args == NULL || args->size() < 1)
7117 this->report_error(_("not enough arguments"));
7118 else if (args->size() > 1)
7119 this->report_error(_("too many arguments"));
7120 else
7121 {
7122 Expression* arg = args->front();
7123 if (!arg->is_type_expression())
7124 {
631d5788 7125 go_error_at(arg->location(), "expected type");
1cce762f 7126 this->set_is_error();
7127 }
7128 else
7129 return Expression::make_allocation(arg->type(), loc);
7130 }
7131 }
7132 break;
7133
7134 case BUILTIN_MAKE:
321e5ad2 7135 return this->lower_make(inserter);
1cce762f 7136
7137 case BUILTIN_RECOVER:
e440a328 7138 if (function != NULL)
7139 function->func_value()->set_calls_recover();
7140 else
7141 {
7142 // Calling recover outside of a function always returns the
7143 // nil empty interface.
823c7e3d 7144 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 7145 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 7146 }
1cce762f 7147 break;
7148
1cce762f 7149 case BUILTIN_DELETE:
7150 {
7151 // Lower to a runtime function call.
7152 const Expression_list* args = this->args();
7153 if (args == NULL || args->size() < 2)
7154 this->report_error(_("not enough arguments"));
7155 else if (args->size() > 2)
7156 this->report_error(_("too many arguments"));
7157 else if (args->front()->type()->map_type() == NULL)
7158 this->report_error(_("argument 1 must be a map"));
7159 else
7160 {
7161 // Since this function returns no value it must appear in
7162 // a statement by itself, so we don't have to worry about
7163 // order of evaluation of values around it. Evaluate the
7164 // map first to get order of evaluation right.
7165 Map_type* mt = args->front()->type()->map_type();
7166 Temporary_statement* map_temp =
7167 Statement::make_temporary(mt, args->front(), loc);
7168 inserter->insert(map_temp);
7169
7170 Temporary_statement* key_temp =
7171 Statement::make_temporary(mt->key_type(), args->back(), loc);
7172 inserter->insert(key_temp);
7173
0d5530d9 7174 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7175 Expression* e2 = Expression::make_temporary_reference(map_temp,
1cce762f 7176 loc);
0d5530d9 7177 Expression* e3 = Expression::make_temporary_reference(key_temp,
1cce762f 7178 loc);
0d5530d9 7179 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
1cce762f 7180 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
0d5530d9 7181 3, e1, e2, e3);
1cce762f 7182 }
7183 }
7184 break;
88b03a70 7185
7186 case BUILTIN_PRINT:
7187 case BUILTIN_PRINTLN:
7188 // Force all the arguments into temporary variables, so that we
7189 // don't try to evaluate something while holding the print lock.
7190 if (this->args() == NULL)
7191 break;
7192 for (Expression_list::iterator pa = this->args()->begin();
7193 pa != this->args()->end();
7194 ++pa)
7195 {
7196 if (!(*pa)->is_variable())
7197 {
7198 Temporary_statement* temp =
7199 Statement::make_temporary(NULL, *pa, loc);
7200 inserter->insert(temp);
7201 *pa = Expression::make_temporary_reference(temp, loc);
7202 }
7203 }
7204 break;
e440a328 7205 }
7206
7207 return this;
7208}
7209
35a54f17 7210// Flatten a builtin call expression. This turns the arguments of copy and
7211// append into temporary expressions.
7212
7213Expression*
321e5ad2 7214Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
35a54f17 7215 Statement_inserter* inserter)
7216{
16cb7fec 7217 Location loc = this->location();
7218
7219 switch (this->code_)
35a54f17 7220 {
16cb7fec 7221 default:
7222 break;
7223
7224 case BUILTIN_APPEND:
321e5ad2 7225 return this->flatten_append(gogo, function, inserter);
7226
16cb7fec 7227 case BUILTIN_COPY:
7228 {
7229 Type* at = this->args()->front()->type();
7230 for (Expression_list::iterator pa = this->args()->begin();
7231 pa != this->args()->end();
7232 ++pa)
7233 {
7234 if ((*pa)->is_nil_expression())
7235 {
7236 Expression* nil = Expression::make_nil(loc);
7237 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7238 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7239 }
7240 if (!(*pa)->is_variable())
7241 {
7242 Temporary_statement* temp =
7243 Statement::make_temporary(NULL, *pa, loc);
7244 inserter->insert(temp);
7245 *pa = Expression::make_temporary_reference(temp, loc);
7246 }
7247 }
7248 }
7249 break;
7250
7251 case BUILTIN_PANIC:
35a54f17 7252 for (Expression_list::iterator pa = this->args()->begin();
16cb7fec 7253 pa != this->args()->end();
7254 ++pa)
7255 {
7256 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
55e8ba6a 7257 {
16cb7fec 7258 Temporary_statement* temp =
7259 Statement::make_temporary(NULL, *pa, loc);
7260 inserter->insert(temp);
7261 *pa = Expression::make_temporary_reference(temp, loc);
55e8ba6a 7262 }
16cb7fec 7263 }
7739537f 7264 break;
0d5530d9 7265
7266 case BUILTIN_LEN:
132ed071 7267 case BUILTIN_CAP:
321e5ad2 7268 {
7269 Expression_list::iterator pa = this->args()->begin();
7270 if (!(*pa)->is_variable()
7271 && ((*pa)->type()->map_type() != NULL
7272 || (*pa)->type()->channel_type() != NULL))
7273 {
7274 Temporary_statement* temp =
7275 Statement::make_temporary(NULL, *pa, loc);
7276 inserter->insert(temp);
7277 *pa = Expression::make_temporary_reference(temp, loc);
7278 }
7279 }
7280 break;
35a54f17 7281 }
16cb7fec 7282
35a54f17 7283 return this;
7284}
7285
a9182619 7286// Lower a make expression.
7287
7288Expression*
321e5ad2 7289Builtin_call_expression::lower_make(Statement_inserter* inserter)
a9182619 7290{
b13c66cd 7291 Location loc = this->location();
a9182619 7292
7293 const Expression_list* args = this->args();
7294 if (args == NULL || args->size() < 1)
7295 {
7296 this->report_error(_("not enough arguments"));
7297 return Expression::make_error(this->location());
7298 }
7299
7300 Expression_list::const_iterator parg = args->begin();
7301
7302 Expression* first_arg = *parg;
7303 if (!first_arg->is_type_expression())
7304 {
631d5788 7305 go_error_at(first_arg->location(), "expected type");
a9182619 7306 this->set_is_error();
7307 return Expression::make_error(this->location());
7308 }
7309 Type* type = first_arg->type();
7310
7311 bool is_slice = false;
7312 bool is_map = false;
7313 bool is_chan = false;
411eb89e 7314 if (type->is_slice_type())
a9182619 7315 is_slice = true;
7316 else if (type->map_type() != NULL)
7317 is_map = true;
7318 else if (type->channel_type() != NULL)
7319 is_chan = true;
7320 else
7321 {
7322 this->report_error(_("invalid type for make function"));
7323 return Expression::make_error(this->location());
7324 }
7325
f6bc81e6 7326 Type_context int_context(Type::lookup_integer_type("int"), false);
7327
a9182619 7328 ++parg;
7329 Expression* len_arg;
7330 if (parg == args->end())
7331 {
7332 if (is_slice)
7333 {
7334 this->report_error(_("length required when allocating a slice"));
7335 return Expression::make_error(this->location());
7336 }
e67508fa 7337 len_arg = Expression::make_integer_ul(0, NULL, loc);
a9182619 7338 }
7339 else
7340 {
7341 len_arg = *parg;
f6bc81e6 7342 len_arg->determine_type(&int_context);
1ad00fd4 7343 if (!this->check_int_value(len_arg, true))
7344 return Expression::make_error(this->location());
a9182619 7345 ++parg;
7346 }
7347
7348 Expression* cap_arg = NULL;
7349 if (is_slice && parg != args->end())
7350 {
7351 cap_arg = *parg;
f6bc81e6 7352 cap_arg->determine_type(&int_context);
1ad00fd4 7353 if (!this->check_int_value(cap_arg, false))
7354 return Expression::make_error(this->location());
7355
7356 Numeric_constant nclen;
7357 Numeric_constant nccap;
7358 unsigned long vlen;
7359 unsigned long vcap;
7360 if (len_arg->numeric_constant_value(&nclen)
7361 && cap_arg->numeric_constant_value(&nccap)
7362 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7363 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7364 && vlen > vcap)
a9182619 7365 {
1ad00fd4 7366 this->report_error(_("len larger than cap"));
a9182619 7367 return Expression::make_error(this->location());
7368 }
1ad00fd4 7369
a9182619 7370 ++parg;
7371 }
7372
7373 if (parg != args->end())
7374 {
7375 this->report_error(_("too many arguments to make"));
7376 return Expression::make_error(this->location());
7377 }
7378
b13c66cd 7379 Location type_loc = first_arg->location();
a9182619 7380
7381 Expression* call;
7382 if (is_slice)
7383 {
321e5ad2 7384 Type* et = type->array_type()->element_type();
7385 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
a9182619 7386 if (cap_arg == NULL)
321e5ad2 7387 {
7388 Temporary_statement* temp = Statement::make_temporary(NULL,
7389 len_arg,
7390 loc);
7391 inserter->insert(temp);
7392 len_arg = Expression::make_temporary_reference(temp, loc);
7393 cap_arg = Expression::make_temporary_reference(temp, loc);
7394 }
7395 call = Runtime::make_call(Runtime::MAKESLICE, loc, 3, type_arg,
7396 len_arg, cap_arg);
a9182619 7397 }
7398 else if (is_map)
321e5ad2 7399 {
7400 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7401 call = Runtime::make_call(Runtime::MAKEMAP, loc, 4, type_arg, len_arg,
7402 Expression::make_nil(loc),
7403 Expression::make_nil(loc));
7404 }
a9182619 7405 else if (is_chan)
321e5ad2 7406 {
7407 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7408 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7409 }
a9182619 7410 else
7411 go_unreachable();
7412
7413 return Expression::make_unsafe_cast(type, call, loc);
7414}
7415
321e5ad2 7416// Flatten a call to the predeclared append function. We do this in
7417// the flatten phase, not the lowering phase, so that we run after
7418// type checking and after order_evaluations.
7419
7420Expression*
7421Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7422 Statement_inserter* inserter)
7423{
7424 if (this->is_error_expression())
7425 return this;
7426
7427 Location loc = this->location();
7428
7429 const Expression_list* args = this->args();
7430 go_assert(args != NULL && !args->empty());
7431
7432 Type* slice_type = args->front()->type();
7433 go_assert(slice_type->is_slice_type());
7434 Type* element_type = slice_type->array_type()->element_type();
7435
7436 if (args->size() == 1)
7437 {
7438 // append(s) evaluates to s.
7439 return args->front();
7440 }
7441
7442 Type* int_type = Type::lookup_integer_type("int");
7443 Type* uint_type = Type::lookup_integer_type("uint");
7444
7445 // Implementing
7446 // append(s1, s2...)
7447 // or
7448 // append(s1, a1, a2, a3, ...)
7449
7450 // s1tmp := s1
7451 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7452 loc);
7453 inserter->insert(s1tmp);
7454
7455 // l1tmp := len(s1tmp)
7456 Named_object* lenfn = gogo->lookup_global("len");
7457 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7458 Expression_list* call_args = new Expression_list();
7459 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7460 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7461 gogo->lower_expression(function, inserter, &len);
7462 gogo->flatten_expression(function, inserter, &len);
7463 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7464 inserter->insert(l1tmp);
7465
7466 Temporary_statement* s2tmp = NULL;
7467 Temporary_statement* l2tmp = NULL;
7468 Expression_list* add = NULL;
7469 Expression* len2;
7470 if (this->is_varargs())
7471 {
7472 go_assert(args->size() == 2);
7473
7474 // s2tmp := s2
7475 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7476 inserter->insert(s2tmp);
7477
7478 // l2tmp := len(s2tmp)
7479 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7480 call_args = new Expression_list();
7481 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7482 len = Expression::make_call(lenref, call_args, false, loc);
7483 gogo->lower_expression(function, inserter, &len);
7484 gogo->flatten_expression(function, inserter, &len);
7485 l2tmp = Statement::make_temporary(int_type, len, loc);
7486 inserter->insert(l2tmp);
7487
7488 // len2 = l2tmp
7489 len2 = Expression::make_temporary_reference(l2tmp, loc);
7490 }
7491 else
7492 {
7493 // We have to ensure that all the arguments are in variables
7494 // now, because otherwise if one of them is an index expression
7495 // into the current slice we could overwrite it before we fetch
7496 // it.
7497 add = new Expression_list();
7498 Expression_list::const_iterator pa = args->begin();
7499 for (++pa; pa != args->end(); ++pa)
7500 {
7501 if ((*pa)->is_variable())
7502 add->push_back(*pa);
7503 else
7504 {
7505 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7506 loc);
7507 inserter->insert(tmp);
7508 add->push_back(Expression::make_temporary_reference(tmp, loc));
7509 }
7510 }
7511
7512 // len2 = len(add)
7513 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7514 }
7515
7516 // ntmp := l1tmp + len2
7517 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7518 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7519 gogo->lower_expression(function, inserter, &sum);
7520 gogo->flatten_expression(function, inserter, &sum);
7521 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7522 inserter->insert(ntmp);
7523
7524 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7525 // growslice(type, s1tmp, ntmp) :
7526 // s1tmp[:ntmp]
7527 // Using uint here means that if the computation of ntmp overflowed,
7528 // we will call growslice which will panic.
7529
7530 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7531 left = Expression::make_cast(uint_type, left, loc);
7532
7533 Named_object* capfn = gogo->lookup_global("cap");
7534 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7535 call_args = new Expression_list();
7536 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7537 Expression* right = Expression::make_call(capref, call_args, false, loc);
7538 right = Expression::make_cast(uint_type, right, loc);
7539
7540 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7541
7542 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7543 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7544 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7545 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7546 a1, a2, a3);
7547 call = Expression::make_unsafe_cast(slice_type, call, loc);
7548
7549 ref = Expression::make_temporary_reference(s1tmp, loc);
7550 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7551 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7552 // FIXME: Mark this index as not requiring bounds checks.
7553 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7554
7555 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7556
7557 gogo->lower_expression(function, inserter, &rhs);
7558 gogo->flatten_expression(function, inserter, &rhs);
7559
7560 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7561 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7562 inserter->insert(assign);
7563
7564 if (this->is_varargs())
7565 {
7566 // copy(s1tmp[l1tmp:], s2tmp)
7567 a1 = Expression::make_temporary_reference(s1tmp, loc);
7568 ref = Expression::make_temporary_reference(l1tmp, loc);
7569 Expression* nil = Expression::make_nil(loc);
7570 // FIXME: Mark this index as not requiring bounds checks.
7571 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7572
7573 a2 = Expression::make_temporary_reference(s2tmp, loc);
7574
7575 Named_object* copyfn = gogo->lookup_global("copy");
7576 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7577 call_args = new Expression_list();
7578 call_args->push_back(a1);
7579 call_args->push_back(a2);
7580 call = Expression::make_call(copyref, call_args, false, loc);
7581 gogo->lower_expression(function, inserter, &call);
7582 gogo->flatten_expression(function, inserter, &call);
7583 inserter->insert(Statement::make_statement(call, false));
7584 }
7585 else
7586 {
7587 // For each argument:
7588 // s1tmp[l1tmp+i] = a
7589 unsigned long i = 0;
7590 for (Expression_list::const_iterator pa = add->begin();
7591 pa != add->end();
7592 ++pa, ++i)
7593 {
7594 ref = Expression::make_temporary_reference(s1tmp, loc);
7595 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7596 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7597 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7598 // FIXME: Mark this index as not requiring bounds checks.
7599 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7600 gogo->lower_expression(function, inserter, &lhs);
7601 gogo->flatten_expression(function, inserter, &lhs);
7602 assign = Statement::make_assignment(lhs, *pa, loc);
7603 inserter->insert(assign);
7604 }
7605 }
7606
7607 return Expression::make_temporary_reference(s1tmp, loc);
7608}
7609
a9182619 7610// Return whether an expression has an integer value. Report an error
7611// if not. This is used when handling calls to the predeclared make
7612// function.
7613
7614bool
1ad00fd4 7615Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7616{
0c77715b 7617 Numeric_constant nc;
1ad00fd4 7618 if (e->numeric_constant_value(&nc))
a9182619 7619 {
1ad00fd4 7620 unsigned long v;
7621 switch (nc.to_unsigned_long(&v))
7622 {
7623 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7624 break;
1ad00fd4 7625 case Numeric_constant::NC_UL_NOTINT:
631d5788 7626 go_error_at(e->location(), "non-integer %s argument to make",
7627 is_length ? "len" : "cap");
1ad00fd4 7628 return false;
7629 case Numeric_constant::NC_UL_NEGATIVE:
631d5788 7630 go_error_at(e->location(), "negative %s argument to make",
7631 is_length ? "len" : "cap");
1ad00fd4 7632 return false;
7633 case Numeric_constant::NC_UL_BIG:
7634 // We don't want to give a compile-time error for a 64-bit
7635 // value on a 32-bit target.
1b10c5e7 7636 break;
1ad00fd4 7637 }
1b10c5e7 7638
7639 mpz_t val;
7640 if (!nc.to_int(&val))
7641 go_unreachable();
7642 int bits = mpz_sizeinbase(val, 2);
7643 mpz_clear(val);
7644 Type* int_type = Type::lookup_integer_type("int");
7645 if (bits >= int_type->integer_type()->bits())
7646 {
631d5788 7647 go_error_at(e->location(), "%s argument too large for make",
7648 is_length ? "len" : "cap");
1b10c5e7 7649 return false;
7650 }
7651
7652 return true;
a9182619 7653 }
7654
1ad00fd4 7655 if (e->type()->integer_type() != NULL)
7656 return true;
7657
631d5788 7658 go_error_at(e->location(), "non-integer %s argument to make",
7659 is_length ? "len" : "cap");
a9182619 7660 return false;
7661}
7662
e440a328 7663// Return the type of the real or imag functions, given the type of
fcbea5e4 7664// the argument. We need to map complex64 to float32 and complex128
7665// to float64, so it has to be done by name. This returns NULL if it
7666// can't figure out the type.
e440a328 7667
7668Type*
7669Builtin_call_expression::real_imag_type(Type* arg_type)
7670{
7671 if (arg_type == NULL || arg_type->is_abstract())
7672 return NULL;
7673 Named_type* nt = arg_type->named_type();
7674 if (nt == NULL)
7675 return NULL;
7676 while (nt->real_type()->named_type() != NULL)
7677 nt = nt->real_type()->named_type();
48080209 7678 if (nt->name() == "complex64")
e440a328 7679 return Type::lookup_float_type("float32");
7680 else if (nt->name() == "complex128")
7681 return Type::lookup_float_type("float64");
7682 else
7683 return NULL;
7684}
7685
48080209 7686// Return the type of the complex function, given the type of one of the
e440a328 7687// argments. Like real_imag_type, we have to map by name.
7688
7689Type*
48080209 7690Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7691{
7692 if (arg_type == NULL || arg_type->is_abstract())
7693 return NULL;
7694 Named_type* nt = arg_type->named_type();
7695 if (nt == NULL)
7696 return NULL;
7697 while (nt->real_type()->named_type() != NULL)
7698 nt = nt->real_type()->named_type();
48080209 7699 if (nt->name() == "float32")
e440a328 7700 return Type::lookup_complex_type("complex64");
7701 else if (nt->name() == "float64")
7702 return Type::lookup_complex_type("complex128");
7703 else
7704 return NULL;
7705}
7706
7707// Return a single argument, or NULL if there isn't one.
7708
7709Expression*
7710Builtin_call_expression::one_arg() const
7711{
7712 const Expression_list* args = this->args();
aa615cb3 7713 if (args == NULL || args->size() != 1)
e440a328 7714 return NULL;
7715 return args->front();
7716}
7717
83921647 7718// A traversal class which looks for a call or receive expression.
7719
7720class Find_call_expression : public Traverse
7721{
7722 public:
7723 Find_call_expression()
7724 : Traverse(traverse_expressions),
7725 found_(false)
7726 { }
7727
7728 int
7729 expression(Expression**);
7730
7731 bool
7732 found()
7733 { return this->found_; }
7734
7735 private:
7736 bool found_;
7737};
7738
7739int
7740Find_call_expression::expression(Expression** pexpr)
7741{
7742 if ((*pexpr)->call_expression() != NULL
7743 || (*pexpr)->receive_expression() != NULL)
7744 {
7745 this->found_ = true;
7746 return TRAVERSE_EXIT;
7747 }
7748 return TRAVERSE_CONTINUE;
7749}
7750
7751// Return whether this is constant: len of a string constant, or len
7752// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7753// unsafe.Alignof.
e440a328 7754
7755bool
7756Builtin_call_expression::do_is_constant() const
7757{
12e69faa 7758 if (this->is_error_expression())
7759 return true;
e440a328 7760 switch (this->code_)
7761 {
7762 case BUILTIN_LEN:
7763 case BUILTIN_CAP:
7764 {
0f914071 7765 if (this->seen_)
7766 return false;
7767
e440a328 7768 Expression* arg = this->one_arg();
7769 if (arg == NULL)
7770 return false;
7771 Type* arg_type = arg->type();
7772
7773 if (arg_type->points_to() != NULL
7774 && arg_type->points_to()->array_type() != NULL
411eb89e 7775 && !arg_type->points_to()->is_slice_type())
e440a328 7776 arg_type = arg_type->points_to();
7777
83921647 7778 // The len and cap functions are only constant if there are no
7779 // function calls or channel operations in the arguments.
7780 // Otherwise we have to make the call.
7781 if (!arg->is_constant())
7782 {
7783 Find_call_expression find_call;
7784 Expression::traverse(&arg, &find_call);
7785 if (find_call.found())
7786 return false;
7787 }
7788
e440a328 7789 if (arg_type->array_type() != NULL
7790 && arg_type->array_type()->length() != NULL)
0f914071 7791 return true;
e440a328 7792
7793 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7794 {
7795 this->seen_ = true;
7796 bool ret = arg->is_constant();
7797 this->seen_ = false;
7798 return ret;
7799 }
e440a328 7800 }
7801 break;
7802
7803 case BUILTIN_SIZEOF:
7804 case BUILTIN_ALIGNOF:
7805 return this->one_arg() != NULL;
7806
7807 case BUILTIN_OFFSETOF:
7808 {
7809 Expression* arg = this->one_arg();
7810 if (arg == NULL)
7811 return false;
7812 return arg->field_reference_expression() != NULL;
7813 }
7814
48080209 7815 case BUILTIN_COMPLEX:
e440a328 7816 {
7817 const Expression_list* args = this->args();
7818 if (args != NULL && args->size() == 2)
7819 return args->front()->is_constant() && args->back()->is_constant();
7820 }
7821 break;
7822
7823 case BUILTIN_REAL:
7824 case BUILTIN_IMAG:
7825 {
7826 Expression* arg = this->one_arg();
7827 return arg != NULL && arg->is_constant();
7828 }
7829
7830 default:
7831 break;
7832 }
7833
7834 return false;
7835}
7836
0c77715b 7837// Return a numeric constant if possible.
e440a328 7838
7839bool
0c77715b 7840Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7841{
7842 if (this->code_ == BUILTIN_LEN
7843 || this->code_ == BUILTIN_CAP)
7844 {
7845 Expression* arg = this->one_arg();
7846 if (arg == NULL)
7847 return false;
7848 Type* arg_type = arg->type();
7849
7850 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7851 {
7852 std::string sval;
7853 if (arg->string_constant_value(&sval))
7854 {
0c77715b 7855 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7856 sval.length());
e440a328 7857 return true;
7858 }
7859 }
7860
7861 if (arg_type->points_to() != NULL
7862 && arg_type->points_to()->array_type() != NULL
411eb89e 7863 && !arg_type->points_to()->is_slice_type())
e440a328 7864 arg_type = arg_type->points_to();
7865
7866 if (arg_type->array_type() != NULL
7867 && arg_type->array_type()->length() != NULL)
7868 {
0f914071 7869 if (this->seen_)
7870 return false;
e440a328 7871 Expression* e = arg_type->array_type()->length();
0f914071 7872 this->seen_ = true;
0c77715b 7873 bool r = e->numeric_constant_value(nc);
0f914071 7874 this->seen_ = false;
7875 if (r)
e440a328 7876 {
0c77715b 7877 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7878 this->location()))
7879 r = false;
e440a328 7880 }
0c77715b 7881 return r;
e440a328 7882 }
7883 }
7884 else if (this->code_ == BUILTIN_SIZEOF
7885 || this->code_ == BUILTIN_ALIGNOF)
7886 {
7887 Expression* arg = this->one_arg();
7888 if (arg == NULL)
7889 return false;
7890 Type* arg_type = arg->type();
5c13bd80 7891 if (arg_type->is_error())
e440a328 7892 return false;
7893 if (arg_type->is_abstract())
7894 return false;
2c809f8f 7895 if (this->seen_)
7896 return false;
927a01eb 7897
3f378015 7898 int64_t ret;
e440a328 7899 if (this->code_ == BUILTIN_SIZEOF)
7900 {
2c809f8f 7901 this->seen_ = true;
7902 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7903 this->seen_ = false;
7904 if (!ok)
e440a328 7905 return false;
7906 }
7907 else if (this->code_ == BUILTIN_ALIGNOF)
7908 {
2c809f8f 7909 bool ok;
7910 this->seen_ = true;
637bd3af 7911 if (arg->field_reference_expression() == NULL)
2c809f8f 7912 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 7913 else
e440a328 7914 {
7915 // Calling unsafe.Alignof(s.f) returns the alignment of
7916 // the type of f when it is used as a field in a struct.
2c809f8f 7917 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 7918 }
2c809f8f 7919 this->seen_ = false;
7920 if (!ok)
7921 return false;
e440a328 7922 }
7923 else
c3e6f413 7924 go_unreachable();
927a01eb 7925
3f378015 7926 mpz_t zval;
7927 set_mpz_from_int64(&zval, ret);
7928 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7929 mpz_clear(zval);
e440a328 7930 return true;
7931 }
7932 else if (this->code_ == BUILTIN_OFFSETOF)
7933 {
7934 Expression* arg = this->one_arg();
7935 if (arg == NULL)
7936 return false;
7937 Field_reference_expression* farg = arg->field_reference_expression();
7938 if (farg == NULL)
7939 return false;
2c809f8f 7940 if (this->seen_)
7941 return false;
7942
3f378015 7943 int64_t total_offset = 0;
9a4bd570 7944 while (true)
7945 {
7946 Expression* struct_expr = farg->expr();
7947 Type* st = struct_expr->type();
7948 if (st->struct_type() == NULL)
7949 return false;
7950 if (st->named_type() != NULL)
7951 st->named_type()->convert(this->gogo_);
3f378015 7952 int64_t offset;
2c809f8f 7953 this->seen_ = true;
7954 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7955 farg->field_index(),
7956 &offset);
7957 this->seen_ = false;
7958 if (!ok)
7959 return false;
9a4bd570 7960 total_offset += offset;
7961 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7962 {
7963 // Go up until we reach the original base.
7964 farg = struct_expr->field_reference_expression();
7965 continue;
7966 }
7967 break;
7968 }
3f378015 7969 mpz_t zval;
7970 set_mpz_from_int64(&zval, total_offset);
7971 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7972 mpz_clear(zval);
e440a328 7973 return true;
7974 }
0c77715b 7975 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 7976 {
7977 Expression* arg = this->one_arg();
7978 if (arg == NULL)
7979 return false;
7980
0c77715b 7981 Numeric_constant argnc;
7982 if (!arg->numeric_constant_value(&argnc))
7983 return false;
7984
fcbea5e4 7985 mpc_t val;
7986 if (!argnc.to_complex(&val))
0c77715b 7987 return false;
e440a328 7988
0c77715b 7989 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7990 if (this->code_ == BUILTIN_REAL)
fcbea5e4 7991 nc->set_float(type, mpc_realref(val));
0c77715b 7992 else
fcbea5e4 7993 nc->set_float(type, mpc_imagref(val));
7994 mpc_clear(val);
0c77715b 7995 return true;
e440a328 7996 }
0c77715b 7997 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 7998 {
7999 const Expression_list* args = this->args();
8000 if (args == NULL || args->size() != 2)
8001 return false;
8002
0c77715b 8003 Numeric_constant rnc;
8004 if (!args->front()->numeric_constant_value(&rnc))
8005 return false;
8006 Numeric_constant inc;
8007 if (!args->back()->numeric_constant_value(&inc))
8008 return false;
8009
8010 if (rnc.type() != NULL
8011 && !rnc.type()->is_abstract()
8012 && inc.type() != NULL
8013 && !inc.type()->is_abstract()
8014 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8015 return false;
8016
e440a328 8017 mpfr_t r;
0c77715b 8018 if (!rnc.to_float(&r))
8019 return false;
8020 mpfr_t i;
8021 if (!inc.to_float(&i))
e440a328 8022 {
8023 mpfr_clear(r);
8024 return false;
8025 }
8026
0c77715b 8027 Type* arg_type = rnc.type();
8028 if (arg_type == NULL || arg_type->is_abstract())
8029 arg_type = inc.type();
e440a328 8030
fcbea5e4 8031 mpc_t val;
8032 mpc_init2(val, mpc_precision);
8033 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
e440a328 8034 mpfr_clear(r);
8035 mpfr_clear(i);
8036
fcbea5e4 8037 Type* type = Builtin_call_expression::complex_type(arg_type);
8038 nc->set_complex(type, val);
8039
8040 mpc_clear(val);
8041
0c77715b 8042 return true;
e440a328 8043 }
8044
8045 return false;
8046}
8047
a7549a6a 8048// Give an error if we are discarding the value of an expression which
8049// should not normally be discarded. We don't give an error for
8050// discarding the value of an ordinary function call, but we do for
8051// builtin functions, purely for consistency with the gc compiler.
8052
4f2138d7 8053bool
a7549a6a 8054Builtin_call_expression::do_discarding_value()
8055{
8056 switch (this->code_)
8057 {
8058 case BUILTIN_INVALID:
8059 default:
8060 go_unreachable();
8061
8062 case BUILTIN_APPEND:
8063 case BUILTIN_CAP:
8064 case BUILTIN_COMPLEX:
8065 case BUILTIN_IMAG:
8066 case BUILTIN_LEN:
8067 case BUILTIN_MAKE:
8068 case BUILTIN_NEW:
8069 case BUILTIN_REAL:
8070 case BUILTIN_ALIGNOF:
8071 case BUILTIN_OFFSETOF:
8072 case BUILTIN_SIZEOF:
8073 this->unused_value_error();
4f2138d7 8074 return false;
a7549a6a 8075
8076 case BUILTIN_CLOSE:
8077 case BUILTIN_COPY:
1cce762f 8078 case BUILTIN_DELETE:
a7549a6a 8079 case BUILTIN_PANIC:
8080 case BUILTIN_PRINT:
8081 case BUILTIN_PRINTLN:
8082 case BUILTIN_RECOVER:
4f2138d7 8083 return true;
a7549a6a 8084 }
8085}
8086
e440a328 8087// Return the type.
8088
8089Type*
8090Builtin_call_expression::do_type()
8091{
79651b1f 8092 if (this->is_error_expression())
8093 return Type::make_error_type();
e440a328 8094 switch (this->code_)
8095 {
8096 case BUILTIN_INVALID:
8097 default:
79651b1f 8098 return Type::make_error_type();
e440a328 8099
8100 case BUILTIN_NEW:
8101 case BUILTIN_MAKE:
8102 {
8103 const Expression_list* args = this->args();
8104 if (args == NULL || args->empty())
8105 return Type::make_error_type();
8106 return Type::make_pointer_type(args->front()->type());
8107 }
8108
8109 case BUILTIN_CAP:
8110 case BUILTIN_COPY:
8111 case BUILTIN_LEN:
7ba86326 8112 return Type::lookup_integer_type("int");
8113
e440a328 8114 case BUILTIN_ALIGNOF:
8115 case BUILTIN_OFFSETOF:
8116 case BUILTIN_SIZEOF:
7ba86326 8117 return Type::lookup_integer_type("uintptr");
e440a328 8118
8119 case BUILTIN_CLOSE:
1cce762f 8120 case BUILTIN_DELETE:
e440a328 8121 case BUILTIN_PANIC:
8122 case BUILTIN_PRINT:
8123 case BUILTIN_PRINTLN:
8124 return Type::make_void_type();
8125
e440a328 8126 case BUILTIN_RECOVER:
823c7e3d 8127 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8128
8129 case BUILTIN_APPEND:
8130 {
8131 const Expression_list* args = this->args();
8132 if (args == NULL || args->empty())
8133 return Type::make_error_type();
3ff4863b 8134 Type *ret = args->front()->type();
8135 if (!ret->is_slice_type())
8136 return Type::make_error_type();
8137 return ret;
e440a328 8138 }
8139
8140 case BUILTIN_REAL:
8141 case BUILTIN_IMAG:
8142 {
8143 Expression* arg = this->one_arg();
8144 if (arg == NULL)
8145 return Type::make_error_type();
8146 Type* t = arg->type();
8147 if (t->is_abstract())
8148 t = t->make_non_abstract_type();
8149 t = Builtin_call_expression::real_imag_type(t);
8150 if (t == NULL)
8151 t = Type::make_error_type();
8152 return t;
8153 }
8154
48080209 8155 case BUILTIN_COMPLEX:
e440a328 8156 {
8157 const Expression_list* args = this->args();
8158 if (args == NULL || args->size() != 2)
8159 return Type::make_error_type();
8160 Type* t = args->front()->type();
8161 if (t->is_abstract())
8162 {
8163 t = args->back()->type();
8164 if (t->is_abstract())
8165 t = t->make_non_abstract_type();
8166 }
48080209 8167 t = Builtin_call_expression::complex_type(t);
e440a328 8168 if (t == NULL)
8169 t = Type::make_error_type();
8170 return t;
8171 }
8172 }
8173}
8174
8175// Determine the type.
8176
8177void
8178Builtin_call_expression::do_determine_type(const Type_context* context)
8179{
fb94b0ca 8180 if (!this->determining_types())
8181 return;
8182
e440a328 8183 this->fn()->determine_type_no_context();
8184
8185 const Expression_list* args = this->args();
8186
8187 bool is_print;
8188 Type* arg_type = NULL;
321e5ad2 8189 Type* trailing_arg_types = NULL;
e440a328 8190 switch (this->code_)
8191 {
8192 case BUILTIN_PRINT:
8193 case BUILTIN_PRINTLN:
8194 // Do not force a large integer constant to "int".
8195 is_print = true;
8196 break;
8197
8198 case BUILTIN_REAL:
8199 case BUILTIN_IMAG:
48080209 8200 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 8201 if (arg_type == NULL)
8202 arg_type = Type::lookup_complex_type("complex128");
e440a328 8203 is_print = false;
8204 break;
8205
48080209 8206 case BUILTIN_COMPLEX:
e440a328 8207 {
48080209 8208 // For the complex function the type of one operand can
e440a328 8209 // determine the type of the other, as in a binary expression.
8210 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 8211 if (arg_type == NULL)
8212 arg_type = Type::lookup_float_type("float64");
e440a328 8213 if (args != NULL && args->size() == 2)
8214 {
8215 Type* t1 = args->front()->type();
c849bb59 8216 Type* t2 = args->back()->type();
e440a328 8217 if (!t1->is_abstract())
8218 arg_type = t1;
8219 else if (!t2->is_abstract())
8220 arg_type = t2;
8221 }
8222 is_print = false;
8223 }
8224 break;
8225
321e5ad2 8226 case BUILTIN_APPEND:
8227 if (!this->is_varargs()
8228 && args != NULL
8229 && !args->empty()
8230 && args->front()->type()->is_slice_type())
8231 trailing_arg_types =
8232 args->front()->type()->array_type()->element_type();
8233 is_print = false;
8234 break;
8235
e440a328 8236 default:
8237 is_print = false;
8238 break;
8239 }
8240
8241 if (args != NULL)
8242 {
8243 for (Expression_list::const_iterator pa = args->begin();
8244 pa != args->end();
8245 ++pa)
8246 {
8247 Type_context subcontext;
8248 subcontext.type = arg_type;
8249
8250 if (is_print)
8251 {
8252 // We want to print large constants, we so can't just
8253 // use the appropriate nonabstract type. Use uint64 for
8254 // an integer if we know it is nonnegative, otherwise
8255 // use int64 for a integer, otherwise use float64 for a
8256 // float or complex128 for a complex.
8257 Type* want_type = NULL;
8258 Type* atype = (*pa)->type();
8259 if (atype->is_abstract())
8260 {
8261 if (atype->integer_type() != NULL)
8262 {
0c77715b 8263 Numeric_constant nc;
8264 if (this->numeric_constant_value(&nc))
8265 {
8266 mpz_t val;
8267 if (nc.to_int(&val))
8268 {
8269 if (mpz_sgn(val) >= 0)
8270 want_type = Type::lookup_integer_type("uint64");
8271 mpz_clear(val);
8272 }
8273 }
8274 if (want_type == NULL)
e440a328 8275 want_type = Type::lookup_integer_type("int64");
e440a328 8276 }
8277 else if (atype->float_type() != NULL)
8278 want_type = Type::lookup_float_type("float64");
8279 else if (atype->complex_type() != NULL)
8280 want_type = Type::lookup_complex_type("complex128");
8281 else if (atype->is_abstract_string_type())
8282 want_type = Type::lookup_string_type();
8283 else if (atype->is_abstract_boolean_type())
8284 want_type = Type::lookup_bool_type();
8285 else
c3e6f413 8286 go_unreachable();
e440a328 8287 subcontext.type = want_type;
8288 }
8289 }
8290
8291 (*pa)->determine_type(&subcontext);
321e5ad2 8292
8293 if (trailing_arg_types != NULL)
8294 {
8295 arg_type = trailing_arg_types;
8296 trailing_arg_types = NULL;
8297 }
e440a328 8298 }
8299 }
8300}
8301
8302// If there is exactly one argument, return true. Otherwise give an
8303// error message and return false.
8304
8305bool
8306Builtin_call_expression::check_one_arg()
8307{
8308 const Expression_list* args = this->args();
8309 if (args == NULL || args->size() < 1)
8310 {
8311 this->report_error(_("not enough arguments"));
8312 return false;
8313 }
8314 else if (args->size() > 1)
8315 {
8316 this->report_error(_("too many arguments"));
8317 return false;
8318 }
8319 if (args->front()->is_error_expression()
5c13bd80 8320 || args->front()->type()->is_error())
e440a328 8321 {
8322 this->set_is_error();
8323 return false;
8324 }
8325 return true;
8326}
8327
8328// Check argument types for a builtin function.
8329
8330void
8331Builtin_call_expression::do_check_types(Gogo*)
8332{
375646ea 8333 if (this->is_error_expression())
8334 return;
e440a328 8335 switch (this->code_)
8336 {
8337 case BUILTIN_INVALID:
8338 case BUILTIN_NEW:
8339 case BUILTIN_MAKE:
cd238b8d 8340 case BUILTIN_DELETE:
e440a328 8341 return;
8342
8343 case BUILTIN_LEN:
8344 case BUILTIN_CAP:
8345 {
8346 // The single argument may be either a string or an array or a
8347 // map or a channel, or a pointer to a closed array.
8348 if (this->check_one_arg())
8349 {
8350 Type* arg_type = this->one_arg()->type();
8351 if (arg_type->points_to() != NULL
8352 && arg_type->points_to()->array_type() != NULL
411eb89e 8353 && !arg_type->points_to()->is_slice_type())
e440a328 8354 arg_type = arg_type->points_to();
8355 if (this->code_ == BUILTIN_CAP)
8356 {
5c13bd80 8357 if (!arg_type->is_error()
e440a328 8358 && arg_type->array_type() == NULL
8359 && arg_type->channel_type() == NULL)
8360 this->report_error(_("argument must be array or slice "
8361 "or channel"));
8362 }
8363 else
8364 {
5c13bd80 8365 if (!arg_type->is_error()
e440a328 8366 && !arg_type->is_string_type()
8367 && arg_type->array_type() == NULL
8368 && arg_type->map_type() == NULL
8369 && arg_type->channel_type() == NULL)
8370 this->report_error(_("argument must be string or "
8371 "array or slice or map or channel"));
8372 }
8373 }
8374 }
8375 break;
8376
8377 case BUILTIN_PRINT:
8378 case BUILTIN_PRINTLN:
8379 {
8380 const Expression_list* args = this->args();
8381 if (args == NULL)
8382 {
8383 if (this->code_ == BUILTIN_PRINT)
631d5788 8384 go_warning_at(this->location(), 0,
e440a328 8385 "no arguments for builtin function %<%s%>",
8386 (this->code_ == BUILTIN_PRINT
8387 ? "print"
8388 : "println"));
8389 }
8390 else
8391 {
8392 for (Expression_list::const_iterator p = args->begin();
8393 p != args->end();
8394 ++p)
8395 {
8396 Type* type = (*p)->type();
5c13bd80 8397 if (type->is_error()
e440a328 8398 || type->is_string_type()
8399 || type->integer_type() != NULL
8400 || type->float_type() != NULL
8401 || type->complex_type() != NULL
8402 || type->is_boolean_type()
8403 || type->points_to() != NULL
8404 || type->interface_type() != NULL
8405 || type->channel_type() != NULL
8406 || type->map_type() != NULL
8407 || type->function_type() != NULL
411eb89e 8408 || type->is_slice_type())
e440a328 8409 ;
acf8e158 8410 else if ((*p)->is_type_expression())
8411 {
8412 // If this is a type expression it's going to give
8413 // an error anyhow, so we don't need one here.
8414 }
e440a328 8415 else
8416 this->report_error(_("unsupported argument type to "
8417 "builtin function"));
8418 }
8419 }
8420 }
8421 break;
8422
8423 case BUILTIN_CLOSE:
e440a328 8424 if (this->check_one_arg())
8425 {
8426 if (this->one_arg()->type()->channel_type() == NULL)
8427 this->report_error(_("argument must be channel"));
5202d986 8428 else if (!this->one_arg()->type()->channel_type()->may_send())
8429 this->report_error(_("cannot close receive-only channel"));
e440a328 8430 }
8431 break;
8432
8433 case BUILTIN_PANIC:
8434 case BUILTIN_SIZEOF:
8435 case BUILTIN_ALIGNOF:
8436 this->check_one_arg();
8437 break;
8438
8439 case BUILTIN_RECOVER:
6334270b 8440 if (this->args() != NULL
8441 && !this->args()->empty()
8442 && !this->recover_arg_is_set_)
e440a328 8443 this->report_error(_("too many arguments"));
8444 break;
8445
8446 case BUILTIN_OFFSETOF:
8447 if (this->check_one_arg())
8448 {
8449 Expression* arg = this->one_arg();
8450 if (arg->field_reference_expression() == NULL)
8451 this->report_error(_("argument must be a field reference"));
8452 }
8453 break;
8454
8455 case BUILTIN_COPY:
8456 {
8457 const Expression_list* args = this->args();
8458 if (args == NULL || args->size() < 2)
8459 {
8460 this->report_error(_("not enough arguments"));
8461 break;
8462 }
8463 else if (args->size() > 2)
8464 {
8465 this->report_error(_("too many arguments"));
8466 break;
8467 }
8468 Type* arg1_type = args->front()->type();
8469 Type* arg2_type = args->back()->type();
5c13bd80 8470 if (arg1_type->is_error() || arg2_type->is_error())
6bebb39d 8471 {
8472 this->set_is_error();
8473 break;
8474 }
e440a328 8475
8476 Type* e1;
411eb89e 8477 if (arg1_type->is_slice_type())
e440a328 8478 e1 = arg1_type->array_type()->element_type();
8479 else
8480 {
8481 this->report_error(_("left argument must be a slice"));
8482 break;
8483 }
8484
411eb89e 8485 if (arg2_type->is_slice_type())
60963afd 8486 {
8487 Type* e2 = arg2_type->array_type()->element_type();
8488 if (!Type::are_identical(e1, e2, true, NULL))
8489 this->report_error(_("element types must be the same"));
8490 }
e440a328 8491 else if (arg2_type->is_string_type())
e440a328 8492 {
60963afd 8493 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8494 this->report_error(_("first argument must be []byte"));
e440a328 8495 }
60963afd 8496 else
8497 this->report_error(_("second argument must be slice or string"));
e440a328 8498 }
8499 break;
8500
8501 case BUILTIN_APPEND:
8502 {
8503 const Expression_list* args = this->args();
321e5ad2 8504 if (args == NULL || args->empty())
e440a328 8505 {
8506 this->report_error(_("not enough arguments"));
8507 break;
8508 }
321e5ad2 8509
8510 Type* slice_type = args->front()->type();
8511 if (!slice_type->is_slice_type())
6bebb39d 8512 {
321e5ad2 8513 if (slice_type->is_error_type())
8514 break;
8515 if (slice_type->is_nil_type())
8516 go_error_at(args->front()->location(), "use of untyped nil");
8517 else
8518 go_error_at(args->front()->location(),
8519 "argument 1 must be a slice");
6bebb39d 8520 this->set_is_error();
8521 break;
8522 }
cd238b8d 8523
321e5ad2 8524 Type* element_type = slice_type->array_type()->element_type();
8525 if (this->is_varargs())
4fd4fcf4 8526 {
321e5ad2 8527 if (!args->back()->type()->is_slice_type()
8528 && !args->back()->type()->is_string_type())
8529 {
8530 go_error_at(args->back()->location(),
8531 "invalid use of %<...%> with non-slice/non-string");
8532 this->set_is_error();
8533 break;
8534 }
4fd4fcf4 8535
321e5ad2 8536 if (args->size() < 2)
8537 {
8538 this->report_error(_("not enough arguments"));
8539 break;
8540 }
8541 if (args->size() > 2)
8542 {
8543 this->report_error(_("too many arguments"));
8544 break;
8545 }
8546
8547 if (args->back()->type()->is_string_type()
8548 && element_type->integer_type() != NULL
8549 && element_type->integer_type()->is_byte())
8550 {
8551 // Permit append(s1, s2...) when s1 is a slice of
8552 // bytes and s2 is a string type.
8553 }
e440a328 8554 else
8555 {
321e5ad2 8556 // We have to test for assignment compatibility to a
8557 // slice of the element type, which is not necessarily
8558 // the same as the type of the first argument: the
8559 // first argument might have a named type.
8560 Type* check_type = Type::make_array_type(element_type, NULL);
8561 std::string reason;
8562 if (!Type::are_assignable(check_type, args->back()->type(),
8563 &reason))
8564 {
8565 if (reason.empty())
8566 go_error_at(args->back()->location(),
8567 "argument 2 has invalid type");
8568 else
8569 go_error_at(args->back()->location(),
8570 "argument 2 has invalid type (%s)",
8571 reason.c_str());
8572 this->set_is_error();
8573 break;
8574 }
8575 }
8576 }
8577 else
8578 {
8579 Expression_list::const_iterator pa = args->begin();
8580 int i = 2;
8581 for (++pa; pa != args->end(); ++pa, ++i)
8582 {
8583 std::string reason;
8584 if (!Type::are_assignable(element_type, (*pa)->type(),
8585 &reason))
8586 {
8587 if (reason.empty())
8588 go_error_at((*pa)->location(),
8589 "argument %d has incompatible type", i);
8590 else
8591 go_error_at((*pa)->location(),
8592 "argument %d has incompatible type (%s)",
8593 i, reason.c_str());
8594 this->set_is_error();
8595 }
e440a328 8596 }
8597 }
e440a328 8598 }
321e5ad2 8599 break;
e440a328 8600
8601 case BUILTIN_REAL:
8602 case BUILTIN_IMAG:
8603 if (this->check_one_arg())
8604 {
8605 if (this->one_arg()->type()->complex_type() == NULL)
8606 this->report_error(_("argument must have complex type"));
8607 }
8608 break;
8609
48080209 8610 case BUILTIN_COMPLEX:
e440a328 8611 {
8612 const Expression_list* args = this->args();
8613 if (args == NULL || args->size() < 2)
8614 this->report_error(_("not enough arguments"));
8615 else if (args->size() > 2)
8616 this->report_error(_("too many arguments"));
8617 else if (args->front()->is_error_expression()
5c13bd80 8618 || args->front()->type()->is_error()
e440a328 8619 || args->back()->is_error_expression()
5c13bd80 8620 || args->back()->type()->is_error())
e440a328 8621 this->set_is_error();
8622 else if (!Type::are_identical(args->front()->type(),
07ba8be5 8623 args->back()->type(), true, NULL))
48080209 8624 this->report_error(_("complex arguments must have identical types"));
e440a328 8625 else if (args->front()->type()->float_type() == NULL)
48080209 8626 this->report_error(_("complex arguments must have "
e440a328 8627 "floating-point type"));
8628 }
8629 break;
8630
8631 default:
c3e6f413 8632 go_unreachable();
e440a328 8633 }
8634}
8635
72666aed 8636Expression*
8637Builtin_call_expression::do_copy()
8638{
8639 Call_expression* bce =
8640 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
da244e59 8641 (this->args() == NULL
8642 ? NULL
8643 : this->args()->copy()),
72666aed 8644 this->is_varargs(),
8645 this->location());
8646
8647 if (this->varargs_are_lowered())
8648 bce->set_varargs_are_lowered();
8649 return bce;
8650}
8651
ea664253 8652// Return the backend representation for a builtin function.
e440a328 8653
ea664253 8654Bexpression*
8655Builtin_call_expression::do_get_backend(Translate_context* context)
e440a328 8656{
8657 Gogo* gogo = context->gogo();
b13c66cd 8658 Location location = this->location();
a0d8874e 8659
8660 if (this->is_erroneous_call())
8661 {
8662 go_assert(saw_errors());
8663 return gogo->backend()->error_expression();
8664 }
8665
e440a328 8666 switch (this->code_)
8667 {
8668 case BUILTIN_INVALID:
8669 case BUILTIN_NEW:
8670 case BUILTIN_MAKE:
c3e6f413 8671 go_unreachable();
e440a328 8672
8673 case BUILTIN_LEN:
8674 case BUILTIN_CAP:
8675 {
8676 const Expression_list* args = this->args();
c484d925 8677 go_assert(args != NULL && args->size() == 1);
2c809f8f 8678 Expression* arg = args->front();
e440a328 8679 Type* arg_type = arg->type();
0f914071 8680
8681 if (this->seen_)
8682 {
c484d925 8683 go_assert(saw_errors());
ea664253 8684 return context->backend()->error_expression();
0f914071 8685 }
8686 this->seen_ = true;
0f914071 8687 this->seen_ = false;
e440a328 8688 if (arg_type->points_to() != NULL)
8689 {
8690 arg_type = arg_type->points_to();
c484d925 8691 go_assert(arg_type->array_type() != NULL
411eb89e 8692 && !arg_type->is_slice_type());
2c809f8f 8693 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8694 }
8695
1b1f2abf 8696 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8697 Expression* val;
e440a328 8698 if (this->code_ == BUILTIN_LEN)
8699 {
8700 if (arg_type->is_string_type())
2c809f8f 8701 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8702 location);
e440a328 8703 else if (arg_type->array_type() != NULL)
0f914071 8704 {
8705 if (this->seen_)
8706 {
c484d925 8707 go_assert(saw_errors());
ea664253 8708 return context->backend()->error_expression();
0f914071 8709 }
8710 this->seen_ = true;
2c809f8f 8711 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8712 this->seen_ = false;
8713 }
0d5530d9 8714 else if (arg_type->map_type() != NULL
8715 || arg_type->channel_type() != NULL)
8716 {
8717 // The first field is the length. If the pointer is
8718 // nil, the length is zero.
8719 Type* pint_type = Type::make_pointer_type(int_type);
8720 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8721 Expression* nil = Expression::make_nil(location);
8722 nil = Expression::make_cast(pint_type, nil, location);
8723 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8724 arg, nil, location);
8725 Expression* zero = Expression::make_integer_ul(0, int_type,
8726 location);
8727 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8728 arg, location);
8729 val = Expression::make_conditional(cmp, zero, indir, location);
8730 }
e440a328 8731 else
c3e6f413 8732 go_unreachable();
e440a328 8733 }
8734 else
8735 {
8736 if (arg_type->array_type() != NULL)
0f914071 8737 {
8738 if (this->seen_)
8739 {
c484d925 8740 go_assert(saw_errors());
ea664253 8741 return context->backend()->error_expression();
0f914071 8742 }
8743 this->seen_ = true;
2c809f8f 8744 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8745 this->seen_ = false;
8746 }
e440a328 8747 else if (arg_type->channel_type() != NULL)
132ed071 8748 {
8749 // The second field is the capacity. If the pointer
8750 // is nil, the capacity is zero.
8751 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8752 Type* pint_type = Type::make_pointer_type(int_type);
8753 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8754 arg,
8755 location);
8756 int off = int_type->integer_type()->bits() / 8;
8757 Expression* eoff = Expression::make_integer_ul(off,
8758 uintptr_type,
8759 location);
8760 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8761 location);
8762 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8763 Expression* nil = Expression::make_nil(location);
8764 nil = Expression::make_cast(pint_type, nil, location);
8765 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8766 arg, nil, location);
8767 Expression* zero = Expression::make_integer_ul(0, int_type,
8768 location);
8769 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8770 parg, location);
8771 val = Expression::make_conditional(cmp, zero, indir, location);
8772 }
e440a328 8773 else
c3e6f413 8774 go_unreachable();
e440a328 8775 }
8776
2c809f8f 8777 return Expression::make_cast(int_type, val,
ea664253 8778 location)->get_backend(context);
e440a328 8779 }
8780
8781 case BUILTIN_PRINT:
8782 case BUILTIN_PRINTLN:
8783 {
8784 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
88b03a70 8785
8786 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
8787 location, 0);
e440a328 8788
8789 const Expression_list* call_args = this->args();
8790 if (call_args != NULL)
8791 {
8792 for (Expression_list::const_iterator p = call_args->begin();
8793 p != call_args->end();
8794 ++p)
8795 {
8796 if (is_ln && p != call_args->begin())
8797 {
2c809f8f 8798 Expression* print_space =
88b03a70 8799 Runtime::make_call(Runtime::PRINTSP, location, 0);
e440a328 8800
2c809f8f 8801 print_stmts =
8802 Expression::make_compound(print_stmts, print_space,
8803 location);
8804 }
e440a328 8805
2c809f8f 8806 Expression* arg = *p;
8807 Type* type = arg->type();
8808 Runtime::Function code;
e440a328 8809 if (type->is_string_type())
88b03a70 8810 code = Runtime::PRINTSTRING;
e440a328 8811 else if (type->integer_type() != NULL
8812 && type->integer_type()->is_unsigned())
8813 {
e440a328 8814 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 8815 arg = Expression::make_cast(itype, arg, location);
88b03a70 8816 code = Runtime::PRINTUINT;
e440a328 8817 }
8818 else if (type->integer_type() != NULL)
8819 {
e440a328 8820 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 8821 arg = Expression::make_cast(itype, arg, location);
88b03a70 8822 code = Runtime::PRINTINT;
e440a328 8823 }
8824 else if (type->float_type() != NULL)
8825 {
2c809f8f 8826 Type* dtype = Type::lookup_float_type("float64");
8827 arg = Expression::make_cast(dtype, arg, location);
88b03a70 8828 code = Runtime::PRINTFLOAT;
e440a328 8829 }
8830 else if (type->complex_type() != NULL)
8831 {
2c809f8f 8832 Type* ctype = Type::lookup_complex_type("complex128");
8833 arg = Expression::make_cast(ctype, arg, location);
88b03a70 8834 code = Runtime::PRINTCOMPLEX;
e440a328 8835 }
8836 else if (type->is_boolean_type())
88b03a70 8837 code = Runtime::PRINTBOOL;
e440a328 8838 else if (type->points_to() != NULL
8839 || type->channel_type() != NULL
8840 || type->map_type() != NULL
8841 || type->function_type() != NULL)
8842 {
2c809f8f 8843 arg = Expression::make_cast(type, arg, location);
88b03a70 8844 code = Runtime::PRINTPOINTER;
e440a328 8845 }
8846 else if (type->interface_type() != NULL)
8847 {
8848 if (type->interface_type()->is_empty())
88b03a70 8849 code = Runtime::PRINTEFACE;
e440a328 8850 else
88b03a70 8851 code = Runtime::PRINTIFACE;
e440a328 8852 }
411eb89e 8853 else if (type->is_slice_type())
88b03a70 8854 code = Runtime::PRINTSLICE;
e440a328 8855 else
cd238b8d 8856 {
8857 go_assert(saw_errors());
ea664253 8858 return context->backend()->error_expression();
cd238b8d 8859 }
e440a328 8860
2c809f8f 8861 Expression* call = Runtime::make_call(code, location, 1, arg);
88b03a70 8862 print_stmts = Expression::make_compound(print_stmts, call,
8863 location);
e440a328 8864 }
8865 }
8866
8867 if (is_ln)
8868 {
2c809f8f 8869 Expression* print_nl =
88b03a70 8870 Runtime::make_call(Runtime::PRINTNL, location, 0);
8871 print_stmts = Expression::make_compound(print_stmts, print_nl,
8872 location);
e440a328 8873 }
8874
88b03a70 8875 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
8876 location, 0);
8877 print_stmts = Expression::make_compound(print_stmts, unlock, location);
32e3ff69 8878
ea664253 8879 return print_stmts->get_backend(context);
e440a328 8880 }
8881
8882 case BUILTIN_PANIC:
8883 {
8884 const Expression_list* args = this->args();
c484d925 8885 go_assert(args != NULL && args->size() == 1);
e440a328 8886 Expression* arg = args->front();
b13c66cd 8887 Type *empty =
823c7e3d 8888 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 8889 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8890
8891 Expression* panic =
8892 Runtime::make_call(Runtime::PANIC, location, 1, arg);
ea664253 8893 return panic->get_backend(context);
e440a328 8894 }
8895
8896 case BUILTIN_RECOVER:
8897 {
8898 // The argument is set when building recover thunks. It's a
8899 // boolean value which is true if we can recover a value now.
8900 const Expression_list* args = this->args();
c484d925 8901 go_assert(args != NULL && args->size() == 1);
e440a328 8902 Expression* arg = args->front();
b13c66cd 8903 Type *empty =
823c7e3d 8904 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8905
e440a328 8906 Expression* nil = Expression::make_nil(location);
2c809f8f 8907 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 8908
8909 // We need to handle a deferred call to recover specially,
8910 // because it changes whether it can recover a panic or not.
8911 // See test7 in test/recover1.go.
2c809f8f 8912 Expression* recover = Runtime::make_call((this->is_deferred()
8913 ? Runtime::DEFERRED_RECOVER
8914 : Runtime::RECOVER),
8915 location, 0);
8916 Expression* cond =
8917 Expression::make_conditional(arg, recover, nil, location);
ea664253 8918 return cond->get_backend(context);
e440a328 8919 }
8920
8921 case BUILTIN_CLOSE:
e440a328 8922 {
8923 const Expression_list* args = this->args();
c484d925 8924 go_assert(args != NULL && args->size() == 1);
e440a328 8925 Expression* arg = args->front();
2c809f8f 8926 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8927 1, arg);
ea664253 8928 return close->get_backend(context);
e440a328 8929 }
8930
8931 case BUILTIN_SIZEOF:
8932 case BUILTIN_OFFSETOF:
8933 case BUILTIN_ALIGNOF:
8934 {
0c77715b 8935 Numeric_constant nc;
8936 unsigned long val;
8937 if (!this->numeric_constant_value(&nc)
8938 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 8939 {
c484d925 8940 go_assert(saw_errors());
ea664253 8941 return context->backend()->error_expression();
7f1d9abd 8942 }
7ba86326 8943 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 8944 mpz_t ival;
8945 nc.get_int(&ival);
8946 Expression* int_cst =
e67508fa 8947 Expression::make_integer_z(&ival, uintptr_type, location);
2c809f8f 8948 mpz_clear(ival);
ea664253 8949 return int_cst->get_backend(context);
e440a328 8950 }
8951
8952 case BUILTIN_COPY:
8953 {
8954 const Expression_list* args = this->args();
c484d925 8955 go_assert(args != NULL && args->size() == 2);
e440a328 8956 Expression* arg1 = args->front();
8957 Expression* arg2 = args->back();
8958
e440a328 8959 Type* arg1_type = arg1->type();
8960 Array_type* at = arg1_type->array_type();
35a54f17 8961 go_assert(arg1->is_variable());
321e5ad2 8962
8963 Expression* call;
e440a328 8964
8965 Type* arg2_type = arg2->type();
2c809f8f 8966 go_assert(arg2->is_variable());
321e5ad2 8967 if (arg2_type->is_string_type())
8968 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
8969 2, arg1, arg2);
e440a328 8970 else
8971 {
321e5ad2 8972 Type* et = at->element_type();
8973 if (et->has_pointer())
8974 {
8975 Expression* td = Expression::make_type_descriptor(et,
8976 location);
8977 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
8978 3, td, arg1, arg2);
8979 }
8980 else
8981 {
8982 Expression* sz = Expression::make_type_info(et,
8983 TYPE_INFO_SIZE);
8984 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
8985 arg1, arg2, sz);
8986 }
e440a328 8987 }
2c809f8f 8988
321e5ad2 8989 return call->get_backend(context);
e440a328 8990 }
8991
8992 case BUILTIN_APPEND:
321e5ad2 8993 // Handled in Builtin_call_expression::flatten_append.
8994 go_unreachable();
e440a328 8995
8996 case BUILTIN_REAL:
8997 case BUILTIN_IMAG:
8998 {
8999 const Expression_list* args = this->args();
c484d925 9000 go_assert(args != NULL && args->size() == 1);
2c809f8f 9001
9002 Bexpression* ret;
ea664253 9003 Bexpression* bcomplex = args->front()->get_backend(context);
2c809f8f 9004 if (this->code_ == BUILTIN_REAL)
9005 ret = gogo->backend()->real_part_expression(bcomplex, location);
9006 else
9007 ret = gogo->backend()->imag_part_expression(bcomplex, location);
ea664253 9008 return ret;
e440a328 9009 }
9010
48080209 9011 case BUILTIN_COMPLEX:
e440a328 9012 {
9013 const Expression_list* args = this->args();
c484d925 9014 go_assert(args != NULL && args->size() == 2);
ea664253 9015 Bexpression* breal = args->front()->get_backend(context);
9016 Bexpression* bimag = args->back()->get_backend(context);
9017 return gogo->backend()->complex_expression(breal, bimag, location);
e440a328 9018 }
9019
9020 default:
c3e6f413 9021 go_unreachable();
e440a328 9022 }
9023}
9024
9025// We have to support exporting a builtin call expression, because
9026// code can set a constant to the result of a builtin expression.
9027
9028void
9029Builtin_call_expression::do_export(Export* exp) const
9030{
0c77715b 9031 Numeric_constant nc;
9032 if (!this->numeric_constant_value(&nc))
9033 {
631d5788 9034 go_error_at(this->location(), "value is not constant");
0c77715b 9035 return;
9036 }
e440a328 9037
0c77715b 9038 if (nc.is_int())
e440a328 9039 {
0c77715b 9040 mpz_t val;
9041 nc.get_int(&val);
e440a328 9042 Integer_expression::export_integer(exp, val);
0c77715b 9043 mpz_clear(val);
e440a328 9044 }
0c77715b 9045 else if (nc.is_float())
e440a328 9046 {
9047 mpfr_t fval;
0c77715b 9048 nc.get_float(&fval);
9049 Float_expression::export_float(exp, fval);
e440a328 9050 mpfr_clear(fval);
9051 }
0c77715b 9052 else if (nc.is_complex())
e440a328 9053 {
fcbea5e4 9054 mpc_t cval;
9055 nc.get_complex(&cval);
9056 Complex_expression::export_complex(exp, cval);
9057 mpc_clear(cval);
e440a328 9058 }
0c77715b 9059 else
9060 go_unreachable();
e440a328 9061
9062 // A trailing space lets us reliably identify the end of the number.
9063 exp->write_c_string(" ");
9064}
9065
9066// Class Call_expression.
9067
8381eda7 9068// A Go function can be viewed in a couple of different ways. The
9069// code of a Go function becomes a backend function with parameters
9070// whose types are simply the backend representation of the Go types.
9071// If there are multiple results, they are returned as a backend
9072// struct.
9073
9074// However, when Go code refers to a function other than simply
9075// calling it, the backend type of that function is actually a struct.
9076// The first field of the struct points to the Go function code
9077// (sometimes a wrapper as described below). The remaining fields
9078// hold addresses of closed-over variables. This struct is called a
9079// closure.
9080
9081// There are a few cases to consider.
9082
9083// A direct function call of a known function in package scope. In
9084// this case there are no closed-over variables, and we know the name
9085// of the function code. We can simply produce a backend call to the
9086// function directly, and not worry about the closure.
9087
9088// A direct function call of a known function literal. In this case
9089// we know the function code and we know the closure. We generate the
9090// function code such that it expects an additional final argument of
9091// the closure type. We pass the closure as the last argument, after
9092// the other arguments.
9093
9094// An indirect function call. In this case we have a closure. We
9095// load the pointer to the function code from the first field of the
9096// closure. We pass the address of the closure as the last argument.
9097
9098// A call to a method of an interface. Type methods are always at
9099// package scope, so we call the function directly, and don't worry
9100// about the closure.
9101
9102// This means that for a function at package scope we have two cases.
9103// One is the direct call, which has no closure. The other is the
9104// indirect call, which does have a closure. We can't simply ignore
9105// the closure, even though it is the last argument, because that will
9106// fail on targets where the function pops its arguments. So when
9107// generating a closure for a package-scope function we set the
9108// function code pointer in the closure to point to a wrapper
9109// function. This wrapper function accepts a final argument that
9110// points to the closure, ignores it, and calls the real function as a
9111// direct function call. This wrapper will normally be efficient, and
9112// can often simply be a tail call to the real function.
9113
9114// We don't use GCC's static chain pointer because 1) we don't need
9115// it; 2) GCC only permits using a static chain to call a known
9116// function, so we can't use it for an indirect call anyhow. Since we
9117// can't use it for an indirect call, we may as well not worry about
9118// using it for a direct call either.
9119
9120// We pass the closure last rather than first because it means that
9121// the function wrapper we put into a closure for a package-scope
9122// function can normally just be a tail call to the real function.
9123
9124// For method expressions we generate a wrapper that loads the
9125// receiver from the closure and then calls the method. This
9126// unfortunately forces reshuffling the arguments, since there is a
9127// new first argument, but we can't avoid reshuffling either for
9128// method expressions or for indirect calls of package-scope
9129// functions, and since the latter are more common we reshuffle for
9130// method expressions.
9131
9132// Note that the Go code retains the Go types. The extra final
9133// argument only appears when we convert to the backend
9134// representation.
9135
e440a328 9136// Traversal.
9137
9138int
9139Call_expression::do_traverse(Traverse* traverse)
9140{
0c0dacab 9141 // If we are calling a function in a different package that returns
9142 // an unnamed type, this may be the only chance we get to traverse
9143 // that type. We don't traverse this->type_ because it may be a
9144 // Call_multiple_result_type that will just lead back here.
9145 if (this->type_ != NULL && !this->type_->is_error_type())
9146 {
9147 Function_type *fntype = this->get_function_type();
9148 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9149 return TRAVERSE_EXIT;
9150 }
e440a328 9151 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9152 return TRAVERSE_EXIT;
9153 if (this->args_ != NULL)
9154 {
9155 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9156 return TRAVERSE_EXIT;
9157 }
9158 return TRAVERSE_CONTINUE;
9159}
9160
9161// Lower a call statement.
9162
9163Expression*
ceeb4318 9164Call_expression::do_lower(Gogo* gogo, Named_object* function,
9165 Statement_inserter* inserter, int)
e440a328 9166{
b13c66cd 9167 Location loc = this->location();
09ea332d 9168
ceeb4318 9169 // A type cast can look like a function call.
e440a328 9170 if (this->fn_->is_type_expression()
9171 && this->args_ != NULL
9172 && this->args_->size() == 1)
9173 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 9174 loc);
e440a328 9175
88f06749 9176 // Because do_type will return an error type and thus prevent future
9177 // errors, check for that case now to ensure that the error gets
9178 // reported.
37448b10 9179 Function_type* fntype = this->get_function_type();
9180 if (fntype == NULL)
88f06749 9181 {
9182 if (!this->fn_->type()->is_error())
9183 this->report_error(_("expected function"));
5f1045b5 9184 this->set_is_error();
9185 return this;
88f06749 9186 }
9187
e440a328 9188 // Handle an argument which is a call to a function which returns
9189 // multiple results.
9190 if (this->args_ != NULL
9191 && this->args_->size() == 1
37448b10 9192 && this->args_->front()->call_expression() != NULL)
e440a328 9193 {
e440a328 9194 size_t rc = this->args_->front()->call_expression()->result_count();
9195 if (rc > 1
37448b10 9196 && ((fntype->parameters() != NULL
9197 && (fntype->parameters()->size() == rc
9198 || (fntype->is_varargs()
9199 && fntype->parameters()->size() - 1 <= rc)))
9200 || fntype->is_builtin()))
e440a328 9201 {
9202 Call_expression* call = this->args_->front()->call_expression();
e90ecd2d 9203 call->set_is_multi_value_arg();
c33af8e4 9204 if (this->is_varargs_)
9205 {
9206 // It is not clear which result of a multiple result call
9207 // the ellipsis operator should be applied to. If we unpack the
9208 // the call into its individual results here, the ellipsis will be
9209 // applied to the last result.
631d5788 9210 go_error_at(call->location(),
9211 _("multiple-value argument in single-value context"));
c33af8e4 9212 return Expression::make_error(call->location());
9213 }
9214
e440a328 9215 Expression_list* args = new Expression_list;
9216 for (size_t i = 0; i < rc; ++i)
9217 args->push_back(Expression::make_call_result(call, i));
9218 // We can't return a new call expression here, because this
42535814 9219 // one may be referenced by Call_result expressions. We
9220 // also can't delete the old arguments, because we may still
9221 // traverse them somewhere up the call stack. FIXME.
e440a328 9222 this->args_ = args;
9223 }
9224 }
9225
37448b10 9226 // Recognize a call to a builtin function.
9227 if (fntype->is_builtin())
9228 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9229 this->is_varargs_, loc);
9230
ceeb4318 9231 // If this call returns multiple results, create a temporary
9232 // variable for each result.
9233 size_t rc = this->result_count();
9234 if (rc > 1 && this->results_ == NULL)
9235 {
9236 std::vector<Temporary_statement*>* temps =
9237 new std::vector<Temporary_statement*>;
9238 temps->reserve(rc);
37448b10 9239 const Typed_identifier_list* results = fntype->results();
ceeb4318 9240 for (Typed_identifier_list::const_iterator p = results->begin();
9241 p != results->end();
9242 ++p)
9243 {
9244 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 9245 NULL, loc);
ceeb4318 9246 inserter->insert(temp);
9247 temps->push_back(temp);
9248 }
9249 this->results_ = temps;
9250 }
9251
e440a328 9252 // Handle a call to a varargs function by packaging up the extra
9253 // parameters.
37448b10 9254 if (fntype->is_varargs())
e440a328 9255 {
e440a328 9256 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 9257 go_assert(parameters != NULL && !parameters->empty());
e440a328 9258 Type* varargs_type = parameters->back().type();
09ea332d 9259 this->lower_varargs(gogo, function, inserter, varargs_type,
0e9a2e72 9260 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
09ea332d 9261 }
9262
9263 // If this is call to a method, call the method directly passing the
9264 // object as the first parameter.
9265 Bound_method_expression* bme = this->fn_->bound_method_expression();
9266 if (bme != NULL)
9267 {
0afbb937 9268 Named_object* methodfn = bme->function();
09ea332d 9269 Expression* first_arg = bme->first_argument();
9270
9271 // We always pass a pointer when calling a method.
9272 if (first_arg->type()->points_to() == NULL
9273 && !first_arg->type()->is_error())
9274 {
9275 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9276 // We may need to create a temporary variable so that we can
9277 // take the address. We can't do that here because it will
9278 // mess up the order of evaluation.
9279 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9280 ue->set_create_temp();
9281 }
9282
9283 // If we are calling a method which was inherited from an
9284 // embedded struct, and the method did not get a stub, then the
9285 // first type may be wrong.
9286 Type* fatype = bme->first_argument_type();
9287 if (fatype != NULL)
9288 {
9289 if (fatype->points_to() == NULL)
9290 fatype = Type::make_pointer_type(fatype);
9291 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9292 }
9293
9294 Expression_list* new_args = new Expression_list();
9295 new_args->push_back(first_arg);
9296 if (this->args_ != NULL)
9297 {
9298 for (Expression_list::const_iterator p = this->args_->begin();
9299 p != this->args_->end();
9300 ++p)
9301 new_args->push_back(*p);
9302 }
9303
9304 // We have to change in place because this structure may be
9305 // referenced by Call_result_expressions. We can't delete the
9306 // old arguments, because we may be traversing them up in some
9307 // caller. FIXME.
9308 this->args_ = new_args;
0afbb937 9309 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 9310 bme->location());
e440a328 9311 }
9312
105f9a24 9313 // Handle a couple of special runtime functions. In the runtime
9314 // package, getcallerpc returns the PC of the caller, and
9315 // getcallersp returns the frame pointer of the caller. Implement
9316 // these by turning them into calls to GCC builtin functions. We
9317 // could implement them in normal code, but then we would have to
9318 // explicitly unwind the stack. These functions are intended to be
9319 // efficient. Note that this technique obviously only works for
9320 // direct calls, but that is the only way they are used. The actual
9321 // argument to these functions is always the address of a parameter;
9322 // we don't need that for the GCC builtin functions, so we just
9323 // ignore it.
9324 if (gogo->compiling_runtime()
9325 && this->args_ != NULL
9326 && this->args_->size() == 1
9327 && gogo->package_name() == "runtime")
9328 {
9329 Func_expression* fe = this->fn_->func_expression();
9330 if (fe != NULL
9331 && fe->named_object()->is_function_declaration()
9332 && fe->named_object()->package() == NULL)
9333 {
9334 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9335 if (n == "getcallerpc")
9336 {
9337 static Named_object* builtin_return_address;
9338 return this->lower_to_builtin(&builtin_return_address,
9339 "__builtin_return_address",
9340 0);
9341 }
9342 else if (n == "getcallersp")
9343 {
9344 static Named_object* builtin_frame_address;
9345 return this->lower_to_builtin(&builtin_frame_address,
9346 "__builtin_frame_address",
9347 1);
9348 }
9349 }
9350 }
9351
e440a328 9352 return this;
9353}
9354
9355// Lower a call to a varargs function. FUNCTION is the function in
9356// which the call occurs--it's not the function we are calling.
9357// VARARGS_TYPE is the type of the varargs parameter, a slice type.
9358// PARAM_COUNT is the number of parameters of the function we are
9359// calling; the last of these parameters will be the varargs
9360// parameter.
9361
09ea332d 9362void
e440a328 9363Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 9364 Statement_inserter* inserter,
0e9a2e72 9365 Type* varargs_type, size_t param_count,
9366 Slice_storage_escape_disp escape_disp)
e440a328 9367{
9368 if (this->varargs_are_lowered_)
09ea332d 9369 return;
e440a328 9370
b13c66cd 9371 Location loc = this->location();
e440a328 9372
c484d925 9373 go_assert(param_count > 0);
411eb89e 9374 go_assert(varargs_type->is_slice_type());
e440a328 9375
9376 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9377 if (arg_count < param_count - 1)
9378 {
9379 // Not enough arguments; will be caught in check_types.
09ea332d 9380 return;
e440a328 9381 }
9382
9383 Expression_list* old_args = this->args_;
9384 Expression_list* new_args = new Expression_list();
9385 bool push_empty_arg = false;
9386 if (old_args == NULL || old_args->empty())
9387 {
c484d925 9388 go_assert(param_count == 1);
e440a328 9389 push_empty_arg = true;
9390 }
9391 else
9392 {
9393 Expression_list::const_iterator pa;
9394 int i = 1;
9395 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9396 {
9397 if (static_cast<size_t>(i) == param_count)
9398 break;
9399 new_args->push_back(*pa);
9400 }
9401
9402 // We have reached the varargs parameter.
9403
9404 bool issued_error = false;
9405 if (pa == old_args->end())
9406 push_empty_arg = true;
9407 else if (pa + 1 == old_args->end() && this->is_varargs_)
9408 new_args->push_back(*pa);
9409 else if (this->is_varargs_)
9410 {
a6645f74 9411 if ((*pa)->type()->is_slice_type())
9412 this->report_error(_("too many arguments"));
9413 else
9414 {
631d5788 9415 go_error_at(this->location(),
9416 _("invalid use of %<...%> with non-slice"));
a6645f74 9417 this->set_is_error();
9418 }
09ea332d 9419 return;
e440a328 9420 }
e440a328 9421 else
9422 {
9423 Type* element_type = varargs_type->array_type()->element_type();
9424 Expression_list* vals = new Expression_list;
9425 for (; pa != old_args->end(); ++pa, ++i)
9426 {
9427 // Check types here so that we get a better message.
9428 Type* patype = (*pa)->type();
b13c66cd 9429 Location paloc = (*pa)->location();
e440a328 9430 if (!this->check_argument_type(i, element_type, patype,
9431 paloc, issued_error))
9432 continue;
9433 vals->push_back(*pa);
9434 }
0e9a2e72 9435 Slice_construction_expression* sce =
e440a328 9436 Expression::make_slice_composite_literal(varargs_type, vals, loc);
0e9a2e72 9437 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9438 sce->set_storage_does_not_escape();
9439 Expression* val = sce;
09ea332d 9440 gogo->lower_expression(function, inserter, &val);
e440a328 9441 new_args->push_back(val);
9442 }
9443 }
9444
9445 if (push_empty_arg)
9446 new_args->push_back(Expression::make_nil(loc));
9447
9448 // We can't return a new call expression here, because this one may
6d4c2432 9449 // be referenced by Call_result expressions. FIXME. We can't
9450 // delete OLD_ARGS because we may have both a Call_expression and a
9451 // Builtin_call_expression which refer to them. FIXME.
e440a328 9452 this->args_ = new_args;
9453 this->varargs_are_lowered_ = true;
e440a328 9454}
9455
105f9a24 9456// Return a call to __builtin_return_address or __builtin_frame_address.
9457
9458Expression*
9459Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9460 int arg)
9461{
9462 if (*pno == NULL)
9463 *pno = Gogo::declare_builtin_rf_address(name);
9464
9465 Location loc = this->location();
9466
9467 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9468 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9469 Expression_list *args = new Expression_list();
9470 args->push_back(a);
9471 Expression* call = Expression::make_call(fn, args, false, loc);
9472
9473 // The builtin functions return void*, but the Go functions return uintptr.
9474 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9475 return Expression::make_cast(uintptr_type, call, loc);
9476}
9477
2c809f8f 9478// Flatten a call with multiple results into a temporary.
9479
9480Expression*
b8e86a51 9481Call_expression::do_flatten(Gogo* gogo, Named_object*,
9482 Statement_inserter* inserter)
2c809f8f 9483{
5bf8be8b 9484 if (this->is_erroneous_call())
9485 {
9486 go_assert(saw_errors());
9487 return Expression::make_error(this->location());
9488 }
b8e86a51 9489
91c0fd76 9490 if (this->is_flattened_)
9491 return this;
9492 this->is_flattened_ = true;
9493
b8e86a51 9494 // Add temporary variables for all arguments that require type
9495 // conversion.
9496 Function_type* fntype = this->get_function_type();
9782d556 9497 if (fntype == NULL)
9498 {
9499 go_assert(saw_errors());
9500 return this;
9501 }
b8e86a51 9502 if (this->args_ != NULL && !this->args_->empty()
9503 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9504 {
9505 bool is_interface_method =
9506 this->fn_->interface_field_reference_expression() != NULL;
9507
9508 Expression_list *args = new Expression_list();
9509 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9510 Expression_list::const_iterator pa = this->args_->begin();
9511 if (!is_interface_method && fntype->is_method())
9512 {
9513 // The receiver argument.
9514 args->push_back(*pa);
9515 ++pa;
9516 }
9517 for (; pa != this->args_->end(); ++pa, ++pp)
9518 {
9519 go_assert(pp != fntype->parameters()->end());
9520 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9521 args->push_back(*pa);
9522 else
9523 {
9524 Location loc = (*pa)->location();
8ba8cc87 9525 Expression* arg = *pa;
9526 if (!arg->is_variable())
9527 {
9528 Temporary_statement *temp =
9529 Statement::make_temporary(NULL, arg, loc);
9530 inserter->insert(temp);
9531 arg = Expression::make_temporary_reference(temp, loc);
9532 }
9533 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9534 loc);
9535 args->push_back(arg);
b8e86a51 9536 }
9537 }
9538 delete this->args_;
9539 this->args_ = args;
9540 }
9541
2c809f8f 9542 size_t rc = this->result_count();
9543 if (rc > 1 && this->call_temp_ == NULL)
9544 {
9545 Struct_field_list* sfl = new Struct_field_list();
9546 Function_type* fntype = this->get_function_type();
9547 const Typed_identifier_list* results = fntype->results();
9548 Location loc = this->location();
9549
9550 int i = 0;
61575e0f 9551 char buf[20];
2c809f8f 9552 for (Typed_identifier_list::const_iterator p = results->begin();
9553 p != results->end();
9554 ++p, ++i)
9555 {
9556 snprintf(buf, sizeof buf, "res%d", i);
9557 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9558 }
9559
9560 Struct_type* st = Type::make_struct_type(sfl, loc);
9561 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9562 inserter->insert(this->call_temp_);
9563 }
9564
9565 return this;
9566}
9567
ceeb4318 9568// Get the function type. This can return NULL in error cases.
e440a328 9569
9570Function_type*
9571Call_expression::get_function_type() const
9572{
9573 return this->fn_->type()->function_type();
9574}
9575
9576// Return the number of values which this call will return.
9577
9578size_t
9579Call_expression::result_count() const
9580{
9581 const Function_type* fntype = this->get_function_type();
9582 if (fntype == NULL)
9583 return 0;
9584 if (fntype->results() == NULL)
9585 return 0;
9586 return fntype->results()->size();
9587}
9588
ceeb4318 9589// Return the temporary which holds a result.
9590
9591Temporary_statement*
9592Call_expression::result(size_t i) const
9593{
cd238b8d 9594 if (this->results_ == NULL || this->results_->size() <= i)
9595 {
9596 go_assert(saw_errors());
9597 return NULL;
9598 }
ceeb4318 9599 return (*this->results_)[i];
9600}
9601
1373401e 9602// Set the number of results expected from a call expression.
9603
9604void
9605Call_expression::set_expected_result_count(size_t count)
9606{
9607 go_assert(this->expected_result_count_ == 0);
9608 this->expected_result_count_ = count;
9609}
9610
e440a328 9611// Return whether this is a call to the predeclared function recover.
9612
9613bool
9614Call_expression::is_recover_call() const
9615{
9616 return this->do_is_recover_call();
9617}
9618
9619// Set the argument to the recover function.
9620
9621void
9622Call_expression::set_recover_arg(Expression* arg)
9623{
9624 this->do_set_recover_arg(arg);
9625}
9626
9627// Virtual functions also implemented by Builtin_call_expression.
9628
9629bool
9630Call_expression::do_is_recover_call() const
9631{
9632 return false;
9633}
9634
9635void
9636Call_expression::do_set_recover_arg(Expression*)
9637{
c3e6f413 9638 go_unreachable();
e440a328 9639}
9640
ceeb4318 9641// We have found an error with this call expression; return true if
9642// we should report it.
9643
9644bool
9645Call_expression::issue_error()
9646{
9647 if (this->issued_error_)
9648 return false;
9649 else
9650 {
9651 this->issued_error_ = true;
9652 return true;
9653 }
9654}
9655
5bf8be8b 9656// Whether or not this call contains errors, either in the call or the
9657// arguments to the call.
9658
9659bool
9660Call_expression::is_erroneous_call()
9661{
9662 if (this->is_error_expression() || this->fn()->is_error_expression())
9663 return true;
9664
9665 if (this->args() == NULL)
9666 return false;
9667 for (Expression_list::iterator pa = this->args()->begin();
9668 pa != this->args()->end();
9669 ++pa)
9670 {
9671 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9672 return true;
9673 }
9674 return false;
9675}
9676
e440a328 9677// Get the type.
9678
9679Type*
9680Call_expression::do_type()
9681{
9682 if (this->type_ != NULL)
9683 return this->type_;
9684
9685 Type* ret;
9686 Function_type* fntype = this->get_function_type();
9687 if (fntype == NULL)
9688 return Type::make_error_type();
9689
9690 const Typed_identifier_list* results = fntype->results();
9691 if (results == NULL)
9692 ret = Type::make_void_type();
9693 else if (results->size() == 1)
9694 ret = results->begin()->type();
9695 else
9696 ret = Type::make_call_multiple_result_type(this);
9697
9698 this->type_ = ret;
9699
9700 return this->type_;
9701}
9702
9703// Determine types for a call expression. We can use the function
9704// parameter types to set the types of the arguments.
9705
9706void
9707Call_expression::do_determine_type(const Type_context*)
9708{
fb94b0ca 9709 if (!this->determining_types())
9710 return;
9711
e440a328 9712 this->fn_->determine_type_no_context();
9713 Function_type* fntype = this->get_function_type();
9714 const Typed_identifier_list* parameters = NULL;
9715 if (fntype != NULL)
9716 parameters = fntype->parameters();
9717 if (this->args_ != NULL)
9718 {
9719 Typed_identifier_list::const_iterator pt;
9720 if (parameters != NULL)
9721 pt = parameters->begin();
09ea332d 9722 bool first = true;
e440a328 9723 for (Expression_list::const_iterator pa = this->args_->begin();
9724 pa != this->args_->end();
9725 ++pa)
9726 {
09ea332d 9727 if (first)
9728 {
9729 first = false;
9730 // If this is a method, the first argument is the
9731 // receiver.
9732 if (fntype != NULL && fntype->is_method())
9733 {
9734 Type* rtype = fntype->receiver()->type();
9735 // The receiver is always passed as a pointer.
9736 if (rtype->points_to() == NULL)
9737 rtype = Type::make_pointer_type(rtype);
9738 Type_context subcontext(rtype, false);
9739 (*pa)->determine_type(&subcontext);
9740 continue;
9741 }
9742 }
9743
e440a328 9744 if (parameters != NULL && pt != parameters->end())
9745 {
9746 Type_context subcontext(pt->type(), false);
9747 (*pa)->determine_type(&subcontext);
9748 ++pt;
9749 }
9750 else
9751 (*pa)->determine_type_no_context();
9752 }
9753 }
9754}
9755
fb94b0ca 9756// Called when determining types for a Call_expression. Return true
9757// if we should go ahead, false if they have already been determined.
9758
9759bool
9760Call_expression::determining_types()
9761{
9762 if (this->types_are_determined_)
9763 return false;
9764 else
9765 {
9766 this->types_are_determined_ = true;
9767 return true;
9768 }
9769}
9770
e440a328 9771// Check types for parameter I.
9772
9773bool
9774Call_expression::check_argument_type(int i, const Type* parameter_type,
9775 const Type* argument_type,
b13c66cd 9776 Location argument_location,
e440a328 9777 bool issued_error)
9778{
9779 std::string reason;
1eae365b 9780 if (!Type::are_assignable(parameter_type, argument_type, &reason))
e440a328 9781 {
9782 if (!issued_error)
9783 {
9784 if (reason.empty())
631d5788 9785 go_error_at(argument_location, "argument %d has incompatible type", i);
e440a328 9786 else
631d5788 9787 go_error_at(argument_location,
9788 "argument %d has incompatible type (%s)",
9789 i, reason.c_str());
e440a328 9790 }
9791 this->set_is_error();
9792 return false;
9793 }
9794 return true;
9795}
9796
9797// Check types.
9798
9799void
9800Call_expression::do_check_types(Gogo*)
9801{
a6645f74 9802 if (this->classification() == EXPRESSION_ERROR)
9803 return;
9804
e440a328 9805 Function_type* fntype = this->get_function_type();
9806 if (fntype == NULL)
9807 {
5c13bd80 9808 if (!this->fn_->type()->is_error())
e440a328 9809 this->report_error(_("expected function"));
9810 return;
9811 }
9812
1373401e 9813 if (this->expected_result_count_ != 0
9814 && this->expected_result_count_ != this->result_count())
9815 {
9816 if (this->issue_error())
9817 this->report_error(_("function result count mismatch"));
9818 this->set_is_error();
9819 return;
9820 }
9821
09ea332d 9822 bool is_method = fntype->is_method();
9823 if (is_method)
e440a328 9824 {
09ea332d 9825 go_assert(this->args_ != NULL && !this->args_->empty());
9826 Type* rtype = fntype->receiver()->type();
9827 Expression* first_arg = this->args_->front();
1eae365b 9828 // We dereference the values since receivers are always passed
9829 // as pointers.
09ea332d 9830 std::string reason;
1eae365b 9831 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9832 &reason))
e440a328 9833 {
09ea332d 9834 if (reason.empty())
9835 this->report_error(_("incompatible type for receiver"));
9836 else
e440a328 9837 {
631d5788 9838 go_error_at(this->location(),
9839 "incompatible type for receiver (%s)",
9840 reason.c_str());
09ea332d 9841 this->set_is_error();
e440a328 9842 }
9843 }
9844 }
9845
9846 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9847 // we don't have to worry about it here unless something is wrong.
9848 if (this->is_varargs_ && !this->varargs_are_lowered_)
9849 {
9850 if (!fntype->is_varargs())
9851 {
631d5788 9852 go_error_at(this->location(),
9853 _("invalid use of %<...%> calling non-variadic function"));
a6645f74 9854 this->set_is_error();
9855 return;
9856 }
9857 }
e440a328 9858
9859 const Typed_identifier_list* parameters = fntype->parameters();
9860 if (this->args_ == NULL)
9861 {
9862 if (parameters != NULL && !parameters->empty())
9863 this->report_error(_("not enough arguments"));
9864 }
9865 else if (parameters == NULL)
09ea332d 9866 {
9867 if (!is_method || this->args_->size() > 1)
9868 this->report_error(_("too many arguments"));
9869 }
1373401e 9870 else if (this->args_->size() == 1
9871 && this->args_->front()->call_expression() != NULL
9872 && this->args_->front()->call_expression()->result_count() > 1)
9873 {
9874 // This is F(G()) when G returns more than one result. If the
9875 // results can be matched to parameters, it would have been
9876 // lowered in do_lower. If we get here we know there is a
9877 // mismatch.
9878 if (this->args_->front()->call_expression()->result_count()
9879 < parameters->size())
9880 this->report_error(_("not enough arguments"));
9881 else
9882 this->report_error(_("too many arguments"));
9883 }
e440a328 9884 else
9885 {
9886 int i = 0;
09ea332d 9887 Expression_list::const_iterator pa = this->args_->begin();
9888 if (is_method)
9889 ++pa;
9890 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9891 pt != parameters->end();
9892 ++pt, ++pa, ++i)
e440a328 9893 {
09ea332d 9894 if (pa == this->args_->end())
e440a328 9895 {
09ea332d 9896 this->report_error(_("not enough arguments"));
e440a328 9897 return;
9898 }
9899 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9900 (*pa)->location(), false);
9901 }
09ea332d 9902 if (pa != this->args_->end())
9903 this->report_error(_("too many arguments"));
e440a328 9904 }
9905}
9906
72666aed 9907Expression*
9908Call_expression::do_copy()
9909{
9910 Call_expression* call =
9911 Expression::make_call(this->fn_->copy(),
9912 (this->args_ == NULL
9913 ? NULL
9914 : this->args_->copy()),
9915 this->is_varargs_, this->location());
9916
9917 if (this->varargs_are_lowered_)
9918 call->set_varargs_are_lowered();
9919 return call;
9920}
9921
e440a328 9922// Return whether we have to use a temporary variable to ensure that
9923// we evaluate this call expression in order. If the call returns no
ceeb4318 9924// results then it will inevitably be executed last.
e440a328 9925
9926bool
9927Call_expression::do_must_eval_in_order() const
9928{
ceeb4318 9929 return this->result_count() > 0;
e440a328 9930}
9931
e440a328 9932// Get the function and the first argument to use when calling an
9933// interface method.
9934
2387f644 9935Expression*
e440a328 9936Call_expression::interface_method_function(
e440a328 9937 Interface_field_reference_expression* interface_method,
2387f644 9938 Expression** first_arg_ptr)
e440a328 9939{
2387f644 9940 *first_arg_ptr = interface_method->get_underlying_object();
9941 return interface_method->get_function();
e440a328 9942}
9943
9944// Build the call expression.
9945
ea664253 9946Bexpression*
9947Call_expression::do_get_backend(Translate_context* context)
e440a328 9948{
2c809f8f 9949 if (this->call_ != NULL)
ea664253 9950 return this->call_;
e440a328 9951
9952 Function_type* fntype = this->get_function_type();
9953 if (fntype == NULL)
ea664253 9954 return context->backend()->error_expression();
e440a328 9955
9956 if (this->fn_->is_error_expression())
ea664253 9957 return context->backend()->error_expression();
e440a328 9958
9959 Gogo* gogo = context->gogo();
b13c66cd 9960 Location location = this->location();
e440a328 9961
9962 Func_expression* func = this->fn_->func_expression();
e440a328 9963 Interface_field_reference_expression* interface_method =
9964 this->fn_->interface_field_reference_expression();
9965 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 9966 const bool is_interface_method = interface_method != NULL;
e440a328 9967
f8bdf81a 9968 bool has_closure_arg;
8381eda7 9969 if (has_closure)
f8bdf81a 9970 has_closure_arg = true;
8381eda7 9971 else if (func != NULL)
f8bdf81a 9972 has_closure_arg = false;
8381eda7 9973 else if (is_interface_method)
f8bdf81a 9974 has_closure_arg = false;
8381eda7 9975 else
f8bdf81a 9976 has_closure_arg = true;
8381eda7 9977
e440a328 9978 int nargs;
2c809f8f 9979 std::vector<Bexpression*> fn_args;
e440a328 9980 if (this->args_ == NULL || this->args_->empty())
9981 {
f8bdf81a 9982 nargs = is_interface_method ? 1 : 0;
2c809f8f 9983 if (nargs > 0)
9984 fn_args.resize(1);
e440a328 9985 }
09ea332d 9986 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9987 {
9988 // Passing a receiver parameter.
9989 go_assert(!is_interface_method
9990 && fntype->is_method()
9991 && this->args_->size() == 1);
f8bdf81a 9992 nargs = 1;
2c809f8f 9993 fn_args.resize(1);
ea664253 9994 fn_args[0] = this->args_->front()->get_backend(context);
09ea332d 9995 }
e440a328 9996 else
9997 {
9998 const Typed_identifier_list* params = fntype->parameters();
e440a328 9999
10000 nargs = this->args_->size();
09ea332d 10001 int i = is_interface_method ? 1 : 0;
e440a328 10002 nargs += i;
2c809f8f 10003 fn_args.resize(nargs);
e440a328 10004
10005 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 10006 Expression_list::const_iterator pe = this->args_->begin();
10007 if (!is_interface_method && fntype->is_method())
10008 {
ea664253 10009 fn_args[i] = (*pe)->get_backend(context);
09ea332d 10010 ++pe;
10011 ++i;
10012 }
10013 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 10014 {
c484d925 10015 go_assert(pp != params->end());
2c809f8f 10016 Expression* arg =
10017 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10018 location);
ea664253 10019 fn_args[i] = arg->get_backend(context);
e440a328 10020 }
c484d925 10021 go_assert(pp == params->end());
f8bdf81a 10022 go_assert(i == nargs);
e440a328 10023 }
10024
2c809f8f 10025 Expression* fn;
10026 Expression* closure = NULL;
8381eda7 10027 if (func != NULL)
10028 {
10029 Named_object* no = func->named_object();
2c809f8f 10030 fn = Expression::make_func_code_reference(no, location);
10031 if (has_closure)
10032 closure = func->closure();
8381eda7 10033 }
09ea332d 10034 else if (!is_interface_method)
8381eda7 10035 {
2c809f8f 10036 closure = this->fn_;
10037
10038 // The backend representation of this function type is a pointer
10039 // to a struct whose first field is the actual function to call.
10040 Type* pfntype =
10041 Type::make_pointer_type(
10042 Type::make_pointer_type(Type::make_void_type()));
10043 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10044 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
10045 }
e440a328 10046 else
cf609de4 10047 {
2387f644 10048 Expression* first_arg;
2c809f8f 10049 fn = this->interface_method_function(interface_method, &first_arg);
ea664253 10050 fn_args[0] = first_arg->get_backend(context);
e440a328 10051 }
10052
1ecc6157 10053 Bexpression* bclosure = NULL;
10054 if (has_closure_arg)
10055 bclosure = closure->get_backend(context);
f8bdf81a 10056 else
1ecc6157 10057 go_assert(closure == NULL);
f8bdf81a 10058
ea664253 10059 Bexpression* bfn = fn->get_backend(context);
80d1e1a8 10060
10061 // When not calling a named function directly, use a type conversion
10062 // in case the type of the function is a recursive type which refers
10063 // to itself. We don't do this for an interface method because 1)
10064 // an interface method never refers to itself, so we always have a
10065 // function type here; 2) we pass an extra first argument to an
10066 // interface method, so fntype is not correct.
10067 if (func == NULL && !is_interface_method)
10068 {
10069 Btype* bft = fntype->get_backend_fntype(gogo);
10070 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10071 }
10072
1ecc6157 10073 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args,
10074 bclosure, location);
e440a328 10075
2c809f8f 10076 if (this->results_ != NULL)
e440a328 10077 {
2c809f8f 10078 go_assert(this->call_temp_ != NULL);
10079 Expression* call_ref =
10080 Expression::make_temporary_reference(this->call_temp_, location);
ea664253 10081 Bexpression* bcall_ref = call_ref->get_backend(context);
2c809f8f 10082 Bstatement* assn_stmt =
10083 gogo->backend()->assignment_statement(bcall_ref, call, location);
e440a328 10084
2c809f8f 10085 this->call_ = this->set_results(context, bcall_ref);
e440a328 10086
2c809f8f 10087 Bexpression* set_and_call =
10088 gogo->backend()->compound_expression(assn_stmt, this->call_,
10089 location);
ea664253 10090 return set_and_call;
2c809f8f 10091 }
e440a328 10092
2c809f8f 10093 this->call_ = call;
ea664253 10094 return this->call_;
e440a328 10095}
10096
ceeb4318 10097// Set the result variables if this call returns multiple results.
10098
2c809f8f 10099Bexpression*
10100Call_expression::set_results(Translate_context* context, Bexpression* call)
ceeb4318 10101{
2c809f8f 10102 Gogo* gogo = context->gogo();
ceeb4318 10103
2c809f8f 10104 Bexpression* results = NULL;
b13c66cd 10105 Location loc = this->location();
2c809f8f 10106
ceeb4318 10107 size_t rc = this->result_count();
2c809f8f 10108 for (size_t i = 0; i < rc; ++i)
ceeb4318 10109 {
ceeb4318 10110 Temporary_statement* temp = this->result(i);
cd238b8d 10111 if (temp == NULL)
10112 {
10113 go_assert(saw_errors());
2c809f8f 10114 return gogo->backend()->error_expression();
cd238b8d 10115 }
ceeb4318 10116 Temporary_reference_expression* ref =
10117 Expression::make_temporary_reference(temp, loc);
10118 ref->set_is_lvalue();
ceeb4318 10119
ea664253 10120 Bexpression* result_ref = ref->get_backend(context);
2c809f8f 10121 Bexpression* call_result =
10122 gogo->backend()->struct_field_expression(call, i, loc);
10123 Bstatement* assn_stmt =
10124 gogo->backend()->assignment_statement(result_ref, call_result, loc);
ceeb4318 10125
2c809f8f 10126 Bexpression* result =
10127 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 10128
2c809f8f 10129 if (results == NULL)
10130 results = result;
10131 else
10132 {
10133 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
10134 results =
10135 gogo->backend()->compound_expression(expr_stmt, results, loc);
10136 }
10137 }
10138 return results;
ceeb4318 10139}
10140
d751bb78 10141// Dump ast representation for a call expressin.
10142
10143void
10144Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10145{
10146 this->fn_->dump_expression(ast_dump_context);
10147 ast_dump_context->ostream() << "(";
10148 if (args_ != NULL)
10149 ast_dump_context->dump_expression_list(this->args_);
10150
10151 ast_dump_context->ostream() << ") ";
10152}
10153
e440a328 10154// Make a call expression.
10155
10156Call_expression*
10157Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 10158 Location location)
e440a328 10159{
10160 return new Call_expression(fn, args, is_varargs, location);
10161}
10162
da244e59 10163// Class Call_result_expression.
e440a328 10164
10165// Traverse a call result.
10166
10167int
10168Call_result_expression::do_traverse(Traverse* traverse)
10169{
10170 if (traverse->remember_expression(this->call_))
10171 {
10172 // We have already traversed the call expression.
10173 return TRAVERSE_CONTINUE;
10174 }
10175 return Expression::traverse(&this->call_, traverse);
10176}
10177
10178// Get the type.
10179
10180Type*
10181Call_result_expression::do_type()
10182{
425dd051 10183 if (this->classification() == EXPRESSION_ERROR)
10184 return Type::make_error_type();
10185
e440a328 10186 // THIS->CALL_ can be replaced with a temporary reference due to
10187 // Call_expression::do_must_eval_in_order when there is an error.
10188 Call_expression* ce = this->call_->call_expression();
10189 if (ce == NULL)
5e85f268 10190 {
10191 this->set_is_error();
10192 return Type::make_error_type();
10193 }
e440a328 10194 Function_type* fntype = ce->get_function_type();
10195 if (fntype == NULL)
5e85f268 10196 {
e37658e2 10197 if (ce->issue_error())
99b3f06f 10198 {
10199 if (!ce->fn()->type()->is_error())
10200 this->report_error(_("expected function"));
10201 }
5e85f268 10202 this->set_is_error();
10203 return Type::make_error_type();
10204 }
e440a328 10205 const Typed_identifier_list* results = fntype->results();
ceeb4318 10206 if (results == NULL || results->size() < 2)
7b8d861f 10207 {
ceeb4318 10208 if (ce->issue_error())
10209 this->report_error(_("number of results does not match "
10210 "number of values"));
7b8d861f 10211 return Type::make_error_type();
10212 }
e440a328 10213 Typed_identifier_list::const_iterator pr = results->begin();
10214 for (unsigned int i = 0; i < this->index_; ++i)
10215 {
10216 if (pr == results->end())
425dd051 10217 break;
e440a328 10218 ++pr;
10219 }
10220 if (pr == results->end())
425dd051 10221 {
ceeb4318 10222 if (ce->issue_error())
10223 this->report_error(_("number of results does not match "
10224 "number of values"));
425dd051 10225 return Type::make_error_type();
10226 }
e440a328 10227 return pr->type();
10228}
10229
425dd051 10230// Check the type. Just make sure that we trigger the warning in
10231// do_type.
e440a328 10232
10233void
10234Call_result_expression::do_check_types(Gogo*)
10235{
425dd051 10236 this->type();
e440a328 10237}
10238
10239// Determine the type. We have nothing to do here, but the 0 result
10240// needs to pass down to the caller.
10241
10242void
10243Call_result_expression::do_determine_type(const Type_context*)
10244{
fb94b0ca 10245 this->call_->determine_type_no_context();
e440a328 10246}
10247
ea664253 10248// Return the backend representation. We just refer to the temporary set by the
10249// call expression. We don't do this at lowering time because it makes it
ceeb4318 10250// hard to evaluate the call at the right time.
e440a328 10251
ea664253 10252Bexpression*
10253Call_result_expression::do_get_backend(Translate_context* context)
e440a328 10254{
ceeb4318 10255 Call_expression* ce = this->call_->call_expression();
cd238b8d 10256 if (ce == NULL)
10257 {
10258 go_assert(this->call_->is_error_expression());
ea664253 10259 return context->backend()->error_expression();
cd238b8d 10260 }
ceeb4318 10261 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 10262 if (ts == NULL)
10263 {
10264 go_assert(saw_errors());
ea664253 10265 return context->backend()->error_expression();
cd238b8d 10266 }
ceeb4318 10267 Expression* ref = Expression::make_temporary_reference(ts, this->location());
ea664253 10268 return ref->get_backend(context);
e440a328 10269}
10270
d751bb78 10271// Dump ast representation for a call result expression.
10272
10273void
10274Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10275 const
10276{
10277 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10278 // (struct) and the fields are referenced instead.
10279 ast_dump_context->ostream() << this->index_ << "@(";
10280 ast_dump_context->dump_expression(this->call_);
10281 ast_dump_context->ostream() << ")";
10282}
10283
e440a328 10284// Make a reference to a single result of a call which returns
10285// multiple results.
10286
10287Expression*
10288Expression::make_call_result(Call_expression* call, unsigned int index)
10289{
10290 return new Call_result_expression(call, index);
10291}
10292
10293// Class Index_expression.
10294
10295// Traversal.
10296
10297int
10298Index_expression::do_traverse(Traverse* traverse)
10299{
10300 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10301 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10302 || (this->end_ != NULL
acf2b673 10303 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10304 || (this->cap_ != NULL
10305 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 10306 return TRAVERSE_EXIT;
10307 return TRAVERSE_CONTINUE;
10308}
10309
10310// Lower an index expression. This converts the generic index
10311// expression into an array index, a string index, or a map index.
10312
10313Expression*
ceeb4318 10314Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 10315{
b13c66cd 10316 Location location = this->location();
e440a328 10317 Expression* left = this->left_;
10318 Expression* start = this->start_;
10319 Expression* end = this->end_;
acf2b673 10320 Expression* cap = this->cap_;
e440a328 10321
10322 Type* type = left->type();
5c13bd80 10323 if (type->is_error())
d9f3743a 10324 {
10325 go_assert(saw_errors());
10326 return Expression::make_error(location);
10327 }
b0cf7ddd 10328 else if (left->is_type_expression())
10329 {
631d5788 10330 go_error_at(location, "attempt to index type expression");
b0cf7ddd 10331 return Expression::make_error(location);
10332 }
e440a328 10333 else if (type->array_type() != NULL)
acf2b673 10334 return Expression::make_array_index(left, start, end, cap, location);
e440a328 10335 else if (type->points_to() != NULL
10336 && type->points_to()->array_type() != NULL
411eb89e 10337 && !type->points_to()->is_slice_type())
e440a328 10338 {
10339 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10340 location);
38092374 10341
10342 // For an ordinary index into the array, the pointer will be
10343 // dereferenced. For a slice it will not--the resulting slice
10344 // will simply reuse the pointer, which is incorrect if that
10345 // pointer is nil.
10346 if (end != NULL || cap != NULL)
10347 deref->issue_nil_check();
10348
acf2b673 10349 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 10350 }
10351 else if (type->is_string_type())
acf2b673 10352 {
10353 if (cap != NULL)
10354 {
631d5788 10355 go_error_at(location, "invalid 3-index slice of string");
acf2b673 10356 return Expression::make_error(location);
10357 }
10358 return Expression::make_string_index(left, start, end, location);
10359 }
e440a328 10360 else if (type->map_type() != NULL)
10361 {
acf2b673 10362 if (end != NULL || cap != NULL)
e440a328 10363 {
631d5788 10364 go_error_at(location, "invalid slice of map");
e440a328 10365 return Expression::make_error(location);
10366 }
0d5530d9 10367 return Expression::make_map_index(left, start, location);
e440a328 10368 }
10369 else
10370 {
631d5788 10371 go_error_at(location,
10372 "attempt to index object which is not array, string, or map");
e440a328 10373 return Expression::make_error(location);
10374 }
10375}
10376
acf2b673 10377// Write an indexed expression
10378// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 10379
10380void
10381Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10382 const Expression* expr,
10383 const Expression* start,
acf2b673 10384 const Expression* end,
10385 const Expression* cap)
d751bb78 10386{
10387 expr->dump_expression(ast_dump_context);
10388 ast_dump_context->ostream() << "[";
10389 start->dump_expression(ast_dump_context);
10390 if (end != NULL)
10391 {
10392 ast_dump_context->ostream() << ":";
10393 end->dump_expression(ast_dump_context);
10394 }
acf2b673 10395 if (cap != NULL)
10396 {
10397 ast_dump_context->ostream() << ":";
10398 cap->dump_expression(ast_dump_context);
10399 }
d751bb78 10400 ast_dump_context->ostream() << "]";
10401}
10402
10403// Dump ast representation for an index expression.
10404
10405void
10406Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10407 const
10408{
10409 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 10410 this->start_, this->end_, this->cap_);
d751bb78 10411}
10412
e440a328 10413// Make an index expression.
10414
10415Expression*
10416Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 10417 Expression* cap, Location location)
e440a328 10418{
acf2b673 10419 return new Index_expression(left, start, end, cap, location);
e440a328 10420}
10421
da244e59 10422// Class Array_index_expression.
e440a328 10423
10424// Array index traversal.
10425
10426int
10427Array_index_expression::do_traverse(Traverse* traverse)
10428{
10429 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10430 return TRAVERSE_EXIT;
10431 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10432 return TRAVERSE_EXIT;
10433 if (this->end_ != NULL)
10434 {
10435 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10436 return TRAVERSE_EXIT;
10437 }
acf2b673 10438 if (this->cap_ != NULL)
10439 {
10440 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10441 return TRAVERSE_EXIT;
10442 }
e440a328 10443 return TRAVERSE_CONTINUE;
10444}
10445
10446// Return the type of an array index.
10447
10448Type*
10449Array_index_expression::do_type()
10450{
10451 if (this->type_ == NULL)
10452 {
10453 Array_type* type = this->array_->type()->array_type();
10454 if (type == NULL)
10455 this->type_ = Type::make_error_type();
10456 else if (this->end_ == NULL)
10457 this->type_ = type->element_type();
411eb89e 10458 else if (type->is_slice_type())
e440a328 10459 {
10460 // A slice of a slice has the same type as the original
10461 // slice.
10462 this->type_ = this->array_->type()->deref();
10463 }
10464 else
10465 {
10466 // A slice of an array is a slice.
10467 this->type_ = Type::make_array_type(type->element_type(), NULL);
10468 }
10469 }
10470 return this->type_;
10471}
10472
10473// Set the type of an array index.
10474
10475void
10476Array_index_expression::do_determine_type(const Type_context*)
10477{
10478 this->array_->determine_type_no_context();
f77aa642 10479
10480 Type_context index_context(Type::lookup_integer_type("int"), false);
10481 if (this->start_->is_constant())
10482 this->start_->determine_type(&index_context);
10483 else
10484 this->start_->determine_type_no_context();
e440a328 10485 if (this->end_ != NULL)
f77aa642 10486 {
10487 if (this->end_->is_constant())
10488 this->end_->determine_type(&index_context);
10489 else
10490 this->end_->determine_type_no_context();
10491 }
acf2b673 10492 if (this->cap_ != NULL)
f77aa642 10493 {
10494 if (this->cap_->is_constant())
10495 this->cap_->determine_type(&index_context);
10496 else
10497 this->cap_->determine_type_no_context();
10498 }
e440a328 10499}
10500
10501// Check types of an array index.
10502
10503void
d0a50ed8 10504Array_index_expression::do_check_types(Gogo* gogo)
e440a328 10505{
f6bc81e6 10506 Numeric_constant nc;
10507 unsigned long v;
10508 if (this->start_->type()->integer_type() == NULL
10509 && !this->start_->type()->is_error()
10510 && (!this->start_->numeric_constant_value(&nc)
10511 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10512 this->report_error(_("index must be integer"));
10513 if (this->end_ != NULL
10514 && this->end_->type()->integer_type() == NULL
99b3f06f 10515 && !this->end_->type()->is_error()
10516 && !this->end_->is_nil_expression()
f6bc81e6 10517 && !this->end_->is_error_expression()
10518 && (!this->end_->numeric_constant_value(&nc)
10519 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10520 this->report_error(_("slice end must be integer"));
acf2b673 10521 if (this->cap_ != NULL
10522 && this->cap_->type()->integer_type() == NULL
10523 && !this->cap_->type()->is_error()
10524 && !this->cap_->is_nil_expression()
10525 && !this->cap_->is_error_expression()
10526 && (!this->cap_->numeric_constant_value(&nc)
10527 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10528 this->report_error(_("slice capacity must be integer"));
e440a328 10529
10530 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 10531 if (array_type == NULL)
10532 {
c484d925 10533 go_assert(this->array_->type()->is_error());
f9c68f17 10534 return;
10535 }
e440a328 10536
10537 unsigned int int_bits =
10538 Type::lookup_integer_type("int")->integer_type()->bits();
10539
0c77715b 10540 Numeric_constant lvalnc;
e440a328 10541 mpz_t lval;
e440a328 10542 bool lval_valid = (array_type->length() != NULL
0c77715b 10543 && array_type->length()->numeric_constant_value(&lvalnc)
10544 && lvalnc.to_int(&lval));
10545 Numeric_constant inc;
e440a328 10546 mpz_t ival;
0bd5d859 10547 bool ival_valid = false;
0c77715b 10548 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10549 {
0bd5d859 10550 ival_valid = true;
e440a328 10551 if (mpz_sgn(ival) < 0
10552 || mpz_sizeinbase(ival, 2) >= int_bits
10553 || (lval_valid
10554 && (this->end_ == NULL
10555 ? mpz_cmp(ival, lval) >= 0
10556 : mpz_cmp(ival, lval) > 0)))
10557 {
631d5788 10558 go_error_at(this->start_->location(), "array index out of bounds");
e440a328 10559 this->set_is_error();
10560 }
10561 }
10562 if (this->end_ != NULL && !this->end_->is_nil_expression())
10563 {
0c77715b 10564 Numeric_constant enc;
10565 mpz_t eval;
acf2b673 10566 bool eval_valid = false;
0c77715b 10567 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10568 {
acf2b673 10569 eval_valid = true;
0c77715b 10570 if (mpz_sgn(eval) < 0
10571 || mpz_sizeinbase(eval, 2) >= int_bits
10572 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 10573 {
631d5788 10574 go_error_at(this->end_->location(), "array index out of bounds");
e440a328 10575 this->set_is_error();
10576 }
0bd5d859 10577 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10578 this->report_error(_("inverted slice range"));
e440a328 10579 }
acf2b673 10580
10581 Numeric_constant cnc;
10582 mpz_t cval;
10583 if (this->cap_ != NULL
10584 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10585 {
10586 if (mpz_sgn(cval) < 0
10587 || mpz_sizeinbase(cval, 2) >= int_bits
10588 || (lval_valid && mpz_cmp(cval, lval) > 0))
10589 {
631d5788 10590 go_error_at(this->cap_->location(), "array index out of bounds");
acf2b673 10591 this->set_is_error();
10592 }
10593 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10594 {
631d5788 10595 go_error_at(this->cap_->location(),
10596 "invalid slice index: capacity less than start");
acf2b673 10597 this->set_is_error();
10598 }
10599 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10600 {
631d5788 10601 go_error_at(this->cap_->location(),
10602 "invalid slice index: capacity less than length");
acf2b673 10603 this->set_is_error();
10604 }
10605 mpz_clear(cval);
10606 }
10607
10608 if (eval_valid)
10609 mpz_clear(eval);
e440a328 10610 }
0bd5d859 10611 if (ival_valid)
10612 mpz_clear(ival);
0c77715b 10613 if (lval_valid)
10614 mpz_clear(lval);
e440a328 10615
10616 // A slice of an array requires an addressable array. A slice of a
10617 // slice is always possible.
411eb89e 10618 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 10619 {
10620 if (!this->array_->is_addressable())
8da39c3b 10621 this->report_error(_("slice of unaddressable value"));
88ec30c8 10622 else
d0a50ed8 10623 {
10624 bool escapes = true;
10625
10626 // When compiling the runtime, a slice operation does not
10627 // cause local variables to escape. When escape analysis
10628 // becomes the default, this should be changed to make it an
10629 // error if we have a slice operation that escapes.
10630 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
10631 escapes = false;
10632
10633 this->array_->address_taken(escapes);
10634 }
88ec30c8 10635 }
e440a328 10636}
10637
2c809f8f 10638// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 10639
10640Expression*
10641Array_index_expression::do_flatten(Gogo*, Named_object*,
10642 Statement_inserter* inserter)
10643{
10644 Location loc = this->location();
5bf8be8b 10645 Expression* array = this->array_;
10646 Expression* start = this->start_;
10647 Expression* end = this->end_;
10648 Expression* cap = this->cap_;
10649 if (array->is_error_expression()
10650 || array->type()->is_error_type()
10651 || start->is_error_expression()
10652 || start->type()->is_error_type()
10653 || (end != NULL
10654 && (end->is_error_expression() || end->type()->is_error_type()))
10655 || (cap != NULL
10656 && (cap->is_error_expression() || cap->type()->is_error_type())))
10657 {
10658 go_assert(saw_errors());
10659 return Expression::make_error(loc);
10660 }
10661
2c809f8f 10662 Temporary_statement* temp;
5bf8be8b 10663 if (array->type()->is_slice_type() && !array->is_variable())
35a54f17 10664 {
5bf8be8b 10665 temp = Statement::make_temporary(NULL, array, loc);
35a54f17 10666 inserter->insert(temp);
10667 this->array_ = Expression::make_temporary_reference(temp, loc);
10668 }
5bf8be8b 10669 if (!start->is_variable())
2c809f8f 10670 {
5bf8be8b 10671 temp = Statement::make_temporary(NULL, start, loc);
2c809f8f 10672 inserter->insert(temp);
10673 this->start_ = Expression::make_temporary_reference(temp, loc);
10674 }
5bf8be8b 10675 if (end != NULL
10676 && !end->is_nil_expression()
10677 && !end->is_variable())
2c809f8f 10678 {
5bf8be8b 10679 temp = Statement::make_temporary(NULL, end, loc);
2c809f8f 10680 inserter->insert(temp);
10681 this->end_ = Expression::make_temporary_reference(temp, loc);
10682 }
5bf8be8b 10683 if (cap!= NULL && !cap->is_variable())
2c809f8f 10684 {
5bf8be8b 10685 temp = Statement::make_temporary(NULL, cap, loc);
2c809f8f 10686 inserter->insert(temp);
10687 this->cap_ = Expression::make_temporary_reference(temp, loc);
10688 }
10689
35a54f17 10690 return this;
10691}
10692
e440a328 10693// Return whether this expression is addressable.
10694
10695bool
10696Array_index_expression::do_is_addressable() const
10697{
10698 // A slice expression is not addressable.
10699 if (this->end_ != NULL)
10700 return false;
10701
10702 // An index into a slice is addressable.
411eb89e 10703 if (this->array_->type()->is_slice_type())
e440a328 10704 return true;
10705
10706 // An index into an array is addressable if the array is
10707 // addressable.
10708 return this->array_->is_addressable();
10709}
10710
ea664253 10711// Get the backend representation for an array index.
e440a328 10712
ea664253 10713Bexpression*
10714Array_index_expression::do_get_backend(Translate_context* context)
e440a328 10715{
e440a328 10716 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10717 if (array_type == NULL)
10718 {
c484d925 10719 go_assert(this->array_->type()->is_error());
ea664253 10720 return context->backend()->error_expression();
d8cd8e2d 10721 }
35a54f17 10722 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10723
2c809f8f 10724 Location loc = this->location();
10725 Gogo* gogo = context->gogo();
10726
6dfedc16 10727 Type* int_type = Type::lookup_integer_type("int");
10728 Btype* int_btype = int_type->get_backend(gogo);
e440a328 10729
2c809f8f 10730 // We need to convert the length and capacity to the Go "int" type here
10731 // because the length of a fixed-length array could be of type "uintptr"
10732 // and gimple disallows binary operations between "uintptr" and other
10733 // integer types. FIXME.
10734 Bexpression* length = NULL;
a04bfdfc 10735 if (this->end_ == NULL || this->end_->is_nil_expression())
10736 {
35a54f17 10737 Expression* len = array_type->get_length(gogo, this->array_);
ea664253 10738 length = len->get_backend(context);
2c809f8f 10739 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 10740 }
10741
2c809f8f 10742 Bexpression* capacity = NULL;
a04bfdfc 10743 if (this->end_ != NULL)
10744 {
35a54f17 10745 Expression* cap = array_type->get_capacity(gogo, this->array_);
ea664253 10746 capacity = cap->get_backend(context);
2c809f8f 10747 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 10748 }
10749
2c809f8f 10750 Bexpression* cap_arg = capacity;
acf2b673 10751 if (this->cap_ != NULL)
10752 {
ea664253 10753 cap_arg = this->cap_->get_backend(context);
2c809f8f 10754 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 10755 }
10756
2c809f8f 10757 if (length == NULL)
10758 length = cap_arg;
e440a328 10759
10760 int code = (array_type->length() != NULL
10761 ? (this->end_ == NULL
10762 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10763 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10764 : (this->end_ == NULL
10765 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10766 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
ea664253 10767 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
2c809f8f 10768
6dfedc16 10769 if (this->start_->type()->integer_type() == NULL
10770 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10771 {
10772 go_assert(saw_errors());
10773 return context->backend()->error_expression();
10774 }
d9f3743a 10775
ea664253 10776 Bexpression* bad_index =
d9f3743a 10777 Expression::check_bounds(this->start_, loc)->get_backend(context);
2c809f8f 10778
ea664253 10779 Bexpression* start = this->start_->get_backend(context);
2c809f8f 10780 start = gogo->backend()->convert_expression(int_btype, start, loc);
10781 Bexpression* start_too_large =
10782 gogo->backend()->binary_expression((this->end_ == NULL
10783 ? OPERATOR_GE
10784 : OPERATOR_GT),
10785 start,
10786 (this->end_ == NULL
10787 ? length
10788 : capacity),
10789 loc);
10790 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10791 bad_index, loc);
e440a328 10792
10793 if (this->end_ == NULL)
10794 {
10795 // Simple array indexing. This has to return an l-value, so
2c809f8f 10796 // wrap the index check into START.
10797 start =
10798 gogo->backend()->conditional_expression(int_btype, bad_index,
10799 crash, start, loc);
e440a328 10800
2c809f8f 10801 Bexpression* ret;
e440a328 10802 if (array_type->length() != NULL)
10803 {
ea664253 10804 Bexpression* array = this->array_->get_backend(context);
2c809f8f 10805 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 10806 }
10807 else
10808 {
2c809f8f 10809 // Slice.
10810 Expression* valptr =
35a54f17 10811 array_type->get_value_pointer(gogo, this->array_);
ea664253 10812 Bexpression* ptr = valptr->get_backend(context);
2c809f8f 10813 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
9b27b43c 10814
10815 Type* ele_type = this->array_->type()->array_type()->element_type();
10816 Btype* ele_btype = ele_type->get_backend(gogo);
10817 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
e440a328 10818 }
ea664253 10819 return ret;
e440a328 10820 }
10821
10822 // Array slice.
10823
acf2b673 10824 if (this->cap_ != NULL)
10825 {
2c809f8f 10826 Bexpression* bounds_bcheck =
ea664253 10827 Expression::check_bounds(this->cap_, loc)->get_backend(context);
2c809f8f 10828 bad_index =
10829 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10830 bad_index, loc);
10831 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10832
10833 Bexpression* cap_too_small =
10834 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10835 Bexpression* cap_too_large =
10836 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10837 Bexpression* bad_cap =
10838 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10839 cap_too_large, loc);
10840 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10841 bad_index, loc);
10842 }
10843
10844 Bexpression* end;
e440a328 10845 if (this->end_->is_nil_expression())
2c809f8f 10846 end = length;
e440a328 10847 else
10848 {
2c809f8f 10849 Bexpression* bounds_bcheck =
ea664253 10850 Expression::check_bounds(this->end_, loc)->get_backend(context);
e440a328 10851
2c809f8f 10852 bad_index =
10853 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10854 bad_index, loc);
e440a328 10855
ea664253 10856 end = this->end_->get_backend(context);
2c809f8f 10857 end = gogo->backend()->convert_expression(int_btype, end, loc);
10858 Bexpression* end_too_small =
10859 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10860 Bexpression* end_too_large =
10861 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10862 Bexpression* bad_end =
10863 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10864 end_too_large, loc);
10865 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10866 bad_index, loc);
e440a328 10867 }
10868
35a54f17 10869 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
ea664253 10870 Bexpression* val = valptr->get_backend(context);
2c809f8f 10871 val = gogo->backend()->pointer_offset_expression(val, start, loc);
e440a328 10872
2c809f8f 10873 Bexpression* result_length =
10874 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 10875
2c809f8f 10876 Bexpression* result_capacity =
10877 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 10878
2c809f8f 10879 Btype* struct_btype = this->type()->get_backend(gogo);
10880 std::vector<Bexpression*> init;
10881 init.push_back(val);
10882 init.push_back(result_length);
10883 init.push_back(result_capacity);
e440a328 10884
2c809f8f 10885 Bexpression* ctor =
10886 gogo->backend()->constructor_expression(struct_btype, init, loc);
ea664253 10887 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10888 crash, ctor, loc);
e440a328 10889}
10890
d751bb78 10891// Dump ast representation for an array index expression.
10892
10893void
10894Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10895 const
10896{
10897 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10898 this->start_, this->end_, this->cap_);
d751bb78 10899}
10900
acf2b673 10901// Make an array index expression. END and CAP may be NULL.
e440a328 10902
10903Expression*
10904Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10905 Expression* end, Expression* cap,
10906 Location location)
e440a328 10907{
acf2b673 10908 return new Array_index_expression(array, start, end, cap, location);
e440a328 10909}
10910
50075d74 10911// Class String_index_expression.
e440a328 10912
10913// String index traversal.
10914
10915int
10916String_index_expression::do_traverse(Traverse* traverse)
10917{
10918 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10919 return TRAVERSE_EXIT;
10920 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10921 return TRAVERSE_EXIT;
10922 if (this->end_ != NULL)
10923 {
10924 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10925 return TRAVERSE_EXIT;
10926 }
10927 return TRAVERSE_CONTINUE;
10928}
10929
2c809f8f 10930Expression*
10931String_index_expression::do_flatten(Gogo*, Named_object*,
10932 Statement_inserter* inserter)
e440a328 10933{
2c809f8f 10934 Location loc = this->location();
5bf8be8b 10935 Expression* string = this->string_;
10936 Expression* start = this->start_;
10937 Expression* end = this->end_;
10938 if (string->is_error_expression()
10939 || string->type()->is_error_type()
10940 || start->is_error_expression()
10941 || start->type()->is_error_type()
10942 || (end != NULL
10943 && (end->is_error_expression() || end->type()->is_error_type())))
10944 {
10945 go_assert(saw_errors());
10946 return Expression::make_error(loc);
10947 }
10948
10949 Temporary_statement* temp;
2c809f8f 10950 if (!this->string_->is_variable())
10951 {
10952 temp = Statement::make_temporary(NULL, this->string_, loc);
10953 inserter->insert(temp);
10954 this->string_ = Expression::make_temporary_reference(temp, loc);
10955 }
10956 if (!this->start_->is_variable())
10957 {
10958 temp = Statement::make_temporary(NULL, this->start_, loc);
10959 inserter->insert(temp);
10960 this->start_ = Expression::make_temporary_reference(temp, loc);
10961 }
10962 if (this->end_ != NULL
10963 && !this->end_->is_nil_expression()
10964 && !this->end_->is_variable())
10965 {
10966 temp = Statement::make_temporary(NULL, this->end_, loc);
10967 inserter->insert(temp);
10968 this->end_ = Expression::make_temporary_reference(temp, loc);
10969 }
10970
10971 return this;
10972}
10973
10974// Return the type of a string index.
10975
10976Type*
10977String_index_expression::do_type()
10978{
10979 if (this->end_ == NULL)
10980 return Type::lookup_integer_type("uint8");
10981 else
10982 return this->string_->type();
10983}
10984
10985// Determine the type of a string index.
10986
10987void
10988String_index_expression::do_determine_type(const Type_context*)
10989{
10990 this->string_->determine_type_no_context();
f77aa642 10991
10992 Type_context index_context(Type::lookup_integer_type("int"), false);
10993 if (this->start_->is_constant())
10994 this->start_->determine_type(&index_context);
10995 else
10996 this->start_->determine_type_no_context();
e440a328 10997 if (this->end_ != NULL)
f77aa642 10998 {
10999 if (this->end_->is_constant())
11000 this->end_->determine_type(&index_context);
11001 else
11002 this->end_->determine_type_no_context();
11003 }
e440a328 11004}
11005
11006// Check types of a string index.
11007
11008void
11009String_index_expression::do_check_types(Gogo*)
11010{
acdc230d 11011 Numeric_constant nc;
11012 unsigned long v;
11013 if (this->start_->type()->integer_type() == NULL
11014 && !this->start_->type()->is_error()
11015 && (!this->start_->numeric_constant_value(&nc)
11016 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 11017 this->report_error(_("index must be integer"));
11018 if (this->end_ != NULL
11019 && this->end_->type()->integer_type() == NULL
acdc230d 11020 && !this->end_->type()->is_error()
11021 && !this->end_->is_nil_expression()
11022 && !this->end_->is_error_expression()
11023 && (!this->end_->numeric_constant_value(&nc)
11024 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 11025 this->report_error(_("slice end must be integer"));
11026
11027 std::string sval;
11028 bool sval_valid = this->string_->string_constant_value(&sval);
11029
0c77715b 11030 Numeric_constant inc;
e440a328 11031 mpz_t ival;
0bd5d859 11032 bool ival_valid = false;
0c77715b 11033 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 11034 {
0bd5d859 11035 ival_valid = true;
e440a328 11036 if (mpz_sgn(ival) < 0
b10f32fb 11037 || (sval_valid
11038 && (this->end_ == NULL
11039 ? mpz_cmp_ui(ival, sval.length()) >= 0
11040 : mpz_cmp_ui(ival, sval.length()) > 0)))
e440a328 11041 {
631d5788 11042 go_error_at(this->start_->location(), "string index out of bounds");
e440a328 11043 this->set_is_error();
11044 }
11045 }
11046 if (this->end_ != NULL && !this->end_->is_nil_expression())
11047 {
0c77715b 11048 Numeric_constant enc;
11049 mpz_t eval;
11050 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 11051 {
0c77715b 11052 if (mpz_sgn(eval) < 0
11053 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 11054 {
631d5788 11055 go_error_at(this->end_->location(), "string index out of bounds");
e440a328 11056 this->set_is_error();
11057 }
0bd5d859 11058 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11059 this->report_error(_("inverted slice range"));
0c77715b 11060 mpz_clear(eval);
e440a328 11061 }
11062 }
0bd5d859 11063 if (ival_valid)
11064 mpz_clear(ival);
e440a328 11065}
11066
ea664253 11067// Get the backend representation for a string index.
e440a328 11068
ea664253 11069Bexpression*
11070String_index_expression::do_get_backend(Translate_context* context)
e440a328 11071{
b13c66cd 11072 Location loc = this->location();
2c809f8f 11073 Expression* string_arg = this->string_;
11074 if (this->string_->type()->points_to() != NULL)
11075 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 11076
2c809f8f 11077 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 11078
2c809f8f 11079 int code = (this->end_ == NULL
11080 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11081 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 11082
2c809f8f 11083 Gogo* gogo = context->gogo();
ea664253 11084 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
1b1f2abf 11085
11086 Type* int_type = Type::lookup_integer_type("int");
e440a328 11087
2c809f8f 11088 // It is possible that an error occurred earlier because the start index
11089 // cannot be represented as an integer type. In this case, we shouldn't
11090 // try casting the starting index into an integer since
11091 // Type_conversion_expression will fail to get the backend representation.
11092 // FIXME.
11093 if (this->start_->type()->integer_type() == NULL
11094 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11095 {
11096 go_assert(saw_errors());
ea664253 11097 return context->backend()->error_expression();
2c809f8f 11098 }
e440a328 11099
2c809f8f 11100 Expression* start = Expression::make_cast(int_type, this->start_, loc);
e440a328 11101
2c809f8f 11102 if (this->end_ == NULL)
11103 {
11104 Expression* length =
11105 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 11106
2c809f8f 11107 Expression* start_too_large =
11108 Expression::make_binary(OPERATOR_GE, start, length, loc);
11109 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11110 bad_index, loc);
11111 Expression* bytes =
11112 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 11113
ea664253 11114 Bexpression* bstart = start->get_backend(context);
11115 Bexpression* ptr = bytes->get_backend(context);
2c809f8f 11116 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
9b27b43c 11117 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11118 Bexpression* index =
11119 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
e440a328 11120
2c809f8f 11121 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
ea664253 11122 Bexpression* index_error = bad_index->get_backend(context);
11123 return gogo->backend()->conditional_expression(byte_btype, index_error,
11124 crash, index, loc);
2c809f8f 11125 }
11126
11127 Expression* end = NULL;
11128 if (this->end_->is_nil_expression())
e67508fa 11129 end = Expression::make_integer_sl(-1, int_type, loc);
e440a328 11130 else
11131 {
2c809f8f 11132 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11133 bad_index =
11134 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11135 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 11136 }
2c809f8f 11137
11138 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11139 string_arg, start, end);
ea664253 11140 Bexpression* bstrslice = strslice->get_backend(context);
2c809f8f 11141
11142 Btype* str_btype = strslice->type()->get_backend(gogo);
ea664253 11143 Bexpression* index_error = bad_index->get_backend(context);
11144 return gogo->backend()->conditional_expression(str_btype, index_error,
11145 crash, bstrslice, loc);
e440a328 11146}
11147
d751bb78 11148// Dump ast representation for a string index expression.
11149
11150void
11151String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11152 const
11153{
acf2b673 11154 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11155 this->start_, this->end_, NULL);
d751bb78 11156}
11157
e440a328 11158// Make a string index expression. END may be NULL.
11159
11160Expression*
11161Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 11162 Expression* end, Location location)
e440a328 11163{
11164 return new String_index_expression(string, start, end, location);
11165}
11166
11167// Class Map_index.
11168
11169// Get the type of the map.
11170
11171Map_type*
11172Map_index_expression::get_map_type() const
11173{
0d5530d9 11174 Map_type* mt = this->map_->type()->map_type();
c7524fae 11175 if (mt == NULL)
c484d925 11176 go_assert(saw_errors());
e440a328 11177 return mt;
11178}
11179
11180// Map index traversal.
11181
11182int
11183Map_index_expression::do_traverse(Traverse* traverse)
11184{
11185 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11186 return TRAVERSE_EXIT;
11187 return Expression::traverse(&this->index_, traverse);
11188}
11189
2c809f8f 11190// We need to pass in a pointer to the key, so flatten the index into a
11191// temporary variable if it isn't already. The value pointer will be
11192// dereferenced and checked for nil, so flatten into a temporary to avoid
11193// recomputation.
11194
11195Expression*
91c0fd76 11196Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
2c809f8f 11197 Statement_inserter* inserter)
11198{
91c0fd76 11199 Location loc = this->location();
2c809f8f 11200 Map_type* mt = this->get_map_type();
5bf8be8b 11201 if (this->index()->is_error_expression()
11202 || this->index()->type()->is_error_type()
11203 || mt->is_error_type())
11204 {
11205 go_assert(saw_errors());
11206 return Expression::make_error(loc);
11207 }
11208
91c0fd76 11209 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11210 {
11211 if (this->index_->type()->interface_type() != NULL
11212 && !this->index_->is_variable())
11213 {
11214 Temporary_statement* temp =
11215 Statement::make_temporary(NULL, this->index_, loc);
11216 inserter->insert(temp);
11217 this->index_ = Expression::make_temporary_reference(temp, loc);
11218 }
11219 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11220 this->index_, loc);
11221 }
2c809f8f 11222
11223 if (!this->index_->is_variable())
11224 {
11225 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
91c0fd76 11226 loc);
2c809f8f 11227 inserter->insert(temp);
91c0fd76 11228 this->index_ = Expression::make_temporary_reference(temp, loc);
2c809f8f 11229 }
11230
11231 if (this->value_pointer_ == NULL)
0d5530d9 11232 this->get_value_pointer(gogo);
5bf8be8b 11233 if (this->value_pointer_->is_error_expression()
11234 || this->value_pointer_->type()->is_error_type())
11235 return Expression::make_error(loc);
2c809f8f 11236 if (!this->value_pointer_->is_variable())
11237 {
11238 Temporary_statement* temp =
91c0fd76 11239 Statement::make_temporary(NULL, this->value_pointer_, loc);
2c809f8f 11240 inserter->insert(temp);
91c0fd76 11241 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
2c809f8f 11242 }
11243
11244 return this;
11245}
11246
e440a328 11247// Return the type of a map index.
11248
11249Type*
11250Map_index_expression::do_type()
11251{
c7524fae 11252 Map_type* mt = this->get_map_type();
11253 if (mt == NULL)
11254 return Type::make_error_type();
0d5530d9 11255 return mt->val_type();
e440a328 11256}
11257
11258// Fix the type of a map index.
11259
11260void
11261Map_index_expression::do_determine_type(const Type_context*)
11262{
11263 this->map_->determine_type_no_context();
c7524fae 11264 Map_type* mt = this->get_map_type();
11265 Type* key_type = mt == NULL ? NULL : mt->key_type();
11266 Type_context subcontext(key_type, false);
e440a328 11267 this->index_->determine_type(&subcontext);
11268}
11269
11270// Check types of a map index.
11271
11272void
11273Map_index_expression::do_check_types(Gogo*)
11274{
11275 std::string reason;
c7524fae 11276 Map_type* mt = this->get_map_type();
11277 if (mt == NULL)
11278 return;
11279 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 11280 {
11281 if (reason.empty())
11282 this->report_error(_("incompatible type for map index"));
11283 else
11284 {
631d5788 11285 go_error_at(this->location(), "incompatible type for map index (%s)",
11286 reason.c_str());
e440a328 11287 this->set_is_error();
11288 }
11289 }
11290}
11291
ea664253 11292// Get the backend representation for a map index.
e440a328 11293
ea664253 11294Bexpression*
11295Map_index_expression::do_get_backend(Translate_context* context)
e440a328 11296{
11297 Map_type* type = this->get_map_type();
c7524fae 11298 if (type == NULL)
2c809f8f 11299 {
11300 go_assert(saw_errors());
ea664253 11301 return context->backend()->error_expression();
2c809f8f 11302 }
e440a328 11303
2c809f8f 11304 go_assert(this->value_pointer_ != NULL
11305 && this->value_pointer_->is_variable());
e440a328 11306
0d5530d9 11307 Expression* val = Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
11308 this->location());
11309 return val->get_backend(context);
e440a328 11310}
11311
0d5530d9 11312// Get an expression for the map index. This returns an expression
11313// that evaluates to a pointer to a value. If the key is not in the
11314// map, the pointer will point to a zero value.
e440a328 11315
2c809f8f 11316Expression*
0d5530d9 11317Map_index_expression::get_value_pointer(Gogo* gogo)
e440a328 11318{
2c809f8f 11319 if (this->value_pointer_ == NULL)
746d2e73 11320 {
2c809f8f 11321 Map_type* type = this->get_map_type();
11322 if (type == NULL)
746d2e73 11323 {
2c809f8f 11324 go_assert(saw_errors());
11325 return Expression::make_error(this->location());
746d2e73 11326 }
e440a328 11327
2c809f8f 11328 Location loc = this->location();
11329 Expression* map_ref = this->map_;
e440a328 11330
0d5530d9 11331 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11332 this->index_,
2c809f8f 11333 loc);
0d5530d9 11334
11335 Expression* zero = type->fat_zero_value(gogo);
11336
11337 Expression* map_index;
11338
11339 if (zero == NULL)
11340 map_index =
11341 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11342 Expression::make_type_descriptor(type, loc),
11343 map_ref, index_ptr);
11344 else
11345 map_index =
11346 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11347 Expression::make_type_descriptor(type, loc),
11348 map_ref, index_ptr, zero);
2c809f8f 11349
11350 Type* val_type = type->val_type();
11351 this->value_pointer_ =
11352 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11353 map_index, this->location());
11354 }
0d5530d9 11355
2c809f8f 11356 return this->value_pointer_;
e440a328 11357}
11358
d751bb78 11359// Dump ast representation for a map index expression
11360
11361void
11362Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11363 const
11364{
acf2b673 11365 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11366 this->index_, NULL, NULL);
d751bb78 11367}
11368
e440a328 11369// Make a map index expression.
11370
11371Map_index_expression*
11372Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 11373 Location location)
e440a328 11374{
11375 return new Map_index_expression(map, index, location);
11376}
11377
11378// Class Field_reference_expression.
11379
149eabc5 11380// Lower a field reference expression. There is nothing to lower, but
11381// this is where we generate the tracking information for fields with
11382// the magic go:"track" tag.
11383
11384Expression*
11385Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11386 Statement_inserter* inserter, int)
11387{
11388 Struct_type* struct_type = this->expr_->type()->struct_type();
11389 if (struct_type == NULL)
11390 {
11391 // Error will be reported elsewhere.
11392 return this;
11393 }
11394 const Struct_field* field = struct_type->field(this->field_index_);
11395 if (field == NULL)
11396 return this;
11397 if (!field->has_tag())
11398 return this;
11399 if (field->tag().find("go:\"track\"") == std::string::npos)
11400 return this;
11401
604e278d 11402 // References from functions generated by the compiler don't count.
c6292d1d 11403 if (function != NULL && function->func_value()->is_type_specific_function())
604e278d 11404 return this;
11405
149eabc5 11406 // We have found a reference to a tracked field. Build a call to
11407 // the runtime function __go_fieldtrack with a string that describes
11408 // the field. FIXME: We should only call this once per referenced
11409 // field per function, not once for each reference to the field.
11410
11411 if (this->called_fieldtrack_)
11412 return this;
11413 this->called_fieldtrack_ = true;
11414
11415 Location loc = this->location();
11416
11417 std::string s = "fieldtrack \"";
11418 Named_type* nt = this->expr_->type()->named_type();
11419 if (nt == NULL || nt->named_object()->package() == NULL)
11420 s.append(gogo->pkgpath());
11421 else
11422 s.append(nt->named_object()->package()->pkgpath());
11423 s.push_back('.');
11424 if (nt != NULL)
5c29ad36 11425 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 11426 s.push_back('.');
11427 s.append(field->field_name());
11428 s.push_back('"');
11429
11430 // We can't use a string here, because internally a string holds a
11431 // pointer to the actual bytes; when the linker garbage collects the
11432 // string, it won't garbage collect the bytes. So we use a
11433 // [...]byte.
11434
e67508fa 11435 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
149eabc5 11436
11437 Type* byte_type = gogo->lookup_global("byte")->type_value();
11438 Type* array_type = Type::make_array_type(byte_type, length_expr);
11439
11440 Expression_list* bytes = new Expression_list();
11441 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11442 {
e67508fa 11443 unsigned char c = static_cast<unsigned char>(*p);
11444 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
149eabc5 11445 }
11446
11447 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 11448 bytes, false, loc);
149eabc5 11449
11450 Variable* var = new Variable(array_type, e, true, false, false, loc);
11451
11452 static int count;
11453 char buf[50];
11454 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11455 ++count;
11456
11457 Named_object* no = gogo->add_variable(buf, var);
11458 e = Expression::make_var_reference(no, loc);
11459 e = Expression::make_unary(OPERATOR_AND, e, loc);
11460
11461 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
604e278d 11462 gogo->lower_expression(function, inserter, &call);
149eabc5 11463 inserter->insert(Statement::make_statement(call, false));
11464
11465 // Put this function, and the global variable we just created, into
11466 // unique sections. This will permit the linker to garbage collect
11467 // them if they are not referenced. The effect is that the only
11468 // strings, indicating field references, that will wind up in the
11469 // executable will be those for functions that are actually needed.
66a6be58 11470 if (function != NULL)
11471 function->func_value()->set_in_unique_section();
149eabc5 11472 var->set_in_unique_section();
11473
11474 return this;
11475}
11476
e440a328 11477// Return the type of a field reference.
11478
11479Type*
11480Field_reference_expression::do_type()
11481{
b0e628fb 11482 Type* type = this->expr_->type();
5c13bd80 11483 if (type->is_error())
b0e628fb 11484 return type;
11485 Struct_type* struct_type = type->struct_type();
c484d925 11486 go_assert(struct_type != NULL);
e440a328 11487 return struct_type->field(this->field_index_)->type();
11488}
11489
11490// Check the types for a field reference.
11491
11492void
11493Field_reference_expression::do_check_types(Gogo*)
11494{
b0e628fb 11495 Type* type = this->expr_->type();
5c13bd80 11496 if (type->is_error())
b0e628fb 11497 return;
11498 Struct_type* struct_type = type->struct_type();
c484d925 11499 go_assert(struct_type != NULL);
11500 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 11501}
11502
ea664253 11503// Get the backend representation for a field reference.
e440a328 11504
ea664253 11505Bexpression*
11506Field_reference_expression::do_get_backend(Translate_context* context)
e440a328 11507{
ea664253 11508 Bexpression* bstruct = this->expr_->get_backend(context);
11509 return context->gogo()->backend()->struct_field_expression(bstruct,
11510 this->field_index_,
11511 this->location());
e440a328 11512}
11513
d751bb78 11514// Dump ast representation for a field reference expression.
11515
11516void
11517Field_reference_expression::do_dump_expression(
11518 Ast_dump_context* ast_dump_context) const
11519{
11520 this->expr_->dump_expression(ast_dump_context);
11521 ast_dump_context->ostream() << "." << this->field_index_;
11522}
11523
e440a328 11524// Make a reference to a qualified identifier in an expression.
11525
11526Field_reference_expression*
11527Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 11528 Location location)
e440a328 11529{
11530 return new Field_reference_expression(expr, field_index, location);
11531}
11532
11533// Class Interface_field_reference_expression.
11534
2387f644 11535// Return an expression for the pointer to the function to call.
e440a328 11536
2387f644 11537Expression*
11538Interface_field_reference_expression::get_function()
e440a328 11539{
2387f644 11540 Expression* ref = this->expr_;
11541 Location loc = this->location();
11542 if (ref->type()->points_to() != NULL)
11543 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 11544
2387f644 11545 Expression* mtable =
11546 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11547 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 11548
11549 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 11550 unsigned int index;
11551 const Struct_field* field = mtable_type->find_local_field(name, &index);
11552 go_assert(field != NULL);
11553 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11554 return Expression::make_field_reference(mtable, index, loc);
e440a328 11555}
11556
2387f644 11557// Return an expression for the first argument to pass to the interface
e440a328 11558// function.
11559
2387f644 11560Expression*
11561Interface_field_reference_expression::get_underlying_object()
e440a328 11562{
2387f644 11563 Expression* expr = this->expr_;
11564 if (expr->type()->points_to() != NULL)
11565 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11566 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11567 this->location());
e440a328 11568}
11569
11570// Traversal.
11571
11572int
11573Interface_field_reference_expression::do_traverse(Traverse* traverse)
11574{
11575 return Expression::traverse(&this->expr_, traverse);
11576}
11577
0afbb937 11578// Lower the expression. If this expression is not called, we need to
11579// evaluate the expression twice when converting to the backend
11580// interface. So introduce a temporary variable if necessary.
11581
11582Expression*
9782d556 11583Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11584 Statement_inserter* inserter)
0afbb937 11585{
5bf8be8b 11586 if (this->expr_->is_error_expression()
11587 || this->expr_->type()->is_error_type())
11588 {
11589 go_assert(saw_errors());
11590 return Expression::make_error(this->location());
11591 }
11592
2387f644 11593 if (!this->expr_->is_variable())
0afbb937 11594 {
11595 Temporary_statement* temp =
11596 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11597 inserter->insert(temp);
11598 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11599 this->location());
11600 }
11601 return this;
11602}
11603
e440a328 11604// Return the type of an interface field reference.
11605
11606Type*
11607Interface_field_reference_expression::do_type()
11608{
11609 Type* expr_type = this->expr_->type();
11610
11611 Type* points_to = expr_type->points_to();
11612 if (points_to != NULL)
11613 expr_type = points_to;
11614
11615 Interface_type* interface_type = expr_type->interface_type();
11616 if (interface_type == NULL)
11617 return Type::make_error_type();
11618
11619 const Typed_identifier* method = interface_type->find_method(this->name_);
11620 if (method == NULL)
11621 return Type::make_error_type();
11622
11623 return method->type();
11624}
11625
11626// Determine types.
11627
11628void
11629Interface_field_reference_expression::do_determine_type(const Type_context*)
11630{
11631 this->expr_->determine_type_no_context();
11632}
11633
11634// Check the types for an interface field reference.
11635
11636void
11637Interface_field_reference_expression::do_check_types(Gogo*)
11638{
11639 Type* type = this->expr_->type();
11640
11641 Type* points_to = type->points_to();
11642 if (points_to != NULL)
11643 type = points_to;
11644
11645 Interface_type* interface_type = type->interface_type();
11646 if (interface_type == NULL)
5c491127 11647 {
11648 if (!type->is_error_type())
11649 this->report_error(_("expected interface or pointer to interface"));
11650 }
e440a328 11651 else
11652 {
11653 const Typed_identifier* method =
11654 interface_type->find_method(this->name_);
11655 if (method == NULL)
11656 {
631d5788 11657 go_error_at(this->location(), "method %qs not in interface",
11658 Gogo::message_name(this->name_).c_str());
e440a328 11659 this->set_is_error();
11660 }
11661 }
11662}
11663
0afbb937 11664// If an interface field reference is not simply called, then it is
11665// represented as a closure. The closure will hold a single variable,
11666// the value of the interface on which the method should be called.
11667// The function will be a simple thunk that pulls the value from the
11668// closure and calls the method with the remaining arguments.
11669
11670// Because method values are not common, we don't build all thunks for
11671// all possible interface methods, but instead only build them as we
11672// need them. In particular, we even build them on demand for
11673// interface methods defined in other packages.
11674
11675Interface_field_reference_expression::Interface_method_thunks
11676 Interface_field_reference_expression::interface_method_thunks;
11677
11678// Find or create the thunk to call method NAME on TYPE.
11679
11680Named_object*
11681Interface_field_reference_expression::create_thunk(Gogo* gogo,
11682 Interface_type* type,
11683 const std::string& name)
11684{
11685 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11686 std::pair<Interface_method_thunks::iterator, bool> ins =
11687 Interface_field_reference_expression::interface_method_thunks.insert(val);
11688 if (ins.second)
11689 {
11690 // This is the first time we have seen this interface.
11691 ins.first->second = new Method_thunks();
11692 }
11693
11694 for (Method_thunks::const_iterator p = ins.first->second->begin();
11695 p != ins.first->second->end();
11696 p++)
11697 if (p->first == name)
11698 return p->second;
11699
11700 Location loc = type->location();
11701
11702 const Typed_identifier* method_id = type->find_method(name);
11703 if (method_id == NULL)
11704 return Named_object::make_erroneous_name(Gogo::thunk_name());
11705
11706 Function_type* orig_fntype = method_id->type()->function_type();
11707 if (orig_fntype == NULL)
11708 return Named_object::make_erroneous_name(Gogo::thunk_name());
11709
11710 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11711 // The type here is wrong--it should be the C function type. But it
11712 // doesn't really matter.
0afbb937 11713 Type* vt = Type::make_pointer_type(Type::make_void_type());
11714 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11715 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11716 Type* closure_type = Type::make_struct_type(sfl, loc);
11717 closure_type = Type::make_pointer_type(closure_type);
11718
f8bdf81a 11719 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11720
da244e59 11721 std::string thunk_name = Gogo::thunk_name();
11722 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
0afbb937 11723 false, loc);
11724
f8bdf81a 11725 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11726 cvar->set_is_used();
1ecc6157 11727 cvar->set_is_closure();
da244e59 11728 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11729 NULL, cvar);
f8bdf81a 11730 new_no->func_value()->set_closure_var(cp);
0afbb937 11731
f8bdf81a 11732 gogo->start_block(loc);
0afbb937 11733
11734 // Field 0 of the closure is the function code pointer, field 1 is
11735 // the value on which to invoke the method.
11736 Expression* arg = Expression::make_var_reference(cp, loc);
11737 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11738 arg = Expression::make_field_reference(arg, 1, loc);
11739
11740 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11741 loc);
11742
11743 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11744 Expression_list* args;
11745 if (orig_params == NULL || orig_params->empty())
11746 args = NULL;
11747 else
11748 {
11749 const Typed_identifier_list* new_params = new_fntype->parameters();
11750 args = new Expression_list();
11751 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11752 p != new_params->end();
0afbb937 11753 ++p)
11754 {
11755 Named_object* p_no = gogo->lookup(p->name(), NULL);
11756 go_assert(p_no != NULL
11757 && p_no->is_variable()
11758 && p_no->var_value()->is_parameter());
11759 args->push_back(Expression::make_var_reference(p_no, loc));
11760 }
11761 }
11762
11763 Call_expression* call = Expression::make_call(ifre, args,
11764 orig_fntype->is_varargs(),
11765 loc);
11766 call->set_varargs_are_lowered();
11767
11768 Statement* s = Statement::make_return_from_call(call, loc);
11769 gogo->add_statement(s);
11770 Block* b = gogo->finish_block(loc);
11771 gogo->add_block(b, loc);
11772 gogo->lower_block(new_no, b);
a32698ee 11773 gogo->flatten_block(new_no, b);
0afbb937 11774 gogo->finish_function(loc);
11775
11776 ins.first->second->push_back(std::make_pair(name, new_no));
11777 return new_no;
11778}
11779
ea664253 11780// Get the backend representation for a method value.
e440a328 11781
ea664253 11782Bexpression*
11783Interface_field_reference_expression::do_get_backend(Translate_context* context)
e440a328 11784{
0afbb937 11785 Interface_type* type = this->expr_->type()->interface_type();
11786 if (type == NULL)
11787 {
11788 go_assert(saw_errors());
ea664253 11789 return context->backend()->error_expression();
0afbb937 11790 }
11791
11792 Named_object* thunk =
11793 Interface_field_reference_expression::create_thunk(context->gogo(),
11794 type, this->name_);
11795 if (thunk->is_erroneous())
11796 {
11797 go_assert(saw_errors());
ea664253 11798 return context->backend()->error_expression();
0afbb937 11799 }
11800
11801 // FIXME: We should lower this earlier, but we can't it lower it in
11802 // the lowering pass because at that point we don't know whether we
11803 // need to create the thunk or not. If the expression is called, we
11804 // don't need the thunk.
11805
11806 Location loc = this->location();
11807
11808 Struct_field_list* fields = new Struct_field_list();
11809 fields->push_back(Struct_field(Typed_identifier("fn.0",
11810 thunk->func_value()->type(),
11811 loc)));
11812 fields->push_back(Struct_field(Typed_identifier("val.1",
11813 this->expr_->type(),
11814 loc)));
11815 Struct_type* st = Type::make_struct_type(fields, loc);
11816
11817 Expression_list* vals = new Expression_list();
11818 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11819 vals->push_back(this->expr_);
11820
11821 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
ea664253 11822 Bexpression* bclosure =
11823 Expression::make_heap_expression(expr, loc)->get_backend(context);
0afbb937 11824
2387f644 11825 Expression* nil_check =
11826 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11827 Expression::make_nil(loc), loc);
ea664253 11828 Bexpression* bnil_check = nil_check->get_backend(context);
0afbb937 11829
2387f644 11830 Gogo* gogo = context->gogo();
ea664253 11831 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11832 loc)->get_backend(context);
2387f644 11833
11834 Bexpression* bcond =
a32698ee 11835 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11836 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
ea664253 11837 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
e440a328 11838}
11839
d751bb78 11840// Dump ast representation for an interface field reference.
11841
11842void
11843Interface_field_reference_expression::do_dump_expression(
11844 Ast_dump_context* ast_dump_context) const
11845{
11846 this->expr_->dump_expression(ast_dump_context);
11847 ast_dump_context->ostream() << "." << this->name_;
11848}
11849
e440a328 11850// Make a reference to a field in an interface.
11851
11852Expression*
11853Expression::make_interface_field_reference(Expression* expr,
11854 const std::string& field,
b13c66cd 11855 Location location)
e440a328 11856{
11857 return new Interface_field_reference_expression(expr, field, location);
11858}
11859
11860// A general selector. This is a Parser_expression for LEFT.NAME. It
11861// is lowered after we know the type of the left hand side.
11862
11863class Selector_expression : public Parser_expression
11864{
11865 public:
11866 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11867 Location location)
e440a328 11868 : Parser_expression(EXPRESSION_SELECTOR, location),
11869 left_(left), name_(name)
11870 { }
11871
11872 protected:
11873 int
11874 do_traverse(Traverse* traverse)
11875 { return Expression::traverse(&this->left_, traverse); }
11876
11877 Expression*
ceeb4318 11878 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11879
11880 Expression*
11881 do_copy()
11882 {
11883 return new Selector_expression(this->left_->copy(), this->name_,
11884 this->location());
11885 }
11886
d751bb78 11887 void
11888 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11889
e440a328 11890 private:
11891 Expression*
11892 lower_method_expression(Gogo*);
11893
11894 // The expression on the left hand side.
11895 Expression* left_;
11896 // The name on the right hand side.
11897 std::string name_;
11898};
11899
11900// Lower a selector expression once we know the real type of the left
11901// hand side.
11902
11903Expression*
ceeb4318 11904Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11905 int)
e440a328 11906{
11907 Expression* left = this->left_;
11908 if (left->is_type_expression())
11909 return this->lower_method_expression(gogo);
11910 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11911 this->location());
11912}
11913
11914// Lower a method expression T.M or (*T).M. We turn this into a
11915// function literal.
11916
11917Expression*
11918Selector_expression::lower_method_expression(Gogo* gogo)
11919{
b13c66cd 11920 Location location = this->location();
868b439e 11921 Type* left_type = this->left_->type();
11922 Type* type = left_type;
e440a328 11923 const std::string& name(this->name_);
11924
11925 bool is_pointer;
11926 if (type->points_to() == NULL)
11927 is_pointer = false;
11928 else
11929 {
11930 is_pointer = true;
11931 type = type->points_to();
11932 }
11933 Named_type* nt = type->named_type();
11934 if (nt == NULL)
11935 {
631d5788 11936 go_error_at(location,
11937 ("method expression requires named type or "
11938 "pointer to named type"));
e440a328 11939 return Expression::make_error(location);
11940 }
11941
11942 bool is_ambiguous;
11943 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 11944 const Typed_identifier* imethod = NULL;
dcc8506b 11945 if (method == NULL && !is_pointer)
ab1468c3 11946 {
11947 Interface_type* it = nt->interface_type();
11948 if (it != NULL)
11949 imethod = it->find_method(name);
11950 }
11951
868b439e 11952 if ((method == NULL && imethod == NULL)
11953 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
e440a328 11954 {
11955 if (!is_ambiguous)
631d5788 11956 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
11957 is_pointer ? "*" : "",
11958 nt->message_name().c_str(),
11959 Gogo::message_name(name).c_str());
e440a328 11960 else
631d5788 11961 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11962 Gogo::message_name(name).c_str(),
11963 is_pointer ? "*" : "",
11964 nt->message_name().c_str());
e440a328 11965 return Expression::make_error(location);
11966 }
11967
ab1468c3 11968 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 11969 {
631d5788 11970 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
11971 nt->message_name().c_str(),
11972 Gogo::message_name(name).c_str());
e440a328 11973 return Expression::make_error(location);
11974 }
11975
11976 // Build a new function type in which the receiver becomes the first
11977 // argument.
ab1468c3 11978 Function_type* method_type;
11979 if (method != NULL)
11980 {
11981 method_type = method->type();
c484d925 11982 go_assert(method_type->is_method());
ab1468c3 11983 }
11984 else
11985 {
11986 method_type = imethod->type()->function_type();
c484d925 11987 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 11988 }
e440a328 11989
11990 const char* const receiver_name = "$this";
11991 Typed_identifier_list* parameters = new Typed_identifier_list();
11992 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11993 location));
11994
11995 const Typed_identifier_list* method_parameters = method_type->parameters();
11996 if (method_parameters != NULL)
11997 {
f470da59 11998 int i = 0;
e440a328 11999 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12000 p != method_parameters->end();
f470da59 12001 ++p, ++i)
12002 {
68883531 12003 if (!p->name().empty())
f470da59 12004 parameters->push_back(*p);
12005 else
12006 {
12007 char buf[20];
12008 snprintf(buf, sizeof buf, "$param%d", i);
12009 parameters->push_back(Typed_identifier(buf, p->type(),
12010 p->location()));
12011 }
12012 }
e440a328 12013 }
12014
12015 const Typed_identifier_list* method_results = method_type->results();
12016 Typed_identifier_list* results;
12017 if (method_results == NULL)
12018 results = NULL;
12019 else
12020 {
12021 results = new Typed_identifier_list();
12022 for (Typed_identifier_list::const_iterator p = method_results->begin();
12023 p != method_results->end();
12024 ++p)
12025 results->push_back(*p);
12026 }
12027
12028 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12029 location);
12030 if (method_type->is_varargs())
12031 fntype->set_is_varargs();
12032
12033 // We generate methods which always takes a pointer to the receiver
12034 // as their first argument. If this is for a pointer type, we can
12035 // simply reuse the existing function. We use an internal hack to
12036 // get the right type.
8381eda7 12037 // FIXME: This optimization is disabled because it doesn't yet work
12038 // with function descriptors when the method expression is not
12039 // directly called.
12040 if (method != NULL && is_pointer && false)
e440a328 12041 {
12042 Named_object* mno = (method->needs_stub_method()
12043 ? method->stub_object()
12044 : method->named_object());
12045 Expression* f = Expression::make_func_reference(mno, NULL, location);
12046 f = Expression::make_cast(fntype, f, location);
12047 Type_conversion_expression* tce =
12048 static_cast<Type_conversion_expression*>(f);
12049 tce->set_may_convert_function_types();
12050 return f;
12051 }
12052
12053 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12054 location);
12055
12056 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 12057 go_assert(vno != NULL);
e440a328 12058 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 12059 Expression* bm;
12060 if (method != NULL)
12061 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12062 else
12063 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 12064
12065 // Even though we found the method above, if it has an error type we
12066 // may see an error here.
12067 if (bm->is_error_expression())
463fe805 12068 {
12069 gogo->finish_function(location);
12070 return bm;
12071 }
e440a328 12072
12073 Expression_list* args;
f470da59 12074 if (parameters->size() <= 1)
e440a328 12075 args = NULL;
12076 else
12077 {
12078 args = new Expression_list();
f470da59 12079 Typed_identifier_list::const_iterator p = parameters->begin();
12080 ++p;
12081 for (; p != parameters->end(); ++p)
e440a328 12082 {
12083 vno = gogo->lookup(p->name(), NULL);
c484d925 12084 go_assert(vno != NULL);
e440a328 12085 args->push_back(Expression::make_var_reference(vno, location));
12086 }
12087 }
12088
ceeb4318 12089 gogo->start_block(location);
12090
e440a328 12091 Call_expression* call = Expression::make_call(bm, args,
12092 method_type->is_varargs(),
12093 location);
12094
0afbb937 12095 Statement* s = Statement::make_return_from_call(call, location);
e440a328 12096 gogo->add_statement(s);
12097
ceeb4318 12098 Block* b = gogo->finish_block(location);
12099
12100 gogo->add_block(b, location);
12101
12102 // Lower the call in case there are multiple results.
12103 gogo->lower_block(no, b);
a32698ee 12104 gogo->flatten_block(no, b);
ceeb4318 12105
e440a328 12106 gogo->finish_function(location);
12107
12108 return Expression::make_func_reference(no, NULL, location);
12109}
12110
d751bb78 12111// Dump the ast for a selector expression.
12112
12113void
12114Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12115 const
12116{
12117 ast_dump_context->dump_expression(this->left_);
12118 ast_dump_context->ostream() << ".";
12119 ast_dump_context->ostream() << this->name_;
12120}
12121
e440a328 12122// Make a selector expression.
12123
12124Expression*
12125Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 12126 Location location)
e440a328 12127{
12128 return new Selector_expression(left, name, location);
12129}
12130
da244e59 12131// Class Allocation_expression.
e440a328 12132
da244e59 12133int
12134Allocation_expression::do_traverse(Traverse* traverse)
e440a328 12135{
da244e59 12136 return Type::traverse(this->type_, traverse);
12137}
e440a328 12138
da244e59 12139Type*
12140Allocation_expression::do_type()
12141{
12142 return Type::make_pointer_type(this->type_);
12143}
e440a328 12144
da244e59 12145// Make a copy of an allocation expression.
e440a328 12146
da244e59 12147Expression*
12148Allocation_expression::do_copy()
12149{
12150 Allocation_expression* alloc =
12151 new Allocation_expression(this->type_, this->location());
12152 if (this->allocate_on_stack_)
12153 alloc->set_allocate_on_stack();
12154 return alloc;
12155}
e440a328 12156
ea664253 12157// Return the backend representation for an allocation expression.
e440a328 12158
ea664253 12159Bexpression*
12160Allocation_expression::do_get_backend(Translate_context* context)
e440a328 12161{
2c809f8f 12162 Gogo* gogo = context->gogo();
12163 Location loc = this->location();
da244e59 12164
45ff893b 12165 Node* n = Node::make_node(this);
12166 if (this->allocate_on_stack_
12167 || (n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
da244e59 12168 {
2a305b85 12169 int64_t size;
12170 bool ok = this->type_->backend_type_size(gogo, &size);
12171 if (!ok)
12172 {
12173 go_assert(saw_errors());
12174 return gogo->backend()->error_expression();
12175 }
d5d1c295 12176 return gogo->backend()->stack_allocation_expression(size, loc);
da244e59 12177 }
12178
2a305b85 12179 Btype* btype = this->type_->get_backend(gogo);
12180 Bexpression* space =
ea664253 12181 gogo->allocate_memory(this->type_, loc)->get_backend(context);
d5d1c295 12182 Btype* pbtype = gogo->backend()->pointer_type(btype);
ea664253 12183 return gogo->backend()->convert_expression(pbtype, space, loc);
e440a328 12184}
12185
d751bb78 12186// Dump ast representation for an allocation expression.
12187
12188void
12189Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12190 const
12191{
12192 ast_dump_context->ostream() << "new(";
12193 ast_dump_context->dump_type(this->type_);
12194 ast_dump_context->ostream() << ")";
12195}
12196
e440a328 12197// Make an allocation expression.
12198
12199Expression*
b13c66cd 12200Expression::make_allocation(Type* type, Location location)
e440a328 12201{
12202 return new Allocation_expression(type, location);
12203}
12204
e32de7ba 12205// Class Ordered_value_list.
e440a328 12206
12207int
e32de7ba 12208Ordered_value_list::traverse_vals(Traverse* traverse)
e440a328 12209{
0c4f5a19 12210 if (this->vals_ != NULL)
12211 {
12212 if (this->traverse_order_ == NULL)
12213 {
12214 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12215 return TRAVERSE_EXIT;
12216 }
12217 else
12218 {
e32de7ba 12219 for (std::vector<unsigned long>::const_iterator p =
12220 this->traverse_order_->begin();
0c4f5a19 12221 p != this->traverse_order_->end();
12222 ++p)
12223 {
12224 if (Expression::traverse(&this->vals_->at(*p), traverse)
12225 == TRAVERSE_EXIT)
12226 return TRAVERSE_EXIT;
12227 }
12228 }
12229 }
e32de7ba 12230 return TRAVERSE_CONTINUE;
12231}
12232
12233// Class Struct_construction_expression.
12234
12235// Traversal.
12236
12237int
12238Struct_construction_expression::do_traverse(Traverse* traverse)
12239{
12240 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12241 return TRAVERSE_EXIT;
e440a328 12242 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12243 return TRAVERSE_EXIT;
12244 return TRAVERSE_CONTINUE;
12245}
12246
12247// Return whether this is a constant initializer.
12248
12249bool
12250Struct_construction_expression::is_constant_struct() const
12251{
e32de7ba 12252 if (this->vals() == NULL)
e440a328 12253 return true;
e32de7ba 12254 for (Expression_list::const_iterator pv = this->vals()->begin();
12255 pv != this->vals()->end();
e440a328 12256 ++pv)
12257 {
12258 if (*pv != NULL
12259 && !(*pv)->is_constant()
12260 && (!(*pv)->is_composite_literal()
12261 || (*pv)->is_nonconstant_composite_literal()))
12262 return false;
12263 }
12264
12265 const Struct_field_list* fields = this->type_->struct_type()->fields();
12266 for (Struct_field_list::const_iterator pf = fields->begin();
12267 pf != fields->end();
12268 ++pf)
12269 {
12270 // There are no constant constructors for interfaces.
12271 if (pf->type()->interface_type() != NULL)
12272 return false;
12273 }
12274
12275 return true;
12276}
12277
f9ca30f9 12278// Return whether this struct is immutable.
12279
12280bool
12281Struct_construction_expression::do_is_immutable() const
12282{
e32de7ba 12283 if (this->vals() == NULL)
f9ca30f9 12284 return true;
e32de7ba 12285 for (Expression_list::const_iterator pv = this->vals()->begin();
12286 pv != this->vals()->end();
f9ca30f9 12287 ++pv)
12288 {
12289 if (*pv != NULL && !(*pv)->is_immutable())
12290 return false;
12291 }
12292 return true;
12293}
12294
e440a328 12295// Final type determination.
12296
12297void
12298Struct_construction_expression::do_determine_type(const Type_context*)
12299{
e32de7ba 12300 if (this->vals() == NULL)
e440a328 12301 return;
12302 const Struct_field_list* fields = this->type_->struct_type()->fields();
e32de7ba 12303 Expression_list::const_iterator pv = this->vals()->begin();
e440a328 12304 for (Struct_field_list::const_iterator pf = fields->begin();
12305 pf != fields->end();
12306 ++pf, ++pv)
12307 {
e32de7ba 12308 if (pv == this->vals()->end())
e440a328 12309 return;
12310 if (*pv != NULL)
12311 {
12312 Type_context subcontext(pf->type(), false);
12313 (*pv)->determine_type(&subcontext);
12314 }
12315 }
a6cb4c0e 12316 // Extra values are an error we will report elsewhere; we still want
12317 // to determine the type to avoid knockon errors.
e32de7ba 12318 for (; pv != this->vals()->end(); ++pv)
a6cb4c0e 12319 (*pv)->determine_type_no_context();
e440a328 12320}
12321
12322// Check types.
12323
12324void
12325Struct_construction_expression::do_check_types(Gogo*)
12326{
e32de7ba 12327 if (this->vals() == NULL)
e440a328 12328 return;
12329
12330 Struct_type* st = this->type_->struct_type();
e32de7ba 12331 if (this->vals()->size() > st->field_count())
e440a328 12332 {
12333 this->report_error(_("too many expressions for struct"));
12334 return;
12335 }
12336
12337 const Struct_field_list* fields = st->fields();
e32de7ba 12338 Expression_list::const_iterator pv = this->vals()->begin();
e440a328 12339 int i = 0;
12340 for (Struct_field_list::const_iterator pf = fields->begin();
12341 pf != fields->end();
12342 ++pf, ++pv, ++i)
12343 {
e32de7ba 12344 if (pv == this->vals()->end())
e440a328 12345 {
12346 this->report_error(_("too few expressions for struct"));
12347 break;
12348 }
12349
12350 if (*pv == NULL)
12351 continue;
12352
12353 std::string reason;
12354 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12355 {
12356 if (reason.empty())
631d5788 12357 go_error_at((*pv)->location(),
12358 "incompatible type for field %d in struct construction",
12359 i + 1);
e440a328 12360 else
631d5788 12361 go_error_at((*pv)->location(),
12362 ("incompatible type for field %d in "
12363 "struct construction (%s)"),
12364 i + 1, reason.c_str());
e440a328 12365 this->set_is_error();
12366 }
12367 }
e32de7ba 12368 go_assert(pv == this->vals()->end());
e440a328 12369}
12370
8ba8cc87 12371// Flatten a struct construction expression. Store the values into
12372// temporaries in case they need interface conversion.
12373
12374Expression*
12375Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12376 Statement_inserter* inserter)
12377{
e32de7ba 12378 if (this->vals() == NULL)
8ba8cc87 12379 return this;
12380
12381 // If this is a constant struct, we don't need temporaries.
12382 if (this->is_constant_struct())
12383 return this;
12384
12385 Location loc = this->location();
e32de7ba 12386 for (Expression_list::iterator pv = this->vals()->begin();
12387 pv != this->vals()->end();
8ba8cc87 12388 ++pv)
12389 {
12390 if (*pv != NULL)
12391 {
5bf8be8b 12392 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12393 {
12394 go_assert(saw_errors());
12395 return Expression::make_error(loc);
12396 }
8ba8cc87 12397 if (!(*pv)->is_variable())
12398 {
12399 Temporary_statement* temp =
12400 Statement::make_temporary(NULL, *pv, loc);
12401 inserter->insert(temp);
12402 *pv = Expression::make_temporary_reference(temp, loc);
12403 }
12404 }
12405 }
12406 return this;
12407}
12408
ea664253 12409// Return the backend representation for constructing a struct.
e440a328 12410
ea664253 12411Bexpression*
12412Struct_construction_expression::do_get_backend(Translate_context* context)
e440a328 12413{
12414 Gogo* gogo = context->gogo();
12415
2c809f8f 12416 Btype* btype = this->type_->get_backend(gogo);
e32de7ba 12417 if (this->vals() == NULL)
ea664253 12418 return gogo->backend()->zero_expression(btype);
e440a328 12419
e440a328 12420 const Struct_field_list* fields = this->type_->struct_type()->fields();
e32de7ba 12421 Expression_list::const_iterator pv = this->vals()->begin();
2c809f8f 12422 std::vector<Bexpression*> init;
12423 for (Struct_field_list::const_iterator pf = fields->begin();
12424 pf != fields->end();
12425 ++pf)
e440a328 12426 {
63697958 12427 Btype* fbtype = pf->type()->get_backend(gogo);
e32de7ba 12428 if (pv == this->vals()->end())
2c809f8f 12429 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12430 else if (*pv == NULL)
12431 {
2c809f8f 12432 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 12433 ++pv;
12434 }
12435 else
12436 {
2c809f8f 12437 Expression* val =
12438 Expression::convert_for_assignment(gogo, pf->type(),
12439 *pv, this->location());
ea664253 12440 init.push_back(val->get_backend(context));
e440a328 12441 ++pv;
12442 }
e440a328 12443 }
ea664253 12444 return gogo->backend()->constructor_expression(btype, init, this->location());
e440a328 12445}
12446
12447// Export a struct construction.
12448
12449void
12450Struct_construction_expression::do_export(Export* exp) const
12451{
12452 exp->write_c_string("convert(");
12453 exp->write_type(this->type_);
e32de7ba 12454 for (Expression_list::const_iterator pv = this->vals()->begin();
12455 pv != this->vals()->end();
e440a328 12456 ++pv)
12457 {
12458 exp->write_c_string(", ");
12459 if (*pv != NULL)
12460 (*pv)->export_expression(exp);
12461 }
12462 exp->write_c_string(")");
12463}
12464
d751bb78 12465// Dump ast representation of a struct construction expression.
12466
12467void
12468Struct_construction_expression::do_dump_expression(
12469 Ast_dump_context* ast_dump_context) const
12470{
d751bb78 12471 ast_dump_context->dump_type(this->type_);
12472 ast_dump_context->ostream() << "{";
e32de7ba 12473 ast_dump_context->dump_expression_list(this->vals());
d751bb78 12474 ast_dump_context->ostream() << "}";
12475}
12476
e440a328 12477// Make a struct composite literal. This used by the thunk code.
12478
12479Expression*
12480Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12481 Location location)
e440a328 12482{
c484d925 12483 go_assert(type->struct_type() != NULL);
e440a328 12484 return new Struct_construction_expression(type, vals, location);
12485}
12486
da244e59 12487// Class Array_construction_expression.
e440a328 12488
12489// Traversal.
12490
12491int
12492Array_construction_expression::do_traverse(Traverse* traverse)
12493{
e32de7ba 12494 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
e440a328 12495 return TRAVERSE_EXIT;
12496 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12497 return TRAVERSE_EXIT;
12498 return TRAVERSE_CONTINUE;
12499}
12500
12501// Return whether this is a constant initializer.
12502
12503bool
12504Array_construction_expression::is_constant_array() const
12505{
e32de7ba 12506 if (this->vals() == NULL)
e440a328 12507 return true;
12508
12509 // There are no constant constructors for interfaces.
12510 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12511 return false;
12512
e32de7ba 12513 for (Expression_list::const_iterator pv = this->vals()->begin();
12514 pv != this->vals()->end();
e440a328 12515 ++pv)
12516 {
12517 if (*pv != NULL
12518 && !(*pv)->is_constant()
12519 && (!(*pv)->is_composite_literal()
12520 || (*pv)->is_nonconstant_composite_literal()))
12521 return false;
12522 }
12523 return true;
12524}
12525
f9ca30f9 12526// Return whether this is an immutable array initializer.
12527
12528bool
12529Array_construction_expression::do_is_immutable() const
12530{
e32de7ba 12531 if (this->vals() == NULL)
f9ca30f9 12532 return true;
e32de7ba 12533 for (Expression_list::const_iterator pv = this->vals()->begin();
12534 pv != this->vals()->end();
f9ca30f9 12535 ++pv)
12536 {
12537 if (*pv != NULL && !(*pv)->is_immutable())
12538 return false;
12539 }
12540 return true;
12541}
12542
e440a328 12543// Final type determination.
12544
12545void
12546Array_construction_expression::do_determine_type(const Type_context*)
12547{
e32de7ba 12548 if (this->vals() == NULL)
e440a328 12549 return;
12550 Type_context subcontext(this->type_->array_type()->element_type(), false);
e32de7ba 12551 for (Expression_list::const_iterator pv = this->vals()->begin();
12552 pv != this->vals()->end();
e440a328 12553 ++pv)
12554 {
12555 if (*pv != NULL)
12556 (*pv)->determine_type(&subcontext);
12557 }
12558}
12559
12560// Check types.
12561
12562void
12563Array_construction_expression::do_check_types(Gogo*)
12564{
e32de7ba 12565 if (this->vals() == NULL)
e440a328 12566 return;
12567
12568 Array_type* at = this->type_->array_type();
12569 int i = 0;
12570 Type* element_type = at->element_type();
e32de7ba 12571 for (Expression_list::const_iterator pv = this->vals()->begin();
12572 pv != this->vals()->end();
e440a328 12573 ++pv, ++i)
12574 {
12575 if (*pv != NULL
12576 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12577 {
631d5788 12578 go_error_at((*pv)->location(),
12579 "incompatible type for element %d in composite literal",
12580 i + 1);
e440a328 12581 this->set_is_error();
12582 }
12583 }
e440a328 12584}
12585
8ba8cc87 12586// Flatten an array construction expression. Store the values into
12587// temporaries in case they need interface conversion.
12588
12589Expression*
12590Array_construction_expression::do_flatten(Gogo*, Named_object*,
12591 Statement_inserter* inserter)
12592{
e32de7ba 12593 if (this->vals() == NULL)
8ba8cc87 12594 return this;
12595
12596 // If this is a constant array, we don't need temporaries.
12597 if (this->is_constant_array())
12598 return this;
12599
12600 Location loc = this->location();
e32de7ba 12601 for (Expression_list::iterator pv = this->vals()->begin();
12602 pv != this->vals()->end();
8ba8cc87 12603 ++pv)
12604 {
12605 if (*pv != NULL)
12606 {
5bf8be8b 12607 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12608 {
12609 go_assert(saw_errors());
12610 return Expression::make_error(loc);
12611 }
8ba8cc87 12612 if (!(*pv)->is_variable())
12613 {
12614 Temporary_statement* temp =
12615 Statement::make_temporary(NULL, *pv, loc);
12616 inserter->insert(temp);
12617 *pv = Expression::make_temporary_reference(temp, loc);
12618 }
12619 }
12620 }
12621 return this;
12622}
12623
2c809f8f 12624// Get a constructor expression for the array values.
e440a328 12625
2c809f8f 12626Bexpression*
12627Array_construction_expression::get_constructor(Translate_context* context,
12628 Btype* array_btype)
e440a328 12629{
e440a328 12630 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12631
12632 std::vector<unsigned long> indexes;
12633 std::vector<Bexpression*> vals;
12634 Gogo* gogo = context->gogo();
e32de7ba 12635 if (this->vals() != NULL)
e440a328 12636 {
12637 size_t i = 0;
ffe743ca 12638 std::vector<unsigned long>::const_iterator pi;
12639 if (this->indexes_ != NULL)
12640 pi = this->indexes_->begin();
e32de7ba 12641 for (Expression_list::const_iterator pv = this->vals()->begin();
12642 pv != this->vals()->end();
e440a328 12643 ++pv, ++i)
12644 {
ffe743ca 12645 if (this->indexes_ != NULL)
12646 go_assert(pi != this->indexes_->end());
ffe743ca 12647
12648 if (this->indexes_ == NULL)
2c809f8f 12649 indexes.push_back(i);
ffe743ca 12650 else
2c809f8f 12651 indexes.push_back(*pi);
e440a328 12652 if (*pv == NULL)
63697958 12653 {
63697958 12654 Btype* ebtype = element_type->get_backend(gogo);
12655 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12656 vals.push_back(zv);
63697958 12657 }
e440a328 12658 else
12659 {
2c809f8f 12660 Expression* val_expr =
12661 Expression::convert_for_assignment(gogo, element_type, *pv,
12662 this->location());
ea664253 12663 vals.push_back(val_expr->get_backend(context));
e440a328 12664 }
ffe743ca 12665 if (this->indexes_ != NULL)
12666 ++pi;
e440a328 12667 }
ffe743ca 12668 if (this->indexes_ != NULL)
12669 go_assert(pi == this->indexes_->end());
e440a328 12670 }
2c809f8f 12671 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12672 vals, this->location());
e440a328 12673}
12674
12675// Export an array construction.
12676
12677void
12678Array_construction_expression::do_export(Export* exp) const
12679{
12680 exp->write_c_string("convert(");
12681 exp->write_type(this->type_);
e32de7ba 12682 if (this->vals() != NULL)
e440a328 12683 {
ffe743ca 12684 std::vector<unsigned long>::const_iterator pi;
12685 if (this->indexes_ != NULL)
12686 pi = this->indexes_->begin();
e32de7ba 12687 for (Expression_list::const_iterator pv = this->vals()->begin();
12688 pv != this->vals()->end();
e440a328 12689 ++pv)
12690 {
12691 exp->write_c_string(", ");
ffe743ca 12692
12693 if (this->indexes_ != NULL)
12694 {
12695 char buf[100];
12696 snprintf(buf, sizeof buf, "%lu", *pi);
12697 exp->write_c_string(buf);
12698 exp->write_c_string(":");
12699 }
12700
e440a328 12701 if (*pv != NULL)
12702 (*pv)->export_expression(exp);
ffe743ca 12703
12704 if (this->indexes_ != NULL)
12705 ++pi;
e440a328 12706 }
12707 }
12708 exp->write_c_string(")");
12709}
12710
0e9a2e72 12711// Dump ast representation of an array construction expression.
d751bb78 12712
12713void
12714Array_construction_expression::do_dump_expression(
12715 Ast_dump_context* ast_dump_context) const
12716{
ffe743ca 12717 Expression* length = this->type_->array_type()->length();
8b1c301d 12718
12719 ast_dump_context->ostream() << "[" ;
12720 if (length != NULL)
12721 {
12722 ast_dump_context->dump_expression(length);
12723 }
12724 ast_dump_context->ostream() << "]" ;
d751bb78 12725 ast_dump_context->dump_type(this->type_);
0e9a2e72 12726 this->dump_slice_storage_expression(ast_dump_context);
d751bb78 12727 ast_dump_context->ostream() << "{" ;
ffe743ca 12728 if (this->indexes_ == NULL)
e32de7ba 12729 ast_dump_context->dump_expression_list(this->vals());
ffe743ca 12730 else
12731 {
e32de7ba 12732 Expression_list::const_iterator pv = this->vals()->begin();
ffe743ca 12733 for (std::vector<unsigned long>::const_iterator pi =
12734 this->indexes_->begin();
12735 pi != this->indexes_->end();
12736 ++pi, ++pv)
12737 {
12738 if (pi != this->indexes_->begin())
12739 ast_dump_context->ostream() << ", ";
12740 ast_dump_context->ostream() << *pi << ':';
12741 ast_dump_context->dump_expression(*pv);
12742 }
12743 }
d751bb78 12744 ast_dump_context->ostream() << "}" ;
12745
12746}
12747
da244e59 12748// Class Fixed_array_construction_expression.
e440a328 12749
da244e59 12750Fixed_array_construction_expression::Fixed_array_construction_expression(
12751 Type* type, const std::vector<unsigned long>* indexes,
12752 Expression_list* vals, Location location)
12753 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12754 type, indexes, vals, location)
12755{ go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12756
ea664253 12757// Return the backend representation for constructing a fixed array.
e440a328 12758
ea664253 12759Bexpression*
12760Fixed_array_construction_expression::do_get_backend(Translate_context* context)
e440a328 12761{
9f0e0513 12762 Type* type = this->type();
12763 Btype* btype = type->get_backend(context->gogo());
ea664253 12764 return this->get_constructor(context, btype);
e440a328 12765}
12766
76f85fd6 12767Expression*
12768Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12769 Location location)
12770{
12771 go_assert(type->array_type() != NULL && !type->is_slice_type());
12772 return new Fixed_array_construction_expression(type, NULL, vals, location);
12773}
12774
da244e59 12775// Class Slice_construction_expression.
e440a328 12776
da244e59 12777Slice_construction_expression::Slice_construction_expression(
12778 Type* type, const std::vector<unsigned long>* indexes,
12779 Expression_list* vals, Location location)
12780 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12781 type, indexes, vals, location),
0e9a2e72 12782 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
12783 storage_escapes_(true)
e440a328 12784{
da244e59 12785 go_assert(type->is_slice_type());
23d77f91 12786
da244e59 12787 unsigned long lenval;
12788 Expression* length;
12789 if (vals == NULL || vals->empty())
12790 lenval = 0;
12791 else
12792 {
12793 if (this->indexes() == NULL)
12794 lenval = vals->size();
12795 else
12796 lenval = indexes->back() + 1;
12797 }
12798 Type* int_type = Type::lookup_integer_type("int");
12799 length = Expression::make_integer_ul(lenval, int_type, location);
12800 Type* element_type = type->array_type()->element_type();
12801 this->valtype_ = Type::make_array_type(element_type, length);
12802}
e440a328 12803
23d77f91 12804// Traversal.
12805
12806int
12807Slice_construction_expression::do_traverse(Traverse* traverse)
12808{
12809 if (this->Array_construction_expression::do_traverse(traverse)
12810 == TRAVERSE_EXIT)
12811 return TRAVERSE_EXIT;
12812 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12813 return TRAVERSE_EXIT;
0e9a2e72 12814 if (this->array_val_ != NULL
12815 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
12816 return TRAVERSE_EXIT;
12817 if (this->slice_storage_ != NULL
12818 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
12819 return TRAVERSE_EXIT;
23d77f91 12820 return TRAVERSE_CONTINUE;
12821}
12822
0e9a2e72 12823// Helper routine to create fixed array value underlying the slice literal.
12824// May be called during flattening, or later during do_get_backend().
e440a328 12825
0e9a2e72 12826Expression*
12827Slice_construction_expression::create_array_val()
e440a328 12828{
f9c68f17 12829 Array_type* array_type = this->type()->array_type();
12830 if (array_type == NULL)
12831 {
c484d925 12832 go_assert(this->type()->is_error());
0e9a2e72 12833 return NULL;
f9c68f17 12834 }
12835
f23d7786 12836 Location loc = this->location();
23d77f91 12837 go_assert(this->valtype_ != NULL);
3d60812e 12838
f23d7786 12839 Expression_list* vals = this->vals();
e440a328 12840 if (this->vals() == NULL || this->vals()->empty())
12841 {
f23d7786 12842 // We need to create a unique value for the empty array literal.
12843 vals = new Expression_list;
12844 vals->push_back(NULL);
e440a328 12845 }
0e9a2e72 12846 return new Fixed_array_construction_expression(
12847 this->valtype_, this->indexes(), vals, loc);
12848}
12849
12850// If we're previous established that the slice storage does not
12851// escape, then create a separate array temp val here for it. We
12852// need to do this as part of flattening so as to be able to insert
12853// the new temp statement.
12854
12855Expression*
12856Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
12857 Statement_inserter* inserter)
12858{
12859 if (this->type()->array_type() == NULL)
12860 return NULL;
12861
12862 // Base class flattening first
12863 this->Array_construction_expression::do_flatten(gogo, no, inserter);
12864
12865 // Create an stack-allocated storage temp if storage won't escape
12866 if (!this->storage_escapes_)
12867 {
12868 Location loc = this->location();
12869 this->array_val_ = create_array_val();
12870 go_assert(this->array_val_);
12871 Temporary_statement* temp =
12872 Statement::make_temporary(this->valtype_, this->array_val_, loc);
12873 inserter->insert(temp);
12874 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
12875 }
12876 return this;
12877}
12878
12879// When dumping a slice construction expression that has an explicit
12880// storeage temp, emit the temp here (if we don't do this the storage
12881// temp appears unused in the AST dump).
12882
12883void
12884Slice_construction_expression::
12885dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
12886{
12887 if (this->slice_storage_ == NULL)
12888 return;
12889 ast_dump_context->ostream() << "storage=" ;
12890 ast_dump_context->dump_expression(this->slice_storage_);
12891}
12892
12893// Return the backend representation for constructing a slice.
12894
12895Bexpression*
12896Slice_construction_expression::do_get_backend(Translate_context* context)
12897{
12898 if (this->array_val_ == NULL)
12899 this->array_val_ = create_array_val();
12900 if (this->array_val_ == NULL)
12901 {
12902 go_assert(this->type()->is_error());
12903 return context->backend()->error_expression();
12904 }
12905
12906 Location loc = this->location();
12907 Array_type* array_type = this->type()->array_type();
12908 Type* element_type = array_type->element_type();
e440a328 12909
0e9a2e72 12910 bool is_constant_initializer = this->array_val_->is_immutable();
d8829beb 12911
12912 // We have to copy the initial values into heap memory if we are in
12913 // a function or if the values are not constants. We also have to
12914 // copy them if they may contain pointers in a non-constant context,
12915 // as otherwise the garbage collector won't see them.
12916 bool copy_to_heap = (context->function() != NULL
12917 || !is_constant_initializer
12918 || (element_type->has_pointer()
12919 && !context->is_const()));
e440a328 12920
f23d7786 12921 Expression* space;
0e9a2e72 12922
12923 if (this->slice_storage_ != NULL)
12924 {
12925 go_assert(!this->storage_escapes_);
12926 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
12927 }
12928 else if (!copy_to_heap)
e440a328 12929 {
f23d7786 12930 // The initializer will only run once.
0e9a2e72 12931 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
f23d7786 12932 space->unary_expression()->set_is_slice_init();
e440a328 12933 }
12934 else
45ff893b 12935 {
0e9a2e72 12936 space = Expression::make_heap_expression(this->array_val_, loc);
45ff893b 12937 Node* n = Node::make_node(this);
12938 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
12939 {
12940 n = Node::make_node(space);
12941 n->set_encoding(Node::ESCAPE_NONE);
12942 }
12943 }
e440a328 12944
2c809f8f 12945 // Build a constructor for the slice.
f23d7786 12946 Expression* len = this->valtype_->array_type()->length();
12947 Expression* slice_val =
12948 Expression::make_slice_value(this->type(), space, len, len, loc);
ea664253 12949 return slice_val->get_backend(context);
e440a328 12950}
12951
12952// Make a slice composite literal. This is used by the type
12953// descriptor code.
12954
0e9a2e72 12955Slice_construction_expression*
e440a328 12956Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12957 Location location)
e440a328 12958{
411eb89e 12959 go_assert(type->is_slice_type());
2c809f8f 12960 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 12961}
12962
da244e59 12963// Class Map_construction_expression.
e440a328 12964
12965// Traversal.
12966
12967int
12968Map_construction_expression::do_traverse(Traverse* traverse)
12969{
12970 if (this->vals_ != NULL
12971 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12972 return TRAVERSE_EXIT;
12973 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12974 return TRAVERSE_EXIT;
12975 return TRAVERSE_CONTINUE;
12976}
12977
2c809f8f 12978// Flatten constructor initializer into a temporary variable since
12979// we need to take its address for __go_construct_map.
12980
12981Expression*
12982Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12983 Statement_inserter* inserter)
12984{
12985 if (!this->is_error_expression()
12986 && this->vals_ != NULL
12987 && !this->vals_->empty()
12988 && this->constructor_temp_ == NULL)
12989 {
12990 Map_type* mt = this->type_->map_type();
12991 Type* key_type = mt->key_type();
12992 Type* val_type = mt->val_type();
12993 this->element_type_ = Type::make_builtin_struct_type(2,
12994 "__key", key_type,
12995 "__val", val_type);
12996
12997 Expression_list* value_pairs = new Expression_list();
12998 Location loc = this->location();
12999
13000 size_t i = 0;
13001 for (Expression_list::const_iterator pv = this->vals_->begin();
13002 pv != this->vals_->end();
13003 ++pv, ++i)
13004 {
13005 Expression_list* key_value_pair = new Expression_list();
91c0fd76 13006 Expression* key = *pv;
5bf8be8b 13007 if (key->is_error_expression() || key->type()->is_error_type())
13008 {
13009 go_assert(saw_errors());
13010 return Expression::make_error(loc);
13011 }
91c0fd76 13012 if (key->type()->interface_type() != NULL && !key->is_variable())
13013 {
13014 Temporary_statement* temp =
13015 Statement::make_temporary(NULL, key, loc);
13016 inserter->insert(temp);
13017 key = Expression::make_temporary_reference(temp, loc);
13018 }
13019 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
2c809f8f 13020
13021 ++pv;
91c0fd76 13022 Expression* val = *pv;
5bf8be8b 13023 if (val->is_error_expression() || val->type()->is_error_type())
13024 {
13025 go_assert(saw_errors());
13026 return Expression::make_error(loc);
13027 }
91c0fd76 13028 if (val->type()->interface_type() != NULL && !val->is_variable())
13029 {
13030 Temporary_statement* temp =
13031 Statement::make_temporary(NULL, val, loc);
13032 inserter->insert(temp);
13033 val = Expression::make_temporary_reference(temp, loc);
13034 }
13035 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
2c809f8f 13036
13037 key_value_pair->push_back(key);
13038 key_value_pair->push_back(val);
13039 value_pairs->push_back(
13040 Expression::make_struct_composite_literal(this->element_type_,
13041 key_value_pair, loc));
13042 }
13043
e67508fa 13044 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
2c809f8f 13045 Type* ctor_type =
13046 Type::make_array_type(this->element_type_, element_count);
13047 Expression* constructor =
13048 new Fixed_array_construction_expression(ctor_type, NULL,
13049 value_pairs, loc);
13050
13051 this->constructor_temp_ =
13052 Statement::make_temporary(NULL, constructor, loc);
13053 constructor->issue_nil_check();
13054 this->constructor_temp_->set_is_address_taken();
13055 inserter->insert(this->constructor_temp_);
13056 }
13057
13058 return this;
13059}
13060
e440a328 13061// Final type determination.
13062
13063void
13064Map_construction_expression::do_determine_type(const Type_context*)
13065{
13066 if (this->vals_ == NULL)
13067 return;
13068
13069 Map_type* mt = this->type_->map_type();
13070 Type_context key_context(mt->key_type(), false);
13071 Type_context val_context(mt->val_type(), false);
13072 for (Expression_list::const_iterator pv = this->vals_->begin();
13073 pv != this->vals_->end();
13074 ++pv)
13075 {
13076 (*pv)->determine_type(&key_context);
13077 ++pv;
13078 (*pv)->determine_type(&val_context);
13079 }
13080}
13081
13082// Check types.
13083
13084void
13085Map_construction_expression::do_check_types(Gogo*)
13086{
13087 if (this->vals_ == NULL)
13088 return;
13089
13090 Map_type* mt = this->type_->map_type();
13091 int i = 0;
13092 Type* key_type = mt->key_type();
13093 Type* val_type = mt->val_type();
13094 for (Expression_list::const_iterator pv = this->vals_->begin();
13095 pv != this->vals_->end();
13096 ++pv, ++i)
13097 {
13098 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13099 {
631d5788 13100 go_error_at((*pv)->location(),
13101 "incompatible type for element %d key in map construction",
13102 i + 1);
e440a328 13103 this->set_is_error();
13104 }
13105 ++pv;
13106 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13107 {
631d5788 13108 go_error_at((*pv)->location(),
13109 ("incompatible type for element %d value "
13110 "in map construction"),
e440a328 13111 i + 1);
13112 this->set_is_error();
13113 }
13114 }
13115}
13116
ea664253 13117// Return the backend representation for constructing a map.
e440a328 13118
ea664253 13119Bexpression*
13120Map_construction_expression::do_get_backend(Translate_context* context)
e440a328 13121{
2c809f8f 13122 if (this->is_error_expression())
ea664253 13123 return context->backend()->error_expression();
2c809f8f 13124 Location loc = this->location();
e440a328 13125
e440a328 13126 size_t i = 0;
2c809f8f 13127 Expression* ventries;
e440a328 13128 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 13129 ventries = Expression::make_nil(loc);
e440a328 13130 else
13131 {
2c809f8f 13132 go_assert(this->constructor_temp_ != NULL);
13133 i = this->vals_->size() / 2;
e440a328 13134
2c809f8f 13135 Expression* ctor_ref =
13136 Expression::make_temporary_reference(this->constructor_temp_, loc);
13137 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13138 }
e440a328 13139
2c809f8f 13140 Map_type* mt = this->type_->map_type();
13141 if (this->element_type_ == NULL)
13142 this->element_type_ =
13143 Type::make_builtin_struct_type(2,
13144 "__key", mt->key_type(),
13145 "__val", mt->val_type());
0d5530d9 13146 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
2c809f8f 13147
13148 Type* uintptr_t = Type::lookup_integer_type("uintptr");
e67508fa 13149 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
2c809f8f 13150
13151 Expression* entry_size =
13152 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13153
13154 unsigned int field_index;
13155 const Struct_field* valfield =
13156 this->element_type_->find_local_field("__val", &field_index);
13157 Expression* val_offset =
13158 Expression::make_struct_field_offset(this->element_type_, valfield);
2c809f8f 13159
13160 Expression* map_ctor =
0d5530d9 13161 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13162 entry_size, val_offset, ventries);
ea664253 13163 return map_ctor->get_backend(context);
2c809f8f 13164}
e440a328 13165
2c809f8f 13166// Export an array construction.
e440a328 13167
2c809f8f 13168void
13169Map_construction_expression::do_export(Export* exp) const
13170{
13171 exp->write_c_string("convert(");
13172 exp->write_type(this->type_);
13173 for (Expression_list::const_iterator pv = this->vals_->begin();
13174 pv != this->vals_->end();
13175 ++pv)
13176 {
13177 exp->write_c_string(", ");
13178 (*pv)->export_expression(exp);
13179 }
13180 exp->write_c_string(")");
13181}
e440a328 13182
2c809f8f 13183// Dump ast representation for a map construction expression.
d751bb78 13184
13185void
13186Map_construction_expression::do_dump_expression(
13187 Ast_dump_context* ast_dump_context) const
13188{
d751bb78 13189 ast_dump_context->ostream() << "{" ;
8b1c301d 13190 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 13191 ast_dump_context->ostream() << "}";
13192}
13193
7795ac51 13194// Class Composite_literal_expression.
e440a328 13195
13196// Traversal.
13197
13198int
13199Composite_literal_expression::do_traverse(Traverse* traverse)
13200{
dbffccfc 13201 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 13202 return TRAVERSE_EXIT;
dbffccfc 13203
13204 // If this is a struct composite literal with keys, then the keys
13205 // are field names, not expressions. We don't want to traverse them
13206 // in that case. If we do, we can give an erroneous error "variable
13207 // initializer refers to itself." See bug482.go in the testsuite.
13208 if (this->has_keys_ && this->vals_ != NULL)
13209 {
13210 // The type may not be resolvable at this point.
13211 Type* type = this->type_;
a01f2481 13212
7795ac51 13213 for (int depth = 0; depth < this->depth_; ++depth)
a01f2481 13214 {
13215 if (type->array_type() != NULL)
13216 type = type->array_type()->element_type();
13217 else if (type->map_type() != NULL)
7795ac51 13218 {
13219 if (this->key_path_[depth])
13220 type = type->map_type()->key_type();
13221 else
13222 type = type->map_type()->val_type();
13223 }
a01f2481 13224 else
13225 {
13226 // This error will be reported during lowering.
13227 return TRAVERSE_CONTINUE;
13228 }
13229 }
13230
dbffccfc 13231 while (true)
13232 {
13233 if (type->classification() == Type::TYPE_NAMED)
13234 type = type->named_type()->real_type();
13235 else if (type->classification() == Type::TYPE_FORWARD)
13236 {
13237 Type* t = type->forwarded();
13238 if (t == type)
13239 break;
13240 type = t;
13241 }
13242 else
13243 break;
13244 }
13245
13246 if (type->classification() == Type::TYPE_STRUCT)
13247 {
13248 Expression_list::iterator p = this->vals_->begin();
13249 while (p != this->vals_->end())
13250 {
13251 // Skip key.
13252 ++p;
13253 go_assert(p != this->vals_->end());
13254 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13255 return TRAVERSE_EXIT;
13256 ++p;
13257 }
13258 return TRAVERSE_CONTINUE;
13259 }
13260 }
13261
13262 if (this->vals_ != NULL)
13263 return this->vals_->traverse(traverse);
13264
13265 return TRAVERSE_CONTINUE;
e440a328 13266}
13267
13268// Lower a generic composite literal into a specific version based on
13269// the type.
13270
13271Expression*
ceeb4318 13272Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13273 Statement_inserter* inserter, int)
e440a328 13274{
13275 Type* type = this->type_;
13276
7795ac51 13277 for (int depth = 0; depth < this->depth_; ++depth)
e440a328 13278 {
13279 if (type->array_type() != NULL)
13280 type = type->array_type()->element_type();
13281 else if (type->map_type() != NULL)
7795ac51 13282 {
13283 if (this->key_path_[depth])
13284 type = type->map_type()->key_type();
13285 else
13286 type = type->map_type()->val_type();
13287 }
e440a328 13288 else
13289 {
5c13bd80 13290 if (!type->is_error())
631d5788 13291 go_error_at(this->location(),
13292 ("may only omit types within composite literals "
13293 "of slice, array, or map type"));
e440a328 13294 return Expression::make_error(this->location());
13295 }
13296 }
13297
e00772b3 13298 Type *pt = type->points_to();
13299 bool is_pointer = false;
13300 if (pt != NULL)
13301 {
13302 is_pointer = true;
13303 type = pt;
13304 }
13305
13306 Expression* ret;
5c13bd80 13307 if (type->is_error())
e440a328 13308 return Expression::make_error(this->location());
13309 else if (type->struct_type() != NULL)
e00772b3 13310 ret = this->lower_struct(gogo, type);
e440a328 13311 else if (type->array_type() != NULL)
113ef6a5 13312 ret = this->lower_array(type);
e440a328 13313 else if (type->map_type() != NULL)
e00772b3 13314 ret = this->lower_map(gogo, function, inserter, type);
e440a328 13315 else
13316 {
631d5788 13317 go_error_at(this->location(),
13318 ("expected struct, slice, array, or map type "
13319 "for composite literal"));
e440a328 13320 return Expression::make_error(this->location());
13321 }
e00772b3 13322
13323 if (is_pointer)
2c809f8f 13324 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 13325
13326 return ret;
e440a328 13327}
13328
13329// Lower a struct composite literal.
13330
13331Expression*
81c4b26b 13332Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 13333{
b13c66cd 13334 Location location = this->location();
e440a328 13335 Struct_type* st = type->struct_type();
13336 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 13337 {
e6013c28 13338 if (this->vals_ != NULL
13339 && !this->vals_->empty()
13340 && type->named_type() != NULL
13341 && type->named_type()->named_object()->package() != NULL)
13342 {
13343 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13344 pf != st->fields()->end();
13345 ++pf)
07daa4e7 13346 {
07ba7f26 13347 if (Gogo::is_hidden_name(pf->field_name())
13348 || pf->is_embedded_builtin(gogo))
631d5788 13349 go_error_at(this->location(),
13350 "assignment of unexported field %qs in %qs literal",
13351 Gogo::message_name(pf->field_name()).c_str(),
13352 type->named_type()->message_name().c_str());
07daa4e7 13353 }
13354 }
13355
13356 return new Struct_construction_expression(type, this->vals_, location);
13357 }
e440a328 13358
13359 size_t field_count = st->field_count();
13360 std::vector<Expression*> vals(field_count);
e32de7ba 13361 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
e440a328 13362 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 13363 Expression* external_expr = NULL;
13364 const Named_object* external_no = NULL;
e440a328 13365 while (p != this->vals_->end())
13366 {
13367 Expression* name_expr = *p;
13368
13369 ++p;
c484d925 13370 go_assert(p != this->vals_->end());
e440a328 13371 Expression* val = *p;
13372
13373 ++p;
13374
13375 if (name_expr == NULL)
13376 {
631d5788 13377 go_error_at(val->location(),
13378 "mixture of field and value initializers");
e440a328 13379 return Expression::make_error(location);
13380 }
13381
13382 bool bad_key = false;
13383 std::string name;
81c4b26b 13384 const Named_object* no = NULL;
e440a328 13385 switch (name_expr->classification())
13386 {
13387 case EXPRESSION_UNKNOWN_REFERENCE:
13388 name = name_expr->unknown_expression()->name();
7f7ce694 13389 if (type->named_type() != NULL)
13390 {
13391 // If the named object found for this field name comes from a
13392 // different package than the struct it is a part of, do not count
13393 // this incorrect lookup as a usage of the object's package.
13394 no = name_expr->unknown_expression()->named_object();
13395 if (no->package() != NULL
13396 && no->package() != type->named_type()->named_object()->package())
13397 no->package()->forget_usage(name_expr);
13398 }
e440a328 13399 break;
13400
13401 case EXPRESSION_CONST_REFERENCE:
81c4b26b 13402 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 13403 break;
13404
13405 case EXPRESSION_TYPE:
13406 {
13407 Type* t = name_expr->type();
13408 Named_type* nt = t->named_type();
13409 if (nt == NULL)
13410 bad_key = true;
13411 else
81c4b26b 13412 no = nt->named_object();
e440a328 13413 }
13414 break;
13415
13416 case EXPRESSION_VAR_REFERENCE:
81c4b26b 13417 no = name_expr->var_expression()->named_object();
e440a328 13418 break;
13419
b0c09712 13420 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13421 no = name_expr->enclosed_var_expression()->variable();
e440a328 13422 break;
13423
b0c09712 13424 case EXPRESSION_FUNC_REFERENCE:
13425 no = name_expr->func_expression()->named_object();
e440a328 13426 break;
13427
13428 default:
13429 bad_key = true;
13430 break;
13431 }
13432 if (bad_key)
13433 {
631d5788 13434 go_error_at(name_expr->location(), "expected struct field name");
e440a328 13435 return Expression::make_error(location);
13436 }
13437
81c4b26b 13438 if (no != NULL)
13439 {
62750cd5 13440 if (no->package() != NULL && external_expr == NULL)
13441 {
13442 external_expr = name_expr;
13443 external_no = no;
13444 }
13445
81c4b26b 13446 name = no->name();
13447
13448 // A predefined name won't be packed. If it starts with a
13449 // lower case letter we need to check for that case, because
2d29d278 13450 // the field name will be packed. FIXME.
81c4b26b 13451 if (!Gogo::is_hidden_name(name)
13452 && name[0] >= 'a'
13453 && name[0] <= 'z')
13454 {
13455 Named_object* gno = gogo->lookup_global(name.c_str());
13456 if (gno == no)
13457 name = gogo->pack_hidden_name(name, false);
13458 }
13459 }
13460
e440a328 13461 unsigned int index;
13462 const Struct_field* sf = st->find_local_field(name, &index);
13463 if (sf == NULL)
13464 {
631d5788 13465 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13466 Gogo::message_name(name).c_str(),
13467 (type->named_type() != NULL
13468 ? type->named_type()->message_name().c_str()
13469 : "unnamed struct"));
e440a328 13470 return Expression::make_error(location);
13471 }
13472 if (vals[index] != NULL)
13473 {
631d5788 13474 go_error_at(name_expr->location(),
13475 "duplicate value for field %qs in %qs",
13476 Gogo::message_name(name).c_str(),
13477 (type->named_type() != NULL
13478 ? type->named_type()->message_name().c_str()
13479 : "unnamed struct"));
e440a328 13480 return Expression::make_error(location);
13481 }
13482
07daa4e7 13483 if (type->named_type() != NULL
13484 && type->named_type()->named_object()->package() != NULL
07ba7f26 13485 && (Gogo::is_hidden_name(sf->field_name())
13486 || sf->is_embedded_builtin(gogo)))
631d5788 13487 go_error_at(name_expr->location(),
13488 "assignment of unexported field %qs in %qs literal",
13489 Gogo::message_name(sf->field_name()).c_str(),
13490 type->named_type()->message_name().c_str());
07daa4e7 13491
e440a328 13492 vals[index] = val;
e32de7ba 13493 traverse_order->push_back(static_cast<unsigned long>(index));
e440a328 13494 }
13495
62750cd5 13496 if (!this->all_are_names_)
13497 {
13498 // This is a weird case like bug462 in the testsuite.
13499 if (external_expr == NULL)
631d5788 13500 go_error_at(this->location(), "unknown field in %qs literal",
13501 (type->named_type() != NULL
13502 ? type->named_type()->message_name().c_str()
13503 : "unnamed struct"));
62750cd5 13504 else
631d5788 13505 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13506 external_no->message_name().c_str(),
13507 (type->named_type() != NULL
13508 ? type->named_type()->message_name().c_str()
13509 : "unnamed struct"));
62750cd5 13510 return Expression::make_error(location);
13511 }
13512
e440a328 13513 Expression_list* list = new Expression_list;
13514 list->reserve(field_count);
13515 for (size_t i = 0; i < field_count; ++i)
13516 list->push_back(vals[i]);
13517
0c4f5a19 13518 Struct_construction_expression* ret =
13519 new Struct_construction_expression(type, list, location);
13520 ret->set_traverse_order(traverse_order);
13521 return ret;
e440a328 13522}
13523
e32de7ba 13524// Index/value/traversal-order triple.
00773463 13525
e32de7ba 13526struct IVT_triple {
13527 unsigned long index;
13528 unsigned long traversal_order;
13529 Expression* expr;
13530 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13531 : index(i), traversal_order(to), expr(e) { }
13532 bool operator<(const IVT_triple& other) const
13533 { return this->index < other.index; }
00773463 13534};
13535
e440a328 13536// Lower an array composite literal.
13537
13538Expression*
113ef6a5 13539Composite_literal_expression::lower_array(Type* type)
e440a328 13540{
b13c66cd 13541 Location location = this->location();
e440a328 13542 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13543 return this->make_array(type, NULL, this->vals_);
e440a328 13544
ffe743ca 13545 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13546 indexes->reserve(this->vals_->size());
00773463 13547 bool indexes_out_of_order = false;
ffe743ca 13548 Expression_list* vals = new Expression_list();
13549 vals->reserve(this->vals_->size());
e440a328 13550 unsigned long index = 0;
13551 Expression_list::const_iterator p = this->vals_->begin();
13552 while (p != this->vals_->end())
13553 {
13554 Expression* index_expr = *p;
13555
13556 ++p;
c484d925 13557 go_assert(p != this->vals_->end());
e440a328 13558 Expression* val = *p;
13559
13560 ++p;
13561
ffe743ca 13562 if (index_expr == NULL)
13563 {
13564 if (!indexes->empty())
13565 indexes->push_back(index);
13566 }
13567 else
e440a328 13568 {
ffe743ca 13569 if (indexes->empty() && !vals->empty())
13570 {
13571 for (size_t i = 0; i < vals->size(); ++i)
13572 indexes->push_back(i);
13573 }
13574
0c77715b 13575 Numeric_constant nc;
13576 if (!index_expr->numeric_constant_value(&nc))
e440a328 13577 {
631d5788 13578 go_error_at(index_expr->location(),
13579 "index expression is not integer constant");
e440a328 13580 return Expression::make_error(location);
13581 }
6f6d9955 13582
0c77715b 13583 switch (nc.to_unsigned_long(&index))
e440a328 13584 {
0c77715b 13585 case Numeric_constant::NC_UL_VALID:
13586 break;
13587 case Numeric_constant::NC_UL_NOTINT:
631d5788 13588 go_error_at(index_expr->location(),
13589 "index expression is not integer constant");
0c77715b 13590 return Expression::make_error(location);
13591 case Numeric_constant::NC_UL_NEGATIVE:
631d5788 13592 go_error_at(index_expr->location(),
13593 "index expression is negative");
e440a328 13594 return Expression::make_error(location);
0c77715b 13595 case Numeric_constant::NC_UL_BIG:
631d5788 13596 go_error_at(index_expr->location(), "index value overflow");
e440a328 13597 return Expression::make_error(location);
0c77715b 13598 default:
13599 go_unreachable();
e440a328 13600 }
6f6d9955 13601
13602 Named_type* ntype = Type::lookup_integer_type("int");
13603 Integer_type* inttype = ntype->integer_type();
0c77715b 13604 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13605 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13606 {
631d5788 13607 go_error_at(index_expr->location(), "index value overflow");
6f6d9955 13608 return Expression::make_error(location);
13609 }
13610
ffe743ca 13611 if (std::find(indexes->begin(), indexes->end(), index)
13612 != indexes->end())
e440a328 13613 {
631d5788 13614 go_error_at(index_expr->location(),
13615 "duplicate value for index %lu",
13616 index);
e440a328 13617 return Expression::make_error(location);
13618 }
ffe743ca 13619
00773463 13620 if (!indexes->empty() && index < indexes->back())
13621 indexes_out_of_order = true;
13622
ffe743ca 13623 indexes->push_back(index);
e440a328 13624 }
13625
ffe743ca 13626 vals->push_back(val);
13627
e440a328 13628 ++index;
13629 }
13630
ffe743ca 13631 if (indexes->empty())
13632 {
13633 delete indexes;
13634 indexes = NULL;
13635 }
e440a328 13636
e32de7ba 13637 std::vector<unsigned long>* traverse_order = NULL;
00773463 13638 if (indexes_out_of_order)
13639 {
e32de7ba 13640 typedef std::vector<IVT_triple> V;
00773463 13641
13642 V v;
13643 v.reserve(indexes->size());
13644 std::vector<unsigned long>::const_iterator pi = indexes->begin();
e32de7ba 13645 unsigned long torder = 0;
00773463 13646 for (Expression_list::const_iterator pe = vals->begin();
13647 pe != vals->end();
e32de7ba 13648 ++pe, ++pi, ++torder)
13649 v.push_back(IVT_triple(*pi, torder, *pe));
00773463 13650
e32de7ba 13651 std::sort(v.begin(), v.end());
00773463 13652
13653 delete indexes;
13654 delete vals;
e32de7ba 13655
00773463 13656 indexes = new std::vector<unsigned long>();
13657 indexes->reserve(v.size());
13658 vals = new Expression_list();
13659 vals->reserve(v.size());
e32de7ba 13660 traverse_order = new std::vector<unsigned long>();
13661 traverse_order->reserve(v.size());
00773463 13662
13663 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13664 {
e32de7ba 13665 indexes->push_back(p->index);
13666 vals->push_back(p->expr);
13667 traverse_order->push_back(p->traversal_order);
00773463 13668 }
13669 }
13670
e32de7ba 13671 Expression* ret = this->make_array(type, indexes, vals);
13672 Array_construction_expression* ace = ret->array_literal();
13673 if (ace != NULL && traverse_order != NULL)
13674 ace->set_traverse_order(traverse_order);
13675 return ret;
e440a328 13676}
13677
13678// Actually build the array composite literal. This handles
13679// [...]{...}.
13680
13681Expression*
ffe743ca 13682Composite_literal_expression::make_array(
13683 Type* type,
13684 const std::vector<unsigned long>* indexes,
13685 Expression_list* vals)
e440a328 13686{
b13c66cd 13687 Location location = this->location();
e440a328 13688 Array_type* at = type->array_type();
ffe743ca 13689
e440a328 13690 if (at->length() != NULL && at->length()->is_nil_expression())
13691 {
ffe743ca 13692 size_t size;
13693 if (vals == NULL)
13694 size = 0;
00773463 13695 else if (indexes != NULL)
13696 size = indexes->back() + 1;
13697 else
ffe743ca 13698 {
13699 size = vals->size();
13700 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13701 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13702 && size >> (it->bits() - 1) != 0)
13703 {
631d5788 13704 go_error_at(location, "too many elements in composite literal");
ffe743ca 13705 return Expression::make_error(location);
13706 }
13707 }
ffe743ca 13708
e67508fa 13709 Expression* elen = Expression::make_integer_ul(size, NULL, location);
e440a328 13710 at = Type::make_array_type(at->element_type(), elen);
13711 type = at;
13712 }
ffe743ca 13713 else if (at->length() != NULL
13714 && !at->length()->is_error_expression()
13715 && this->vals_ != NULL)
13716 {
13717 Numeric_constant nc;
13718 unsigned long val;
13719 if (at->length()->numeric_constant_value(&nc)
13720 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13721 {
13722 if (indexes == NULL)
13723 {
13724 if (this->vals_->size() > val)
13725 {
631d5788 13726 go_error_at(location,
13727 "too many elements in composite literal");
ffe743ca 13728 return Expression::make_error(location);
13729 }
13730 }
13731 else
13732 {
00773463 13733 unsigned long max = indexes->back();
ffe743ca 13734 if (max >= val)
13735 {
631d5788 13736 go_error_at(location,
13737 ("some element keys in composite literal "
13738 "are out of range"));
ffe743ca 13739 return Expression::make_error(location);
13740 }
13741 }
13742 }
13743 }
13744
e440a328 13745 if (at->length() != NULL)
ffe743ca 13746 return new Fixed_array_construction_expression(type, indexes, vals,
13747 location);
e440a328 13748 else
2c809f8f 13749 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 13750}
13751
13752// Lower a map composite literal.
13753
13754Expression*
a287720d 13755Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13756 Statement_inserter* inserter,
a287720d 13757 Type* type)
e440a328 13758{
b13c66cd 13759 Location location = this->location();
e440a328 13760 if (this->vals_ != NULL)
13761 {
13762 if (!this->has_keys_)
13763 {
631d5788 13764 go_error_at(location, "map composite literal must have keys");
e440a328 13765 return Expression::make_error(location);
13766 }
13767
a287720d 13768 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13769 p != this->vals_->end();
13770 p += 2)
13771 {
13772 if (*p == NULL)
13773 {
13774 ++p;
631d5788 13775 go_error_at((*p)->location(),
13776 ("map composite literal must "
13777 "have keys for every value"));
e440a328 13778 return Expression::make_error(location);
13779 }
a287720d 13780 // Make sure we have lowered the key; it may not have been
13781 // lowered in order to handle keys for struct composite
13782 // literals. Lower it now to get the right error message.
13783 if ((*p)->unknown_expression() != NULL)
13784 {
13785 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 13786 gogo->lower_expression(function, inserter, &*p);
c484d925 13787 go_assert((*p)->is_error_expression());
a287720d 13788 return Expression::make_error(location);
13789 }
e440a328 13790 }
13791 }
13792
13793 return new Map_construction_expression(type, this->vals_, location);
13794}
13795
d751bb78 13796// Dump ast representation for a composite literal expression.
13797
13798void
13799Composite_literal_expression::do_dump_expression(
13800 Ast_dump_context* ast_dump_context) const
13801{
8b1c301d 13802 ast_dump_context->ostream() << "composite(";
d751bb78 13803 ast_dump_context->dump_type(this->type_);
13804 ast_dump_context->ostream() << ", {";
8b1c301d 13805 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 13806 ast_dump_context->ostream() << "})";
13807}
13808
e440a328 13809// Make a composite literal expression.
13810
13811Expression*
13812Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 13813 Expression_list* vals, bool all_are_names,
b13c66cd 13814 Location location)
e440a328 13815{
13816 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 13817 all_are_names, location);
e440a328 13818}
13819
13820// Return whether this expression is a composite literal.
13821
13822bool
13823Expression::is_composite_literal() const
13824{
13825 switch (this->classification_)
13826 {
13827 case EXPRESSION_COMPOSITE_LITERAL:
13828 case EXPRESSION_STRUCT_CONSTRUCTION:
13829 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 13830 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13831 case EXPRESSION_MAP_CONSTRUCTION:
13832 return true;
13833 default:
13834 return false;
13835 }
13836}
13837
13838// Return whether this expression is a composite literal which is not
13839// constant.
13840
13841bool
13842Expression::is_nonconstant_composite_literal() const
13843{
13844 switch (this->classification_)
13845 {
13846 case EXPRESSION_STRUCT_CONSTRUCTION:
13847 {
13848 const Struct_construction_expression *psce =
13849 static_cast<const Struct_construction_expression*>(this);
13850 return !psce->is_constant_struct();
13851 }
13852 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13853 {
13854 const Fixed_array_construction_expression *pace =
13855 static_cast<const Fixed_array_construction_expression*>(this);
13856 return !pace->is_constant_array();
13857 }
2c809f8f 13858 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13859 {
2c809f8f 13860 const Slice_construction_expression *pace =
13861 static_cast<const Slice_construction_expression*>(this);
e440a328 13862 return !pace->is_constant_array();
13863 }
13864 case EXPRESSION_MAP_CONSTRUCTION:
13865 return true;
13866 default:
13867 return false;
13868 }
13869}
13870
35a54f17 13871// Return true if this is a variable or temporary_variable.
13872
13873bool
13874Expression::is_variable() const
13875{
13876 switch (this->classification_)
13877 {
13878 case EXPRESSION_VAR_REFERENCE:
13879 case EXPRESSION_TEMPORARY_REFERENCE:
13880 case EXPRESSION_SET_AND_USE_TEMPORARY:
b0c09712 13881 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
35a54f17 13882 return true;
13883 default:
13884 return false;
13885 }
13886}
13887
e440a328 13888// Return true if this is a reference to a local variable.
13889
13890bool
13891Expression::is_local_variable() const
13892{
13893 const Var_expression* ve = this->var_expression();
13894 if (ve == NULL)
13895 return false;
13896 const Named_object* no = ve->named_object();
13897 return (no->is_result_variable()
13898 || (no->is_variable() && !no->var_value()->is_global()));
13899}
13900
13901// Class Type_guard_expression.
13902
13903// Traversal.
13904
13905int
13906Type_guard_expression::do_traverse(Traverse* traverse)
13907{
13908 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13909 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13910 return TRAVERSE_EXIT;
13911 return TRAVERSE_CONTINUE;
13912}
13913
2c809f8f 13914Expression*
13915Type_guard_expression::do_flatten(Gogo*, Named_object*,
13916 Statement_inserter* inserter)
13917{
5bf8be8b 13918 if (this->expr_->is_error_expression()
13919 || this->expr_->type()->is_error_type())
13920 {
13921 go_assert(saw_errors());
13922 return Expression::make_error(this->location());
13923 }
13924
2c809f8f 13925 if (!this->expr_->is_variable())
13926 {
13927 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13928 this->location());
13929 inserter->insert(temp);
13930 this->expr_ =
13931 Expression::make_temporary_reference(temp, this->location());
13932 }
13933 return this;
13934}
13935
e440a328 13936// Check types of a type guard expression. The expression must have
13937// an interface type, but the actual type conversion is checked at run
13938// time.
13939
13940void
13941Type_guard_expression::do_check_types(Gogo*)
13942{
e440a328 13943 Type* expr_type = this->expr_->type();
7e9da23f 13944 if (expr_type->interface_type() == NULL)
f725ade8 13945 {
5c13bd80 13946 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 13947 this->report_error(_("type assertion only valid for interface types"));
13948 this->set_is_error();
13949 }
e440a328 13950 else if (this->type_->interface_type() == NULL)
13951 {
13952 std::string reason;
13953 if (!expr_type->interface_type()->implements_interface(this->type_,
13954 &reason))
13955 {
5c13bd80 13956 if (!this->type_->is_error())
e440a328 13957 {
f725ade8 13958 if (reason.empty())
13959 this->report_error(_("impossible type assertion: "
13960 "type does not implement interface"));
13961 else
631d5788 13962 go_error_at(this->location(),
13963 ("impossible type assertion: "
13964 "type does not implement interface (%s)"),
13965 reason.c_str());
e440a328 13966 }
f725ade8 13967 this->set_is_error();
e440a328 13968 }
13969 }
13970}
13971
ea664253 13972// Return the backend representation for a type guard expression.
e440a328 13973
ea664253 13974Bexpression*
13975Type_guard_expression::do_get_backend(Translate_context* context)
e440a328 13976{
2c809f8f 13977 Expression* conversion;
7e9da23f 13978 if (this->type_->interface_type() != NULL)
2c809f8f 13979 conversion =
13980 Expression::convert_interface_to_interface(this->type_, this->expr_,
13981 true, this->location());
e440a328 13982 else
2c809f8f 13983 conversion =
13984 Expression::convert_for_assignment(context->gogo(), this->type_,
13985 this->expr_, this->location());
13986
ea664253 13987 return conversion->get_backend(context);
e440a328 13988}
13989
d751bb78 13990// Dump ast representation for a type guard expression.
13991
13992void
2c809f8f 13993Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 13994 const
13995{
13996 this->expr_->dump_expression(ast_dump_context);
13997 ast_dump_context->ostream() << ".";
13998 ast_dump_context->dump_type(this->type_);
13999}
14000
e440a328 14001// Make a type guard expression.
14002
14003Expression*
14004Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 14005 Location location)
e440a328 14006{
14007 return new Type_guard_expression(expr, type, location);
14008}
14009
2c809f8f 14010// Class Heap_expression.
e440a328 14011
da244e59 14012// Return the type of the expression stored on the heap.
e440a328 14013
da244e59 14014Type*
14015Heap_expression::do_type()
14016{ return Type::make_pointer_type(this->expr_->type()); }
e440a328 14017
ea664253 14018// Return the backend representation for allocating an expression on the heap.
e440a328 14019
ea664253 14020Bexpression*
14021Heap_expression::do_get_backend(Translate_context* context)
e440a328 14022{
02c19a1a 14023 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
ea664253 14024 return context->backend()->error_expression();
2c809f8f 14025
02c19a1a 14026 Location loc = this->location();
2c809f8f 14027 Gogo* gogo = context->gogo();
02c19a1a 14028 Btype* btype = this->type()->get_backend(gogo);
45ff893b 14029
14030 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
14031 Node* n = Node::make_node(this);
14032 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
14033 alloc->allocation_expression()->set_allocate_on_stack();
14034 Bexpression* space = alloc->get_backend(context);
02c19a1a 14035
14036 Bstatement* decl;
14037 Named_object* fn = context->function();
14038 go_assert(fn != NULL);
14039 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14040 Bvariable* space_temp =
14041 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14042 space, true, loc, &decl);
14043 space = gogo->backend()->var_expression(space_temp, loc);
9b27b43c 14044 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
14045 Bexpression* ref =
14046 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
02c19a1a 14047
ea664253 14048 Bexpression* bexpr = this->expr_->get_backend(context);
02c19a1a 14049 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
14050 decl = gogo->backend()->compound_statement(decl, assn);
14051 space = gogo->backend()->var_expression(space_temp, loc);
ea664253 14052 return gogo->backend()->compound_expression(decl, space, loc);
e440a328 14053}
14054
2c809f8f 14055// Dump ast representation for a heap expression.
d751bb78 14056
14057void
2c809f8f 14058Heap_expression::do_dump_expression(
d751bb78 14059 Ast_dump_context* ast_dump_context) const
14060{
14061 ast_dump_context->ostream() << "&(";
14062 ast_dump_context->dump_expression(this->expr_);
14063 ast_dump_context->ostream() << ")";
14064}
14065
2c809f8f 14066// Allocate an expression on the heap.
e440a328 14067
14068Expression*
2c809f8f 14069Expression::make_heap_expression(Expression* expr, Location location)
e440a328 14070{
2c809f8f 14071 return new Heap_expression(expr, location);
e440a328 14072}
14073
14074// Class Receive_expression.
14075
14076// Return the type of a receive expression.
14077
14078Type*
14079Receive_expression::do_type()
14080{
e429e3bd 14081 if (this->is_error_expression())
14082 return Type::make_error_type();
e440a328 14083 Channel_type* channel_type = this->channel_->type()->channel_type();
14084 if (channel_type == NULL)
e429e3bd 14085 {
14086 this->report_error(_("expected channel"));
14087 return Type::make_error_type();
14088 }
e440a328 14089 return channel_type->element_type();
14090}
14091
14092// Check types for a receive expression.
14093
14094void
14095Receive_expression::do_check_types(Gogo*)
14096{
14097 Type* type = this->channel_->type();
5c13bd80 14098 if (type->is_error())
e440a328 14099 {
e429e3bd 14100 go_assert(saw_errors());
e440a328 14101 this->set_is_error();
14102 return;
14103 }
14104 if (type->channel_type() == NULL)
14105 {
14106 this->report_error(_("expected channel"));
14107 return;
14108 }
14109 if (!type->channel_type()->may_receive())
14110 {
14111 this->report_error(_("invalid receive on send-only channel"));
14112 return;
14113 }
14114}
14115
2c809f8f 14116// Flattening for receive expressions creates a temporary variable to store
14117// received data in for receives.
14118
14119Expression*
14120Receive_expression::do_flatten(Gogo*, Named_object*,
14121 Statement_inserter* inserter)
14122{
14123 Channel_type* channel_type = this->channel_->type()->channel_type();
14124 if (channel_type == NULL)
14125 {
14126 go_assert(saw_errors());
14127 return this;
14128 }
5bf8be8b 14129 else if (this->channel_->is_error_expression())
14130 {
14131 go_assert(saw_errors());
14132 return Expression::make_error(this->location());
14133 }
2c809f8f 14134
14135 Type* element_type = channel_type->element_type();
14136 if (this->temp_receiver_ == NULL)
14137 {
14138 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14139 this->location());
14140 this->temp_receiver_->set_is_address_taken();
14141 inserter->insert(this->temp_receiver_);
14142 }
14143
14144 return this;
14145}
14146
ea664253 14147// Get the backend representation for a receive expression.
e440a328 14148
ea664253 14149Bexpression*
14150Receive_expression::do_get_backend(Translate_context* context)
e440a328 14151{
f24f10bb 14152 Location loc = this->location();
14153
e440a328 14154 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 14155 if (channel_type == NULL)
14156 {
c484d925 14157 go_assert(this->channel_->type()->is_error());
ea664253 14158 return context->backend()->error_expression();
5b8368f4 14159 }
f24f10bb 14160 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 14161
2c809f8f 14162 Expression* recv_ref =
14163 Expression::make_temporary_reference(this->temp_receiver_, loc);
14164 Expression* recv_addr =
14165 Expression::make_temporary_reference(this->temp_receiver_, loc);
14166 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
132ed071 14167 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 3,
14168 td, this->channel_, recv_addr);
ea664253 14169 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
e440a328 14170}
14171
d751bb78 14172// Dump ast representation for a receive expression.
14173
14174void
14175Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14176{
14177 ast_dump_context->ostream() << " <- " ;
14178 ast_dump_context->dump_expression(channel_);
14179}
14180
e440a328 14181// Make a receive expression.
14182
14183Receive_expression*
b13c66cd 14184Expression::make_receive(Expression* channel, Location location)
e440a328 14185{
14186 return new Receive_expression(channel, location);
14187}
14188
e440a328 14189// An expression which evaluates to a pointer to the type descriptor
14190// of a type.
14191
14192class Type_descriptor_expression : public Expression
14193{
14194 public:
b13c66cd 14195 Type_descriptor_expression(Type* type, Location location)
e440a328 14196 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14197 type_(type)
14198 { }
14199
14200 protected:
4b686186 14201 int
14202 do_traverse(Traverse*);
14203
e440a328 14204 Type*
14205 do_type()
14206 { return Type::make_type_descriptor_ptr_type(); }
14207
f9ca30f9 14208 bool
14209 do_is_immutable() const
14210 { return true; }
14211
e440a328 14212 void
14213 do_determine_type(const Type_context*)
14214 { }
14215
14216 Expression*
14217 do_copy()
14218 { return this; }
14219
ea664253 14220 Bexpression*
14221 do_get_backend(Translate_context* context)
a1d23b41 14222 {
ea664253 14223 return this->type_->type_descriptor_pointer(context->gogo(),
14224 this->location());
a1d23b41 14225 }
e440a328 14226
d751bb78 14227 void
14228 do_dump_expression(Ast_dump_context*) const;
14229
e440a328 14230 private:
14231 // The type for which this is the descriptor.
14232 Type* type_;
14233};
14234
4b686186 14235int
14236Type_descriptor_expression::do_traverse(Traverse* traverse)
14237{
14238 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14239 return TRAVERSE_EXIT;
14240 return TRAVERSE_CONTINUE;
14241}
14242
d751bb78 14243// Dump ast representation for a type descriptor expression.
14244
14245void
14246Type_descriptor_expression::do_dump_expression(
14247 Ast_dump_context* ast_dump_context) const
14248{
14249 ast_dump_context->dump_type(this->type_);
14250}
14251
e440a328 14252// Make a type descriptor expression.
14253
14254Expression*
b13c66cd 14255Expression::make_type_descriptor(Type* type, Location location)
e440a328 14256{
14257 return new Type_descriptor_expression(type, location);
14258}
14259
aa5ae575 14260// An expression which evaluates to a pointer to the Garbage Collection symbol
14261// of a type.
14262
14263class GC_symbol_expression : public Expression
14264{
14265 public:
14266 GC_symbol_expression(Type* type)
14267 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14268 type_(type)
14269 {}
14270
14271 protected:
14272 Type*
14273 do_type()
23d77f91 14274 { return Type::lookup_integer_type("uintptr"); }
aa5ae575 14275
14276 bool
14277 do_is_immutable() const
14278 { return true; }
14279
14280 void
14281 do_determine_type(const Type_context*)
14282 { }
14283
14284 Expression*
14285 do_copy()
14286 { return this; }
14287
14288 Bexpression*
14289 do_get_backend(Translate_context* context)
14290 { return this->type_->gc_symbol_pointer(context->gogo()); }
14291
14292 void
14293 do_dump_expression(Ast_dump_context*) const;
14294
14295 private:
14296 // The type which this gc symbol describes.
14297 Type* type_;
14298};
14299
14300// Dump ast representation for a gc symbol expression.
14301
14302void
14303GC_symbol_expression::do_dump_expression(
14304 Ast_dump_context* ast_dump_context) const
14305{
14306 ast_dump_context->ostream() << "gcdata(";
14307 ast_dump_context->dump_type(this->type_);
14308 ast_dump_context->ostream() << ")";
14309}
14310
14311// Make a gc symbol expression.
14312
14313Expression*
14314Expression::make_gc_symbol(Type* type)
14315{
14316 return new GC_symbol_expression(type);
14317}
14318
e440a328 14319// An expression which evaluates to some characteristic of a type.
14320// This is only used to initialize fields of a type descriptor. Using
14321// a new expression class is slightly inefficient but gives us a good
14322// separation between the frontend and the middle-end with regard to
14323// how types are laid out.
14324
14325class Type_info_expression : public Expression
14326{
14327 public:
14328 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 14329 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 14330 type_(type), type_info_(type_info)
14331 { }
14332
14333 protected:
0e168074 14334 bool
14335 do_is_immutable() const
14336 { return true; }
14337
e440a328 14338 Type*
14339 do_type();
14340
14341 void
14342 do_determine_type(const Type_context*)
14343 { }
14344
14345 Expression*
14346 do_copy()
14347 { return this; }
14348
ea664253 14349 Bexpression*
14350 do_get_backend(Translate_context* context);
e440a328 14351
d751bb78 14352 void
14353 do_dump_expression(Ast_dump_context*) const;
14354
e440a328 14355 private:
14356 // The type for which we are getting information.
14357 Type* type_;
14358 // What information we want.
14359 Type_info type_info_;
14360};
14361
14362// The type is chosen to match what the type descriptor struct
14363// expects.
14364
14365Type*
14366Type_info_expression::do_type()
14367{
14368 switch (this->type_info_)
14369 {
14370 case TYPE_INFO_SIZE:
14371 return Type::lookup_integer_type("uintptr");
14372 case TYPE_INFO_ALIGNMENT:
14373 case TYPE_INFO_FIELD_ALIGNMENT:
14374 return Type::lookup_integer_type("uint8");
14375 default:
c3e6f413 14376 go_unreachable();
e440a328 14377 }
14378}
14379
ea664253 14380// Return the backend representation for type information.
e440a328 14381
ea664253 14382Bexpression*
14383Type_info_expression::do_get_backend(Translate_context* context)
e440a328 14384{
927a01eb 14385 Gogo* gogo = context->gogo();
2a305b85 14386 bool ok = true;
3f378015 14387 int64_t val;
927a01eb 14388 switch (this->type_info_)
e440a328 14389 {
927a01eb 14390 case TYPE_INFO_SIZE:
2a305b85 14391 ok = this->type_->backend_type_size(gogo, &val);
927a01eb 14392 break;
14393 case TYPE_INFO_ALIGNMENT:
2a305b85 14394 ok = this->type_->backend_type_align(gogo, &val);
927a01eb 14395 break;
14396 case TYPE_INFO_FIELD_ALIGNMENT:
2a305b85 14397 ok = this->type_->backend_type_field_align(gogo, &val);
927a01eb 14398 break;
14399 default:
14400 go_unreachable();
e440a328 14401 }
2a305b85 14402 if (!ok)
14403 {
14404 go_assert(saw_errors());
14405 return gogo->backend()->error_expression();
14406 }
3f378015 14407 Expression* e = Expression::make_integer_int64(val, this->type(),
14408 this->location());
14409 return e->get_backend(context);
e440a328 14410}
14411
d751bb78 14412// Dump ast representation for a type info expression.
14413
14414void
14415Type_info_expression::do_dump_expression(
14416 Ast_dump_context* ast_dump_context) const
14417{
14418 ast_dump_context->ostream() << "typeinfo(";
14419 ast_dump_context->dump_type(this->type_);
14420 ast_dump_context->ostream() << ",";
14421 ast_dump_context->ostream() <<
14422 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14423 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14424 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14425 : "unknown");
14426 ast_dump_context->ostream() << ")";
14427}
14428
e440a328 14429// Make a type info expression.
14430
14431Expression*
14432Expression::make_type_info(Type* type, Type_info type_info)
14433{
14434 return new Type_info_expression(type, type_info);
14435}
14436
35a54f17 14437// An expression that evaluates to some characteristic of a slice.
14438// This is used when indexing, bound-checking, or nil checking a slice.
14439
14440class Slice_info_expression : public Expression
14441{
14442 public:
14443 Slice_info_expression(Expression* slice, Slice_info slice_info,
14444 Location location)
14445 : Expression(EXPRESSION_SLICE_INFO, location),
14446 slice_(slice), slice_info_(slice_info)
14447 { }
14448
14449 protected:
14450 Type*
14451 do_type();
14452
14453 void
14454 do_determine_type(const Type_context*)
14455 { }
14456
14457 Expression*
14458 do_copy()
14459 {
14460 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14461 this->location());
14462 }
14463
ea664253 14464 Bexpression*
14465 do_get_backend(Translate_context* context);
35a54f17 14466
14467 void
14468 do_dump_expression(Ast_dump_context*) const;
14469
14470 void
14471 do_issue_nil_check()
14472 { this->slice_->issue_nil_check(); }
14473
14474 private:
14475 // The slice for which we are getting information.
14476 Expression* slice_;
14477 // What information we want.
14478 Slice_info slice_info_;
14479};
14480
14481// Return the type of the slice info.
14482
14483Type*
14484Slice_info_expression::do_type()
14485{
14486 switch (this->slice_info_)
14487 {
14488 case SLICE_INFO_VALUE_POINTER:
14489 return Type::make_pointer_type(
14490 this->slice_->type()->array_type()->element_type());
14491 case SLICE_INFO_LENGTH:
14492 case SLICE_INFO_CAPACITY:
14493 return Type::lookup_integer_type("int");
14494 default:
14495 go_unreachable();
14496 }
14497}
14498
ea664253 14499// Return the backend information for slice information.
35a54f17 14500
ea664253 14501Bexpression*
14502Slice_info_expression::do_get_backend(Translate_context* context)
35a54f17 14503{
14504 Gogo* gogo = context->gogo();
ea664253 14505 Bexpression* bslice = this->slice_->get_backend(context);
35a54f17 14506 switch (this->slice_info_)
14507 {
14508 case SLICE_INFO_VALUE_POINTER:
14509 case SLICE_INFO_LENGTH:
14510 case SLICE_INFO_CAPACITY:
ea664253 14511 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14512 this->location());
35a54f17 14513 break;
14514 default:
14515 go_unreachable();
14516 }
35a54f17 14517}
14518
14519// Dump ast representation for a type info expression.
14520
14521void
14522Slice_info_expression::do_dump_expression(
14523 Ast_dump_context* ast_dump_context) const
14524{
14525 ast_dump_context->ostream() << "sliceinfo(";
14526 this->slice_->dump_expression(ast_dump_context);
14527 ast_dump_context->ostream() << ",";
14528 ast_dump_context->ostream() <<
14529 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14530 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14531 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14532 : "unknown");
14533 ast_dump_context->ostream() << ")";
14534}
14535
14536// Make a slice info expression.
14537
14538Expression*
14539Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14540 Location location)
14541{
14542 return new Slice_info_expression(slice, slice_info, location);
14543}
14544
2c809f8f 14545// An expression that represents a slice value: a struct with value pointer,
14546// length, and capacity fields.
14547
14548class Slice_value_expression : public Expression
14549{
14550 public:
14551 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14552 Expression* cap, Location location)
14553 : Expression(EXPRESSION_SLICE_VALUE, location),
14554 type_(type), valptr_(valptr), len_(len), cap_(cap)
14555 { }
14556
14557 protected:
14558 int
14559 do_traverse(Traverse*);
14560
14561 Type*
14562 do_type()
14563 { return this->type_; }
14564
14565 void
14566 do_determine_type(const Type_context*)
14567 { go_unreachable(); }
14568
14569 Expression*
14570 do_copy()
14571 {
14572 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14573 this->len_->copy(), this->cap_->copy(),
14574 this->location());
14575 }
14576
ea664253 14577 Bexpression*
14578 do_get_backend(Translate_context* context);
2c809f8f 14579
14580 void
14581 do_dump_expression(Ast_dump_context*) const;
14582
14583 private:
14584 // The type of the slice value.
14585 Type* type_;
14586 // The pointer to the values in the slice.
14587 Expression* valptr_;
14588 // The length of the slice.
14589 Expression* len_;
14590 // The capacity of the slice.
14591 Expression* cap_;
14592};
14593
14594int
14595Slice_value_expression::do_traverse(Traverse* traverse)
14596{
55e8ba6a 14597 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14598 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2c809f8f 14599 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14600 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14601 return TRAVERSE_EXIT;
14602 return TRAVERSE_CONTINUE;
14603}
14604
ea664253 14605Bexpression*
14606Slice_value_expression::do_get_backend(Translate_context* context)
2c809f8f 14607{
14608 std::vector<Bexpression*> vals(3);
ea664253 14609 vals[0] = this->valptr_->get_backend(context);
14610 vals[1] = this->len_->get_backend(context);
14611 vals[2] = this->cap_->get_backend(context);
2c809f8f 14612
14613 Gogo* gogo = context->gogo();
14614 Btype* btype = this->type_->get_backend(gogo);
ea664253 14615 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 14616}
14617
14618void
14619Slice_value_expression::do_dump_expression(
14620 Ast_dump_context* ast_dump_context) const
14621{
14622 ast_dump_context->ostream() << "slicevalue(";
14623 ast_dump_context->ostream() << "values: ";
14624 this->valptr_->dump_expression(ast_dump_context);
14625 ast_dump_context->ostream() << ", length: ";
14626 this->len_->dump_expression(ast_dump_context);
14627 ast_dump_context->ostream() << ", capacity: ";
14628 this->cap_->dump_expression(ast_dump_context);
14629 ast_dump_context->ostream() << ")";
14630}
14631
14632Expression*
14633Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14634 Expression* cap, Location location)
14635{
14636 go_assert(at->is_slice_type());
14637 return new Slice_value_expression(at, valptr, len, cap, location);
14638}
2387f644 14639
14640// An expression that evaluates to some characteristic of a non-empty interface.
14641// This is used to access the method table or underlying object of an interface.
14642
14643class Interface_info_expression : public Expression
14644{
14645 public:
14646 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 14647 Location location)
2387f644 14648 : Expression(EXPRESSION_INTERFACE_INFO, location),
14649 iface_(iface), iface_info_(iface_info)
14650 { }
14651
14652 protected:
14653 Type*
14654 do_type();
14655
14656 void
14657 do_determine_type(const Type_context*)
14658 { }
14659
14660 Expression*
14661 do_copy()
14662 {
14663 return new Interface_info_expression(this->iface_->copy(),
14664 this->iface_info_, this->location());
14665 }
14666
ea664253 14667 Bexpression*
14668 do_get_backend(Translate_context* context);
2387f644 14669
14670 void
14671 do_dump_expression(Ast_dump_context*) const;
14672
14673 void
14674 do_issue_nil_check()
14675 { this->iface_->issue_nil_check(); }
14676
14677 private:
14678 // The interface for which we are getting information.
14679 Expression* iface_;
14680 // What information we want.
14681 Interface_info iface_info_;
14682};
14683
14684// Return the type of the interface info.
14685
14686Type*
14687Interface_info_expression::do_type()
14688{
14689 switch (this->iface_info_)
14690 {
14691 case INTERFACE_INFO_METHODS:
14692 {
625d3118 14693 typedef Unordered_map(Interface_type*, Type*) Hashtable;
14694 static Hashtable result_types;
14695
14696 Interface_type* itype = this->iface_->type()->interface_type();
14697
14698 Hashtable::const_iterator p = result_types.find(itype);
14699 if (p != result_types.end())
14700 return p->second;
14701
2c809f8f 14702 Type* pdt = Type::make_type_descriptor_ptr_type();
625d3118 14703 if (itype->is_empty())
14704 {
14705 result_types[itype] = pdt;
14706 return pdt;
14707 }
2c809f8f 14708
2387f644 14709 Location loc = this->location();
14710 Struct_field_list* sfl = new Struct_field_list();
2387f644 14711 sfl->push_back(
14712 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14713
2387f644 14714 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14715 p != itype->methods()->end();
14716 ++p)
14717 {
14718 Function_type* ft = p->type()->function_type();
14719 go_assert(ft->receiver() == NULL);
14720
14721 const Typed_identifier_list* params = ft->parameters();
14722 Typed_identifier_list* mparams = new Typed_identifier_list();
14723 if (params != NULL)
14724 mparams->reserve(params->size() + 1);
14725 Type* vt = Type::make_pointer_type(Type::make_void_type());
14726 mparams->push_back(Typed_identifier("", vt, ft->location()));
14727 if (params != NULL)
14728 {
14729 for (Typed_identifier_list::const_iterator pp = params->begin();
14730 pp != params->end();
14731 ++pp)
14732 mparams->push_back(*pp);
14733 }
14734
14735 Typed_identifier_list* mresults = (ft->results() == NULL
14736 ? NULL
14737 : ft->results()->copy());
14738 Backend_function_type* mft =
14739 Type::make_backend_function_type(NULL, mparams, mresults,
14740 ft->location());
14741
14742 std::string fname = Gogo::unpack_hidden_name(p->name());
14743 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14744 }
14745
625d3118 14746 Pointer_type *pt = Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14747 result_types[itype] = pt;
14748 return pt;
2387f644 14749 }
14750 case INTERFACE_INFO_OBJECT:
14751 return Type::make_pointer_type(Type::make_void_type());
14752 default:
14753 go_unreachable();
14754 }
14755}
14756
ea664253 14757// Return the backend representation for interface information.
2387f644 14758
ea664253 14759Bexpression*
14760Interface_info_expression::do_get_backend(Translate_context* context)
2387f644 14761{
14762 Gogo* gogo = context->gogo();
ea664253 14763 Bexpression* biface = this->iface_->get_backend(context);
2387f644 14764 switch (this->iface_info_)
14765 {
14766 case INTERFACE_INFO_METHODS:
14767 case INTERFACE_INFO_OBJECT:
ea664253 14768 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14769 this->location());
2387f644 14770 break;
14771 default:
14772 go_unreachable();
14773 }
2387f644 14774}
14775
14776// Dump ast representation for an interface info expression.
14777
14778void
14779Interface_info_expression::do_dump_expression(
14780 Ast_dump_context* ast_dump_context) const
14781{
2c809f8f 14782 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 14783 ast_dump_context->ostream() << "interfaceinfo(";
14784 this->iface_->dump_expression(ast_dump_context);
14785 ast_dump_context->ostream() << ",";
14786 ast_dump_context->ostream() <<
2c809f8f 14787 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14788 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 14789 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14790 : "unknown");
14791 ast_dump_context->ostream() << ")";
14792}
14793
14794// Make an interface info expression.
14795
14796Expression*
14797Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14798 Location location)
14799{
14800 return new Interface_info_expression(iface, iface_info, location);
14801}
14802
2c809f8f 14803// An expression that represents an interface value. The first field is either
14804// a type descriptor for an empty interface or a pointer to the interface method
14805// table for a non-empty interface. The second field is always the object.
14806
14807class Interface_value_expression : public Expression
14808{
14809 public:
14810 Interface_value_expression(Type* type, Expression* first_field,
14811 Expression* obj, Location location)
14812 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14813 type_(type), first_field_(first_field), obj_(obj)
14814 { }
14815
14816 protected:
14817 int
14818 do_traverse(Traverse*);
14819
14820 Type*
14821 do_type()
14822 { return this->type_; }
14823
14824 void
14825 do_determine_type(const Type_context*)
14826 { go_unreachable(); }
14827
14828 Expression*
14829 do_copy()
14830 {
14831 return new Interface_value_expression(this->type_,
14832 this->first_field_->copy(),
14833 this->obj_->copy(), this->location());
14834 }
14835
ea664253 14836 Bexpression*
14837 do_get_backend(Translate_context* context);
2c809f8f 14838
14839 void
14840 do_dump_expression(Ast_dump_context*) const;
14841
14842 private:
14843 // The type of the interface value.
14844 Type* type_;
14845 // The first field of the interface (either a type descriptor or a pointer
14846 // to the method table.
14847 Expression* first_field_;
14848 // The underlying object of the interface.
14849 Expression* obj_;
14850};
14851
14852int
14853Interface_value_expression::do_traverse(Traverse* traverse)
14854{
14855 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14856 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14857 return TRAVERSE_EXIT;
14858 return TRAVERSE_CONTINUE;
14859}
14860
ea664253 14861Bexpression*
14862Interface_value_expression::do_get_backend(Translate_context* context)
2c809f8f 14863{
14864 std::vector<Bexpression*> vals(2);
ea664253 14865 vals[0] = this->first_field_->get_backend(context);
14866 vals[1] = this->obj_->get_backend(context);
2c809f8f 14867
14868 Gogo* gogo = context->gogo();
14869 Btype* btype = this->type_->get_backend(gogo);
ea664253 14870 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 14871}
14872
14873void
14874Interface_value_expression::do_dump_expression(
14875 Ast_dump_context* ast_dump_context) const
14876{
14877 ast_dump_context->ostream() << "interfacevalue(";
14878 ast_dump_context->ostream() <<
14879 (this->type_->interface_type()->is_empty()
14880 ? "type_descriptor: "
14881 : "methods: ");
14882 this->first_field_->dump_expression(ast_dump_context);
14883 ast_dump_context->ostream() << ", object: ";
14884 this->obj_->dump_expression(ast_dump_context);
14885 ast_dump_context->ostream() << ")";
14886}
14887
14888Expression*
14889Expression::make_interface_value(Type* type, Expression* first_value,
14890 Expression* object, Location location)
14891{
14892 return new Interface_value_expression(type, first_value, object, location);
14893}
14894
14895// An interface method table for a pair of types: an interface type and a type
14896// that implements that interface.
14897
14898class Interface_mtable_expression : public Expression
14899{
14900 public:
14901 Interface_mtable_expression(Interface_type* itype, Type* type,
14902 bool is_pointer, Location location)
14903 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14904 itype_(itype), type_(type), is_pointer_(is_pointer),
14905 method_table_type_(NULL), bvar_(NULL)
14906 { }
14907
14908 protected:
14909 int
14910 do_traverse(Traverse*);
14911
14912 Type*
14913 do_type();
14914
14915 bool
14916 is_immutable() const
14917 { return true; }
14918
14919 void
14920 do_determine_type(const Type_context*)
14921 { go_unreachable(); }
14922
14923 Expression*
14924 do_copy()
14925 {
14926 return new Interface_mtable_expression(this->itype_, this->type_,
14927 this->is_pointer_, this->location());
14928 }
14929
14930 bool
14931 do_is_addressable() const
14932 { return true; }
14933
ea664253 14934 Bexpression*
14935 do_get_backend(Translate_context* context);
2c809f8f 14936
14937 void
14938 do_dump_expression(Ast_dump_context*) const;
14939
14940 private:
14941 // The interface type for which the methods are defined.
14942 Interface_type* itype_;
14943 // The type to construct the interface method table for.
14944 Type* type_;
14945 // Whether this table contains the method set for the receiver type or the
14946 // pointer receiver type.
14947 bool is_pointer_;
14948 // The type of the method table.
14949 Type* method_table_type_;
14950 // The backend variable that refers to the interface method table.
14951 Bvariable* bvar_;
14952};
14953
14954int
14955Interface_mtable_expression::do_traverse(Traverse* traverse)
14956{
14957 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14958 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14959 return TRAVERSE_EXIT;
14960 return TRAVERSE_CONTINUE;
14961}
14962
14963Type*
14964Interface_mtable_expression::do_type()
14965{
14966 if (this->method_table_type_ != NULL)
14967 return this->method_table_type_;
14968
14969 const Typed_identifier_list* interface_methods = this->itype_->methods();
14970 go_assert(!interface_methods->empty());
14971
14972 Struct_field_list* sfl = new Struct_field_list;
14973 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14974 this->location());
14975 sfl->push_back(Struct_field(tid));
14976 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14977 p != interface_methods->end();
14978 ++p)
14979 sfl->push_back(Struct_field(*p));
14980 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14981 return this->method_table_type_;
14982}
14983
ea664253 14984Bexpression*
14985Interface_mtable_expression::do_get_backend(Translate_context* context)
2c809f8f 14986{
14987 Gogo* gogo = context->gogo();
2c809f8f 14988 Location loc = Linemap::predeclared_location();
14989 if (this->bvar_ != NULL)
ea664253 14990 return gogo->backend()->var_expression(this->bvar_, this->location());
2c809f8f 14991
14992 const Typed_identifier_list* interface_methods = this->itype_->methods();
14993 go_assert(!interface_methods->empty());
14994
14995 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14996 + this->itype_->mangled_name(gogo)
14997 + "__"
14998 + this->type_->mangled_name(gogo));
14999
15000 // See whether this interface has any hidden methods.
15001 bool has_hidden_methods = false;
15002 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15003 p != interface_methods->end();
15004 ++p)
15005 {
15006 if (Gogo::is_hidden_name(p->name()))
15007 {
15008 has_hidden_methods = true;
15009 break;
15010 }
15011 }
15012
15013 // We already know that the named type is convertible to the
15014 // interface. If the interface has hidden methods, and the named
15015 // type is defined in a different package, then the interface
15016 // conversion table will be defined by that other package.
15017 if (has_hidden_methods
15018 && this->type_->named_type() != NULL
15019 && this->type_->named_type()->named_object()->package() != NULL)
15020 {
15021 Btype* btype = this->type()->get_backend(gogo);
15022 this->bvar_ =
15023 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
ea664253 15024 return gogo->backend()->var_expression(this->bvar_, this->location());
2c809f8f 15025 }
15026
15027 // The first element is the type descriptor.
15028 Type* td_type;
15029 if (!this->is_pointer_)
15030 td_type = this->type_;
15031 else
15032 td_type = Type::make_pointer_type(this->type_);
15033
15034 // Build an interface method table for a type: a type descriptor followed by a
15035 // list of function pointers, one for each interface method. This is used for
15036 // interfaces.
15037 Expression_list* svals = new Expression_list();
15038 svals->push_back(Expression::make_type_descriptor(td_type, loc));
15039
15040 Named_type* nt = this->type_->named_type();
15041 Struct_type* st = this->type_->struct_type();
15042 go_assert(nt != NULL || st != NULL);
15043
15044 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15045 p != interface_methods->end();
15046 ++p)
15047 {
15048 bool is_ambiguous;
15049 Method* m;
15050 if (nt != NULL)
15051 m = nt->method_function(p->name(), &is_ambiguous);
15052 else
15053 m = st->method_function(p->name(), &is_ambiguous);
15054 go_assert(m != NULL);
15055 Named_object* no = m->named_object();
15056
15057 go_assert(no->is_function() || no->is_function_declaration());
15058 svals->push_back(Expression::make_func_code_reference(no, loc));
15059 }
15060
15061 Btype* btype = this->type()->get_backend(gogo);
15062 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
15063 svals, loc);
ea664253 15064 Bexpression* ctor = mtable->get_backend(context);
2c809f8f 15065
15066 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
15067 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
15068 !is_public, btype, loc);
15069 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15070 !is_public, btype, loc, ctor);
ea664253 15071 return gogo->backend()->var_expression(this->bvar_, loc);
2c809f8f 15072}
15073
15074void
15075Interface_mtable_expression::do_dump_expression(
15076 Ast_dump_context* ast_dump_context) const
15077{
15078 ast_dump_context->ostream() << "__go_"
15079 << (this->is_pointer_ ? "pimt__" : "imt_");
15080 ast_dump_context->dump_type(this->itype_);
15081 ast_dump_context->ostream() << "__";
15082 ast_dump_context->dump_type(this->type_);
15083}
15084
15085Expression*
15086Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15087 bool is_pointer, Location location)
15088{
15089 return new Interface_mtable_expression(itype, type, is_pointer, location);
15090}
15091
e440a328 15092// An expression which evaluates to the offset of a field within a
15093// struct. This, like Type_info_expression, q.v., is only used to
15094// initialize fields of a type descriptor.
15095
15096class Struct_field_offset_expression : public Expression
15097{
15098 public:
15099 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 15100 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15101 Linemap::predeclared_location()),
e440a328 15102 type_(type), field_(field)
15103 { }
15104
15105 protected:
f23d7786 15106 bool
15107 do_is_immutable() const
15108 { return true; }
15109
e440a328 15110 Type*
15111 do_type()
15112 { return Type::lookup_integer_type("uintptr"); }
15113
15114 void
15115 do_determine_type(const Type_context*)
15116 { }
15117
15118 Expression*
15119 do_copy()
15120 { return this; }
15121
ea664253 15122 Bexpression*
15123 do_get_backend(Translate_context* context);
e440a328 15124
d751bb78 15125 void
15126 do_dump_expression(Ast_dump_context*) const;
15127
e440a328 15128 private:
15129 // The type of the struct.
15130 Struct_type* type_;
15131 // The field.
15132 const Struct_field* field_;
15133};
15134
ea664253 15135// Return the backend representation for a struct field offset.
e440a328 15136
ea664253 15137Bexpression*
15138Struct_field_offset_expression::do_get_backend(Translate_context* context)
e440a328 15139{
e440a328 15140 const Struct_field_list* fields = this->type_->fields();
e440a328 15141 Struct_field_list::const_iterator p;
2c8bda43 15142 unsigned i = 0;
e440a328 15143 for (p = fields->begin();
15144 p != fields->end();
2c8bda43 15145 ++p, ++i)
15146 if (&*p == this->field_)
15147 break;
c484d925 15148 go_assert(&*p == this->field_);
e440a328 15149
2c8bda43 15150 Gogo* gogo = context->gogo();
15151 Btype* btype = this->type_->get_backend(gogo);
15152
3f378015 15153 int64_t offset = gogo->backend()->type_field_offset(btype, i);
2c8bda43 15154 Type* uptr_type = Type::lookup_integer_type("uintptr");
e67508fa 15155 Expression* ret =
3f378015 15156 Expression::make_integer_int64(offset, uptr_type,
15157 Linemap::predeclared_location());
ea664253 15158 return ret->get_backend(context);
e440a328 15159}
15160
d751bb78 15161// Dump ast representation for a struct field offset expression.
15162
15163void
15164Struct_field_offset_expression::do_dump_expression(
15165 Ast_dump_context* ast_dump_context) const
15166{
15167 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 15168 ast_dump_context->dump_type(this->type_);
15169 ast_dump_context->ostream() << '.';
15170 ast_dump_context->ostream() <<
15171 Gogo::message_name(this->field_->field_name());
d751bb78 15172 ast_dump_context->ostream() << ")";
15173}
15174
e440a328 15175// Make an expression for a struct field offset.
15176
15177Expression*
15178Expression::make_struct_field_offset(Struct_type* type,
15179 const Struct_field* field)
15180{
15181 return new Struct_field_offset_expression(type, field);
15182}
15183
15184// An expression which evaluates to the address of an unnamed label.
15185
15186class Label_addr_expression : public Expression
15187{
15188 public:
b13c66cd 15189 Label_addr_expression(Label* label, Location location)
e440a328 15190 : Expression(EXPRESSION_LABEL_ADDR, location),
15191 label_(label)
15192 { }
15193
15194 protected:
15195 Type*
15196 do_type()
15197 { return Type::make_pointer_type(Type::make_void_type()); }
15198
15199 void
15200 do_determine_type(const Type_context*)
15201 { }
15202
15203 Expression*
15204 do_copy()
15205 { return new Label_addr_expression(this->label_, this->location()); }
15206
ea664253 15207 Bexpression*
15208 do_get_backend(Translate_context* context)
15209 { return this->label_->get_addr(context, this->location()); }
e440a328 15210
d751bb78 15211 void
15212 do_dump_expression(Ast_dump_context* ast_dump_context) const
15213 { ast_dump_context->ostream() << this->label_->name(); }
15214
e440a328 15215 private:
15216 // The label whose address we are taking.
15217 Label* label_;
15218};
15219
15220// Make an expression for the address of an unnamed label.
15221
15222Expression*
b13c66cd 15223Expression::make_label_addr(Label* label, Location location)
e440a328 15224{
15225 return new Label_addr_expression(label, location);
15226}
15227
da244e59 15228// Class Conditional_expression.
283a177b 15229
2c809f8f 15230// Traversal.
15231
15232int
15233Conditional_expression::do_traverse(Traverse* traverse)
15234{
15235 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15236 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15237 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15238 return TRAVERSE_EXIT;
15239 return TRAVERSE_CONTINUE;
15240}
15241
283a177b 15242// Return the type of the conditional expression.
15243
15244Type*
15245Conditional_expression::do_type()
15246{
15247 Type* result_type = Type::make_void_type();
2c809f8f 15248 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15249 NULL))
283a177b 15250 result_type = this->then_->type();
15251 else if (this->then_->is_nil_expression()
15252 || this->else_->is_nil_expression())
15253 result_type = (!this->then_->is_nil_expression()
15254 ? this->then_->type()
15255 : this->else_->type());
15256 return result_type;
15257}
15258
2c809f8f 15259// Determine type for a conditional expression.
15260
15261void
15262Conditional_expression::do_determine_type(const Type_context* context)
15263{
15264 this->cond_->determine_type_no_context();
15265 this->then_->determine_type(context);
15266 this->else_->determine_type(context);
15267}
15268
283a177b 15269// Get the backend representation of a conditional expression.
15270
ea664253 15271Bexpression*
15272Conditional_expression::do_get_backend(Translate_context* context)
283a177b 15273{
15274 Gogo* gogo = context->gogo();
15275 Btype* result_btype = this->type()->get_backend(gogo);
ea664253 15276 Bexpression* cond = this->cond_->get_backend(context);
15277 Bexpression* then = this->then_->get_backend(context);
15278 Bexpression* belse = this->else_->get_backend(context);
15279 return gogo->backend()->conditional_expression(result_btype, cond, then,
15280 belse, this->location());
283a177b 15281}
15282
15283// Dump ast representation of a conditional expression.
15284
15285void
15286Conditional_expression::do_dump_expression(
15287 Ast_dump_context* ast_dump_context) const
15288{
15289 ast_dump_context->ostream() << "(";
15290 ast_dump_context->dump_expression(this->cond_);
15291 ast_dump_context->ostream() << " ? ";
15292 ast_dump_context->dump_expression(this->then_);
15293 ast_dump_context->ostream() << " : ";
15294 ast_dump_context->dump_expression(this->else_);
15295 ast_dump_context->ostream() << ") ";
15296}
15297
15298// Make a conditional expression.
15299
15300Expression*
15301Expression::make_conditional(Expression* cond, Expression* then,
15302 Expression* else_expr, Location location)
15303{
15304 return new Conditional_expression(cond, then, else_expr, location);
15305}
15306
da244e59 15307// Class Compound_expression.
2c809f8f 15308
15309// Traversal.
15310
15311int
15312Compound_expression::do_traverse(Traverse* traverse)
15313{
15314 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15315 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15316 return TRAVERSE_EXIT;
15317 return TRAVERSE_CONTINUE;
15318}
15319
15320// Return the type of the compound expression.
15321
15322Type*
15323Compound_expression::do_type()
15324{
15325 return this->expr_->type();
15326}
15327
15328// Determine type for a compound expression.
15329
15330void
15331Compound_expression::do_determine_type(const Type_context* context)
15332{
15333 this->init_->determine_type_no_context();
15334 this->expr_->determine_type(context);
15335}
15336
15337// Get the backend representation of a compound expression.
15338
ea664253 15339Bexpression*
15340Compound_expression::do_get_backend(Translate_context* context)
2c809f8f 15341{
15342 Gogo* gogo = context->gogo();
ea664253 15343 Bexpression* binit = this->init_->get_backend(context);
2c809f8f 15344 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
ea664253 15345 Bexpression* bexpr = this->expr_->get_backend(context);
15346 return gogo->backend()->compound_expression(init_stmt, bexpr,
15347 this->location());
2c809f8f 15348}
15349
15350// Dump ast representation of a conditional expression.
15351
15352void
15353Compound_expression::do_dump_expression(
15354 Ast_dump_context* ast_dump_context) const
15355{
15356 ast_dump_context->ostream() << "(";
15357 ast_dump_context->dump_expression(this->init_);
15358 ast_dump_context->ostream() << ",";
15359 ast_dump_context->dump_expression(this->expr_);
15360 ast_dump_context->ostream() << ") ";
15361}
15362
15363// Make a compound expression.
15364
15365Expression*
15366Expression::make_compound(Expression* init, Expression* expr, Location location)
15367{
15368 return new Compound_expression(init, expr, location);
15369}
15370
e440a328 15371// Import an expression. This comes at the end in order to see the
15372// various class definitions.
15373
15374Expression*
15375Expression::import_expression(Import* imp)
15376{
15377 int c = imp->peek_char();
15378 if (imp->match_c_string("- ")
15379 || imp->match_c_string("! ")
15380 || imp->match_c_string("^ "))
15381 return Unary_expression::do_import(imp);
15382 else if (c == '(')
15383 return Binary_expression::do_import(imp);
15384 else if (imp->match_c_string("true")
15385 || imp->match_c_string("false"))
15386 return Boolean_expression::do_import(imp);
15387 else if (c == '"')
15388 return String_expression::do_import(imp);
15389 else if (c == '-' || (c >= '0' && c <= '9'))
15390 {
15391 // This handles integers, floats and complex constants.
15392 return Integer_expression::do_import(imp);
15393 }
15394 else if (imp->match_c_string("nil"))
15395 return Nil_expression::do_import(imp);
15396 else if (imp->match_c_string("convert"))
15397 return Type_conversion_expression::do_import(imp);
15398 else
15399 {
631d5788 15400 go_error_at(imp->location(), "import error: expected expression");
e440a328 15401 return Expression::make_error(imp->location());
15402 }
15403}
15404
15405// Class Expression_list.
15406
15407// Traverse the list.
15408
15409int
15410Expression_list::traverse(Traverse* traverse)
15411{
15412 for (Expression_list::iterator p = this->begin();
15413 p != this->end();
15414 ++p)
15415 {
15416 if (*p != NULL)
15417 {
15418 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15419 return TRAVERSE_EXIT;
15420 }
15421 }
15422 return TRAVERSE_CONTINUE;
15423}
15424
15425// Copy the list.
15426
15427Expression_list*
15428Expression_list::copy()
15429{
15430 Expression_list* ret = new Expression_list();
15431 for (Expression_list::iterator p = this->begin();
15432 p != this->end();
15433 ++p)
15434 {
15435 if (*p == NULL)
15436 ret->push_back(NULL);
15437 else
15438 ret->push_back((*p)->copy());
15439 }
15440 return ret;
15441}
15442
15443// Return whether an expression list has an error expression.
15444
15445bool
15446Expression_list::contains_error() const
15447{
15448 for (Expression_list::const_iterator p = this->begin();
15449 p != this->end();
15450 ++p)
15451 if (*p != NULL && (*p)->is_error_expression())
15452 return true;
15453 return false;
15454}
0c77715b 15455
15456// Class Numeric_constant.
15457
15458// Destructor.
15459
15460Numeric_constant::~Numeric_constant()
15461{
15462 this->clear();
15463}
15464
15465// Copy constructor.
15466
15467Numeric_constant::Numeric_constant(const Numeric_constant& a)
15468 : classification_(a.classification_), type_(a.type_)
15469{
15470 switch (a.classification_)
15471 {
15472 case NC_INVALID:
15473 break;
15474 case NC_INT:
15475 case NC_RUNE:
15476 mpz_init_set(this->u_.int_val, a.u_.int_val);
15477 break;
15478 case NC_FLOAT:
15479 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15480 break;
15481 case NC_COMPLEX:
fcbea5e4 15482 mpc_init2(this->u_.complex_val, mpc_precision);
15483 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15484 break;
15485 default:
15486 go_unreachable();
15487 }
15488}
15489
15490// Assignment operator.
15491
15492Numeric_constant&
15493Numeric_constant::operator=(const Numeric_constant& a)
15494{
15495 this->clear();
15496 this->classification_ = a.classification_;
15497 this->type_ = a.type_;
15498 switch (a.classification_)
15499 {
15500 case NC_INVALID:
15501 break;
15502 case NC_INT:
15503 case NC_RUNE:
15504 mpz_init_set(this->u_.int_val, a.u_.int_val);
15505 break;
15506 case NC_FLOAT:
15507 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15508 break;
15509 case NC_COMPLEX:
fcbea5e4 15510 mpc_init2(this->u_.complex_val, mpc_precision);
15511 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15512 break;
15513 default:
15514 go_unreachable();
15515 }
15516 return *this;
15517}
15518
15519// Clear the contents.
15520
15521void
15522Numeric_constant::clear()
15523{
15524 switch (this->classification_)
15525 {
15526 case NC_INVALID:
15527 break;
15528 case NC_INT:
15529 case NC_RUNE:
15530 mpz_clear(this->u_.int_val);
15531 break;
15532 case NC_FLOAT:
15533 mpfr_clear(this->u_.float_val);
15534 break;
15535 case NC_COMPLEX:
fcbea5e4 15536 mpc_clear(this->u_.complex_val);
0c77715b 15537 break;
15538 default:
15539 go_unreachable();
15540 }
15541 this->classification_ = NC_INVALID;
15542}
15543
15544// Set to an unsigned long value.
15545
15546void
15547Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15548{
15549 this->clear();
15550 this->classification_ = NC_INT;
15551 this->type_ = type;
15552 mpz_init_set_ui(this->u_.int_val, val);
15553}
15554
15555// Set to an integer value.
15556
15557void
15558Numeric_constant::set_int(Type* type, const mpz_t val)
15559{
15560 this->clear();
15561 this->classification_ = NC_INT;
15562 this->type_ = type;
15563 mpz_init_set(this->u_.int_val, val);
15564}
15565
15566// Set to a rune value.
15567
15568void
15569Numeric_constant::set_rune(Type* type, const mpz_t val)
15570{
15571 this->clear();
15572 this->classification_ = NC_RUNE;
15573 this->type_ = type;
15574 mpz_init_set(this->u_.int_val, val);
15575}
15576
15577// Set to a floating point value.
15578
15579void
15580Numeric_constant::set_float(Type* type, const mpfr_t val)
15581{
15582 this->clear();
15583 this->classification_ = NC_FLOAT;
15584 this->type_ = type;
833b523c 15585 // Numeric constants do not have negative zero values, so remove
15586 // them here. They also don't have infinity or NaN values, but we
15587 // should never see them here.
15588 if (mpfr_zero_p(val))
15589 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15590 else
15591 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15592}
15593
15594// Set to a complex value.
15595
15596void
fcbea5e4 15597Numeric_constant::set_complex(Type* type, const mpc_t val)
0c77715b 15598{
15599 this->clear();
15600 this->classification_ = NC_COMPLEX;
15601 this->type_ = type;
fcbea5e4 15602 mpc_init2(this->u_.complex_val, mpc_precision);
15603 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
0c77715b 15604}
15605
15606// Get an int value.
15607
15608void
15609Numeric_constant::get_int(mpz_t* val) const
15610{
15611 go_assert(this->is_int());
15612 mpz_init_set(*val, this->u_.int_val);
15613}
15614
15615// Get a rune value.
15616
15617void
15618Numeric_constant::get_rune(mpz_t* val) const
15619{
15620 go_assert(this->is_rune());
15621 mpz_init_set(*val, this->u_.int_val);
15622}
15623
15624// Get a floating point value.
15625
15626void
15627Numeric_constant::get_float(mpfr_t* val) const
15628{
15629 go_assert(this->is_float());
15630 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15631}
15632
15633// Get a complex value.
15634
15635void
fcbea5e4 15636Numeric_constant::get_complex(mpc_t* val) const
0c77715b 15637{
15638 go_assert(this->is_complex());
fcbea5e4 15639 mpc_init2(*val, mpc_precision);
15640 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15641}
15642
15643// Express value as unsigned long if possible.
15644
15645Numeric_constant::To_unsigned_long
15646Numeric_constant::to_unsigned_long(unsigned long* val) const
15647{
15648 switch (this->classification_)
15649 {
15650 case NC_INT:
15651 case NC_RUNE:
15652 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15653 case NC_FLOAT:
15654 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15655 case NC_COMPLEX:
fcbea5e4 15656 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15657 return NC_UL_NOTINT;
fcbea5e4 15658 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15659 val);
0c77715b 15660 default:
15661 go_unreachable();
15662 }
15663}
15664
15665// Express integer value as unsigned long if possible.
15666
15667Numeric_constant::To_unsigned_long
15668Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15669 unsigned long *val) const
15670{
15671 if (mpz_sgn(ival) < 0)
15672 return NC_UL_NEGATIVE;
15673 unsigned long ui = mpz_get_ui(ival);
15674 if (mpz_cmp_ui(ival, ui) != 0)
15675 return NC_UL_BIG;
15676 *val = ui;
15677 return NC_UL_VALID;
15678}
15679
15680// Express floating point value as unsigned long if possible.
15681
15682Numeric_constant::To_unsigned_long
15683Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15684 unsigned long *val) const
15685{
15686 if (!mpfr_integer_p(fval))
15687 return NC_UL_NOTINT;
15688 mpz_t ival;
15689 mpz_init(ival);
15690 mpfr_get_z(ival, fval, GMP_RNDN);
15691 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15692 mpz_clear(ival);
15693 return ret;
15694}
15695
15696// Convert value to integer if possible.
15697
15698bool
15699Numeric_constant::to_int(mpz_t* val) const
15700{
15701 switch (this->classification_)
15702 {
15703 case NC_INT:
15704 case NC_RUNE:
15705 mpz_init_set(*val, this->u_.int_val);
15706 return true;
15707 case NC_FLOAT:
15708 if (!mpfr_integer_p(this->u_.float_val))
15709 return false;
15710 mpz_init(*val);
15711 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15712 return true;
15713 case NC_COMPLEX:
fcbea5e4 15714 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15715 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
0c77715b 15716 return false;
15717 mpz_init(*val);
fcbea5e4 15718 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15719 return true;
15720 default:
15721 go_unreachable();
15722 }
15723}
15724
15725// Convert value to floating point if possible.
15726
15727bool
15728Numeric_constant::to_float(mpfr_t* val) const
15729{
15730 switch (this->classification_)
15731 {
15732 case NC_INT:
15733 case NC_RUNE:
15734 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15735 return true;
15736 case NC_FLOAT:
15737 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15738 return true;
15739 case NC_COMPLEX:
fcbea5e4 15740 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15741 return false;
fcbea5e4 15742 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15743 return true;
15744 default:
15745 go_unreachable();
15746 }
15747}
15748
15749// Convert value to complex.
15750
15751bool
fcbea5e4 15752Numeric_constant::to_complex(mpc_t* val) const
0c77715b 15753{
fcbea5e4 15754 mpc_init2(*val, mpc_precision);
0c77715b 15755 switch (this->classification_)
15756 {
15757 case NC_INT:
15758 case NC_RUNE:
fcbea5e4 15759 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
0c77715b 15760 return true;
15761 case NC_FLOAT:
fcbea5e4 15762 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
0c77715b 15763 return true;
15764 case NC_COMPLEX:
fcbea5e4 15765 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15766 return true;
15767 default:
15768 go_unreachable();
15769 }
15770}
15771
15772// Get the type.
15773
15774Type*
15775Numeric_constant::type() const
15776{
15777 if (this->type_ != NULL)
15778 return this->type_;
15779 switch (this->classification_)
15780 {
15781 case NC_INT:
15782 return Type::make_abstract_integer_type();
15783 case NC_RUNE:
15784 return Type::make_abstract_character_type();
15785 case NC_FLOAT:
15786 return Type::make_abstract_float_type();
15787 case NC_COMPLEX:
15788 return Type::make_abstract_complex_type();
15789 default:
15790 go_unreachable();
15791 }
15792}
15793
15794// If the constant can be expressed in TYPE, then set the type of the
15795// constant to TYPE and return true. Otherwise return false, and, if
15796// ISSUE_ERROR is true, report an appropriate error message.
15797
15798bool
15799Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15800{
15801 bool ret;
f11c2155 15802 if (type == NULL || type->is_error())
0c77715b 15803 ret = true;
15804 else if (type->integer_type() != NULL)
15805 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15806 else if (type->float_type() != NULL)
15807 ret = this->check_float_type(type->float_type(), issue_error, loc);
15808 else if (type->complex_type() != NULL)
15809 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15810 else
5706ab68 15811 {
15812 ret = false;
15813 if (issue_error)
15814 go_assert(saw_errors());
15815 }
0c77715b 15816 if (ret)
15817 this->type_ = type;
15818 return ret;
15819}
15820
15821// Check whether the constant can be expressed in an integer type.
15822
15823bool
15824Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
71a45216 15825 Location location)
0c77715b 15826{
15827 mpz_t val;
15828 switch (this->classification_)
15829 {
15830 case NC_INT:
15831 case NC_RUNE:
15832 mpz_init_set(val, this->u_.int_val);
15833 break;
15834
15835 case NC_FLOAT:
15836 if (!mpfr_integer_p(this->u_.float_val))
15837 {
15838 if (issue_error)
71a45216 15839 {
631d5788 15840 go_error_at(location,
15841 "floating point constant truncated to integer");
71a45216 15842 this->set_invalid();
15843 }
0c77715b 15844 return false;
15845 }
15846 mpz_init(val);
15847 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15848 break;
15849
15850 case NC_COMPLEX:
fcbea5e4 15851 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15852 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15853 {
15854 if (issue_error)
71a45216 15855 {
631d5788 15856 go_error_at(location, "complex constant truncated to integer");
71a45216 15857 this->set_invalid();
15858 }
0c77715b 15859 return false;
15860 }
15861 mpz_init(val);
fcbea5e4 15862 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15863 break;
15864
15865 default:
15866 go_unreachable();
15867 }
15868
15869 bool ret;
15870 if (type->is_abstract())
15871 ret = true;
15872 else
15873 {
15874 int bits = mpz_sizeinbase(val, 2);
15875 if (type->is_unsigned())
15876 {
15877 // For an unsigned type we can only accept a nonnegative
15878 // number, and we must be able to represents at least BITS.
15879 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15880 }
15881 else
15882 {
15883 // For a signed type we need an extra bit to indicate the
15884 // sign. We have to handle the most negative integer
15885 // specially.
15886 ret = (bits + 1 <= type->bits()
15887 || (bits <= type->bits()
15888 && mpz_sgn(val) < 0
15889 && (mpz_scan1(val, 0)
15890 == static_cast<unsigned long>(type->bits() - 1))
15891 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15892 }
15893 }
15894
15895 if (!ret && issue_error)
71a45216 15896 {
631d5788 15897 go_error_at(location, "integer constant overflow");
71a45216 15898 this->set_invalid();
15899 }
0c77715b 15900
15901 return ret;
15902}
15903
15904// Check whether the constant can be expressed in a floating point
15905// type.
15906
15907bool
15908Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15909 Location location)
0c77715b 15910{
15911 mpfr_t val;
15912 switch (this->classification_)
15913 {
15914 case NC_INT:
15915 case NC_RUNE:
15916 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15917 break;
15918
15919 case NC_FLOAT:
15920 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15921 break;
15922
15923 case NC_COMPLEX:
fcbea5e4 15924 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15925 {
15926 if (issue_error)
71a45216 15927 {
15928 this->set_invalid();
631d5788 15929 go_error_at(location, "complex constant truncated to float");
71a45216 15930 }
0c77715b 15931 return false;
15932 }
fcbea5e4 15933 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15934 break;
15935
15936 default:
15937 go_unreachable();
15938 }
15939
15940 bool ret;
15941 if (type->is_abstract())
15942 ret = true;
15943 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15944 {
15945 // A NaN or Infinity always fits in the range of the type.
15946 ret = true;
15947 }
15948 else
15949 {
15950 mp_exp_t exp = mpfr_get_exp(val);
15951 mp_exp_t max_exp;
15952 switch (type->bits())
15953 {
15954 case 32:
15955 max_exp = 128;
15956 break;
15957 case 64:
15958 max_exp = 1024;
15959 break;
15960 default:
15961 go_unreachable();
15962 }
15963
15964 ret = exp <= max_exp;
d0bcce51 15965
15966 if (ret)
15967 {
15968 // Round the constant to the desired type.
15969 mpfr_t t;
15970 mpfr_init(t);
15971 switch (type->bits())
15972 {
15973 case 32:
15974 mpfr_set_prec(t, 24);
15975 break;
15976 case 64:
15977 mpfr_set_prec(t, 53);
15978 break;
15979 default:
15980 go_unreachable();
15981 }
15982 mpfr_set(t, val, GMP_RNDN);
15983 mpfr_set(val, t, GMP_RNDN);
15984 mpfr_clear(t);
15985
15986 this->set_float(type, val);
15987 }
0c77715b 15988 }
15989
15990 mpfr_clear(val);
15991
15992 if (!ret && issue_error)
71a45216 15993 {
631d5788 15994 go_error_at(location, "floating point constant overflow");
71a45216 15995 this->set_invalid();
15996 }
0c77715b 15997
15998 return ret;
15999}
16000
16001// Check whether the constant can be expressed in a complex type.
16002
16003bool
16004Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 16005 Location location)
0c77715b 16006{
16007 if (type->is_abstract())
16008 return true;
16009
16010 mp_exp_t max_exp;
16011 switch (type->bits())
16012 {
16013 case 64:
16014 max_exp = 128;
16015 break;
16016 case 128:
16017 max_exp = 1024;
16018 break;
16019 default:
16020 go_unreachable();
16021 }
16022
fcbea5e4 16023 mpc_t val;
16024 mpc_init2(val, mpc_precision);
0c77715b 16025 switch (this->classification_)
16026 {
16027 case NC_INT:
16028 case NC_RUNE:
fcbea5e4 16029 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
0c77715b 16030 break;
16031
16032 case NC_FLOAT:
fcbea5e4 16033 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
0c77715b 16034 break;
16035
16036 case NC_COMPLEX:
fcbea5e4 16037 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
0c77715b 16038 break;
16039
16040 default:
16041 go_unreachable();
16042 }
16043
d0bcce51 16044 bool ret = true;
fcbea5e4 16045 if (!mpfr_nan_p(mpc_realref(val))
16046 && !mpfr_inf_p(mpc_realref(val))
16047 && !mpfr_zero_p(mpc_realref(val))
16048 && mpfr_get_exp(mpc_realref(val)) > max_exp)
d0bcce51 16049 {
16050 if (issue_error)
71a45216 16051 {
631d5788 16052 go_error_at(location, "complex real part overflow");
71a45216 16053 this->set_invalid();
16054 }
d0bcce51 16055 ret = false;
16056 }
0c77715b 16057
fcbea5e4 16058 if (!mpfr_nan_p(mpc_imagref(val))
16059 && !mpfr_inf_p(mpc_imagref(val))
16060 && !mpfr_zero_p(mpc_imagref(val))
16061 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
d0bcce51 16062 {
16063 if (issue_error)
71a45216 16064 {
631d5788 16065 go_error_at(location, "complex imaginary part overflow");
71a45216 16066 this->set_invalid();
16067 }
d0bcce51 16068 ret = false;
16069 }
0c77715b 16070
d0bcce51 16071 if (ret)
16072 {
16073 // Round the constant to the desired type.
fcbea5e4 16074 mpc_t t;
d0bcce51 16075 switch (type->bits())
16076 {
16077 case 64:
fcbea5e4 16078 mpc_init2(t, 24);
d0bcce51 16079 break;
16080 case 128:
fcbea5e4 16081 mpc_init2(t, 53);
d0bcce51 16082 break;
16083 default:
16084 go_unreachable();
16085 }
fcbea5e4 16086 mpc_set(t, val, MPC_RNDNN);
16087 mpc_set(val, t, MPC_RNDNN);
16088 mpc_clear(t);
d0bcce51 16089
fcbea5e4 16090 this->set_complex(type, val);
d0bcce51 16091 }
16092
fcbea5e4 16093 mpc_clear(val);
0c77715b 16094
16095 return ret;
16096}
16097
16098// Return an Expression for this value.
16099
16100Expression*
16101Numeric_constant::expression(Location loc) const
16102{
16103 switch (this->classification_)
16104 {
16105 case NC_INT:
e67508fa 16106 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
0c77715b 16107 case NC_RUNE:
16108 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16109 case NC_FLOAT:
16110 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16111 case NC_COMPLEX:
fcbea5e4 16112 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
71a45216 16113 case NC_INVALID:
16114 go_assert(saw_errors());
16115 return Expression::make_error(loc);
0c77715b 16116 default:
16117 go_unreachable();
16118 }
16119}