]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/go/gofrontend/expressions.cc
Fix for PR ipa/63569.
[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"
13#include "types.h"
14#include "export.h"
15#include "import.h"
16#include "statements.h"
17#include "lex.h"
a9182619 18#include "runtime.h"
6e193e6f 19#include "backend.h"
e440a328 20#include "expressions.h"
d751bb78 21#include "ast-dump.h"
e440a328 22
23// Class Expression.
24
25Expression::Expression(Expression_classification classification,
b13c66cd 26 Location location)
e440a328 27 : classification_(classification), location_(location)
28{
29}
30
31Expression::~Expression()
32{
33}
34
e440a328 35// Traverse the expressions.
36
37int
38Expression::traverse(Expression** pexpr, Traverse* traverse)
39{
40 Expression* expr = *pexpr;
41 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
42 {
43 int t = traverse->expression(pexpr);
44 if (t == TRAVERSE_EXIT)
45 return TRAVERSE_EXIT;
46 else if (t == TRAVERSE_SKIP_COMPONENTS)
47 return TRAVERSE_CONTINUE;
48 }
49 return expr->do_traverse(traverse);
50}
51
52// Traverse subexpressions of this expression.
53
54int
55Expression::traverse_subexpressions(Traverse* traverse)
56{
57 return this->do_traverse(traverse);
58}
59
60// Default implementation for do_traverse for child classes.
61
62int
63Expression::do_traverse(Traverse*)
64{
65 return TRAVERSE_CONTINUE;
66}
67
68// This virtual function is called by the parser if the value of this
a7549a6a 69// expression is being discarded. By default, we give an error.
70// Expressions with side effects override.
e440a328 71
4f2138d7 72bool
e440a328 73Expression::do_discarding_value()
74{
a7549a6a 75 this->unused_value_error();
4f2138d7 76 return false;
e440a328 77}
78
79// This virtual function is called to export expressions. This will
80// only be used by expressions which may be constant.
81
82void
83Expression::do_export(Export*) const
84{
c3e6f413 85 go_unreachable();
e440a328 86}
87
a7549a6a 88// Give an error saying that the value of the expression is not used.
e440a328 89
90void
a7549a6a 91Expression::unused_value_error()
e440a328 92{
4f2138d7 93 this->report_error(_("value computed is not used"));
e440a328 94}
95
96// Note that this expression is an error. This is called by children
97// when they discover an error.
98
99void
100Expression::set_is_error()
101{
102 this->classification_ = EXPRESSION_ERROR;
103}
104
105// For children to call to report an error conveniently.
106
107void
108Expression::report_error(const char* msg)
109{
110 error_at(this->location_, "%s", msg);
111 this->set_is_error();
112}
113
114// Set types of variables and constants. This is implemented by the
115// child class.
116
117void
118Expression::determine_type(const Type_context* context)
119{
120 this->do_determine_type(context);
121}
122
123// Set types when there is no context.
124
125void
126Expression::determine_type_no_context()
127{
128 Type_context context;
129 this->do_determine_type(&context);
130}
131
2c809f8f 132// Return an expression handling any conversions which must be done during
e440a328 133// assignment.
134
2c809f8f 135Expression*
136Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
137 Expression* rhs, Location location)
e440a328 138{
2c809f8f 139 Type* rhs_type = rhs->type();
140 if (lhs_type->is_error()
141 || rhs_type->is_error()
142 || rhs->is_error_expression())
143 return Expression::make_error(location);
e440a328 144
54211955 145 if (lhs_type->forwarded() != rhs_type->forwarded()
146 && lhs_type->interface_type() != NULL)
e440a328 147 {
148 if (rhs_type->interface_type() == NULL)
2c809f8f 149 return Expression::convert_type_to_interface(lhs_type, rhs, location);
e440a328 150 else
2c809f8f 151 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
152 location);
e440a328 153 }
54211955 154 else if (lhs_type->forwarded() != rhs_type->forwarded()
155 && rhs_type->interface_type() != NULL)
2c809f8f 156 return Expression::convert_interface_to_type(lhs_type, rhs, location);
411eb89e 157 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
e440a328 158 {
2c809f8f 159 // Assigning nil to a slice.
2c809f8f 160 Expression* nil = Expression::make_nil(location);
e67508fa 161 Expression* zero = Expression::make_integer_ul(0, NULL, location);
2c809f8f 162 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
e440a328 163 }
164 else if (rhs_type->is_nil_type())
2c809f8f 165 return Expression::make_nil(location);
166 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
e440a328 167 {
168 // No conversion is needed.
2c809f8f 169 return rhs;
170 }
171 else if (lhs_type->points_to() != NULL)
172 return Expression::make_unsafe_cast(lhs_type, rhs, location);
173 else if (lhs_type->is_numeric_type())
174 return Expression::make_cast(lhs_type, rhs, location);
175 else if ((lhs_type->struct_type() != NULL
176 && rhs_type->struct_type() != NULL)
177 || (lhs_type->array_type() != NULL
178 && rhs_type->array_type() != NULL))
e440a328 179 {
bb92f513 180 // Avoid confusion from zero sized variables which may be
181 // represented as non-zero-sized.
2c809f8f 182 // TODO(cmang): This check is for a GCC-specific issue, and should be
183 // removed from the frontend. FIXME.
184 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
185 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
186 if (rhs_size == 0 || lhs_size == 0)
187 return rhs;
bb92f513 188
e440a328 189 // This conversion must be permitted by Go, or we wouldn't have
190 // gotten here.
2c809f8f 191 return Expression::make_unsafe_cast(lhs_type, rhs, location);
e440a328 192 }
193 else
2c809f8f 194 return rhs;
e440a328 195}
196
2c809f8f 197// Return an expression for a conversion from a non-interface type to an
e440a328 198// interface type.
199
2c809f8f 200Expression*
201Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
202 Location location)
e440a328 203{
e440a328 204 Interface_type* lhs_interface_type = lhs_type->interface_type();
205 bool lhs_is_empty = lhs_interface_type->is_empty();
206
207 // Since RHS_TYPE is a static type, we can create the interface
208 // method table at compile time.
209
210 // When setting an interface to nil, we just set both fields to
211 // NULL.
2c809f8f 212 Type* rhs_type = rhs->type();
e440a328 213 if (rhs_type->is_nil_type())
63697958 214 {
2c809f8f 215 Expression* nil = Expression::make_nil(location);
216 return Expression::make_interface_value(lhs_type, nil, nil, location);
63697958 217 }
e440a328 218
219 // This should have been checked already.
c484d925 220 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
e440a328 221
e440a328 222 // An interface is a tuple. If LHS_TYPE is an empty interface type,
223 // then the first field is the type descriptor for RHS_TYPE.
224 // Otherwise it is the interface method table for RHS_TYPE.
2c809f8f 225 Expression* first_field;
e440a328 226 if (lhs_is_empty)
2c809f8f 227 first_field = Expression::make_type_descriptor(rhs_type, location);
e440a328 228 else
229 {
230 // Build the interface method table for this interface and this
231 // object type: a list of function pointers for each interface
232 // method.
233 Named_type* rhs_named_type = rhs_type->named_type();
c0cab2ec 234 Struct_type* rhs_struct_type = rhs_type->struct_type();
e440a328 235 bool is_pointer = false;
c0cab2ec 236 if (rhs_named_type == NULL && rhs_struct_type == NULL)
e440a328 237 {
238 rhs_named_type = rhs_type->deref()->named_type();
c0cab2ec 239 rhs_struct_type = rhs_type->deref()->struct_type();
e440a328 240 is_pointer = true;
241 }
c0cab2ec 242 if (rhs_named_type != NULL)
2c809f8f 243 first_field =
244 rhs_named_type->interface_method_table(lhs_interface_type,
245 is_pointer);
c0cab2ec 246 else if (rhs_struct_type != NULL)
2c809f8f 247 first_field =
248 rhs_struct_type->interface_method_table(lhs_interface_type,
249 is_pointer);
c0cab2ec 250 else
2c809f8f 251 first_field = Expression::make_nil(location);
e440a328 252 }
e440a328 253
2c809f8f 254 Expression* obj;
e440a328 255 if (rhs_type->points_to() != NULL)
256 {
2c809f8f 257 // We are assigning a pointer to the interface; the interface
e440a328 258 // holds the pointer itself.
2c809f8f 259 obj = rhs;
260 }
261 else
262 {
263 // We are assigning a non-pointer value to the interface; the
264 // interface gets a copy of the value in the heap.
265 obj = Expression::make_heap_expression(rhs, location);
e440a328 266 }
267
2c809f8f 268 return Expression::make_interface_value(lhs_type, first_field, obj, location);
269}
e440a328 270
2c809f8f 271// Return an expression for the type descriptor of RHS.
e440a328 272
2c809f8f 273Expression*
274Expression::get_interface_type_descriptor(Expression* rhs)
275{
276 go_assert(rhs->type()->interface_type() != NULL);
277 Location location = rhs->location();
e440a328 278
2c809f8f 279 // The type descriptor is the first field of an empty interface.
280 if (rhs->type()->interface_type()->is_empty())
281 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
282 location);
283
284 Expression* mtable =
285 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
e440a328 286
2c809f8f 287 Expression* descriptor =
288 Expression::make_unary(OPERATOR_MULT, mtable, location);
289 descriptor = Expression::make_field_reference(descriptor, 0, location);
290 Expression* nil = Expression::make_nil(location);
e440a328 291
2c809f8f 292 Expression* eq =
293 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
294 return Expression::make_conditional(eq, nil, descriptor, location);
e440a328 295}
296
2c809f8f 297// Return an expression for the conversion of an interface type to an
e440a328 298// interface type.
299
2c809f8f 300Expression*
301Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
302 bool for_type_guard,
303 Location location)
e440a328 304{
8ba8cc87 305 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
306 return rhs;
307
e440a328 308 Interface_type* lhs_interface_type = lhs_type->interface_type();
309 bool lhs_is_empty = lhs_interface_type->is_empty();
310
e440a328 311 // In the general case this requires runtime examination of the type
312 // method table to match it up with the interface methods.
313
314 // FIXME: If all of the methods in the right hand side interface
315 // also appear in the left hand side interface, then we don't need
316 // to do a runtime check, although we still need to build a new
317 // method table.
318
8ba8cc87 319 // We are going to evaluate RHS multiple times.
320 go_assert(rhs->is_variable());
321
e440a328 322 // Get the type descriptor for the right hand side. This will be
323 // NULL for a nil interface.
2c809f8f 324 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
325 Expression* lhs_type_expr =
326 Expression::make_type_descriptor(lhs_type, location);
e440a328 327
2c809f8f 328 Expression* first_field;
e440a328 329 if (for_type_guard)
330 {
331 // A type assertion fails when converting a nil interface.
2c809f8f 332 first_field =
333 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
334 lhs_type_expr, rhs_type_expr);
e440a328 335 }
336 else if (lhs_is_empty)
337 {
2c809f8f 338 // A conversion to an empty interface always succeeds, and the
e440a328 339 // first field is just the type descriptor of the object.
2c809f8f 340 first_field = rhs_type_expr;
e440a328 341 }
342 else
343 {
344 // A conversion to a non-empty interface may fail, but unlike a
345 // type assertion converting nil will always succeed.
2c809f8f 346 first_field =
347 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
348 lhs_type_expr, rhs_type_expr);
e440a328 349 }
350
351 // The second field is simply the object pointer.
2c809f8f 352 Expression* obj =
353 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
354 return Expression::make_interface_value(lhs_type, first_field, obj, location);
e440a328 355}
356
2c809f8f 357// Return an expression for the conversion of an interface type to a
e440a328 358// non-interface type.
359
2c809f8f 360Expression*
361Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
362 Location location)
e440a328 363{
8ba8cc87 364 // We are going to evaluate RHS multiple times.
365 go_assert(rhs->is_variable());
366
e440a328 367 // Call a function to check that the type is valid. The function
368 // will panic with an appropriate runtime type error if the type is
369 // not valid.
2c809f8f 370 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
371 location);
372 Expression* rhs_descriptor =
373 Expression::get_interface_type_descriptor(rhs);
374
375 Type* rhs_type = rhs->type();
376 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
377 location);
378
379 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
380 location, 3, lhs_type_expr,
381 rhs_descriptor, rhs_inter_expr);
e440a328 382
383 // If the call succeeds, pull out the value.
2c809f8f 384 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
385 location);
e440a328 386
387 // If the value is a pointer, then it is the value we want.
388 // Otherwise it points to the value.
389 if (lhs_type->points_to() == NULL)
390 {
2c809f8f 391 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
392 location);
393 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
e440a328 394 }
2c809f8f 395 return Expression::make_compound(check_iface, obj, location);
e440a328 396}
397
ea664253 398// Convert an expression to its backend representation. This is implemented by
399// the child class. Not that it is not in general safe to call this multiple
e440a328 400// times for a single expression, but that we don't catch such errors.
401
ea664253 402Bexpression*
403Expression::get_backend(Translate_context* context)
e440a328 404{
405 // The child may have marked this expression as having an error.
406 if (this->classification_ == EXPRESSION_ERROR)
ea664253 407 return context->backend()->error_expression();
e440a328 408
ea664253 409 return this->do_get_backend(context);
e440a328 410}
411
48c2a53a 412// Return a backend expression for VAL.
413Bexpression*
414Expression::backend_numeric_constant_expression(Translate_context* context,
415 Numeric_constant* val)
e440a328 416{
48c2a53a 417 Gogo* gogo = context->gogo();
418 Type* type = val->type();
419 if (type == NULL)
420 return gogo->backend()->error_expression();
e440a328 421
48c2a53a 422 Btype* btype = type->get_backend(gogo);
423 Bexpression* ret;
424 if (type->integer_type() != NULL)
e440a328 425 {
426 mpz_t ival;
48c2a53a 427 if (!val->to_int(&ival))
428 {
429 go_assert(saw_errors());
430 return gogo->backend()->error_expression();
431 }
432 ret = gogo->backend()->integer_constant_expression(btype, ival);
e440a328 433 mpz_clear(ival);
e440a328 434 }
48c2a53a 435 else if (type->float_type() != NULL)
e440a328 436 {
48c2a53a 437 mpfr_t fval;
438 if (!val->to_float(&fval))
439 {
440 go_assert(saw_errors());
441 return gogo->backend()->error_expression();
442 }
443 ret = gogo->backend()->float_constant_expression(btype, fval);
444 mpfr_clear(fval);
e440a328 445 }
48c2a53a 446 else if (type->complex_type() != NULL)
e440a328 447 {
fcbea5e4 448 mpc_t cval;
449 if (!val->to_complex(&cval))
48c2a53a 450 {
451 go_assert(saw_errors());
452 return gogo->backend()->error_expression();
453 }
fcbea5e4 454 ret = gogo->backend()->complex_constant_expression(btype, cval);
455 mpc_clear(cval);
e440a328 456 }
457 else
c3e6f413 458 go_unreachable();
e440a328 459
48c2a53a 460 return ret;
e440a328 461}
462
2c809f8f 463// Return an expression which evaluates to true if VAL, of arbitrary integer
464// type, is negative or is more than the maximum value of the Go type "int".
e440a328 465
2c809f8f 466Expression*
467Expression::check_bounds(Expression* val, Location loc)
e440a328 468{
2c809f8f 469 Type* val_type = val->type();
470 Type* bound_type = Type::lookup_integer_type("int");
471
472 int val_type_size;
473 bool val_is_unsigned = false;
474 if (val_type->integer_type() != NULL)
475 {
476 val_type_size = val_type->integer_type()->bits();
477 val_is_unsigned = val_type->integer_type()->is_unsigned();
478 }
479 else
480 {
481 if (!val_type->is_numeric_type()
482 || !Type::are_convertible(bound_type, val_type, NULL))
483 {
484 go_assert(saw_errors());
485 return Expression::make_boolean(true, loc);
486 }
e440a328 487
2c809f8f 488 if (val_type->complex_type() != NULL)
489 val_type_size = val_type->complex_type()->bits();
490 else
491 val_type_size = val_type->float_type()->bits();
492 }
493
494 Expression* negative_index = Expression::make_boolean(false, loc);
495 Expression* index_overflows = Expression::make_boolean(false, loc);
496 if (!val_is_unsigned)
e440a328 497 {
e67508fa 498 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
2c809f8f 499 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
e440a328 500 }
501
2c809f8f 502 int bound_type_size = bound_type->integer_type()->bits();
c3068ac0 503 if (val_type_size > bound_type_size
504 || (val_type_size == bound_type_size
2c809f8f 505 && val_is_unsigned))
506 {
507 mpz_t one;
508 mpz_init_set_ui(one, 1UL);
509
510 // maxval = 2^(bound_type_size - 1) - 1
511 mpz_t maxval;
512 mpz_init(maxval);
513 mpz_mul_2exp(maxval, one, bound_type_size - 1);
514 mpz_sub_ui(maxval, maxval, 1);
e67508fa 515 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
2c809f8f 516 mpz_clear(one);
517 mpz_clear(maxval);
518
519 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
e440a328 520 }
521
2c809f8f 522 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
523 loc);
e440a328 524}
525
d751bb78 526void
527Expression::dump_expression(Ast_dump_context* ast_dump_context) const
528{
529 this->do_dump_expression(ast_dump_context);
530}
531
e440a328 532// Error expressions. This are used to avoid cascading errors.
533
534class Error_expression : public Expression
535{
536 public:
b13c66cd 537 Error_expression(Location location)
e440a328 538 : Expression(EXPRESSION_ERROR, location)
539 { }
540
541 protected:
542 bool
543 do_is_constant() const
544 { return true; }
545
0e168074 546 bool
547 do_is_immutable() const
548 { return true; }
549
e440a328 550 bool
0c77715b 551 do_numeric_constant_value(Numeric_constant* nc) const
e440a328 552 {
0c77715b 553 nc->set_unsigned_long(NULL, 0);
e440a328 554 return true;
555 }
556
4f2138d7 557 bool
e440a328 558 do_discarding_value()
4f2138d7 559 { return true; }
e440a328 560
561 Type*
562 do_type()
563 { return Type::make_error_type(); }
564
565 void
566 do_determine_type(const Type_context*)
567 { }
568
569 Expression*
570 do_copy()
571 { return this; }
572
573 bool
574 do_is_addressable() const
575 { return true; }
576
ea664253 577 Bexpression*
578 do_get_backend(Translate_context* context)
579 { return context->backend()->error_expression(); }
d751bb78 580
581 void
582 do_dump_expression(Ast_dump_context*) const;
e440a328 583};
584
d751bb78 585// Dump the ast representation for an error expression to a dump context.
586
587void
588Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
589{
590 ast_dump_context->ostream() << "_Error_" ;
591}
592
e440a328 593Expression*
b13c66cd 594Expression::make_error(Location location)
e440a328 595{
596 return new Error_expression(location);
597}
598
599// An expression which is really a type. This is used during parsing.
600// It is an error if these survive after lowering.
601
602class
603Type_expression : public Expression
604{
605 public:
b13c66cd 606 Type_expression(Type* type, Location location)
e440a328 607 : Expression(EXPRESSION_TYPE, location),
608 type_(type)
609 { }
610
611 protected:
612 int
613 do_traverse(Traverse* traverse)
614 { return Type::traverse(this->type_, traverse); }
615
616 Type*
617 do_type()
618 { return this->type_; }
619
620 void
621 do_determine_type(const Type_context*)
622 { }
623
624 void
625 do_check_types(Gogo*)
626 { this->report_error(_("invalid use of type")); }
627
628 Expression*
629 do_copy()
630 { return this; }
631
ea664253 632 Bexpression*
633 do_get_backend(Translate_context*)
c3e6f413 634 { go_unreachable(); }
e440a328 635
d751bb78 636 void do_dump_expression(Ast_dump_context*) const;
637
e440a328 638 private:
639 // The type which we are representing as an expression.
640 Type* type_;
641};
642
d751bb78 643void
644Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
645{
646 ast_dump_context->dump_type(this->type_);
647}
648
e440a328 649Expression*
b13c66cd 650Expression::make_type(Type* type, Location location)
e440a328 651{
652 return new Type_expression(type, location);
653}
654
e03bdf36 655// Class Parser_expression.
656
657Type*
658Parser_expression::do_type()
659{
660 // We should never really ask for the type of a Parser_expression.
661 // However, it can happen, at least when we have an invalid const
662 // whose initializer refers to the const itself. In that case we
663 // may ask for the type when lowering the const itself.
c484d925 664 go_assert(saw_errors());
e03bdf36 665 return Type::make_error_type();
666}
667
e440a328 668// Class Var_expression.
669
670// Lower a variable expression. Here we just make sure that the
671// initialization expression of the variable has been lowered. This
672// ensures that we will be able to determine the type of the variable
673// if necessary.
674
675Expression*
ceeb4318 676Var_expression::do_lower(Gogo* gogo, Named_object* function,
677 Statement_inserter* inserter, int)
e440a328 678{
679 if (this->variable_->is_variable())
680 {
681 Variable* var = this->variable_->var_value();
682 // This is either a local variable or a global variable. A
683 // reference to a variable which is local to an enclosing
684 // function will be a reference to a field in a closure.
685 if (var->is_global())
ceeb4318 686 {
687 function = NULL;
688 inserter = NULL;
689 }
690 var->lower_init_expression(gogo, function, inserter);
e440a328 691 }
692 return this;
693}
694
e440a328 695// Return the type of a reference to a variable.
696
697Type*
698Var_expression::do_type()
699{
700 if (this->variable_->is_variable())
701 return this->variable_->var_value()->type();
702 else if (this->variable_->is_result_variable())
703 return this->variable_->result_var_value()->type();
704 else
c3e6f413 705 go_unreachable();
e440a328 706}
707
0ab09e06 708// Determine the type of a reference to a variable.
709
710void
711Var_expression::do_determine_type(const Type_context*)
712{
713 if (this->variable_->is_variable())
714 this->variable_->var_value()->determine_type();
715}
716
e440a328 717// Something takes the address of this variable. This means that we
718// may want to move the variable onto the heap.
719
720void
721Var_expression::do_address_taken(bool escapes)
722{
723 if (!escapes)
f325319b 724 {
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_non_escaping_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_non_escaping_address_taken();
729 else
730 go_unreachable();
731 }
e440a328 732 else
f325319b 733 {
734 if (this->variable_->is_variable())
735 this->variable_->var_value()->set_address_taken();
736 else if (this->variable_->is_result_variable())
737 this->variable_->result_var_value()->set_address_taken();
738 else
739 go_unreachable();
740 }
e440a328 741}
742
ea664253 743// Get the backend representation for a reference to a variable.
e440a328 744
ea664253 745Bexpression*
746Var_expression::do_get_backend(Translate_context* context)
e440a328 747{
fe2f84cf 748 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
749 context->function());
fe2f84cf 750 bool is_in_heap;
c6777780 751 Location loc = this->location();
9b27b43c 752 Btype* btype;
753 Gogo* gogo = context->gogo();
fe2f84cf 754 if (this->variable_->is_variable())
9b27b43c 755 {
756 is_in_heap = this->variable_->var_value()->is_in_heap();
757 btype = this->variable_->var_value()->type()->get_backend(gogo);
758 }
fe2f84cf 759 else if (this->variable_->is_result_variable())
9b27b43c 760 {
761 is_in_heap = this->variable_->result_var_value()->is_in_heap();
762 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
763 }
fe2f84cf 764 else
c3e6f413 765 go_unreachable();
c6777780 766
767 Bexpression* ret = context->backend()->var_expression(bvar, loc);
fe2f84cf 768 if (is_in_heap)
9b27b43c 769 ret = context->backend()->indirect_expression(btype, ret, true, loc);
ea664253 770 return ret;
e440a328 771}
772
d751bb78 773// Ast dump for variable expression.
774
775void
776Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
777{
778 ast_dump_context->ostream() << this->variable_->name() ;
779}
780
e440a328 781// Make a reference to a variable in an expression.
782
783Expression*
b13c66cd 784Expression::make_var_reference(Named_object* var, Location location)
e440a328 785{
786 if (var->is_sink())
787 return Expression::make_sink(location);
788
789 // FIXME: Creating a new object for each reference to a variable is
790 // wasteful.
791 return new Var_expression(var, location);
792}
793
794// Class Temporary_reference_expression.
795
796// The type.
797
798Type*
799Temporary_reference_expression::do_type()
800{
801 return this->statement_->type();
802}
803
804// Called if something takes the address of this temporary variable.
805// We never have to move temporary variables to the heap, but we do
806// need to know that they must live in the stack rather than in a
807// register.
808
809void
810Temporary_reference_expression::do_address_taken(bool)
811{
812 this->statement_->set_is_address_taken();
813}
814
ea664253 815// Get a backend expression referring to the variable.
e440a328 816
ea664253 817Bexpression*
818Temporary_reference_expression::do_get_backend(Translate_context* context)
e440a328 819{
cd440cff 820 Gogo* gogo = context->gogo();
eefc1ed3 821 Bvariable* bvar = this->statement_->get_backend_variable(context);
cd440cff 822 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
eefc1ed3 823
cd440cff 824 // The backend can't always represent the same set of recursive types
eefc1ed3 825 // that the Go frontend can. In some cases this means that a
826 // temporary variable won't have the right backend type. Correct
827 // that here by adding a type cast. We need to use base() to push
828 // the circularity down one level.
cd440cff 829 Type* stype = this->statement_->type();
ceeb4318 830 if (!this->is_lvalue_
cd440cff 831 && stype->has_pointer()
832 && stype->deref()->is_void_type())
eefc1ed3 833 {
cd440cff 834 Btype* btype = this->type()->base()->get_backend(gogo);
835 ret = gogo->backend()->convert_expression(btype, ret, this->location());
eefc1ed3 836 }
ea664253 837 return ret;
e440a328 838}
839
d751bb78 840// Ast dump for temporary reference.
841
842void
843Temporary_reference_expression::do_dump_expression(
844 Ast_dump_context* ast_dump_context) const
845{
846 ast_dump_context->dump_temp_variable_name(this->statement_);
847}
848
e440a328 849// Make a reference to a temporary variable.
850
ceeb4318 851Temporary_reference_expression*
e440a328 852Expression::make_temporary_reference(Temporary_statement* statement,
b13c66cd 853 Location location)
e440a328 854{
855 return new Temporary_reference_expression(statement, location);
856}
857
e9d3367e 858// Class Set_and_use_temporary_expression.
859
860// Return the type.
861
862Type*
863Set_and_use_temporary_expression::do_type()
864{
865 return this->statement_->type();
866}
867
0afbb937 868// Determine the type of the expression.
869
870void
871Set_and_use_temporary_expression::do_determine_type(
872 const Type_context* context)
873{
874 this->expr_->determine_type(context);
875}
876
e9d3367e 877// Take the address.
878
879void
880Set_and_use_temporary_expression::do_address_taken(bool)
881{
882 this->statement_->set_is_address_taken();
883}
884
885// Return the backend representation.
886
ea664253 887Bexpression*
888Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
e9d3367e 889{
e9d3367e 890 Location loc = this->location();
a302c105 891 Gogo* gogo = context->gogo();
892 Bvariable* bvar = this->statement_->get_backend_variable(context);
893 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
894
ea664253 895 Bexpression* bexpr = this->expr_->get_backend(context);
a302c105 896 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
897 var_ref = gogo->backend()->var_expression(bvar, loc);
898 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
ea664253 899 return ret;
e9d3367e 900}
901
902// Dump.
903
904void
905Set_and_use_temporary_expression::do_dump_expression(
906 Ast_dump_context* ast_dump_context) const
907{
908 ast_dump_context->ostream() << '(';
909 ast_dump_context->dump_temp_variable_name(this->statement_);
910 ast_dump_context->ostream() << " = ";
911 this->expr_->dump_expression(ast_dump_context);
912 ast_dump_context->ostream() << ')';
913}
914
915// Make a set-and-use temporary.
916
917Set_and_use_temporary_expression*
918Expression::make_set_and_use_temporary(Temporary_statement* statement,
919 Expression* expr, Location location)
920{
921 return new Set_and_use_temporary_expression(statement, expr, location);
922}
923
e440a328 924// A sink expression--a use of the blank identifier _.
925
926class Sink_expression : public Expression
927{
928 public:
b13c66cd 929 Sink_expression(Location location)
e440a328 930 : Expression(EXPRESSION_SINK, location),
aa93217a 931 type_(NULL), bvar_(NULL)
e440a328 932 { }
933
934 protected:
4f2138d7 935 bool
e440a328 936 do_discarding_value()
4f2138d7 937 { return true; }
e440a328 938
939 Type*
940 do_type();
941
942 void
943 do_determine_type(const Type_context*);
944
945 Expression*
946 do_copy()
947 { return new Sink_expression(this->location()); }
948
ea664253 949 Bexpression*
950 do_get_backend(Translate_context*);
e440a328 951
d751bb78 952 void
953 do_dump_expression(Ast_dump_context*) const;
954
e440a328 955 private:
956 // The type of this sink variable.
957 Type* type_;
958 // The temporary variable we generate.
aa93217a 959 Bvariable* bvar_;
e440a328 960};
961
962// Return the type of a sink expression.
963
964Type*
965Sink_expression::do_type()
966{
967 if (this->type_ == NULL)
968 return Type::make_sink_type();
969 return this->type_;
970}
971
972// Determine the type of a sink expression.
973
974void
975Sink_expression::do_determine_type(const Type_context* context)
976{
977 if (context->type != NULL)
978 this->type_ = context->type;
979}
980
981// Return a temporary variable for a sink expression. This will
982// presumably be a write-only variable which the middle-end will drop.
983
ea664253 984Bexpression*
985Sink_expression::do_get_backend(Translate_context* context)
e440a328 986{
aa93217a 987 Location loc = this->location();
988 Gogo* gogo = context->gogo();
989 if (this->bvar_ == NULL)
e440a328 990 {
c484d925 991 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
aa93217a 992 Named_object* fn = context->function();
993 go_assert(fn != NULL);
994 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
9f0e0513 995 Btype* bt = this->type_->get_backend(context->gogo());
aa93217a 996 Bstatement* decl;
997 this->bvar_ =
998 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
999 false, loc, &decl);
1000 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
1001 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
ea664253 1002 return var_ref;
e440a328 1003 }
ea664253 1004 return gogo->backend()->var_expression(this->bvar_, loc);
e440a328 1005}
1006
d751bb78 1007// Ast dump for sink expression.
1008
1009void
1010Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1011{
1012 ast_dump_context->ostream() << "_" ;
1013}
1014
e440a328 1015// Make a sink expression.
1016
1017Expression*
b13c66cd 1018Expression::make_sink(Location location)
e440a328 1019{
1020 return new Sink_expression(location);
1021}
1022
1023// Class Func_expression.
1024
1025// FIXME: Can a function expression appear in a constant expression?
1026// The value is unchanging. Initializing a constant to the address of
1027// a function seems like it could work, though there might be little
1028// point to it.
1029
e440a328 1030// Traversal.
1031
1032int
1033Func_expression::do_traverse(Traverse* traverse)
1034{
1035 return (this->closure_ == NULL
1036 ? TRAVERSE_CONTINUE
1037 : Expression::traverse(&this->closure_, traverse));
1038}
1039
1040// Return the type of a function expression.
1041
1042Type*
1043Func_expression::do_type()
1044{
1045 if (this->function_->is_function())
1046 return this->function_->func_value()->type();
1047 else if (this->function_->is_function_declaration())
1048 return this->function_->func_declaration_value()->type();
1049 else
c3e6f413 1050 go_unreachable();
e440a328 1051}
1052
ea664253 1053// Get the backend representation for the code of a function expression.
e440a328 1054
97267c39 1055Bexpression*
8381eda7 1056Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
e440a328 1057{
1058 Function_type* fntype;
8381eda7 1059 if (no->is_function())
1060 fntype = no->func_value()->type();
1061 else if (no->is_function_declaration())
1062 fntype = no->func_declaration_value()->type();
e440a328 1063 else
c3e6f413 1064 go_unreachable();
e440a328 1065
1066 // Builtin functions are handled specially by Call_expression. We
1067 // can't take their address.
1068 if (fntype->is_builtin())
1069 {
8381eda7 1070 error_at(loc,
cb0e02f3 1071 "invalid use of special builtin function %qs; must be called",
8381eda7 1072 no->message_name().c_str());
97267c39 1073 return gogo->backend()->error_expression();
e440a328 1074 }
1075
97267c39 1076 Bfunction* fndecl;
e440a328 1077 if (no->is_function())
cf3cae55 1078 fndecl = no->func_value()->get_or_make_decl(gogo, no);
e440a328 1079 else if (no->is_function_declaration())
cf3cae55 1080 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
e440a328 1081 else
c3e6f413 1082 go_unreachable();
e440a328 1083
97267c39 1084 return gogo->backend()->function_code_expression(fndecl, loc);
e440a328 1085}
1086
ea664253 1087// Get the backend representation for a function expression. This is used when
1088// we take the address of a function rather than simply calling it. A func
8381eda7 1089// value is represented as a pointer to a block of memory. The first
1090// word of that memory is a pointer to the function code. The
1091// remaining parts of that memory are the addresses of variables that
1092// the function closes over.
e440a328 1093
ea664253 1094Bexpression*
1095Func_expression::do_get_backend(Translate_context* context)
e440a328 1096{
8381eda7 1097 // If there is no closure, just use the function descriptor.
2010c17a 1098 if (this->closure_ == NULL)
8381eda7 1099 {
1100 Gogo* gogo = context->gogo();
1101 Named_object* no = this->function_;
1102 Expression* descriptor;
1103 if (no->is_function())
1104 descriptor = no->func_value()->descriptor(gogo, no);
1105 else if (no->is_function_declaration())
1106 {
1107 if (no->func_declaration_value()->type()->is_builtin())
1108 {
1109 error_at(this->location(),
1110 ("invalid use of special builtin function %qs; "
1111 "must be called"),
1112 no->message_name().c_str());
ea664253 1113 return gogo->backend()->error_expression();
8381eda7 1114 }
1115 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1116 }
1117 else
1118 go_unreachable();
2010c17a 1119
ea664253 1120 Bexpression* bdesc = descriptor->get_backend(context);
1121 return gogo->backend()->address_expression(bdesc, this->location());
8381eda7 1122 }
e440a328 1123
8381eda7 1124 go_assert(this->function_->func_value()->enclosing() != NULL);
e440a328 1125
8381eda7 1126 // If there is a closure, then the closure is itself the function
1127 // expression. It is a pointer to a struct whose first field points
1128 // to the function code and whose remaining fields are the addresses
1129 // of the closed-over variables.
ea664253 1130 return this->closure_->get_backend(context);
e440a328 1131}
1132
d751bb78 1133// Ast dump for function.
1134
1135void
1136Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1137{
8b1c301d 1138 ast_dump_context->ostream() << this->function_->name();
1139 if (this->closure_ != NULL)
1140 {
1141 ast_dump_context->ostream() << " {closure = ";
1142 this->closure_->dump_expression(ast_dump_context);
1143 ast_dump_context->ostream() << "}";
1144 }
d751bb78 1145}
1146
e440a328 1147// Make a reference to a function in an expression.
1148
1149Expression*
1150Expression::make_func_reference(Named_object* function, Expression* closure,
b13c66cd 1151 Location location)
e440a328 1152{
1153 return new Func_expression(function, closure, location);
1154}
1155
c6837989 1156// Class Func_descriptor_expression.
8381eda7 1157
c6837989 1158// Constructor.
8381eda7 1159
c6837989 1160Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1161 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
f8bdf81a 1162 fn_(fn), dvar_(NULL)
c6837989 1163{
1164 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1165}
8381eda7 1166
c6837989 1167// Traversal.
8381eda7 1168
c6837989 1169int
1170Func_descriptor_expression::do_traverse(Traverse*)
1171{
1172 return TRAVERSE_CONTINUE;
1173}
8381eda7 1174
1175// All function descriptors have the same type.
1176
1177Type* Func_descriptor_expression::descriptor_type;
1178
1179void
1180Func_descriptor_expression::make_func_descriptor_type()
1181{
1182 if (Func_descriptor_expression::descriptor_type != NULL)
1183 return;
1184 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1185 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1186 Func_descriptor_expression::descriptor_type =
1187 Type::make_builtin_named_type("functionDescriptor", struct_type);
1188}
1189
1190Type*
1191Func_descriptor_expression::do_type()
1192{
1193 Func_descriptor_expression::make_func_descriptor_type();
1194 return Func_descriptor_expression::descriptor_type;
1195}
1196
ea664253 1197// The backend representation for a function descriptor.
8381eda7 1198
ea664253 1199Bexpression*
1200Func_descriptor_expression::do_get_backend(Translate_context* context)
8381eda7 1201{
8381eda7 1202 Named_object* no = this->fn_;
1203 Location loc = no->location();
ea664253 1204 if (this->dvar_ != NULL)
1205 return context->backend()->var_expression(this->dvar_, loc);
8381eda7 1206
ea664253 1207 Gogo* gogo = context->gogo();
8381eda7 1208 std::string var_name;
1209 if (no->package() == NULL)
1210 var_name = gogo->pkgpath_symbol();
1211 else
1212 var_name = no->package()->pkgpath_symbol();
1213 var_name.push_back('.');
1214 var_name.append(Gogo::unpack_hidden_name(no->name()));
1215 var_name.append("$descriptor");
1216
1217 Btype* btype = this->type()->get_backend(gogo);
1218
1219 Bvariable* bvar;
1220 if (no->package() != NULL
1221 || Linemap::is_predeclared_location(no->location()))
f8bdf81a 1222 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1223 loc);
8381eda7 1224 else
1225 {
1226 Location bloc = Linemap::predeclared_location();
1227 bool is_hidden = ((no->is_function()
1228 && no->func_value()->enclosing() != NULL)
1229 || Gogo::is_thunk(no));
1230 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1231 btype, bloc);
1232 Expression_list* vals = new Expression_list();
f8bdf81a 1233 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
8381eda7 1234 Expression* init =
1235 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1236 Translate_context bcontext(gogo, NULL, NULL, NULL);
1237 bcontext.set_is_const();
ea664253 1238 Bexpression* binit = init->get_backend(&bcontext);
8381eda7 1239 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1240 false, btype, bloc, binit);
1241 }
1242
1243 this->dvar_ = bvar;
ea664253 1244 return gogo->backend()->var_expression(bvar, loc);
8381eda7 1245}
1246
c6837989 1247// Print a function descriptor expression.
1248
1249void
1250Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1251{
1252 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1253}
1254
8381eda7 1255// Make a function descriptor expression.
1256
c6837989 1257Func_descriptor_expression*
1258Expression::make_func_descriptor(Named_object* fn)
8381eda7 1259{
c6837989 1260 return new Func_descriptor_expression(fn);
8381eda7 1261}
1262
1263// Make the function descriptor type, so that it can be converted.
1264
1265void
1266Expression::make_func_descriptor_type()
1267{
1268 Func_descriptor_expression::make_func_descriptor_type();
1269}
1270
1271// A reference to just the code of a function.
1272
1273class Func_code_reference_expression : public Expression
1274{
1275 public:
1276 Func_code_reference_expression(Named_object* function, Location location)
1277 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1278 function_(function)
1279 { }
1280
1281 protected:
1282 int
1283 do_traverse(Traverse*)
1284 { return TRAVERSE_CONTINUE; }
1285
f9ca30f9 1286 bool
1287 do_is_immutable() const
1288 { return true; }
1289
8381eda7 1290 Type*
1291 do_type()
1292 { return Type::make_pointer_type(Type::make_void_type()); }
1293
1294 void
1295 do_determine_type(const Type_context*)
1296 { }
1297
1298 Expression*
1299 do_copy()
1300 {
1301 return Expression::make_func_code_reference(this->function_,
1302 this->location());
1303 }
1304
ea664253 1305 Bexpression*
1306 do_get_backend(Translate_context*);
8381eda7 1307
1308 void
1309 do_dump_expression(Ast_dump_context* context) const
1310 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1311
1312 private:
1313 // The function.
1314 Named_object* function_;
1315};
1316
ea664253 1317// Get the backend representation for a reference to function code.
8381eda7 1318
ea664253 1319Bexpression*
1320Func_code_reference_expression::do_get_backend(Translate_context* context)
8381eda7 1321{
ea664253 1322 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1323 this->location());
8381eda7 1324}
1325
1326// Make a reference to the code of a function.
1327
1328Expression*
1329Expression::make_func_code_reference(Named_object* function, Location location)
1330{
1331 return new Func_code_reference_expression(function, location);
1332}
1333
e440a328 1334// Class Unknown_expression.
1335
1336// Return the name of an unknown expression.
1337
1338const std::string&
1339Unknown_expression::name() const
1340{
1341 return this->named_object_->name();
1342}
1343
1344// Lower a reference to an unknown name.
1345
1346Expression*
ceeb4318 1347Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 1348{
b13c66cd 1349 Location location = this->location();
e440a328 1350 Named_object* no = this->named_object_;
deded542 1351 Named_object* real;
1352 if (!no->is_unknown())
1353 real = no;
1354 else
e440a328 1355 {
deded542 1356 real = no->unknown_value()->real_named_object();
1357 if (real == NULL)
1358 {
1359 if (this->is_composite_literal_key_)
1360 return this;
acf8e158 1361 if (!this->no_error_message_)
1362 error_at(location, "reference to undefined name %qs",
1363 this->named_object_->message_name().c_str());
deded542 1364 return Expression::make_error(location);
1365 }
e440a328 1366 }
1367 switch (real->classification())
1368 {
1369 case Named_object::NAMED_OBJECT_CONST:
1370 return Expression::make_const_reference(real, location);
1371 case Named_object::NAMED_OBJECT_TYPE:
1372 return Expression::make_type(real->type_value(), location);
1373 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1374 if (this->is_composite_literal_key_)
1375 return this;
acf8e158 1376 if (!this->no_error_message_)
1377 error_at(location, "reference to undefined type %qs",
1378 real->message_name().c_str());
e440a328 1379 return Expression::make_error(location);
1380 case Named_object::NAMED_OBJECT_VAR:
7d834090 1381 real->var_value()->set_is_used();
e440a328 1382 return Expression::make_var_reference(real, location);
1383 case Named_object::NAMED_OBJECT_FUNC:
1384 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1385 return Expression::make_func_reference(real, NULL, location);
1386 case Named_object::NAMED_OBJECT_PACKAGE:
1387 if (this->is_composite_literal_key_)
1388 return this;
acf8e158 1389 if (!this->no_error_message_)
1390 error_at(location, "unexpected reference to package");
e440a328 1391 return Expression::make_error(location);
1392 default:
c3e6f413 1393 go_unreachable();
e440a328 1394 }
1395}
1396
d751bb78 1397// Dump the ast representation for an unknown expression to a dump context.
1398
1399void
1400Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1401{
1402 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1403 << ")";
d751bb78 1404}
1405
e440a328 1406// Make a reference to an unknown name.
1407
acf8e158 1408Unknown_expression*
b13c66cd 1409Expression::make_unknown_reference(Named_object* no, Location location)
e440a328 1410{
e440a328 1411 return new Unknown_expression(no, location);
1412}
1413
1414// A boolean expression.
1415
1416class Boolean_expression : public Expression
1417{
1418 public:
b13c66cd 1419 Boolean_expression(bool val, Location location)
e440a328 1420 : Expression(EXPRESSION_BOOLEAN, location),
1421 val_(val), type_(NULL)
1422 { }
1423
1424 static Expression*
1425 do_import(Import*);
1426
1427 protected:
1428 bool
1429 do_is_constant() const
1430 { return true; }
1431
0e168074 1432 bool
1433 do_is_immutable() const
1434 { return true; }
1435
e440a328 1436 Type*
1437 do_type();
1438
1439 void
1440 do_determine_type(const Type_context*);
1441
1442 Expression*
1443 do_copy()
1444 { return this; }
1445
ea664253 1446 Bexpression*
1447 do_get_backend(Translate_context* context)
1448 { return context->backend()->boolean_constant_expression(this->val_); }
e440a328 1449
1450 void
1451 do_export(Export* exp) const
1452 { exp->write_c_string(this->val_ ? "true" : "false"); }
1453
d751bb78 1454 void
1455 do_dump_expression(Ast_dump_context* ast_dump_context) const
1456 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1457
e440a328 1458 private:
1459 // The constant.
1460 bool val_;
1461 // The type as determined by context.
1462 Type* type_;
1463};
1464
1465// Get the type.
1466
1467Type*
1468Boolean_expression::do_type()
1469{
1470 if (this->type_ == NULL)
1471 this->type_ = Type::make_boolean_type();
1472 return this->type_;
1473}
1474
1475// Set the type from the context.
1476
1477void
1478Boolean_expression::do_determine_type(const Type_context* context)
1479{
1480 if (this->type_ != NULL && !this->type_->is_abstract())
1481 ;
1482 else if (context->type != NULL && context->type->is_boolean_type())
1483 this->type_ = context->type;
1484 else if (!context->may_be_abstract)
1485 this->type_ = Type::lookup_bool_type();
1486}
1487
1488// Import a boolean constant.
1489
1490Expression*
1491Boolean_expression::do_import(Import* imp)
1492{
1493 if (imp->peek_char() == 't')
1494 {
1495 imp->require_c_string("true");
1496 return Expression::make_boolean(true, imp->location());
1497 }
1498 else
1499 {
1500 imp->require_c_string("false");
1501 return Expression::make_boolean(false, imp->location());
1502 }
1503}
1504
1505// Make a boolean expression.
1506
1507Expression*
b13c66cd 1508Expression::make_boolean(bool val, Location location)
e440a328 1509{
1510 return new Boolean_expression(val, location);
1511}
1512
1513// Class String_expression.
1514
1515// Get the type.
1516
1517Type*
1518String_expression::do_type()
1519{
1520 if (this->type_ == NULL)
1521 this->type_ = Type::make_string_type();
1522 return this->type_;
1523}
1524
1525// Set the type from the context.
1526
1527void
1528String_expression::do_determine_type(const Type_context* context)
1529{
1530 if (this->type_ != NULL && !this->type_->is_abstract())
1531 ;
1532 else if (context->type != NULL && context->type->is_string_type())
1533 this->type_ = context->type;
1534 else if (!context->may_be_abstract)
1535 this->type_ = Type::lookup_string_type();
1536}
1537
1538// Build a string constant.
1539
ea664253 1540Bexpression*
1541String_expression::do_get_backend(Translate_context* context)
e440a328 1542{
2c809f8f 1543 Gogo* gogo = context->gogo();
1544 Btype* btype = Type::make_string_type()->get_backend(gogo);
1545
1546 Location loc = this->location();
1547 std::vector<Bexpression*> init(2);
1548 Bexpression* str_cst =
1549 gogo->backend()->string_constant_expression(this->val_);
1550 init[0] = gogo->backend()->address_expression(str_cst, loc);
1551
1552 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1553 mpz_t lenval;
1554 mpz_init_set_ui(lenval, this->val_.length());
1555 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1556 mpz_clear(lenval);
1557
ea664253 1558 return gogo->backend()->constructor_expression(btype, init, loc);
e440a328 1559}
1560
8b1c301d 1561 // Write string literal to string dump.
e440a328 1562
1563void
8b1c301d 1564String_expression::export_string(String_dump* exp,
1565 const String_expression* str)
e440a328 1566{
1567 std::string s;
8b1c301d 1568 s.reserve(str->val_.length() * 4 + 2);
e440a328 1569 s += '"';
8b1c301d 1570 for (std::string::const_iterator p = str->val_.begin();
1571 p != str->val_.end();
e440a328 1572 ++p)
1573 {
1574 if (*p == '\\' || *p == '"')
1575 {
1576 s += '\\';
1577 s += *p;
1578 }
1579 else if (*p >= 0x20 && *p < 0x7f)
1580 s += *p;
1581 else if (*p == '\n')
1582 s += "\\n";
1583 else if (*p == '\t')
1584 s += "\\t";
1585 else
1586 {
1587 s += "\\x";
1588 unsigned char c = *p;
1589 unsigned int dig = c >> 4;
1590 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1591 dig = c & 0xf;
1592 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1593 }
1594 }
1595 s += '"';
1596 exp->write_string(s);
1597}
1598
8b1c301d 1599// Export a string expression.
1600
1601void
1602String_expression::do_export(Export* exp) const
1603{
1604 String_expression::export_string(exp, this);
1605}
1606
e440a328 1607// Import a string expression.
1608
1609Expression*
1610String_expression::do_import(Import* imp)
1611{
1612 imp->require_c_string("\"");
1613 std::string val;
1614 while (true)
1615 {
1616 int c = imp->get_char();
1617 if (c == '"' || c == -1)
1618 break;
1619 if (c != '\\')
1620 val += static_cast<char>(c);
1621 else
1622 {
1623 c = imp->get_char();
1624 if (c == '\\' || c == '"')
1625 val += static_cast<char>(c);
1626 else if (c == 'n')
1627 val += '\n';
1628 else if (c == 't')
1629 val += '\t';
1630 else if (c == 'x')
1631 {
1632 c = imp->get_char();
1633 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1634 c = imp->get_char();
1635 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1636 char v = (vh << 4) | vl;
1637 val += v;
1638 }
1639 else
1640 {
1641 error_at(imp->location(), "bad string constant");
1642 return Expression::make_error(imp->location());
1643 }
1644 }
1645 }
1646 return Expression::make_string(val, imp->location());
1647}
1648
d751bb78 1649// Ast dump for string expression.
1650
1651void
1652String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1653{
8b1c301d 1654 String_expression::export_string(ast_dump_context, this);
d751bb78 1655}
1656
e440a328 1657// Make a string expression.
1658
1659Expression*
b13c66cd 1660Expression::make_string(const std::string& val, Location location)
e440a328 1661{
1662 return new String_expression(val, location);
1663}
1664
2c809f8f 1665// An expression that evaluates to some characteristic of a string.
1666// This is used when indexing, bound-checking, or nil checking a string.
1667
1668class String_info_expression : public Expression
1669{
1670 public:
1671 String_info_expression(Expression* string, String_info string_info,
1672 Location location)
1673 : Expression(EXPRESSION_STRING_INFO, location),
1674 string_(string), string_info_(string_info)
1675 { }
1676
1677 protected:
1678 Type*
1679 do_type();
1680
1681 void
1682 do_determine_type(const Type_context*)
1683 { go_unreachable(); }
1684
1685 Expression*
1686 do_copy()
1687 {
1688 return new String_info_expression(this->string_->copy(), this->string_info_,
1689 this->location());
1690 }
1691
ea664253 1692 Bexpression*
1693 do_get_backend(Translate_context* context);
2c809f8f 1694
1695 void
1696 do_dump_expression(Ast_dump_context*) const;
1697
1698 void
1699 do_issue_nil_check()
1700 { this->string_->issue_nil_check(); }
1701
1702 private:
1703 // The string for which we are getting information.
1704 Expression* string_;
1705 // What information we want.
1706 String_info string_info_;
1707};
1708
1709// Return the type of the string info.
1710
1711Type*
1712String_info_expression::do_type()
1713{
1714 switch (this->string_info_)
1715 {
1716 case STRING_INFO_DATA:
1717 {
1718 Type* byte_type = Type::lookup_integer_type("uint8");
1719 return Type::make_pointer_type(byte_type);
1720 }
1721 case STRING_INFO_LENGTH:
1722 return Type::lookup_integer_type("int");
1723 default:
1724 go_unreachable();
1725 }
1726}
1727
1728// Return string information in GENERIC.
1729
ea664253 1730Bexpression*
1731String_info_expression::do_get_backend(Translate_context* context)
2c809f8f 1732{
1733 Gogo* gogo = context->gogo();
1734
ea664253 1735 Bexpression* bstring = this->string_->get_backend(context);
2c809f8f 1736 switch (this->string_info_)
1737 {
1738 case STRING_INFO_DATA:
1739 case STRING_INFO_LENGTH:
ea664253 1740 return gogo->backend()->struct_field_expression(bstring,
1741 this->string_info_,
1742 this->location());
2c809f8f 1743 break;
1744 default:
1745 go_unreachable();
1746 }
2c809f8f 1747}
1748
1749// Dump ast representation for a type info expression.
1750
1751void
1752String_info_expression::do_dump_expression(
1753 Ast_dump_context* ast_dump_context) const
1754{
1755 ast_dump_context->ostream() << "stringinfo(";
1756 this->string_->dump_expression(ast_dump_context);
1757 ast_dump_context->ostream() << ",";
1758 ast_dump_context->ostream() <<
1759 (this->string_info_ == STRING_INFO_DATA ? "data"
1760 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1761 : "unknown");
1762 ast_dump_context->ostream() << ")";
1763}
1764
1765// Make a string info expression.
1766
1767Expression*
1768Expression::make_string_info(Expression* string, String_info string_info,
1769 Location location)
1770{
1771 return new String_info_expression(string, string_info, location);
1772}
1773
e440a328 1774// Make an integer expression.
1775
1776class Integer_expression : public Expression
1777{
1778 public:
5d4b8566 1779 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1780 Location location)
e440a328 1781 : Expression(EXPRESSION_INTEGER, location),
5d4b8566 1782 type_(type), is_character_constant_(is_character_constant)
e440a328 1783 { mpz_init_set(this->val_, *val); }
1784
1785 static Expression*
1786 do_import(Import*);
1787
8b1c301d 1788 // Write VAL to string dump.
e440a328 1789 static void
8b1c301d 1790 export_integer(String_dump* exp, const mpz_t val);
e440a328 1791
d751bb78 1792 // Write VAL to dump context.
1793 static void
1794 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1795
e440a328 1796 protected:
1797 bool
1798 do_is_constant() const
1799 { return true; }
1800
0e168074 1801 bool
1802 do_is_immutable() const
1803 { return true; }
1804
e440a328 1805 bool
0c77715b 1806 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 1807
1808 Type*
1809 do_type();
1810
1811 void
1812 do_determine_type(const Type_context* context);
1813
1814 void
1815 do_check_types(Gogo*);
1816
ea664253 1817 Bexpression*
1818 do_get_backend(Translate_context*);
e440a328 1819
1820 Expression*
1821 do_copy()
5d4b8566 1822 {
1823 if (this->is_character_constant_)
1824 return Expression::make_character(&this->val_, this->type_,
1825 this->location());
1826 else
e67508fa 1827 return Expression::make_integer_z(&this->val_, this->type_,
1828 this->location());
5d4b8566 1829 }
e440a328 1830
1831 void
1832 do_export(Export*) const;
1833
d751bb78 1834 void
1835 do_dump_expression(Ast_dump_context*) const;
1836
e440a328 1837 private:
1838 // The integer value.
1839 mpz_t val_;
1840 // The type so far.
1841 Type* type_;
5d4b8566 1842 // Whether this is a character constant.
1843 bool is_character_constant_;
e440a328 1844};
1845
0c77715b 1846// Return a numeric constant for this expression. We have to mark
1847// this as a character when appropriate.
e440a328 1848
1849bool
0c77715b 1850Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 1851{
0c77715b 1852 if (this->is_character_constant_)
1853 nc->set_rune(this->type_, this->val_);
1854 else
1855 nc->set_int(this->type_, this->val_);
e440a328 1856 return true;
1857}
1858
1859// Return the current type. If we haven't set the type yet, we return
1860// an abstract integer type.
1861
1862Type*
1863Integer_expression::do_type()
1864{
1865 if (this->type_ == NULL)
5d4b8566 1866 {
1867 if (this->is_character_constant_)
1868 this->type_ = Type::make_abstract_character_type();
1869 else
1870 this->type_ = Type::make_abstract_integer_type();
1871 }
e440a328 1872 return this->type_;
1873}
1874
1875// Set the type of the integer value. Here we may switch from an
1876// abstract type to a real type.
1877
1878void
1879Integer_expression::do_determine_type(const Type_context* context)
1880{
1881 if (this->type_ != NULL && !this->type_->is_abstract())
1882 ;
0c77715b 1883 else if (context->type != NULL && context->type->is_numeric_type())
e440a328 1884 this->type_ = context->type;
1885 else if (!context->may_be_abstract)
5d4b8566 1886 {
1887 if (this->is_character_constant_)
1888 this->type_ = Type::lookup_integer_type("int32");
1889 else
1890 this->type_ = Type::lookup_integer_type("int");
1891 }
e440a328 1892}
1893
e440a328 1894// Check the type of an integer constant.
1895
1896void
1897Integer_expression::do_check_types(Gogo*)
1898{
0c77715b 1899 Type* type = this->type_;
1900 if (type == NULL)
e440a328 1901 return;
0c77715b 1902 Numeric_constant nc;
1903 if (this->is_character_constant_)
1904 nc.set_rune(NULL, this->val_);
1905 else
1906 nc.set_int(NULL, this->val_);
1907 if (!nc.set_type(type, true, this->location()))
e440a328 1908 this->set_is_error();
1909}
1910
ea664253 1911// Get the backend representation for an integer constant.
e440a328 1912
ea664253 1913Bexpression*
1914Integer_expression::do_get_backend(Translate_context* context)
e440a328 1915{
48c2a53a 1916 Type* resolved_type = NULL;
e440a328 1917 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 1918 resolved_type = this->type_;
e440a328 1919 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1920 {
1921 // We are converting to an abstract floating point type.
48c2a53a 1922 resolved_type = Type::lookup_float_type("float64");
e440a328 1923 }
1924 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1925 {
1926 // We are converting to an abstract complex type.
48c2a53a 1927 resolved_type = Type::lookup_complex_type("complex128");
e440a328 1928 }
1929 else
1930 {
1931 // If we still have an abstract type here, then this is being
1932 // used in a constant expression which didn't get reduced for
1933 // some reason. Use a type which will fit the value. We use <,
1934 // not <=, because we need an extra bit for the sign bit.
1935 int bits = mpz_sizeinbase(this->val_, 2);
1b1f2abf 1936 Type* int_type = Type::lookup_integer_type("int");
1937 if (bits < int_type->integer_type()->bits())
48c2a53a 1938 resolved_type = int_type;
e440a328 1939 else if (bits < 64)
48c2a53a 1940 resolved_type = Type::lookup_integer_type("int64");
e440a328 1941 else
48c2a53a 1942 {
1943 if (!saw_errors())
1944 error_at(this->location(),
1945 "unknown type for large integer constant");
ea664253 1946 return context->gogo()->backend()->error_expression();
48c2a53a 1947 }
e440a328 1948 }
48c2a53a 1949 Numeric_constant nc;
1950 nc.set_int(resolved_type, this->val_);
ea664253 1951 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 1952}
1953
1954// Write VAL to export data.
1955
1956void
8b1c301d 1957Integer_expression::export_integer(String_dump* exp, const mpz_t val)
e440a328 1958{
1959 char* s = mpz_get_str(NULL, 10, val);
1960 exp->write_c_string(s);
1961 free(s);
1962}
1963
1964// Export an integer in a constant expression.
1965
1966void
1967Integer_expression::do_export(Export* exp) const
1968{
1969 Integer_expression::export_integer(exp, this->val_);
5d4b8566 1970 if (this->is_character_constant_)
1971 exp->write_c_string("'");
e440a328 1972 // A trailing space lets us reliably identify the end of the number.
1973 exp->write_c_string(" ");
1974}
1975
1976// Import an integer, floating point, or complex value. This handles
1977// all these types because they all start with digits.
1978
1979Expression*
1980Integer_expression::do_import(Import* imp)
1981{
1982 std::string num = imp->read_identifier();
1983 imp->require_c_string(" ");
1984 if (!num.empty() && num[num.length() - 1] == 'i')
1985 {
1986 mpfr_t real;
1987 size_t plus_pos = num.find('+', 1);
1988 size_t minus_pos = num.find('-', 1);
1989 size_t pos;
1990 if (plus_pos == std::string::npos)
1991 pos = minus_pos;
1992 else if (minus_pos == std::string::npos)
1993 pos = plus_pos;
1994 else
1995 {
1996 error_at(imp->location(), "bad number in import data: %qs",
1997 num.c_str());
1998 return Expression::make_error(imp->location());
1999 }
2000 if (pos == std::string::npos)
2001 mpfr_set_ui(real, 0, GMP_RNDN);
2002 else
2003 {
2004 std::string real_str = num.substr(0, pos);
2005 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2006 {
2007 error_at(imp->location(), "bad number in import data: %qs",
2008 real_str.c_str());
2009 return Expression::make_error(imp->location());
2010 }
2011 }
2012
2013 std::string imag_str;
2014 if (pos == std::string::npos)
2015 imag_str = num;
2016 else
2017 imag_str = num.substr(pos);
2018 imag_str = imag_str.substr(0, imag_str.size() - 1);
2019 mpfr_t imag;
2020 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2021 {
2022 error_at(imp->location(), "bad number in import data: %qs",
2023 imag_str.c_str());
2024 return Expression::make_error(imp->location());
2025 }
fcbea5e4 2026 mpc_t cval;
2027 mpc_init2(cval, mpc_precision);
2028 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
e440a328 2029 mpfr_clear(real);
2030 mpfr_clear(imag);
fcbea5e4 2031 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2032 mpc_clear(cval);
e440a328 2033 return ret;
2034 }
2035 else if (num.find('.') == std::string::npos
2036 && num.find('E') == std::string::npos)
2037 {
5d4b8566 2038 bool is_character_constant = (!num.empty()
2039 && num[num.length() - 1] == '\'');
2040 if (is_character_constant)
2041 num = num.substr(0, num.length() - 1);
e440a328 2042 mpz_t val;
2043 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2044 {
2045 error_at(imp->location(), "bad number in import data: %qs",
2046 num.c_str());
2047 return Expression::make_error(imp->location());
2048 }
5d4b8566 2049 Expression* ret;
2050 if (is_character_constant)
2051 ret = Expression::make_character(&val, NULL, imp->location());
2052 else
e67508fa 2053 ret = Expression::make_integer_z(&val, NULL, imp->location());
e440a328 2054 mpz_clear(val);
2055 return ret;
2056 }
2057 else
2058 {
2059 mpfr_t val;
2060 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2061 {
2062 error_at(imp->location(), "bad number in import data: %qs",
2063 num.c_str());
2064 return Expression::make_error(imp->location());
2065 }
2066 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2067 mpfr_clear(val);
2068 return ret;
2069 }
2070}
d751bb78 2071// Ast dump for integer expression.
2072
2073void
2074Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2075{
5d4b8566 2076 if (this->is_character_constant_)
2077 ast_dump_context->ostream() << '\'';
8b1c301d 2078 Integer_expression::export_integer(ast_dump_context, this->val_);
5d4b8566 2079 if (this->is_character_constant_)
2080 ast_dump_context->ostream() << '\'';
d751bb78 2081}
2082
e67508fa 2083// Build a new integer value from a multi-precision integer.
e440a328 2084
2085Expression*
e67508fa 2086Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
5d4b8566 2087{
2088 return new Integer_expression(val, type, false, location);
2089}
2090
e67508fa 2091// Build a new integer value from an unsigned long.
2092
2093Expression*
2094Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2095{
2096 mpz_t zval;
2097 mpz_init_set_ui(zval, val);
2098 Expression* ret = Expression::make_integer_z(&zval, type, location);
2099 mpz_clear(zval);
2100 return ret;
2101}
2102
2103// Build a new integer value from a signed long.
2104
2105Expression*
2106Expression::make_integer_sl(long val, Type *type, Location location)
2107{
2108 mpz_t zval;
2109 mpz_init_set_si(zval, val);
2110 Expression* ret = Expression::make_integer_z(&zval, type, location);
2111 mpz_clear(zval);
2112 return ret;
2113}
2114
5d4b8566 2115// Build a new character constant value.
2116
2117Expression*
2118Expression::make_character(const mpz_t* val, Type* type, Location location)
e440a328 2119{
5d4b8566 2120 return new Integer_expression(val, type, true, location);
e440a328 2121}
2122
2123// Floats.
2124
2125class Float_expression : public Expression
2126{
2127 public:
b13c66cd 2128 Float_expression(const mpfr_t* val, Type* type, Location location)
e440a328 2129 : Expression(EXPRESSION_FLOAT, location),
2130 type_(type)
2131 {
2132 mpfr_init_set(this->val_, *val, GMP_RNDN);
2133 }
2134
e440a328 2135 // Write VAL to export data.
2136 static void
8b1c301d 2137 export_float(String_dump* exp, const mpfr_t val);
2138
d751bb78 2139 // Write VAL to dump file.
2140 static void
2141 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
e440a328 2142
2143 protected:
2144 bool
2145 do_is_constant() const
2146 { return true; }
2147
0e168074 2148 bool
2149 do_is_immutable() const
2150 { return true; }
2151
e440a328 2152 bool
0c77715b 2153 do_numeric_constant_value(Numeric_constant* nc) const
2154 {
2155 nc->set_float(this->type_, this->val_);
2156 return true;
2157 }
e440a328 2158
2159 Type*
2160 do_type();
2161
2162 void
2163 do_determine_type(const Type_context*);
2164
2165 void
2166 do_check_types(Gogo*);
2167
2168 Expression*
2169 do_copy()
2170 { return Expression::make_float(&this->val_, this->type_,
2171 this->location()); }
2172
ea664253 2173 Bexpression*
2174 do_get_backend(Translate_context*);
e440a328 2175
2176 void
2177 do_export(Export*) const;
2178
d751bb78 2179 void
2180 do_dump_expression(Ast_dump_context*) const;
2181
e440a328 2182 private:
2183 // The floating point value.
2184 mpfr_t val_;
2185 // The type so far.
2186 Type* type_;
2187};
2188
e440a328 2189// Return the current type. If we haven't set the type yet, we return
2190// an abstract float type.
2191
2192Type*
2193Float_expression::do_type()
2194{
2195 if (this->type_ == NULL)
2196 this->type_ = Type::make_abstract_float_type();
2197 return this->type_;
2198}
2199
2200// Set the type of the float value. Here we may switch from an
2201// abstract type to a real type.
2202
2203void
2204Float_expression::do_determine_type(const Type_context* context)
2205{
2206 if (this->type_ != NULL && !this->type_->is_abstract())
2207 ;
2208 else if (context->type != NULL
2209 && (context->type->integer_type() != NULL
2210 || context->type->float_type() != NULL
2211 || context->type->complex_type() != NULL))
2212 this->type_ = context->type;
2213 else if (!context->may_be_abstract)
48080209 2214 this->type_ = Type::lookup_float_type("float64");
e440a328 2215}
2216
e440a328 2217// Check the type of a float value.
2218
2219void
2220Float_expression::do_check_types(Gogo*)
2221{
0c77715b 2222 Type* type = this->type_;
2223 if (type == NULL)
e440a328 2224 return;
0c77715b 2225 Numeric_constant nc;
2226 nc.set_float(NULL, this->val_);
2227 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2228 this->set_is_error();
e440a328 2229}
2230
ea664253 2231// Get the backend representation for a float constant.
e440a328 2232
ea664253 2233Bexpression*
2234Float_expression::do_get_backend(Translate_context* context)
e440a328 2235{
48c2a53a 2236 Type* resolved_type;
e440a328 2237 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2238 resolved_type = this->type_;
e440a328 2239 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2240 {
2241 // We have an abstract integer type. We just hope for the best.
48c2a53a 2242 resolved_type = Type::lookup_integer_type("int");
2243 }
2244 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2245 {
2246 // We are converting to an abstract complex type.
2247 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2248 }
2249 else
2250 {
2251 // If we still have an abstract type here, then this is being
2252 // used in a constant expression which didn't get reduced. We
2253 // just use float64 and hope for the best.
48c2a53a 2254 resolved_type = Type::lookup_float_type("float64");
e440a328 2255 }
48c2a53a 2256
2257 Numeric_constant nc;
2258 nc.set_float(resolved_type, this->val_);
ea664253 2259 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2260}
2261
8b1c301d 2262// Write a floating point number to a string dump.
e440a328 2263
2264void
8b1c301d 2265Float_expression::export_float(String_dump *exp, const mpfr_t val)
e440a328 2266{
2267 mp_exp_t exponent;
2268 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2269 if (*s == '-')
2270 exp->write_c_string("-");
2271 exp->write_c_string("0.");
2272 exp->write_c_string(*s == '-' ? s + 1 : s);
2273 mpfr_free_str(s);
2274 char buf[30];
2275 snprintf(buf, sizeof buf, "E%ld", exponent);
2276 exp->write_c_string(buf);
2277}
2278
2279// Export a floating point number in a constant expression.
2280
2281void
2282Float_expression::do_export(Export* exp) const
2283{
2284 Float_expression::export_float(exp, this->val_);
2285 // A trailing space lets us reliably identify the end of the number.
2286 exp->write_c_string(" ");
2287}
2288
d751bb78 2289// Dump a floating point number to the dump file.
2290
2291void
2292Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2293{
8b1c301d 2294 Float_expression::export_float(ast_dump_context, this->val_);
d751bb78 2295}
2296
e440a328 2297// Make a float expression.
2298
2299Expression*
b13c66cd 2300Expression::make_float(const mpfr_t* val, Type* type, Location location)
e440a328 2301{
2302 return new Float_expression(val, type, location);
2303}
2304
2305// Complex numbers.
2306
2307class Complex_expression : public Expression
2308{
2309 public:
fcbea5e4 2310 Complex_expression(const mpc_t* val, Type* type, Location location)
e440a328 2311 : Expression(EXPRESSION_COMPLEX, location),
2312 type_(type)
2313 {
fcbea5e4 2314 mpc_init2(this->val_, mpc_precision);
2315 mpc_set(this->val_, *val, MPC_RNDNN);
e440a328 2316 }
2317
fcbea5e4 2318 // Write VAL to string dump.
e440a328 2319 static void
fcbea5e4 2320 export_complex(String_dump* exp, const mpc_t val);
e440a328 2321
d751bb78 2322 // Write REAL/IMAG to dump context.
2323 static void
fcbea5e4 2324 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
d751bb78 2325
e440a328 2326 protected:
2327 bool
2328 do_is_constant() const
2329 { return true; }
2330
0e168074 2331 bool
2332 do_is_immutable() const
2333 { return true; }
2334
e440a328 2335 bool
0c77715b 2336 do_numeric_constant_value(Numeric_constant* nc) const
2337 {
fcbea5e4 2338 nc->set_complex(this->type_, this->val_);
0c77715b 2339 return true;
2340 }
e440a328 2341
2342 Type*
2343 do_type();
2344
2345 void
2346 do_determine_type(const Type_context*);
2347
2348 void
2349 do_check_types(Gogo*);
2350
2351 Expression*
2352 do_copy()
2353 {
fcbea5e4 2354 return Expression::make_complex(&this->val_, this->type_,
e440a328 2355 this->location());
2356 }
2357
ea664253 2358 Bexpression*
2359 do_get_backend(Translate_context*);
e440a328 2360
2361 void
2362 do_export(Export*) const;
2363
d751bb78 2364 void
2365 do_dump_expression(Ast_dump_context*) const;
2366
e440a328 2367 private:
fcbea5e4 2368 // The complex value.
2369 mpc_t val_;
e440a328 2370 // The type if known.
2371 Type* type_;
2372};
2373
e440a328 2374// Return the current type. If we haven't set the type yet, we return
2375// an abstract complex type.
2376
2377Type*
2378Complex_expression::do_type()
2379{
2380 if (this->type_ == NULL)
2381 this->type_ = Type::make_abstract_complex_type();
2382 return this->type_;
2383}
2384
2385// Set the type of the complex value. Here we may switch from an
2386// abstract type to a real type.
2387
2388void
2389Complex_expression::do_determine_type(const Type_context* context)
2390{
2391 if (this->type_ != NULL && !this->type_->is_abstract())
2392 ;
2393 else if (context->type != NULL
2394 && context->type->complex_type() != NULL)
2395 this->type_ = context->type;
2396 else if (!context->may_be_abstract)
48080209 2397 this->type_ = Type::lookup_complex_type("complex128");
e440a328 2398}
2399
e440a328 2400// Check the type of a complex value.
2401
2402void
2403Complex_expression::do_check_types(Gogo*)
2404{
0c77715b 2405 Type* type = this->type_;
2406 if (type == NULL)
e440a328 2407 return;
0c77715b 2408 Numeric_constant nc;
fcbea5e4 2409 nc.set_complex(NULL, this->val_);
0c77715b 2410 if (!nc.set_type(this->type_, true, this->location()))
e440a328 2411 this->set_is_error();
2412}
2413
ea664253 2414// Get the backend representation for a complex constant.
e440a328 2415
ea664253 2416Bexpression*
2417Complex_expression::do_get_backend(Translate_context* context)
e440a328 2418{
48c2a53a 2419 Type* resolved_type;
e440a328 2420 if (this->type_ != NULL && !this->type_->is_abstract())
48c2a53a 2421 resolved_type = this->type_;
2422 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2423 {
2424 // We are converting to an abstract integer type.
2425 resolved_type = Type::lookup_integer_type("int");
2426 }
2427 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2428 {
2429 // We are converting to an abstract float type.
2430 resolved_type = Type::lookup_float_type("float64");
2431 }
e440a328 2432 else
2433 {
2434 // If we still have an abstract type here, this this is being
2435 // used in a constant expression which didn't get reduced. We
2436 // just use complex128 and hope for the best.
48c2a53a 2437 resolved_type = Type::lookup_complex_type("complex128");
e440a328 2438 }
48c2a53a 2439
2440 Numeric_constant nc;
fcbea5e4 2441 nc.set_complex(resolved_type, this->val_);
ea664253 2442 return Expression::backend_numeric_constant_expression(context, &nc);
e440a328 2443}
2444
2445// Write REAL/IMAG to export data.
2446
2447void
fcbea5e4 2448Complex_expression::export_complex(String_dump* exp, const mpc_t val)
e440a328 2449{
fcbea5e4 2450 if (!mpfr_zero_p(mpc_realref(val)))
e440a328 2451 {
fcbea5e4 2452 Float_expression::export_float(exp, mpc_realref(val));
2453 if (mpfr_sgn(mpc_imagref(val)) > 0)
e440a328 2454 exp->write_c_string("+");
2455 }
fcbea5e4 2456 Float_expression::export_float(exp, mpc_imagref(val));
e440a328 2457 exp->write_c_string("i");
2458}
2459
2460// Export a complex number in a constant expression.
2461
2462void
2463Complex_expression::do_export(Export* exp) const
2464{
fcbea5e4 2465 Complex_expression::export_complex(exp, this->val_);
e440a328 2466 // A trailing space lets us reliably identify the end of the number.
2467 exp->write_c_string(" ");
2468}
2469
d751bb78 2470// Dump a complex expression to the dump file.
2471
2472void
2473Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2474{
fcbea5e4 2475 Complex_expression::export_complex(ast_dump_context, this->val_);
d751bb78 2476}
2477
e440a328 2478// Make a complex expression.
2479
2480Expression*
fcbea5e4 2481Expression::make_complex(const mpc_t* val, Type* type, Location location)
e440a328 2482{
fcbea5e4 2483 return new Complex_expression(val, type, location);
e440a328 2484}
2485
d5b605df 2486// Find a named object in an expression.
2487
2488class Find_named_object : public Traverse
2489{
2490 public:
2491 Find_named_object(Named_object* no)
2492 : Traverse(traverse_expressions),
2493 no_(no), found_(false)
2494 { }
2495
2496 // Whether we found the object.
2497 bool
2498 found() const
2499 { return this->found_; }
2500
2501 protected:
2502 int
2503 expression(Expression**);
2504
2505 private:
2506 // The object we are looking for.
2507 Named_object* no_;
2508 // Whether we found it.
2509 bool found_;
2510};
2511
e440a328 2512// A reference to a const in an expression.
2513
2514class Const_expression : public Expression
2515{
2516 public:
b13c66cd 2517 Const_expression(Named_object* constant, Location location)
e440a328 2518 : Expression(EXPRESSION_CONST_REFERENCE, location),
13e818f5 2519 constant_(constant), type_(NULL), seen_(false)
e440a328 2520 { }
2521
d5b605df 2522 Named_object*
2523 named_object()
2524 { return this->constant_; }
2525
a7f064d5 2526 // Check that the initializer does not refer to the constant itself.
2527 void
2528 check_for_init_loop();
2529
e440a328 2530 protected:
ba4aedd4 2531 int
2532 do_traverse(Traverse*);
2533
e440a328 2534 Expression*
ceeb4318 2535 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 2536
2537 bool
2538 do_is_constant() const
2539 { return true; }
2540
0e168074 2541 bool
2542 do_is_immutable() const
2543 { return true; }
2544
e440a328 2545 bool
0c77715b 2546 do_numeric_constant_value(Numeric_constant* nc) const;
e440a328 2547
2548 bool
af6b489a 2549 do_string_constant_value(std::string* val) const;
e440a328 2550
2551 Type*
2552 do_type();
2553
2554 // The type of a const is set by the declaration, not the use.
2555 void
2556 do_determine_type(const Type_context*);
2557
2558 void
2559 do_check_types(Gogo*);
2560
2561 Expression*
2562 do_copy()
2563 { return this; }
2564
ea664253 2565 Bexpression*
2566 do_get_backend(Translate_context* context);
e440a328 2567
2568 // When exporting a reference to a const as part of a const
2569 // expression, we export the value. We ignore the fact that it has
2570 // a name.
2571 void
2572 do_export(Export* exp) const
2573 { this->constant_->const_value()->expr()->export_expression(exp); }
2574
d751bb78 2575 void
2576 do_dump_expression(Ast_dump_context*) const;
2577
e440a328 2578 private:
2579 // The constant.
2580 Named_object* constant_;
2581 // The type of this reference. This is used if the constant has an
2582 // abstract type.
2583 Type* type_;
13e818f5 2584 // Used to prevent infinite recursion when a constant incorrectly
2585 // refers to itself.
2586 mutable bool seen_;
e440a328 2587};
2588
ba4aedd4 2589// Traversal.
2590
2591int
2592Const_expression::do_traverse(Traverse* traverse)
2593{
2594 if (this->type_ != NULL)
2595 return Type::traverse(this->type_, traverse);
2596 return TRAVERSE_CONTINUE;
2597}
2598
e440a328 2599// Lower a constant expression. This is where we convert the
2600// predeclared constant iota into an integer value.
2601
2602Expression*
ceeb4318 2603Const_expression::do_lower(Gogo* gogo, Named_object*,
2604 Statement_inserter*, int iota_value)
e440a328 2605{
2606 if (this->constant_->const_value()->expr()->classification()
2607 == EXPRESSION_IOTA)
2608 {
2609 if (iota_value == -1)
2610 {
2611 error_at(this->location(),
2612 "iota is only defined in const declarations");
2613 iota_value = 0;
2614 }
e67508fa 2615 return Expression::make_integer_ul(iota_value, NULL, this->location());
e440a328 2616 }
2617
2618 // Make sure that the constant itself has been lowered.
2619 gogo->lower_constant(this->constant_);
2620
2621 return this;
2622}
2623
0c77715b 2624// Return a numeric constant value.
e440a328 2625
2626bool
0c77715b 2627Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 2628{
13e818f5 2629 if (this->seen_)
2630 return false;
2631
e440a328 2632 Expression* e = this->constant_->const_value()->expr();
0c77715b 2633
13e818f5 2634 this->seen_ = true;
2635
0c77715b 2636 bool r = e->numeric_constant_value(nc);
e440a328 2637
13e818f5 2638 this->seen_ = false;
2639
e440a328 2640 Type* ctype;
2641 if (this->type_ != NULL)
2642 ctype = this->type_;
2643 else
2644 ctype = this->constant_->const_value()->type();
e440a328 2645 if (r && ctype != NULL)
2646 {
0c77715b 2647 if (!nc->set_type(ctype, false, this->location()))
e440a328 2648 return false;
e440a328 2649 }
e440a328 2650
e440a328 2651 return r;
2652}
2653
af6b489a 2654bool
2655Const_expression::do_string_constant_value(std::string* val) const
2656{
2657 if (this->seen_)
2658 return false;
2659
2660 Expression* e = this->constant_->const_value()->expr();
2661
2662 this->seen_ = true;
2663 bool ok = e->string_constant_value(val);
2664 this->seen_ = false;
2665
2666 return ok;
2667}
2668
e440a328 2669// Return the type of the const reference.
2670
2671Type*
2672Const_expression::do_type()
2673{
2674 if (this->type_ != NULL)
2675 return this->type_;
13e818f5 2676
2f78f012 2677 Named_constant* nc = this->constant_->const_value();
2678
2679 if (this->seen_ || nc->lowering())
13e818f5 2680 {
2681 this->report_error(_("constant refers to itself"));
2682 this->type_ = Type::make_error_type();
2683 return this->type_;
2684 }
2685
2686 this->seen_ = true;
2687
e440a328 2688 Type* ret = nc->type();
13e818f5 2689
e440a328 2690 if (ret != NULL)
13e818f5 2691 {
2692 this->seen_ = false;
2693 return ret;
2694 }
2695
e440a328 2696 // During parsing, a named constant may have a NULL type, but we
2697 // must not return a NULL type here.
13e818f5 2698 ret = nc->expr()->type();
2699
2700 this->seen_ = false;
2701
2702 return ret;
e440a328 2703}
2704
2705// Set the type of the const reference.
2706
2707void
2708Const_expression::do_determine_type(const Type_context* context)
2709{
2710 Type* ctype = this->constant_->const_value()->type();
2711 Type* cetype = (ctype != NULL
2712 ? ctype
2713 : this->constant_->const_value()->expr()->type());
2714 if (ctype != NULL && !ctype->is_abstract())
2715 ;
2716 else if (context->type != NULL
0c77715b 2717 && context->type->is_numeric_type()
2718 && cetype->is_numeric_type())
e440a328 2719 this->type_ = context->type;
2720 else if (context->type != NULL
2721 && context->type->is_string_type()
2722 && cetype->is_string_type())
2723 this->type_ = context->type;
2724 else if (context->type != NULL
2725 && context->type->is_boolean_type()
2726 && cetype->is_boolean_type())
2727 this->type_ = context->type;
2728 else if (!context->may_be_abstract)
2729 {
2730 if (cetype->is_abstract())
2731 cetype = cetype->make_non_abstract_type();
2732 this->type_ = cetype;
2733 }
2734}
2735
a7f064d5 2736// Check for a loop in which the initializer of a constant refers to
2737// the constant itself.
e440a328 2738
2739void
a7f064d5 2740Const_expression::check_for_init_loop()
e440a328 2741{
5c13bd80 2742 if (this->type_ != NULL && this->type_->is_error())
d5b605df 2743 return;
2744
a7f064d5 2745 if (this->seen_)
2746 {
2747 this->report_error(_("constant refers to itself"));
2748 this->type_ = Type::make_error_type();
2749 return;
2750 }
2751
d5b605df 2752 Expression* init = this->constant_->const_value()->expr();
2753 Find_named_object find_named_object(this->constant_);
a7f064d5 2754
2755 this->seen_ = true;
d5b605df 2756 Expression::traverse(&init, &find_named_object);
a7f064d5 2757 this->seen_ = false;
2758
d5b605df 2759 if (find_named_object.found())
2760 {
5c13bd80 2761 if (this->type_ == NULL || !this->type_->is_error())
a7f064d5 2762 {
2763 this->report_error(_("constant refers to itself"));
2764 this->type_ = Type::make_error_type();
2765 }
d5b605df 2766 return;
2767 }
a7f064d5 2768}
2769
2770// Check types of a const reference.
2771
2772void
2773Const_expression::do_check_types(Gogo*)
2774{
5c13bd80 2775 if (this->type_ != NULL && this->type_->is_error())
a7f064d5 2776 return;
2777
2778 this->check_for_init_loop();
d5b605df 2779
0c77715b 2780 // Check that numeric constant fits in type.
2781 if (this->type_ != NULL && this->type_->is_numeric_type())
e440a328 2782 {
0c77715b 2783 Numeric_constant nc;
2784 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
e440a328 2785 {
0c77715b 2786 if (!nc.set_type(this->type_, true, this->location()))
2787 this->set_is_error();
e440a328 2788 }
e440a328 2789 }
2790}
2791
ea664253 2792// Return the backend representation for a const reference.
e440a328 2793
ea664253 2794Bexpression*
2795Const_expression::do_get_backend(Translate_context* context)
e440a328 2796{
2c809f8f 2797 if (this->type_ != NULL && this->type_->is_error())
ea664253 2798 return context->backend()->error_expression();
e440a328 2799
2800 // If the type has been set for this expression, but the underlying
2801 // object is an abstract int or float, we try to get the abstract
2802 // value. Otherwise we may lose something in the conversion.
f2de4532 2803 Expression* expr = this->constant_->const_value()->expr();
e440a328 2804 if (this->type_ != NULL
0c77715b 2805 && this->type_->is_numeric_type()
a68492b4 2806 && (this->constant_->const_value()->type() == NULL
2807 || this->constant_->const_value()->type()->is_abstract()))
e440a328 2808 {
0c77715b 2809 Numeric_constant nc;
2810 if (expr->numeric_constant_value(&nc)
2811 && nc.set_type(this->type_, false, this->location()))
e440a328 2812 {
0c77715b 2813 Expression* e = nc.expression(this->location());
ea664253 2814 return e->get_backend(context);
e440a328 2815 }
e440a328 2816 }
2817
2c809f8f 2818 if (this->type_ != NULL)
f2de4532 2819 expr = Expression::make_cast(this->type_, expr, this->location());
ea664253 2820 return expr->get_backend(context);
e440a328 2821}
2822
d751bb78 2823// Dump ast representation for constant expression.
2824
2825void
2826Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2827{
2828 ast_dump_context->ostream() << this->constant_->name();
2829}
2830
e440a328 2831// Make a reference to a constant in an expression.
2832
2833Expression*
2834Expression::make_const_reference(Named_object* constant,
b13c66cd 2835 Location location)
e440a328 2836{
2837 return new Const_expression(constant, location);
2838}
2839
d5b605df 2840// Find a named object in an expression.
2841
2842int
2843Find_named_object::expression(Expression** pexpr)
2844{
2845 switch ((*pexpr)->classification())
2846 {
2847 case Expression::EXPRESSION_CONST_REFERENCE:
a7f064d5 2848 {
2849 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2850 if (ce->named_object() == this->no_)
2851 break;
2852
2853 // We need to check a constant initializer explicitly, as
2854 // loops here will not be caught by the loop checking for
2855 // variable initializers.
2856 ce->check_for_init_loop();
2857
2858 return TRAVERSE_CONTINUE;
2859 }
2860
d5b605df 2861 case Expression::EXPRESSION_VAR_REFERENCE:
2862 if ((*pexpr)->var_expression()->named_object() == this->no_)
2863 break;
2864 return TRAVERSE_CONTINUE;
2865 case Expression::EXPRESSION_FUNC_REFERENCE:
2866 if ((*pexpr)->func_expression()->named_object() == this->no_)
2867 break;
2868 return TRAVERSE_CONTINUE;
2869 default:
2870 return TRAVERSE_CONTINUE;
2871 }
2872 this->found_ = true;
2873 return TRAVERSE_EXIT;
2874}
2875
e440a328 2876// The nil value.
2877
2878class Nil_expression : public Expression
2879{
2880 public:
b13c66cd 2881 Nil_expression(Location location)
e440a328 2882 : Expression(EXPRESSION_NIL, location)
2883 { }
2884
2885 static Expression*
2886 do_import(Import*);
2887
2888 protected:
2889 bool
2890 do_is_constant() const
2891 { return true; }
2892
f9ca30f9 2893 bool
2894 do_is_immutable() const
2895 { return true; }
2896
e440a328 2897 Type*
2898 do_type()
2899 { return Type::make_nil_type(); }
2900
2901 void
2902 do_determine_type(const Type_context*)
2903 { }
2904
2905 Expression*
2906 do_copy()
2907 { return this; }
2908
ea664253 2909 Bexpression*
2910 do_get_backend(Translate_context* context)
2911 { return context->backend()->nil_pointer_expression(); }
e440a328 2912
2913 void
2914 do_export(Export* exp) const
2915 { exp->write_c_string("nil"); }
d751bb78 2916
2917 void
2918 do_dump_expression(Ast_dump_context* ast_dump_context) const
2919 { ast_dump_context->ostream() << "nil"; }
e440a328 2920};
2921
2922// Import a nil expression.
2923
2924Expression*
2925Nil_expression::do_import(Import* imp)
2926{
2927 imp->require_c_string("nil");
2928 return Expression::make_nil(imp->location());
2929}
2930
2931// Make a nil expression.
2932
2933Expression*
b13c66cd 2934Expression::make_nil(Location location)
e440a328 2935{
2936 return new Nil_expression(location);
2937}
2938
2939// The value of the predeclared constant iota. This is little more
2940// than a marker. This will be lowered to an integer in
2941// Const_expression::do_lower, which is where we know the value that
2942// it should have.
2943
2944class Iota_expression : public Parser_expression
2945{
2946 public:
b13c66cd 2947 Iota_expression(Location location)
e440a328 2948 : Parser_expression(EXPRESSION_IOTA, location)
2949 { }
2950
2951 protected:
2952 Expression*
ceeb4318 2953 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
c3e6f413 2954 { go_unreachable(); }
e440a328 2955
2956 // There should only ever be one of these.
2957 Expression*
2958 do_copy()
c3e6f413 2959 { go_unreachable(); }
d751bb78 2960
2961 void
2962 do_dump_expression(Ast_dump_context* ast_dump_context) const
2963 { ast_dump_context->ostream() << "iota"; }
e440a328 2964};
2965
2966// Make an iota expression. This is only called for one case: the
2967// value of the predeclared constant iota.
2968
2969Expression*
2970Expression::make_iota()
2971{
b13c66cd 2972 static Iota_expression iota_expression(Linemap::unknown_location());
e440a328 2973 return &iota_expression;
2974}
2975
2976// A type conversion expression.
2977
2978class Type_conversion_expression : public Expression
2979{
2980 public:
2981 Type_conversion_expression(Type* type, Expression* expr,
b13c66cd 2982 Location location)
e440a328 2983 : Expression(EXPRESSION_CONVERSION, location),
2984 type_(type), expr_(expr), may_convert_function_types_(false)
2985 { }
2986
2987 // Return the type to which we are converting.
2988 Type*
2989 type() const
2990 { return this->type_; }
2991
2992 // Return the expression which we are converting.
2993 Expression*
2994 expr() const
2995 { return this->expr_; }
2996
2997 // Permit converting from one function type to another. This is
2998 // used internally for method expressions.
2999 void
3000 set_may_convert_function_types()
3001 {
3002 this->may_convert_function_types_ = true;
3003 }
3004
3005 // Import a type conversion expression.
3006 static Expression*
3007 do_import(Import*);
3008
3009 protected:
3010 int
3011 do_traverse(Traverse* traverse);
3012
3013 Expression*
ceeb4318 3014 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 3015
35a54f17 3016 Expression*
3017 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3018
e440a328 3019 bool
1ca01a59 3020 do_is_constant() const;
e440a328 3021
0e168074 3022 bool
3023 do_is_immutable() const;
3024
e440a328 3025 bool
0c77715b 3026 do_numeric_constant_value(Numeric_constant*) const;
e440a328 3027
3028 bool
3029 do_string_constant_value(std::string*) const;
3030
3031 Type*
3032 do_type()
3033 { return this->type_; }
3034
3035 void
3036 do_determine_type(const Type_context*)
3037 {
3038 Type_context subcontext(this->type_, false);
3039 this->expr_->determine_type(&subcontext);
3040 }
3041
3042 void
3043 do_check_types(Gogo*);
3044
3045 Expression*
3046 do_copy()
3047 {
3048 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3049 this->location());
3050 }
3051
ea664253 3052 Bexpression*
3053 do_get_backend(Translate_context* context);
e440a328 3054
3055 void
3056 do_export(Export*) const;
3057
d751bb78 3058 void
3059 do_dump_expression(Ast_dump_context*) const;
3060
e440a328 3061 private:
3062 // The type to convert to.
3063 Type* type_;
3064 // The expression to convert.
3065 Expression* expr_;
3066 // True if this is permitted to convert function types. This is
3067 // used internally for method expressions.
3068 bool may_convert_function_types_;
3069};
3070
3071// Traversal.
3072
3073int
3074Type_conversion_expression::do_traverse(Traverse* traverse)
3075{
3076 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3077 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3078 return TRAVERSE_EXIT;
3079 return TRAVERSE_CONTINUE;
3080}
3081
3082// Convert to a constant at lowering time.
3083
3084Expression*
ceeb4318 3085Type_conversion_expression::do_lower(Gogo*, Named_object*,
3086 Statement_inserter*, int)
e440a328 3087{
3088 Type* type = this->type_;
3089 Expression* val = this->expr_;
b13c66cd 3090 Location location = this->location();
e440a328 3091
0c77715b 3092 if (type->is_numeric_type())
e440a328 3093 {
0c77715b 3094 Numeric_constant nc;
3095 if (val->numeric_constant_value(&nc))
e440a328 3096 {
0c77715b 3097 if (!nc.set_type(type, true, location))
3098 return Expression::make_error(location);
3099 return nc.expression(location);
e440a328 3100 }
e440a328 3101 }
3102
55072f2b 3103 if (type->is_slice_type())
e440a328 3104 {
3105 Type* element_type = type->array_type()->element_type()->forwarded();
60963afd 3106 bool is_byte = (element_type->integer_type() != NULL
3107 && element_type->integer_type()->is_byte());
3108 bool is_rune = (element_type->integer_type() != NULL
3109 && element_type->integer_type()->is_rune());
3110 if (is_byte || is_rune)
e440a328 3111 {
3112 std::string s;
3113 if (val->string_constant_value(&s))
3114 {
3115 Expression_list* vals = new Expression_list();
3116 if (is_byte)
3117 {
3118 for (std::string::const_iterator p = s.begin();
3119 p != s.end();
3120 p++)
3121 {
e67508fa 3122 unsigned char c = static_cast<unsigned char>(*p);
3123 vals->push_back(Expression::make_integer_ul(c,
3124 element_type,
3125 location));
e440a328 3126 }
3127 }
3128 else
3129 {
3130 const char *p = s.data();
3131 const char *pend = s.data() + s.length();
3132 while (p < pend)
3133 {
3134 unsigned int c;
3135 int adv = Lex::fetch_char(p, &c);
3136 if (adv == 0)
3137 {
3138 warning_at(this->location(), 0,
3139 "invalid UTF-8 encoding");
3140 adv = 1;
3141 }
3142 p += adv;
e67508fa 3143 vals->push_back(Expression::make_integer_ul(c,
3144 element_type,
3145 location));
e440a328 3146 }
3147 }
3148
3149 return Expression::make_slice_composite_literal(type, vals,
3150 location);
3151 }
3152 }
3153 }
3154
3155 return this;
3156}
3157
35a54f17 3158// Flatten a type conversion by using a temporary variable for the slice
3159// in slice to string conversions.
3160
3161Expression*
3162Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3163 Statement_inserter* inserter)
3164{
2c809f8f 3165 if (((this->type()->is_string_type()
3166 && this->expr_->type()->is_slice_type())
8ba8cc87 3167 || this->expr_->type()->interface_type() != NULL)
35a54f17 3168 && !this->expr_->is_variable())
3169 {
3170 Temporary_statement* temp =
3171 Statement::make_temporary(NULL, this->expr_, this->location());
3172 inserter->insert(temp);
3173 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3174 }
3175 return this;
3176}
3177
1ca01a59 3178// Return whether a type conversion is a constant.
3179
3180bool
3181Type_conversion_expression::do_is_constant() const
3182{
3183 if (!this->expr_->is_constant())
3184 return false;
3185
3186 // A conversion to a type that may not be used as a constant is not
3187 // a constant. For example, []byte(nil).
3188 Type* type = this->type_;
3189 if (type->integer_type() == NULL
3190 && type->float_type() == NULL
3191 && type->complex_type() == NULL
3192 && !type->is_boolean_type()
3193 && !type->is_string_type())
3194 return false;
3195
3196 return true;
3197}
3198
0e168074 3199// Return whether a type conversion is immutable.
3200
3201bool
3202Type_conversion_expression::do_is_immutable() const
3203{
3204 Type* type = this->type_;
3205 Type* expr_type = this->expr_->type();
3206
3207 if (type->interface_type() != NULL
3208 || expr_type->interface_type() != NULL)
3209 return false;
3210
3211 if (!this->expr_->is_immutable())
3212 return false;
3213
3214 if (Type::are_identical(type, expr_type, false, NULL))
3215 return true;
3216
3217 return type->is_basic_type() && expr_type->is_basic_type();
3218}
3219
0c77715b 3220// Return the constant numeric value if there is one.
e440a328 3221
3222bool
0c77715b 3223Type_conversion_expression::do_numeric_constant_value(
3224 Numeric_constant* nc) const
e440a328 3225{
0c77715b 3226 if (!this->type_->is_numeric_type())
e440a328 3227 return false;
0c77715b 3228 if (!this->expr_->numeric_constant_value(nc))
e440a328 3229 return false;
0c77715b 3230 return nc->set_type(this->type_, false, this->location());
e440a328 3231}
3232
3233// Return the constant string value if there is one.
3234
3235bool
3236Type_conversion_expression::do_string_constant_value(std::string* val) const
3237{
3238 if (this->type_->is_string_type()
3239 && this->expr_->type()->integer_type() != NULL)
3240 {
0c77715b 3241 Numeric_constant nc;
3242 if (this->expr_->numeric_constant_value(&nc))
e440a328 3243 {
0c77715b 3244 unsigned long ival;
3245 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
e440a328 3246 {
0c77715b 3247 val->clear();
3248 Lex::append_char(ival, true, val, this->location());
e440a328 3249 return true;
3250 }
3251 }
e440a328 3252 }
3253
3254 // FIXME: Could handle conversion from const []int here.
3255
3256 return false;
3257}
3258
3259// Check that types are convertible.
3260
3261void
3262Type_conversion_expression::do_check_types(Gogo*)
3263{
3264 Type* type = this->type_;
3265 Type* expr_type = this->expr_->type();
3266 std::string reason;
3267
5c13bd80 3268 if (type->is_error() || expr_type->is_error())
842f6425 3269 {
842f6425 3270 this->set_is_error();
3271 return;
3272 }
3273
e440a328 3274 if (this->may_convert_function_types_
3275 && type->function_type() != NULL
3276 && expr_type->function_type() != NULL)
3277 return;
3278
3279 if (Type::are_convertible(type, expr_type, &reason))
3280 return;
3281
3282 error_at(this->location(), "%s", reason.c_str());
3283 this->set_is_error();
3284}
3285
ea664253 3286// Get the backend representation for a type conversion.
e440a328 3287
ea664253 3288Bexpression*
3289Type_conversion_expression::do_get_backend(Translate_context* context)
e440a328 3290{
e440a328 3291 Type* type = this->type_;
3292 Type* expr_type = this->expr_->type();
2c809f8f 3293
3294 Gogo* gogo = context->gogo();
3295 Btype* btype = type->get_backend(gogo);
ea664253 3296 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3297 Location loc = this->location();
3298
3299 if (Type::are_identical(type, expr_type, false, NULL))
ea664253 3300 return gogo->backend()->convert_expression(btype, bexpr, loc);
2c809f8f 3301 else if (type->interface_type() != NULL
3302 || expr_type->interface_type() != NULL)
e440a328 3303 {
2c809f8f 3304 Expression* conversion =
3305 Expression::convert_for_assignment(gogo, type, this->expr_,
3306 this->location());
ea664253 3307 return conversion->get_backend(context);
e440a328 3308 }
3309 else if (type->is_string_type()
3310 && expr_type->integer_type() != NULL)
3311 {
2c809f8f 3312 mpz_t intval;
3313 Numeric_constant nc;
3314 if (this->expr_->numeric_constant_value(&nc)
3315 && nc.to_int(&intval)
3316 && mpz_fits_ushort_p(intval))
e440a328 3317 {
e440a328 3318 std::string s;
2c809f8f 3319 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3320 mpz_clear(intval);
3321 Expression* se = Expression::make_string(s, loc);
ea664253 3322 return se->get_backend(context);
e440a328 3323 }
3324
f16ab008 3325 Expression* i2s_expr =
2c809f8f 3326 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
ea664253 3327 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
e440a328 3328 }
55072f2b 3329 else if (type->is_string_type() && expr_type->is_slice_type())
e440a328 3330 {
55072f2b 3331 Array_type* a = expr_type->array_type();
e440a328 3332 Type* e = a->element_type()->forwarded();
c484d925 3333 go_assert(e->integer_type() != NULL);
35a54f17 3334 go_assert(this->expr_->is_variable());
3335
3336 Runtime::Function code;
60963afd 3337 if (e->integer_type()->is_byte())
35a54f17 3338 code = Runtime::BYTE_ARRAY_TO_STRING;
e440a328 3339 else
35a54f17 3340 {
3341 go_assert(e->integer_type()->is_rune());
3342 code = Runtime::INT_ARRAY_TO_STRING;
3343 }
3344 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3345 Expression* len = a->get_length(gogo, this->expr_);
ea664253 3346 return Runtime::make_call(code, loc, 2, valptr,
3347 len)->get_backend(context);
e440a328 3348 }
411eb89e 3349 else if (type->is_slice_type() && expr_type->is_string_type())
e440a328 3350 {
3351 Type* e = type->array_type()->element_type()->forwarded();
c484d925 3352 go_assert(e->integer_type() != NULL);
6c252e42 3353
2c809f8f 3354 Runtime::Function code;
60963afd 3355 if (e->integer_type()->is_byte())
2c809f8f 3356 code = Runtime::STRING_TO_BYTE_ARRAY;
e440a328 3357 else
3358 {
60963afd 3359 go_assert(e->integer_type()->is_rune());
2c809f8f 3360 code = Runtime::STRING_TO_INT_ARRAY;
e440a328 3361 }
2c809f8f 3362 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
ea664253 3363 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
2c809f8f 3364 }
3365 else if (type->is_numeric_type())
3366 {
3367 go_assert(Type::are_convertible(type, expr_type, NULL));
ea664253 3368 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3369 }
3370 else if ((type->is_unsafe_pointer_type()
2c809f8f 3371 && (expr_type->points_to() != NULL
3372 || expr_type->integer_type()))
3373 || (expr_type->is_unsafe_pointer_type()
3374 && type->points_to() != NULL)
3375 || (this->may_convert_function_types_
3376 && type->function_type() != NULL
3377 && expr_type->function_type() != NULL))
ea664253 3378 return gogo->backend()->convert_expression(btype, bexpr, loc);
e440a328 3379 else
2c809f8f 3380 {
3381 Expression* conversion =
3382 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
ea664253 3383 return conversion->get_backend(context);
2c809f8f 3384 }
e440a328 3385}
3386
3387// Output a type conversion in a constant expression.
3388
3389void
3390Type_conversion_expression::do_export(Export* exp) const
3391{
3392 exp->write_c_string("convert(");
3393 exp->write_type(this->type_);
3394 exp->write_c_string(", ");
3395 this->expr_->export_expression(exp);
3396 exp->write_c_string(")");
3397}
3398
3399// Import a type conversion or a struct construction.
3400
3401Expression*
3402Type_conversion_expression::do_import(Import* imp)
3403{
3404 imp->require_c_string("convert(");
3405 Type* type = imp->read_type();
3406 imp->require_c_string(", ");
3407 Expression* val = Expression::import_expression(imp);
3408 imp->require_c_string(")");
3409 return Expression::make_cast(type, val, imp->location());
3410}
3411
d751bb78 3412// Dump ast representation for a type conversion expression.
3413
3414void
3415Type_conversion_expression::do_dump_expression(
3416 Ast_dump_context* ast_dump_context) const
3417{
3418 ast_dump_context->dump_type(this->type_);
3419 ast_dump_context->ostream() << "(";
3420 ast_dump_context->dump_expression(this->expr_);
3421 ast_dump_context->ostream() << ") ";
3422}
3423
e440a328 3424// Make a type cast expression.
3425
3426Expression*
b13c66cd 3427Expression::make_cast(Type* type, Expression* val, Location location)
e440a328 3428{
3429 if (type->is_error_type() || val->is_error_expression())
3430 return Expression::make_error(location);
3431 return new Type_conversion_expression(type, val, location);
3432}
3433
9581e91d 3434// An unsafe type conversion, used to pass values to builtin functions.
3435
3436class Unsafe_type_conversion_expression : public Expression
3437{
3438 public:
3439 Unsafe_type_conversion_expression(Type* type, Expression* expr,
b13c66cd 3440 Location location)
9581e91d 3441 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3442 type_(type), expr_(expr)
3443 { }
3444
3445 protected:
3446 int
3447 do_traverse(Traverse* traverse);
3448
aa5ae575 3449 bool
3450 do_is_immutable() const;
3451
9581e91d 3452 Type*
3453 do_type()
3454 { return this->type_; }
3455
3456 void
3457 do_determine_type(const Type_context*)
a9182619 3458 { this->expr_->determine_type_no_context(); }
9581e91d 3459
3460 Expression*
3461 do_copy()
3462 {
3463 return new Unsafe_type_conversion_expression(this->type_,
3464 this->expr_->copy(),
3465 this->location());
3466 }
3467
ea664253 3468 Bexpression*
3469 do_get_backend(Translate_context*);
9581e91d 3470
d751bb78 3471 void
3472 do_dump_expression(Ast_dump_context*) const;
3473
9581e91d 3474 private:
3475 // The type to convert to.
3476 Type* type_;
3477 // The expression to convert.
3478 Expression* expr_;
3479};
3480
3481// Traversal.
3482
3483int
3484Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3485{
3486 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3487 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3488 return TRAVERSE_EXIT;
3489 return TRAVERSE_CONTINUE;
3490}
3491
aa5ae575 3492// Return whether an unsafe type conversion is immutable.
3493
3494bool
3495Unsafe_type_conversion_expression::do_is_immutable() const
3496{
3497 Type* type = this->type_;
3498 Type* expr_type = this->expr_->type();
3499
3500 if (type->interface_type() != NULL
3501 || expr_type->interface_type() != NULL)
3502 return false;
3503
3504 if (!this->expr_->is_immutable())
3505 return false;
3506
3507 if (Type::are_convertible(type, expr_type, NULL))
3508 return true;
3509
3510 return type->is_basic_type() && expr_type->is_basic_type();
3511}
3512
9581e91d 3513// Convert to backend representation.
3514
ea664253 3515Bexpression*
3516Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
9581e91d 3517{
3518 // We are only called for a limited number of cases.
3519
3520 Type* t = this->type_;
3521 Type* et = this->expr_->type();
2c809f8f 3522 if (t->array_type() != NULL)
3523 go_assert(et->array_type() != NULL
3524 && t->is_slice_type() == et->is_slice_type());
3525 else if (t->struct_type() != NULL)
9581e91d 3526 {
2c809f8f 3527 if (t->named_type() != NULL
3528 && et->named_type() != NULL
3529 && !Type::are_convertible(t, et, NULL))
3530 {
3531 go_assert(saw_errors());
ea664253 3532 return context->backend()->error_expression();
2c809f8f 3533 }
3534
3535 go_assert(et->struct_type() != NULL
3536 && Type::are_convertible(t, et, NULL));
3537 }
3538 else if (t->map_type() != NULL)
c484d925 3539 go_assert(et->map_type() != NULL);
9581e91d 3540 else if (t->channel_type() != NULL)
c484d925 3541 go_assert(et->channel_type() != NULL);
09ea332d 3542 else if (t->points_to() != NULL)
2c809f8f 3543 go_assert(et->points_to() != NULL
3544 || et->channel_type() != NULL
3545 || et->map_type() != NULL
3546 || et->function_type() != NULL
3547 || et->is_nil_type());
9581e91d 3548 else if (et->is_unsafe_pointer_type())
c484d925 3549 go_assert(t->points_to() != NULL);
2c809f8f 3550 else if (t->interface_type() != NULL)
9581e91d 3551 {
2c809f8f 3552 bool empty_iface = t->interface_type()->is_empty();
c484d925 3553 go_assert(et->interface_type() != NULL
2c809f8f 3554 && et->interface_type()->is_empty() == empty_iface);
9581e91d 3555 }
588e3cf9 3556 else if (t->integer_type() != NULL)
2c809f8f 3557 go_assert(et->is_boolean_type()
3558 || et->integer_type() != NULL
3559 || et->function_type() != NULL
3560 || et->points_to() != NULL
3561 || et->map_type() != NULL
8ba8cc87 3562 || et->channel_type() != NULL
3563 || et->is_nil_type());
9581e91d 3564 else
c3e6f413 3565 go_unreachable();
9581e91d 3566
2c809f8f 3567 Gogo* gogo = context->gogo();
3568 Btype* btype = t->get_backend(gogo);
ea664253 3569 Bexpression* bexpr = this->expr_->get_backend(context);
2c809f8f 3570 Location loc = this->location();
ea664253 3571 return gogo->backend()->convert_expression(btype, bexpr, loc);
9581e91d 3572}
3573
d751bb78 3574// Dump ast representation for an unsafe type conversion expression.
3575
3576void
3577Unsafe_type_conversion_expression::do_dump_expression(
3578 Ast_dump_context* ast_dump_context) const
3579{
3580 ast_dump_context->dump_type(this->type_);
3581 ast_dump_context->ostream() << "(";
3582 ast_dump_context->dump_expression(this->expr_);
3583 ast_dump_context->ostream() << ") ";
3584}
3585
9581e91d 3586// Make an unsafe type conversion expression.
3587
3588Expression*
3589Expression::make_unsafe_cast(Type* type, Expression* expr,
b13c66cd 3590 Location location)
9581e91d 3591{
3592 return new Unsafe_type_conversion_expression(type, expr, location);
3593}
3594
76f85fd6 3595// Class Unary_expression.
e440a328 3596
3597// If we are taking the address of a composite literal, and the
2c809f8f 3598// contents are not constant, then we want to make a heap expression
e440a328 3599// instead.
3600
3601Expression*
ceeb4318 3602Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 3603{
b13c66cd 3604 Location loc = this->location();
e440a328 3605 Operator op = this->op_;
3606 Expression* expr = this->expr_;
3607
3608 if (op == OPERATOR_MULT && expr->is_type_expression())
3609 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3610
3611 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3612 // moving x to the heap. FIXME: Is it worth doing a real escape
3613 // analysis here? This case is found in math/unsafe.go and is
3614 // therefore worth special casing.
3615 if (op == OPERATOR_MULT)
3616 {
3617 Expression* e = expr;
3618 while (e->classification() == EXPRESSION_CONVERSION)
3619 {
3620 Type_conversion_expression* te
3621 = static_cast<Type_conversion_expression*>(e);
3622 e = te->expr();
3623 }
3624
3625 if (e->classification() == EXPRESSION_UNARY)
3626 {
3627 Unary_expression* ue = static_cast<Unary_expression*>(e);
3628 if (ue->op_ == OPERATOR_AND)
3629 {
3630 if (e == expr)
3631 {
3632 // *&x == x.
f4dea966 3633 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3634 {
3635 error_at(ue->location(),
3636 "invalid operand for unary %<&%>");
3637 this->set_is_error();
3638 }
e440a328 3639 return ue->expr_;
3640 }
3641 ue->set_does_not_escape();
3642 }
3643 }
3644 }
3645
55661ce9 3646 // Catching an invalid indirection of unsafe.Pointer here avoid
3647 // having to deal with TYPE_VOID in other places.
3648 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3649 {
3650 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3651 return Expression::make_error(this->location());
3652 }
3653
d9f3743a 3654 // Check for an invalid pointer dereference. We need to do this
3655 // here because Unary_expression::do_type will return an error type
3656 // in this case. That can cause code to appear erroneous, and
3657 // therefore disappear at lowering time, without any error message.
3658 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3659 {
3660 this->report_error(_("expected pointer"));
3661 return Expression::make_error(this->location());
3662 }
3663
59a401fe 3664 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
e440a328 3665 {
0c77715b 3666 Numeric_constant nc;
3667 if (expr->numeric_constant_value(&nc))
e440a328 3668 {
0c77715b 3669 Numeric_constant result;
3670 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3671 return result.expression(loc);
e440a328 3672 }
3673 }
3674
3675 return this;
3676}
3677
f9ca30f9 3678// Flatten expression if a nil check must be performed and create temporary
3679// variables if necessary.
3680
3681Expression*
3682Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3683 Statement_inserter* inserter)
3684{
f4dea966 3685 if (this->is_error_expression() || this->expr_->is_error_expression())
3686 return Expression::make_error(this->location());
3687
f9ca30f9 3688 Location location = this->location();
3689 if (this->op_ == OPERATOR_MULT
3690 && !this->expr_->is_variable())
3691 {
3692 go_assert(this->expr_->type()->points_to() != NULL);
3693 Type* ptype = this->expr_->type()->points_to();
3694 if (!ptype->is_void_type())
3695 {
3696 Btype* pbtype = ptype->get_backend(gogo);
3697 size_t s = gogo->backend()->type_size(pbtype);
3698 if (s >= 4096 || this->issue_nil_check_)
3699 {
3700 Temporary_statement* temp =
3701 Statement::make_temporary(NULL, this->expr_, location);
3702 inserter->insert(temp);
3703 this->expr_ =
3704 Expression::make_temporary_reference(temp, location);
3705 }
3706 }
3707 }
3708
3709 if (this->create_temp_ && !this->expr_->is_variable())
3710 {
3711 Temporary_statement* temp =
3712 Statement::make_temporary(NULL, this->expr_, location);
3713 inserter->insert(temp);
3714 this->expr_ = Expression::make_temporary_reference(temp, location);
3715 }
3716
3717 return this;
3718}
3719
e440a328 3720// Return whether a unary expression is a constant.
3721
3722bool
3723Unary_expression::do_is_constant() const
3724{
3725 if (this->op_ == OPERATOR_MULT)
3726 {
3727 // Indirecting through a pointer is only constant if the object
3728 // to which the expression points is constant, but we currently
3729 // have no way to determine that.
3730 return false;
3731 }
3732 else if (this->op_ == OPERATOR_AND)
3733 {
3734 // Taking the address of a variable is constant if it is a
f9ca30f9 3735 // global variable, not constant otherwise. In other cases taking the
3736 // address is probably not a constant.
e440a328 3737 Var_expression* ve = this->expr_->var_expression();
3738 if (ve != NULL)
3739 {
3740 Named_object* no = ve->named_object();
3741 return no->is_variable() && no->var_value()->is_global();
3742 }
3743 return false;
3744 }
3745 else
3746 return this->expr_->is_constant();
3747}
3748
0c77715b 3749// Apply unary opcode OP to UNC, setting NC. Return true if this
3750// could be done, false if not. Issue errors for overflow.
e440a328 3751
3752bool
0c77715b 3753Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3754 Location location, Numeric_constant* nc)
e440a328 3755{
3756 switch (op)
3757 {
3758 case OPERATOR_PLUS:
0c77715b 3759 *nc = *unc;
e440a328 3760 return true;
0c77715b 3761
e440a328 3762 case OPERATOR_MINUS:
0c77715b 3763 if (unc->is_int() || unc->is_rune())
3764 break;
3765 else if (unc->is_float())
3766 {
3767 mpfr_t uval;
3768 unc->get_float(&uval);
3769 mpfr_t val;
3770 mpfr_init(val);
3771 mpfr_neg(val, uval, GMP_RNDN);
3772 nc->set_float(unc->type(), val);
3773 mpfr_clear(uval);
3774 mpfr_clear(val);
3775 return true;
3776 }
3777 else if (unc->is_complex())
3778 {
fcbea5e4 3779 mpc_t uval;
3780 unc->get_complex(&uval);
3781 mpc_t val;
3782 mpc_init2(val, mpc_precision);
3783 mpc_neg(val, uval, MPC_RNDNN);
3784 nc->set_complex(unc->type(), val);
3785 mpc_clear(uval);
3786 mpc_clear(val);
0c77715b 3787 return true;
3788 }
e440a328 3789 else
0c77715b 3790 go_unreachable();
e440a328 3791
0c77715b 3792 case OPERATOR_XOR:
3793 break;
68448d53 3794
59a401fe 3795 case OPERATOR_NOT:
e440a328 3796 case OPERATOR_AND:
3797 case OPERATOR_MULT:
3798 return false;
0c77715b 3799
e440a328 3800 default:
c3e6f413 3801 go_unreachable();
e440a328 3802 }
e440a328 3803
0c77715b 3804 if (!unc->is_int() && !unc->is_rune())
3805 return false;
3806
3807 mpz_t uval;
8387e1df 3808 if (unc->is_rune())
3809 unc->get_rune(&uval);
3810 else
3811 unc->get_int(&uval);
0c77715b 3812 mpz_t val;
3813 mpz_init(val);
e440a328 3814
e440a328 3815 switch (op)
3816 {
e440a328 3817 case OPERATOR_MINUS:
0c77715b 3818 mpz_neg(val, uval);
3819 break;
3820
e440a328 3821 case OPERATOR_NOT:
0c77715b 3822 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3823 break;
3824
e440a328 3825 case OPERATOR_XOR:
0c77715b 3826 {
3827 Type* utype = unc->type();
3828 if (utype->integer_type() == NULL
3829 || utype->integer_type()->is_abstract())
3830 mpz_com(val, uval);
3831 else
3832 {
3833 // The number of HOST_WIDE_INTs that it takes to represent
3834 // UVAL.
3835 size_t count = ((mpz_sizeinbase(uval, 2)
3836 + HOST_BITS_PER_WIDE_INT
3837 - 1)
3838 / HOST_BITS_PER_WIDE_INT);
e440a328 3839
0c77715b 3840 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3841 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3842
3843 size_t obits = utype->integer_type()->bits();
3844
3845 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3846 {
3847 mpz_t adj;
3848 mpz_init_set_ui(adj, 1);
3849 mpz_mul_2exp(adj, adj, obits);
3850 mpz_add(uval, uval, adj);
3851 mpz_clear(adj);
3852 }
3853
3854 size_t ecount;
3855 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3856 go_assert(ecount <= count);
3857
3858 // Trim down to the number of words required by the type.
3859 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3860 / HOST_BITS_PER_WIDE_INT);
3861 go_assert(ocount <= count);
3862
3863 for (size_t i = 0; i < ocount; ++i)
3864 phwi[i] = ~phwi[i];
3865
3866 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3867 if (clearbits != 0)
3868 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3869 >> clearbits);
3870
3871 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3872
3873 if (!utype->integer_type()->is_unsigned()
3874 && mpz_tstbit(val, obits - 1))
3875 {
3876 mpz_t adj;
3877 mpz_init_set_ui(adj, 1);
3878 mpz_mul_2exp(adj, adj, obits);
3879 mpz_sub(val, val, adj);
3880 mpz_clear(adj);
3881 }
3882
3883 delete[] phwi;
3884 }
3885 }
3886 break;
e440a328 3887
e440a328 3888 default:
c3e6f413 3889 go_unreachable();
e440a328 3890 }
e440a328 3891
0c77715b 3892 if (unc->is_rune())
3893 nc->set_rune(NULL, val);
e440a328 3894 else
0c77715b 3895 nc->set_int(NULL, val);
e440a328 3896
0c77715b 3897 mpz_clear(uval);
3898 mpz_clear(val);
e440a328 3899
0c77715b 3900 return nc->set_type(unc->type(), true, location);
e440a328 3901}
3902
0c77715b 3903// Return the integral constant value of a unary expression, if it has one.
e440a328 3904
3905bool
0c77715b 3906Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 3907{
0c77715b 3908 Numeric_constant unc;
3909 if (!this->expr_->numeric_constant_value(&unc))
3910 return false;
3911 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3912 nc);
e440a328 3913}
3914
3915// Return the type of a unary expression.
3916
3917Type*
3918Unary_expression::do_type()
3919{
3920 switch (this->op_)
3921 {
3922 case OPERATOR_PLUS:
3923 case OPERATOR_MINUS:
3924 case OPERATOR_NOT:
3925 case OPERATOR_XOR:
3926 return this->expr_->type();
3927
3928 case OPERATOR_AND:
3929 return Type::make_pointer_type(this->expr_->type());
3930
3931 case OPERATOR_MULT:
3932 {
3933 Type* subtype = this->expr_->type();
3934 Type* points_to = subtype->points_to();
3935 if (points_to == NULL)
3936 return Type::make_error_type();
3937 return points_to;
3938 }
3939
3940 default:
c3e6f413 3941 go_unreachable();
e440a328 3942 }
3943}
3944
3945// Determine abstract types for a unary expression.
3946
3947void
3948Unary_expression::do_determine_type(const Type_context* context)
3949{
3950 switch (this->op_)
3951 {
3952 case OPERATOR_PLUS:
3953 case OPERATOR_MINUS:
3954 case OPERATOR_NOT:
3955 case OPERATOR_XOR:
3956 this->expr_->determine_type(context);
3957 break;
3958
3959 case OPERATOR_AND:
3960 // Taking the address of something.
3961 {
3962 Type* subtype = (context->type == NULL
3963 ? NULL
3964 : context->type->points_to());
3965 Type_context subcontext(subtype, false);
3966 this->expr_->determine_type(&subcontext);
3967 }
3968 break;
3969
3970 case OPERATOR_MULT:
3971 // Indirecting through a pointer.
3972 {
3973 Type* subtype = (context->type == NULL
3974 ? NULL
3975 : Type::make_pointer_type(context->type));
3976 Type_context subcontext(subtype, false);
3977 this->expr_->determine_type(&subcontext);
3978 }
3979 break;
3980
3981 default:
c3e6f413 3982 go_unreachable();
e440a328 3983 }
3984}
3985
3986// Check types for a unary expression.
3987
3988void
3989Unary_expression::do_check_types(Gogo*)
3990{
9fe897ef 3991 Type* type = this->expr_->type();
5c13bd80 3992 if (type->is_error())
9fe897ef 3993 {
3994 this->set_is_error();
3995 return;
3996 }
3997
e440a328 3998 switch (this->op_)
3999 {
4000 case OPERATOR_PLUS:
4001 case OPERATOR_MINUS:
9fe897ef 4002 if (type->integer_type() == NULL
4003 && type->float_type() == NULL
4004 && type->complex_type() == NULL)
4005 this->report_error(_("expected numeric type"));
e440a328 4006 break;
4007
4008 case OPERATOR_NOT:
59a401fe 4009 if (!type->is_boolean_type())
4010 this->report_error(_("expected boolean type"));
4011 break;
4012
e440a328 4013 case OPERATOR_XOR:
9fe897ef 4014 if (type->integer_type() == NULL
4015 && !type->is_boolean_type())
4016 this->report_error(_("expected integer or boolean type"));
e440a328 4017 break;
4018
4019 case OPERATOR_AND:
4020 if (!this->expr_->is_addressable())
09ea332d 4021 {
4022 if (!this->create_temp_)
f4dea966 4023 {
4024 error_at(this->location(), "invalid operand for unary %<&%>");
4025 this->set_is_error();
4026 }
09ea332d 4027 }
e440a328 4028 else
56080003 4029 {
4030 this->expr_->address_taken(this->escapes_);
4031 this->expr_->issue_nil_check();
4032 }
e440a328 4033 break;
4034
4035 case OPERATOR_MULT:
4036 // Indirecting through a pointer.
9fe897ef 4037 if (type->points_to() == NULL)
4038 this->report_error(_("expected pointer"));
e440a328 4039 break;
4040
4041 default:
c3e6f413 4042 go_unreachable();
e440a328 4043 }
4044}
4045
ea664253 4046// Get the backend representation for a unary expression.
e440a328 4047
ea664253 4048Bexpression*
4049Unary_expression::do_get_backend(Translate_context* context)
e440a328 4050{
1b1f2abf 4051 Gogo* gogo = context->gogo();
e9d3367e 4052 Location loc = this->location();
4053
4054 // Taking the address of a set-and-use-temporary expression requires
4055 // setting the temporary and then taking the address.
4056 if (this->op_ == OPERATOR_AND)
4057 {
4058 Set_and_use_temporary_expression* sut =
4059 this->expr_->set_and_use_temporary_expression();
4060 if (sut != NULL)
4061 {
4062 Temporary_statement* temp = sut->temporary();
4063 Bvariable* bvar = temp->get_backend_variable(context);
f9ca30f9 4064 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
ea664253 4065 Bexpression* bval = sut->expression()->get_backend(context);
f9ca30f9 4066
4067 Bstatement* bassign =
4068 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4069 Bexpression* bvar_addr =
4070 gogo->backend()->address_expression(bvar_expr, loc);
ea664253 4071 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
e9d3367e 4072 }
4073 }
4074
f9ca30f9 4075 Bexpression* ret;
ea664253 4076 Bexpression* bexpr = this->expr_->get_backend(context);
f9ca30f9 4077 Btype* btype = this->expr_->type()->get_backend(gogo);
e440a328 4078 switch (this->op_)
4079 {
4080 case OPERATOR_PLUS:
f9ca30f9 4081 ret = bexpr;
4082 break;
e440a328 4083
4084 case OPERATOR_MINUS:
f9ca30f9 4085 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4086 ret = gogo->backend()->convert_expression(btype, ret, loc);
4087 break;
e440a328 4088
4089 case OPERATOR_NOT:
e440a328 4090 case OPERATOR_XOR:
f9ca30f9 4091 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4092 break;
e440a328 4093
4094 case OPERATOR_AND:
09ea332d 4095 if (!this->create_temp_)
4096 {
4097 // We should not see a non-constant constructor here; cases
4098 // where we would see one should have been moved onto the
4099 // heap at parse time. Taking the address of a nonconstant
4100 // constructor will not do what the programmer expects.
f9ca30f9 4101
4102 go_assert(!this->expr_->is_composite_literal()
4103 || this->expr_->is_immutable());
24060bf9 4104 if (this->expr_->classification() == EXPRESSION_UNARY)
4105 {
4106 Unary_expression* ue =
4107 static_cast<Unary_expression*>(this->expr_);
4108 go_assert(ue->op() != OPERATOR_AND);
4109 }
09ea332d 4110 }
e440a328 4111
f23d7786 4112 static unsigned int counter;
4113 char buf[100];
4114 if (this->is_gc_root_ || this->is_slice_init_)
76f85fd6 4115 {
f23d7786 4116 bool copy_to_heap = false;
4117 if (this->is_gc_root_)
4118 {
4119 // Build a decl for a GC root variable. GC roots are mutable, so
4120 // they cannot be represented as an immutable_struct in the
4121 // backend.
4122 static unsigned int root_counter;
4123 snprintf(buf, sizeof buf, "gc%u", root_counter);
4124 ++root_counter;
4125 }
4126 else
4127 {
4128 // Build a decl for a slice value initializer. An immutable slice
4129 // value initializer may have to be copied to the heap if it
4130 // contains pointers in a non-constant context.
4131 snprintf(buf, sizeof buf, "C%u", counter);
4132 ++counter;
4133
4134 Array_type* at = this->expr_->type()->array_type();
4135 go_assert(at != NULL);
4136
4137 // If we are not copying the value to the heap, we will only
4138 // initialize the value once, so we can use this directly
4139 // rather than copying it. In that case we can't make it
4140 // read-only, because the program is permitted to change it.
4141 copy_to_heap = (at->element_type()->has_pointer()
4142 && !context->is_const());
4143 }
4144 Bvariable* implicit =
aa5ae575 4145 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
5892f89f 4146 false, 0);
aa5ae575 4147 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4148 true, copy_to_heap, false,
4149 bexpr);
f23d7786 4150 bexpr = gogo->backend()->var_expression(implicit, loc);
76f85fd6 4151 }
4152 else if ((this->expr_->is_composite_literal()
f9ca30f9 4153 || this->expr_->string_expression() != NULL)
4154 && this->expr_->is_immutable())
4155 {
76f85fd6 4156 // Build a decl for a constant constructor.
f9ca30f9 4157 snprintf(buf, sizeof buf, "C%u", counter);
4158 ++counter;
4159
4160 Bvariable* decl =
4161 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4162 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4163 btype, loc, bexpr);
4164 bexpr = gogo->backend()->var_expression(decl, loc);
4165 }
09ea332d 4166
f9ca30f9 4167 go_assert(!this->create_temp_ || this->expr_->is_variable());
4168 ret = gogo->backend()->address_expression(bexpr, loc);
4169 break;
e440a328 4170
4171 case OPERATOR_MULT:
4172 {
f9ca30f9 4173 go_assert(this->expr_->type()->points_to() != NULL);
e440a328 4174
4175 // If we are dereferencing the pointer to a large struct, we
4176 // need to check for nil. We don't bother to check for small
4177 // structs because we expect the system to crash on a nil
56080003 4178 // pointer dereference. However, if we know the address of this
4179 // expression is being taken, we must always check for nil.
f9ca30f9 4180
4181 Type* ptype = this->expr_->type()->points_to();
4182 Btype* pbtype = ptype->get_backend(gogo);
4183 if (!ptype->is_void_type())
e440a328 4184 {
f9ca30f9 4185 size_t s = gogo->backend()->type_size(pbtype);
4186 if (s >= 4096 || this->issue_nil_check_)
19b4f09b 4187 {
f9ca30f9 4188 go_assert(this->expr_->is_variable());
ea664253 4189 Bexpression* nil =
4190 Expression::make_nil(loc)->get_backend(context);
f9ca30f9 4191 Bexpression* compare =
4192 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4193 nil, loc);
f9ca30f9 4194 Bexpression* crash =
ea664253 4195 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4196 loc)->get_backend(context);
f9ca30f9 4197 bexpr = gogo->backend()->conditional_expression(btype, compare,
4198 crash, bexpr,
4199 loc);
4200
19b4f09b 4201 }
e440a328 4202 }
9b27b43c 4203 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
e440a328 4204 }
f9ca30f9 4205 break;
e440a328 4206
4207 default:
c3e6f413 4208 go_unreachable();
e440a328 4209 }
f9ca30f9 4210
ea664253 4211 return ret;
e440a328 4212}
4213
4214// Export a unary expression.
4215
4216void
4217Unary_expression::do_export(Export* exp) const
4218{
4219 switch (this->op_)
4220 {
4221 case OPERATOR_PLUS:
4222 exp->write_c_string("+ ");
4223 break;
4224 case OPERATOR_MINUS:
4225 exp->write_c_string("- ");
4226 break;
4227 case OPERATOR_NOT:
4228 exp->write_c_string("! ");
4229 break;
4230 case OPERATOR_XOR:
4231 exp->write_c_string("^ ");
4232 break;
4233 case OPERATOR_AND:
4234 case OPERATOR_MULT:
4235 default:
c3e6f413 4236 go_unreachable();
e440a328 4237 }
4238 this->expr_->export_expression(exp);
4239}
4240
4241// Import a unary expression.
4242
4243Expression*
4244Unary_expression::do_import(Import* imp)
4245{
4246 Operator op;
4247 switch (imp->get_char())
4248 {
4249 case '+':
4250 op = OPERATOR_PLUS;
4251 break;
4252 case '-':
4253 op = OPERATOR_MINUS;
4254 break;
4255 case '!':
4256 op = OPERATOR_NOT;
4257 break;
4258 case '^':
4259 op = OPERATOR_XOR;
4260 break;
4261 default:
c3e6f413 4262 go_unreachable();
e440a328 4263 }
4264 imp->require_c_string(" ");
4265 Expression* expr = Expression::import_expression(imp);
4266 return Expression::make_unary(op, expr, imp->location());
4267}
4268
d751bb78 4269// Dump ast representation of an unary expression.
4270
4271void
4272Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4273{
4274 ast_dump_context->dump_operator(this->op_);
4275 ast_dump_context->ostream() << "(";
4276 ast_dump_context->dump_expression(this->expr_);
4277 ast_dump_context->ostream() << ") ";
4278}
4279
e440a328 4280// Make a unary expression.
4281
4282Expression*
b13c66cd 4283Expression::make_unary(Operator op, Expression* expr, Location location)
e440a328 4284{
4285 return new Unary_expression(op, expr, location);
4286}
4287
4288// If this is an indirection through a pointer, return the expression
4289// being pointed through. Otherwise return this.
4290
4291Expression*
4292Expression::deref()
4293{
4294 if (this->classification_ == EXPRESSION_UNARY)
4295 {
4296 Unary_expression* ue = static_cast<Unary_expression*>(this);
4297 if (ue->op() == OPERATOR_MULT)
4298 return ue->operand();
4299 }
4300 return this;
4301}
4302
4303// Class Binary_expression.
4304
4305// Traversal.
4306
4307int
4308Binary_expression::do_traverse(Traverse* traverse)
4309{
4310 int t = Expression::traverse(&this->left_, traverse);
4311 if (t == TRAVERSE_EXIT)
4312 return TRAVERSE_EXIT;
4313 return Expression::traverse(&this->right_, traverse);
4314}
4315
0c77715b 4316// Return the type to use for a binary operation on operands of
4317// LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4318// such may be NULL or abstract.
4319
4320bool
4321Binary_expression::operation_type(Operator op, Type* left_type,
4322 Type* right_type, Type** result_type)
4323{
4324 if (left_type != right_type
4325 && !left_type->is_abstract()
4326 && !right_type->is_abstract()
4327 && left_type->base() != right_type->base()
4328 && op != OPERATOR_LSHIFT
4329 && op != OPERATOR_RSHIFT)
4330 {
4331 // May be a type error--let it be diagnosed elsewhere.
4332 return false;
4333 }
4334
4335 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4336 {
4337 if (left_type->integer_type() != NULL)
4338 *result_type = left_type;
4339 else
4340 *result_type = Type::make_abstract_integer_type();
4341 }
4342 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4343 *result_type = left_type;
4344 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4345 *result_type = right_type;
4346 else if (!left_type->is_abstract())
4347 *result_type = left_type;
4348 else if (!right_type->is_abstract())
4349 *result_type = right_type;
4350 else if (left_type->complex_type() != NULL)
4351 *result_type = left_type;
4352 else if (right_type->complex_type() != NULL)
4353 *result_type = right_type;
4354 else if (left_type->float_type() != NULL)
4355 *result_type = left_type;
4356 else if (right_type->float_type() != NULL)
4357 *result_type = right_type;
4358 else if (left_type->integer_type() != NULL
4359 && left_type->integer_type()->is_rune())
4360 *result_type = left_type;
4361 else if (right_type->integer_type() != NULL
4362 && right_type->integer_type()->is_rune())
4363 *result_type = right_type;
4364 else
4365 *result_type = left_type;
4366
4367 return true;
4368}
4369
4370// Convert an integer comparison code and an operator to a boolean
4371// value.
e440a328 4372
4373bool
0c77715b 4374Binary_expression::cmp_to_bool(Operator op, int cmp)
e440a328 4375{
e440a328 4376 switch (op)
4377 {
4378 case OPERATOR_EQEQ:
0c77715b 4379 return cmp == 0;
4380 break;
e440a328 4381 case OPERATOR_NOTEQ:
0c77715b 4382 return cmp != 0;
4383 break;
e440a328 4384 case OPERATOR_LT:
0c77715b 4385 return cmp < 0;
4386 break;
e440a328 4387 case OPERATOR_LE:
0c77715b 4388 return cmp <= 0;
e440a328 4389 case OPERATOR_GT:
0c77715b 4390 return cmp > 0;
e440a328 4391 case OPERATOR_GE:
0c77715b 4392 return cmp >= 0;
e440a328 4393 default:
c3e6f413 4394 go_unreachable();
e440a328 4395 }
4396}
4397
0c77715b 4398// Compare constants according to OP.
e440a328 4399
4400bool
0c77715b 4401Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4402 Numeric_constant* right_nc,
4403 Location location, bool* result)
e440a328 4404{
0c77715b 4405 Type* left_type = left_nc->type();
4406 Type* right_type = right_nc->type();
4407
4408 Type* type;
4409 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4410 return false;
4411
4412 // When comparing an untyped operand to a typed operand, we are
4413 // effectively coercing the untyped operand to the other operand's
4414 // type, so make sure that is valid.
4415 if (!left_nc->set_type(type, true, location)
4416 || !right_nc->set_type(type, true, location))
4417 return false;
4418
4419 bool ret;
4420 int cmp;
4421 if (type->complex_type() != NULL)
4422 {
4423 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4424 return false;
4425 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4426 }
4427 else if (type->float_type() != NULL)
4428 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
e440a328 4429 else
0c77715b 4430 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4431
4432 if (ret)
4433 *result = Binary_expression::cmp_to_bool(op, cmp);
4434
4435 return ret;
4436}
4437
4438// Compare integer constants.
4439
4440bool
4441Binary_expression::compare_integer(const Numeric_constant* left_nc,
4442 const Numeric_constant* right_nc,
4443 int* cmp)
4444{
4445 mpz_t left_val;
4446 if (!left_nc->to_int(&left_val))
4447 return false;
4448 mpz_t right_val;
4449 if (!right_nc->to_int(&right_val))
e440a328 4450 {
0c77715b 4451 mpz_clear(left_val);
4452 return false;
e440a328 4453 }
0c77715b 4454
4455 *cmp = mpz_cmp(left_val, right_val);
4456
4457 mpz_clear(left_val);
4458 mpz_clear(right_val);
4459
4460 return true;
4461}
4462
4463// Compare floating point constants.
4464
4465bool
4466Binary_expression::compare_float(const Numeric_constant* left_nc,
4467 const Numeric_constant* right_nc,
4468 int* cmp)
4469{
4470 mpfr_t left_val;
4471 if (!left_nc->to_float(&left_val))
4472 return false;
4473 mpfr_t right_val;
4474 if (!right_nc->to_float(&right_val))
e440a328 4475 {
0c77715b 4476 mpfr_clear(left_val);
4477 return false;
4478 }
4479
4480 // We already coerced both operands to the same type. If that type
4481 // is not an abstract type, we need to round the values accordingly.
4482 Type* type = left_nc->type();
4483 if (!type->is_abstract() && type->float_type() != NULL)
4484 {
4485 int bits = type->float_type()->bits();
4486 mpfr_prec_round(left_val, bits, GMP_RNDN);
4487 mpfr_prec_round(right_val, bits, GMP_RNDN);
e440a328 4488 }
0c77715b 4489
4490 *cmp = mpfr_cmp(left_val, right_val);
4491
4492 mpfr_clear(left_val);
4493 mpfr_clear(right_val);
4494
4495 return true;
e440a328 4496}
4497
0c77715b 4498// Compare complex constants. Complex numbers may only be compared
4499// for equality.
e440a328 4500
4501bool
0c77715b 4502Binary_expression::compare_complex(const Numeric_constant* left_nc,
4503 const Numeric_constant* right_nc,
4504 int* cmp)
e440a328 4505{
fcbea5e4 4506 mpc_t left_val;
4507 if (!left_nc->to_complex(&left_val))
0c77715b 4508 return false;
fcbea5e4 4509 mpc_t right_val;
4510 if (!right_nc->to_complex(&right_val))
e440a328 4511 {
fcbea5e4 4512 mpc_clear(left_val);
0c77715b 4513 return false;
e440a328 4514 }
0c77715b 4515
4516 // We already coerced both operands to the same type. If that type
4517 // is not an abstract type, we need to round the values accordingly.
4518 Type* type = left_nc->type();
4519 if (!type->is_abstract() && type->complex_type() != NULL)
e440a328 4520 {
0c77715b 4521 int bits = type->complex_type()->bits();
fcbea5e4 4522 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4523 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4524 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4525 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
e440a328 4526 }
0c77715b 4527
fcbea5e4 4528 *cmp = mpc_cmp(left_val, right_val) != 0;
0c77715b 4529
fcbea5e4 4530 mpc_clear(left_val);
4531 mpc_clear(right_val);
0c77715b 4532
4533 return true;
e440a328 4534}
4535
0c77715b 4536// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4537// true if this could be done, false if not. Issue errors at LOCATION
4538// as appropriate.
e440a328 4539
4540bool
0c77715b 4541Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4542 Numeric_constant* right_nc,
4543 Location location, Numeric_constant* nc)
e440a328 4544{
e440a328 4545 switch (op)
4546 {
4547 case OPERATOR_OROR:
4548 case OPERATOR_ANDAND:
4549 case OPERATOR_EQEQ:
4550 case OPERATOR_NOTEQ:
4551 case OPERATOR_LT:
4552 case OPERATOR_LE:
4553 case OPERATOR_GT:
4554 case OPERATOR_GE:
9767e2d3 4555 // These return boolean values, not numeric.
4556 return false;
0c77715b 4557 default:
4558 break;
4559 }
4560
4561 Type* left_type = left_nc->type();
4562 Type* right_type = right_nc->type();
4563
4564 Type* type;
4565 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4566 return false;
4567
4568 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4569
4570 // When combining an untyped operand with a typed operand, we are
4571 // effectively coercing the untyped operand to the other operand's
4572 // type, so make sure that is valid.
4573 if (!left_nc->set_type(type, true, location))
4574 return false;
4575 if (!is_shift && !right_nc->set_type(type, true, location))
4576 return false;
4577
4578 bool r;
4579 if (type->complex_type() != NULL)
4580 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4581 else if (type->float_type() != NULL)
4582 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4583 else
4584 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4585
4586 if (r)
4587 r = nc->set_type(type, true, location);
4588
4589 return r;
4590}
4591
4592// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4593// integer operations. Return true if this could be done, false if
4594// not.
4595
4596bool
4597Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4598 const Numeric_constant* right_nc,
4599 Location location, Numeric_constant* nc)
4600{
4601 mpz_t left_val;
4602 if (!left_nc->to_int(&left_val))
4603 return false;
4604 mpz_t right_val;
4605 if (!right_nc->to_int(&right_val))
4606 {
4607 mpz_clear(left_val);
e440a328 4608 return false;
0c77715b 4609 }
4610
4611 mpz_t val;
4612 mpz_init(val);
4613
4614 switch (op)
4615 {
e440a328 4616 case OPERATOR_PLUS:
4617 mpz_add(val, left_val, right_val);
2c809f8f 4618 if (mpz_sizeinbase(val, 2) > 0x100000)
4619 {
4620 error_at(location, "constant addition overflow");
4621 mpz_set_ui(val, 1);
4622 }
e440a328 4623 break;
4624 case OPERATOR_MINUS:
4625 mpz_sub(val, left_val, right_val);
2c809f8f 4626 if (mpz_sizeinbase(val, 2) > 0x100000)
4627 {
4628 error_at(location, "constant subtraction overflow");
4629 mpz_set_ui(val, 1);
4630 }
e440a328 4631 break;
4632 case OPERATOR_OR:
4633 mpz_ior(val, left_val, right_val);
4634 break;
4635 case OPERATOR_XOR:
4636 mpz_xor(val, left_val, right_val);
4637 break;
4638 case OPERATOR_MULT:
4639 mpz_mul(val, left_val, right_val);
2c809f8f 4640 if (mpz_sizeinbase(val, 2) > 0x100000)
4641 {
4642 error_at(location, "constant multiplication overflow");
4643 mpz_set_ui(val, 1);
4644 }
e440a328 4645 break;
4646 case OPERATOR_DIV:
4647 if (mpz_sgn(right_val) != 0)
4648 mpz_tdiv_q(val, left_val, right_val);
4649 else
4650 {
4651 error_at(location, "division by zero");
4652 mpz_set_ui(val, 0);
e440a328 4653 }
4654 break;
4655 case OPERATOR_MOD:
4656 if (mpz_sgn(right_val) != 0)
4657 mpz_tdiv_r(val, left_val, right_val);
4658 else
4659 {
4660 error_at(location, "division by zero");
4661 mpz_set_ui(val, 0);
e440a328 4662 }
4663 break;
4664 case OPERATOR_LSHIFT:
4665 {
4666 unsigned long shift = mpz_get_ui(right_val);
0c77715b 4667 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4668 mpz_mul_2exp(val, left_val, shift);
4669 else
e440a328 4670 {
4671 error_at(location, "shift count overflow");
2c809f8f 4672 mpz_set_ui(val, 1);
e440a328 4673 }
e440a328 4674 break;
4675 }
4676 break;
4677 case OPERATOR_RSHIFT:
4678 {
4679 unsigned long shift = mpz_get_ui(right_val);
4680 if (mpz_cmp_ui(right_val, shift) != 0)
4681 {
4682 error_at(location, "shift count overflow");
2c809f8f 4683 mpz_set_ui(val, 1);
e440a328 4684 }
e440a328 4685 else
0c77715b 4686 {
4687 if (mpz_cmp_ui(left_val, 0) >= 0)
4688 mpz_tdiv_q_2exp(val, left_val, shift);
4689 else
4690 mpz_fdiv_q_2exp(val, left_val, shift);
4691 }
e440a328 4692 break;
4693 }
4694 break;
4695 case OPERATOR_AND:
4696 mpz_and(val, left_val, right_val);
4697 break;
4698 case OPERATOR_BITCLEAR:
4699 {
4700 mpz_t tval;
4701 mpz_init(tval);
4702 mpz_com(tval, right_val);
4703 mpz_and(val, left_val, tval);
4704 mpz_clear(tval);
4705 }
4706 break;
4707 default:
c3e6f413 4708 go_unreachable();
e440a328 4709 }
4710
0c77715b 4711 mpz_clear(left_val);
4712 mpz_clear(right_val);
e440a328 4713
0c77715b 4714 if (left_nc->is_rune()
4715 || (op != OPERATOR_LSHIFT
4716 && op != OPERATOR_RSHIFT
4717 && right_nc->is_rune()))
4718 nc->set_rune(NULL, val);
4719 else
4720 nc->set_int(NULL, val);
4721
4722 mpz_clear(val);
e440a328 4723
4724 return true;
4725}
4726
0c77715b 4727// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4728// floating point operations. Return true if this could be done,
4729// false if not.
e440a328 4730
4731bool
0c77715b 4732Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4733 const Numeric_constant* right_nc,
4734 Location location, Numeric_constant* nc)
e440a328 4735{
0c77715b 4736 mpfr_t left_val;
4737 if (!left_nc->to_float(&left_val))
4738 return false;
4739 mpfr_t right_val;
4740 if (!right_nc->to_float(&right_val))
e440a328 4741 {
0c77715b 4742 mpfr_clear(left_val);
e440a328 4743 return false;
0c77715b 4744 }
4745
4746 mpfr_t val;
4747 mpfr_init(val);
4748
4749 bool ret = true;
4750 switch (op)
4751 {
e440a328 4752 case OPERATOR_PLUS:
4753 mpfr_add(val, left_val, right_val, GMP_RNDN);
4754 break;
4755 case OPERATOR_MINUS:
4756 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4757 break;
4758 case OPERATOR_OR:
4759 case OPERATOR_XOR:
4760 case OPERATOR_AND:
4761 case OPERATOR_BITCLEAR:
0c77715b 4762 case OPERATOR_MOD:
4763 case OPERATOR_LSHIFT:
4764 case OPERATOR_RSHIFT:
4765 mpfr_set_ui(val, 0, GMP_RNDN);
4766 ret = false;
4767 break;
e440a328 4768 case OPERATOR_MULT:
4769 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4770 break;
4771 case OPERATOR_DIV:
0c77715b 4772 if (!mpfr_zero_p(right_val))
4773 mpfr_div(val, left_val, right_val, GMP_RNDN);
4774 else
4775 {
4776 error_at(location, "division by zero");
4777 mpfr_set_ui(val, 0, GMP_RNDN);
4778 }
e440a328 4779 break;
e440a328 4780 default:
c3e6f413 4781 go_unreachable();
e440a328 4782 }
4783
0c77715b 4784 mpfr_clear(left_val);
4785 mpfr_clear(right_val);
e440a328 4786
0c77715b 4787 nc->set_float(NULL, val);
4788 mpfr_clear(val);
e440a328 4789
0c77715b 4790 return ret;
e440a328 4791}
4792
0c77715b 4793// Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4794// complex operations. Return true if this could be done, false if
4795// not.
e440a328 4796
4797bool
0c77715b 4798Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4799 const Numeric_constant* right_nc,
4800 Location location, Numeric_constant* nc)
e440a328 4801{
fcbea5e4 4802 mpc_t left_val;
4803 if (!left_nc->to_complex(&left_val))
0c77715b 4804 return false;
fcbea5e4 4805 mpc_t right_val;
4806 if (!right_nc->to_complex(&right_val))
e440a328 4807 {
fcbea5e4 4808 mpc_clear(left_val);
e440a328 4809 return false;
0c77715b 4810 }
4811
fcbea5e4 4812 mpc_t val;
4813 mpc_init2(val, mpc_precision);
0c77715b 4814
4815 bool ret = true;
4816 switch (op)
4817 {
e440a328 4818 case OPERATOR_PLUS:
fcbea5e4 4819 mpc_add(val, left_val, right_val, MPC_RNDNN);
e440a328 4820 break;
4821 case OPERATOR_MINUS:
fcbea5e4 4822 mpc_sub(val, left_val, right_val, MPC_RNDNN);
e440a328 4823 break;
4824 case OPERATOR_OR:
4825 case OPERATOR_XOR:
4826 case OPERATOR_AND:
4827 case OPERATOR_BITCLEAR:
0c77715b 4828 case OPERATOR_MOD:
4829 case OPERATOR_LSHIFT:
4830 case OPERATOR_RSHIFT:
fcbea5e4 4831 mpc_set_ui(val, 0, MPC_RNDNN);
0c77715b 4832 ret = false;
4833 break;
e440a328 4834 case OPERATOR_MULT:
fcbea5e4 4835 mpc_mul(val, left_val, right_val, MPC_RNDNN);
e440a328 4836 break;
4837 case OPERATOR_DIV:
fcbea5e4 4838 if (mpc_cmp_si(right_val, 0) == 0)
4839 {
4840 error_at(location, "division by zero");
4841 mpc_set_ui(val, 0, MPC_RNDNN);
4842 break;
4843 }
4844 mpc_div(val, left_val, right_val, MPC_RNDNN);
e440a328 4845 break;
e440a328 4846 default:
c3e6f413 4847 go_unreachable();
e440a328 4848 }
4849
fcbea5e4 4850 mpc_clear(left_val);
4851 mpc_clear(right_val);
e440a328 4852
fcbea5e4 4853 nc->set_complex(NULL, val);
4854 mpc_clear(val);
e440a328 4855
0c77715b 4856 return ret;
e440a328 4857}
4858
4859// Lower a binary expression. We have to evaluate constant
4860// expressions now, in order to implement Go's unlimited precision
4861// constants.
4862
4863Expression*
e9d3367e 4864Binary_expression::do_lower(Gogo* gogo, Named_object*,
4865 Statement_inserter* inserter, int)
e440a328 4866{
b13c66cd 4867 Location location = this->location();
e440a328 4868 Operator op = this->op_;
4869 Expression* left = this->left_;
4870 Expression* right = this->right_;
4871
4872 const bool is_comparison = (op == OPERATOR_EQEQ
4873 || op == OPERATOR_NOTEQ
4874 || op == OPERATOR_LT
4875 || op == OPERATOR_LE
4876 || op == OPERATOR_GT
4877 || op == OPERATOR_GE);
4878
0c77715b 4879 // Numeric constant expressions.
e440a328 4880 {
0c77715b 4881 Numeric_constant left_nc;
4882 Numeric_constant right_nc;
4883 if (left->numeric_constant_value(&left_nc)
4884 && right->numeric_constant_value(&right_nc))
e440a328 4885 {
0c77715b 4886 if (is_comparison)
e440a328 4887 {
0c77715b 4888 bool result;
4889 if (!Binary_expression::compare_constant(op, &left_nc,
4890 &right_nc, location,
4891 &result))
4892 return this;
e90c9dfc 4893 return Expression::make_cast(Type::make_boolean_type(),
0c77715b 4894 Expression::make_boolean(result,
4895 location),
4896 location);
e440a328 4897 }
4898 else
4899 {
0c77715b 4900 Numeric_constant nc;
4901 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
4902 location, &nc))
4903 return this;
4904 return nc.expression(location);
e440a328 4905 }
4906 }
e440a328 4907 }
4908
4909 // String constant expressions.
315fa98d 4910 if (left->type()->is_string_type() && right->type()->is_string_type())
e440a328 4911 {
4912 std::string left_string;
4913 std::string right_string;
4914 if (left->string_constant_value(&left_string)
4915 && right->string_constant_value(&right_string))
315fa98d 4916 {
4917 if (op == OPERATOR_PLUS)
4918 return Expression::make_string(left_string + right_string,
4919 location);
4920 else if (is_comparison)
4921 {
4922 int cmp = left_string.compare(right_string);
0c77715b 4923 bool r = Binary_expression::cmp_to_bool(op, cmp);
e90c9dfc 4924 return Expression::make_boolean(r, location);
b40dc774 4925 }
4926 }
b40dc774 4927 }
4928
ceeb12d7 4929 // Lower struct, array, and some interface comparisons.
e9d3367e 4930 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
4931 {
b79832ca 4932 if (left->type()->struct_type() != NULL
4933 && right->type()->struct_type() != NULL)
e9d3367e 4934 return this->lower_struct_comparison(gogo, inserter);
4935 else if (left->type()->array_type() != NULL
b79832ca 4936 && !left->type()->is_slice_type()
4937 && right->type()->array_type() != NULL
4938 && !right->type()->is_slice_type())
e9d3367e 4939 return this->lower_array_comparison(gogo, inserter);
ceeb12d7 4940 else if ((left->type()->interface_type() != NULL
4941 && right->type()->interface_type() == NULL)
4942 || (left->type()->interface_type() == NULL
4943 && right->type()->interface_type() != NULL))
4944 return this->lower_interface_value_comparison(gogo, inserter);
e9d3367e 4945 }
4946
e440a328 4947 return this;
4948}
4949
e9d3367e 4950// Lower a struct comparison.
4951
4952Expression*
4953Binary_expression::lower_struct_comparison(Gogo* gogo,
4954 Statement_inserter* inserter)
4955{
4956 Struct_type* st = this->left_->type()->struct_type();
4957 Struct_type* st2 = this->right_->type()->struct_type();
4958 if (st2 == NULL)
4959 return this;
4960 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
4961 return this;
4962 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
4963 this->right_->type(), NULL))
4964 return this;
4965
4966 // See if we can compare using memcmp. As a heuristic, we use
4967 // memcmp rather than field references and comparisons if there are
4968 // more than two fields.
113ef6a5 4969 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
e9d3367e 4970 return this->lower_compare_to_memcmp(gogo, inserter);
4971
4972 Location loc = this->location();
4973
4974 Expression* left = this->left_;
4975 Temporary_statement* left_temp = NULL;
4976 if (left->var_expression() == NULL
4977 && left->temporary_reference_expression() == NULL)
4978 {
4979 left_temp = Statement::make_temporary(left->type(), NULL, loc);
4980 inserter->insert(left_temp);
4981 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
4982 }
4983
4984 Expression* right = this->right_;
4985 Temporary_statement* right_temp = NULL;
4986 if (right->var_expression() == NULL
4987 && right->temporary_reference_expression() == NULL)
4988 {
4989 right_temp = Statement::make_temporary(right->type(), NULL, loc);
4990 inserter->insert(right_temp);
4991 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
4992 }
4993
4994 Expression* ret = Expression::make_boolean(true, loc);
4995 const Struct_field_list* fields = st->fields();
4996 unsigned int field_index = 0;
4997 for (Struct_field_list::const_iterator pf = fields->begin();
4998 pf != fields->end();
4999 ++pf, ++field_index)
5000 {
f5165c05 5001 if (Gogo::is_sink_name(pf->field_name()))
5002 continue;
5003
e9d3367e 5004 if (field_index > 0)
5005 {
5006 if (left_temp == NULL)
5007 left = left->copy();
5008 else
5009 left = Expression::make_temporary_reference(left_temp, loc);
5010 if (right_temp == NULL)
5011 right = right->copy();
5012 else
5013 right = Expression::make_temporary_reference(right_temp, loc);
5014 }
5015 Expression* f1 = Expression::make_field_reference(left, field_index,
5016 loc);
5017 Expression* f2 = Expression::make_field_reference(right, field_index,
5018 loc);
5019 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5020 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5021 }
5022
5023 if (this->op_ == OPERATOR_NOTEQ)
5024 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5025
5026 return ret;
5027}
5028
5029// Lower an array comparison.
5030
5031Expression*
5032Binary_expression::lower_array_comparison(Gogo* gogo,
5033 Statement_inserter* inserter)
5034{
5035 Array_type* at = this->left_->type()->array_type();
5036 Array_type* at2 = this->right_->type()->array_type();
5037 if (at2 == NULL)
5038 return this;
5039 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5040 return this;
5041 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5042 this->right_->type(), NULL))
5043 return this;
5044
5045 // Call memcmp directly if possible. This may let the middle-end
5046 // optimize the call.
113ef6a5 5047 if (at->compare_is_identity(gogo))
e9d3367e 5048 return this->lower_compare_to_memcmp(gogo, inserter);
5049
5050 // Call the array comparison function.
5051 Named_object* hash_fn;
5052 Named_object* equal_fn;
5053 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5054 &hash_fn, &equal_fn);
5055
5056 Location loc = this->location();
5057
5058 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5059
5060 Expression_list* args = new Expression_list();
5061 args->push_back(this->operand_address(inserter, this->left_));
5062 args->push_back(this->operand_address(inserter, this->right_));
5063 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5064
5065 Expression* ret = Expression::make_call(func, args, false, loc);
5066
5067 if (this->op_ == OPERATOR_NOTEQ)
5068 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5069
5070 return ret;
5071}
5072
ceeb12d7 5073// Lower an interface to value comparison.
5074
5075Expression*
5076Binary_expression::lower_interface_value_comparison(Gogo*,
5077 Statement_inserter* inserter)
5078{
5079 Type* left_type = this->left_->type();
5080 Type* right_type = this->right_->type();
5081 Interface_type* ift;
5082 if (left_type->interface_type() != NULL)
5083 {
5084 ift = left_type->interface_type();
5085 if (!ift->implements_interface(right_type, NULL))
5086 return this;
5087 }
5088 else
5089 {
5090 ift = right_type->interface_type();
5091 if (!ift->implements_interface(left_type, NULL))
5092 return this;
5093 }
5094 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5095 return this;
5096
5097 Location loc = this->location();
5098
5099 if (left_type->interface_type() == NULL
5100 && left_type->points_to() == NULL
5101 && !this->left_->is_addressable())
5102 {
5103 Temporary_statement* temp =
5104 Statement::make_temporary(left_type, NULL, loc);
5105 inserter->insert(temp);
5106 this->left_ =
5107 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5108 }
5109
5110 if (right_type->interface_type() == NULL
5111 && right_type->points_to() == NULL
5112 && !this->right_->is_addressable())
5113 {
5114 Temporary_statement* temp =
5115 Statement::make_temporary(right_type, NULL, loc);
5116 inserter->insert(temp);
5117 this->right_ =
5118 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5119 }
5120
5121 return this;
5122}
5123
e9d3367e 5124// Lower a struct or array comparison to a call to memcmp.
5125
5126Expression*
5127Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5128{
5129 Location loc = this->location();
5130
5131 Expression* a1 = this->operand_address(inserter, this->left_);
5132 Expression* a2 = this->operand_address(inserter, this->right_);
5133 Expression* len = Expression::make_type_info(this->left_->type(),
5134 TYPE_INFO_SIZE);
5135
5136 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
e67508fa 5137 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
e9d3367e 5138 return Expression::make_binary(this->op_, call, zero, loc);
5139}
5140
a32698ee 5141Expression*
5c3f3470 5142Binary_expression::do_flatten(Gogo* gogo, Named_object*,
a32698ee 5143 Statement_inserter* inserter)
5144{
5145 Location loc = this->location();
5146 Temporary_statement* temp;
5147 if (this->left_->type()->is_string_type()
5148 && this->op_ == OPERATOR_PLUS)
5149 {
5150 if (!this->left_->is_variable())
5151 {
5152 temp = Statement::make_temporary(NULL, this->left_, loc);
5153 inserter->insert(temp);
5154 this->left_ = Expression::make_temporary_reference(temp, loc);
5155 }
5156 if (!this->right_->is_variable())
5157 {
5158 temp =
5159 Statement::make_temporary(this->left_->type(), this->right_, loc);
5160 this->right_ = Expression::make_temporary_reference(temp, loc);
5161 inserter->insert(temp);
5162 }
5163 }
5164
5165 Type* left_type = this->left_->type();
5166 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5167 || this->op_ == OPERATOR_RSHIFT);
5168 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5169 left_type->integer_type() != NULL)
5170 || this->op_ == OPERATOR_MOD);
5171
a32698ee 5172 if (is_shift_op
5c3f3470 5173 || (is_idiv_op
5174 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
a32698ee 5175 {
5176 if (!this->left_->is_variable())
5177 {
5178 temp = Statement::make_temporary(NULL, this->left_, loc);
5179 inserter->insert(temp);
5180 this->left_ = Expression::make_temporary_reference(temp, loc);
5181 }
5182 if (!this->right_->is_variable())
5183 {
5184 temp =
5185 Statement::make_temporary(NULL, this->right_, loc);
5186 this->right_ = Expression::make_temporary_reference(temp, loc);
5187 inserter->insert(temp);
5188 }
5189 }
5190 return this;
5191}
5192
5193
e9d3367e 5194// Return the address of EXPR, cast to unsafe.Pointer.
5195
5196Expression*
5197Binary_expression::operand_address(Statement_inserter* inserter,
5198 Expression* expr)
5199{
5200 Location loc = this->location();
5201
5202 if (!expr->is_addressable())
5203 {
5204 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5205 loc);
5206 inserter->insert(temp);
5207 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5208 }
5209 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5210 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5211 Type* void_type = Type::make_void_type();
5212 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5213 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5214}
5215
0c77715b 5216// Return the numeric constant value, if it has one.
e440a328 5217
5218bool
0c77715b 5219Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 5220{
0c77715b 5221 Numeric_constant left_nc;
5222 if (!this->left_->numeric_constant_value(&left_nc))
5223 return false;
5224 Numeric_constant right_nc;
5225 if (!this->right_->numeric_constant_value(&right_nc))
5226 return false;
9767e2d3 5227 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
0c77715b 5228 this->location(), nc);
e440a328 5229}
5230
5231// Note that the value is being discarded.
5232
4f2138d7 5233bool
e440a328 5234Binary_expression::do_discarding_value()
5235{
5236 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
4f2138d7 5237 return this->right_->discarding_value();
e440a328 5238 else
4f2138d7 5239 {
5240 this->unused_value_error();
5241 return false;
5242 }
e440a328 5243}
5244
5245// Get type.
5246
5247Type*
5248Binary_expression::do_type()
5249{
5f5fea79 5250 if (this->classification() == EXPRESSION_ERROR)
5251 return Type::make_error_type();
5252
e440a328 5253 switch (this->op_)
5254 {
e440a328 5255 case OPERATOR_EQEQ:
5256 case OPERATOR_NOTEQ:
5257 case OPERATOR_LT:
5258 case OPERATOR_LE:
5259 case OPERATOR_GT:
5260 case OPERATOR_GE:
e90c9dfc 5261 if (this->type_ == NULL)
5262 this->type_ = Type::make_boolean_type();
5263 return this->type_;
e440a328 5264
5265 case OPERATOR_PLUS:
5266 case OPERATOR_MINUS:
5267 case OPERATOR_OR:
5268 case OPERATOR_XOR:
5269 case OPERATOR_MULT:
5270 case OPERATOR_DIV:
5271 case OPERATOR_MOD:
5272 case OPERATOR_AND:
5273 case OPERATOR_BITCLEAR:
e90c9dfc 5274 case OPERATOR_OROR:
5275 case OPERATOR_ANDAND:
e440a328 5276 {
0c77715b 5277 Type* type;
5278 if (!Binary_expression::operation_type(this->op_,
5279 this->left_->type(),
5280 this->right_->type(),
5281 &type))
5282 return Type::make_error_type();
5283 return type;
e440a328 5284 }
5285
5286 case OPERATOR_LSHIFT:
5287 case OPERATOR_RSHIFT:
5288 return this->left_->type();
5289
5290 default:
c3e6f413 5291 go_unreachable();
e440a328 5292 }
5293}
5294
5295// Set type for a binary expression.
5296
5297void
5298Binary_expression::do_determine_type(const Type_context* context)
5299{
5300 Type* tleft = this->left_->type();
5301 Type* tright = this->right_->type();
5302
5303 // Both sides should have the same type, except for the shift
5304 // operations. For a comparison, we should ignore the incoming
5305 // type.
5306
5307 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5308 || this->op_ == OPERATOR_RSHIFT);
5309
5310 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5311 || this->op_ == OPERATOR_NOTEQ
5312 || this->op_ == OPERATOR_LT
5313 || this->op_ == OPERATOR_LE
5314 || this->op_ == OPERATOR_GT
5315 || this->op_ == OPERATOR_GE);
5316
5317 Type_context subcontext(*context);
5318
5319 if (is_comparison)
5320 {
5321 // In a comparison, the context does not determine the types of
5322 // the operands.
5323 subcontext.type = NULL;
5324 }
5325
5326 // Set the context for the left hand operand.
5327 if (is_shift_op)
5328 {
b40dc774 5329 // The right hand operand of a shift plays no role in
5330 // determining the type of the left hand operand.
e440a328 5331 }
5332 else if (!tleft->is_abstract())
5333 subcontext.type = tleft;
5334 else if (!tright->is_abstract())
5335 subcontext.type = tright;
5336 else if (subcontext.type == NULL)
5337 {
5338 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5339 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5340 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5341 {
5342 // Both sides have an abstract integer, abstract float, or
5343 // abstract complex type. Just let CONTEXT determine
5344 // whether they may remain abstract or not.
5345 }
5346 else if (tleft->complex_type() != NULL)
5347 subcontext.type = tleft;
5348 else if (tright->complex_type() != NULL)
5349 subcontext.type = tright;
5350 else if (tleft->float_type() != NULL)
5351 subcontext.type = tleft;
5352 else if (tright->float_type() != NULL)
5353 subcontext.type = tright;
5354 else
5355 subcontext.type = tleft;
f58a23ae 5356
5357 if (subcontext.type != NULL && !context->may_be_abstract)
5358 subcontext.type = subcontext.type->make_non_abstract_type();
e440a328 5359 }
5360
5361 this->left_->determine_type(&subcontext);
5362
e440a328 5363 if (is_shift_op)
5364 {
b40dc774 5365 // We may have inherited an unusable type for the shift operand.
5366 // Give a useful error if that happened.
5367 if (tleft->is_abstract()
5368 && subcontext.type != NULL
8ab6effb 5369 && !subcontext.may_be_abstract
f6bc81e6 5370 && subcontext.type->interface_type() == NULL
8ab6effb 5371 && subcontext.type->integer_type() == NULL)
b40dc774 5372 this->report_error(("invalid context-determined non-integer type "
8ab6effb 5373 "for left operand of shift"));
b40dc774 5374
5375 // The context for the right hand operand is the same as for the
5376 // left hand operand, except for a shift operator.
e440a328 5377 subcontext.type = Type::lookup_integer_type("uint");
5378 subcontext.may_be_abstract = false;
5379 }
5380
5381 this->right_->determine_type(&subcontext);
e90c9dfc 5382
5383 if (is_comparison)
5384 {
5385 if (this->type_ != NULL && !this->type_->is_abstract())
5386 ;
5387 else if (context->type != NULL && context->type->is_boolean_type())
5388 this->type_ = context->type;
5389 else if (!context->may_be_abstract)
5390 this->type_ = Type::lookup_bool_type();
5391 }
e440a328 5392}
5393
5394// Report an error if the binary operator OP does not support TYPE.
be8b5eee 5395// OTYPE is the type of the other operand. Return whether the
5396// operation is OK. This should not be used for shift.
e440a328 5397
5398bool
be8b5eee 5399Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
b13c66cd 5400 Location location)
e440a328 5401{
5402 switch (op)
5403 {
5404 case OPERATOR_OROR:
5405 case OPERATOR_ANDAND:
5406 if (!type->is_boolean_type())
5407 {
5408 error_at(location, "expected boolean type");
5409 return false;
5410 }
5411 break;
5412
5413 case OPERATOR_EQEQ:
5414 case OPERATOR_NOTEQ:
e9d3367e 5415 {
5416 std::string reason;
5417 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5418 {
5419 error_at(location, "%s", reason.c_str());
5420 return false;
5421 }
5422 }
e440a328 5423 break;
5424
5425 case OPERATOR_LT:
5426 case OPERATOR_LE:
5427 case OPERATOR_GT:
5428 case OPERATOR_GE:
e9d3367e 5429 {
5430 std::string reason;
5431 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5432 {
5433 error_at(location, "%s", reason.c_str());
5434 return false;
5435 }
5436 }
e440a328 5437 break;
5438
5439 case OPERATOR_PLUS:
5440 case OPERATOR_PLUSEQ:
5441 if (type->integer_type() == NULL
5442 && type->float_type() == NULL
5443 && type->complex_type() == NULL
5444 && !type->is_string_type())
5445 {
5446 error_at(location,
5447 "expected integer, floating, complex, or string type");
5448 return false;
5449 }
5450 break;
5451
5452 case OPERATOR_MINUS:
5453 case OPERATOR_MINUSEQ:
5454 case OPERATOR_MULT:
5455 case OPERATOR_MULTEQ:
5456 case OPERATOR_DIV:
5457 case OPERATOR_DIVEQ:
5458 if (type->integer_type() == NULL
5459 && type->float_type() == NULL
5460 && type->complex_type() == NULL)
5461 {
5462 error_at(location, "expected integer, floating, or complex type");
5463 return false;
5464 }
5465 break;
5466
5467 case OPERATOR_MOD:
5468 case OPERATOR_MODEQ:
5469 case OPERATOR_OR:
5470 case OPERATOR_OREQ:
5471 case OPERATOR_AND:
5472 case OPERATOR_ANDEQ:
5473 case OPERATOR_XOR:
5474 case OPERATOR_XOREQ:
5475 case OPERATOR_BITCLEAR:
5476 case OPERATOR_BITCLEAREQ:
5477 if (type->integer_type() == NULL)
5478 {
5479 error_at(location, "expected integer type");
5480 return false;
5481 }
5482 break;
5483
5484 default:
c3e6f413 5485 go_unreachable();
e440a328 5486 }
5487
5488 return true;
5489}
5490
5491// Check types.
5492
5493void
5494Binary_expression::do_check_types(Gogo*)
5495{
5f5fea79 5496 if (this->classification() == EXPRESSION_ERROR)
5497 return;
5498
e440a328 5499 Type* left_type = this->left_->type();
5500 Type* right_type = this->right_->type();
5c13bd80 5501 if (left_type->is_error() || right_type->is_error())
9fe897ef 5502 {
5503 this->set_is_error();
5504 return;
5505 }
e440a328 5506
5507 if (this->op_ == OPERATOR_EQEQ
5508 || this->op_ == OPERATOR_NOTEQ
5509 || this->op_ == OPERATOR_LT
5510 || this->op_ == OPERATOR_LE
5511 || this->op_ == OPERATOR_GT
5512 || this->op_ == OPERATOR_GE)
5513 {
907c5ecd 5514 if (left_type->is_nil_type() && right_type->is_nil_type())
5515 {
5516 this->report_error(_("invalid comparison of nil with nil"));
5517 return;
5518 }
e440a328 5519 if (!Type::are_assignable(left_type, right_type, NULL)
5520 && !Type::are_assignable(right_type, left_type, NULL))
5521 {
5522 this->report_error(_("incompatible types in binary expression"));
5523 return;
5524 }
5525 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5526 right_type,
e440a328 5527 this->location())
5528 || !Binary_expression::check_operator_type(this->op_, right_type,
be8b5eee 5529 left_type,
e440a328 5530 this->location()))
5531 {
5532 this->set_is_error();
5533 return;
5534 }
5535 }
5536 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5537 {
5538 if (!Type::are_compatible_for_binop(left_type, right_type))
5539 {
5540 this->report_error(_("incompatible types in binary expression"));
5541 return;
5542 }
5543 if (!Binary_expression::check_operator_type(this->op_, left_type,
be8b5eee 5544 right_type,
e440a328 5545 this->location()))
5546 {
5547 this->set_is_error();
5548 return;
5549 }
5c65b19d 5550 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5551 {
5552 // Division by a zero integer constant is an error.
5553 Numeric_constant rconst;
5554 unsigned long rval;
5555 if (left_type->integer_type() != NULL
5556 && this->right_->numeric_constant_value(&rconst)
5557 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5558 && rval == 0)
5559 {
5560 this->report_error(_("integer division by zero"));
5561 return;
5562 }
5563 }
e440a328 5564 }
5565 else
5566 {
5567 if (left_type->integer_type() == NULL)
5568 this->report_error(_("shift of non-integer operand"));
5569
5570 if (!right_type->is_abstract()
5571 && (right_type->integer_type() == NULL
5572 || !right_type->integer_type()->is_unsigned()))
5573 this->report_error(_("shift count not unsigned integer"));
5574 else
5575 {
0c77715b 5576 Numeric_constant nc;
5577 if (this->right_->numeric_constant_value(&nc))
e440a328 5578 {
0c77715b 5579 mpz_t val;
5580 if (!nc.to_int(&val))
5581 this->report_error(_("shift count not unsigned integer"));
5582 else
a4eba91b 5583 {
0c77715b 5584 if (mpz_sgn(val) < 0)
5585 {
5586 this->report_error(_("negative shift count"));
0c77715b 5587 Location rloc = this->right_->location();
e67508fa 5588 this->right_ = Expression::make_integer_ul(0, right_type,
5589 rloc);
0c77715b 5590 }
5591 mpz_clear(val);
a4eba91b 5592 }
e440a328 5593 }
e440a328 5594 }
5595 }
5596}
5597
ea664253 5598// Get the backend representation for a binary expression.
e440a328 5599
ea664253 5600Bexpression*
5601Binary_expression::do_get_backend(Translate_context* context)
e440a328 5602{
1b1f2abf 5603 Gogo* gogo = context->gogo();
a32698ee 5604 Location loc = this->location();
5605 Type* left_type = this->left_->type();
5606 Type* right_type = this->right_->type();
1b1f2abf 5607
e440a328 5608 bool use_left_type = true;
5609 bool is_shift_op = false;
29a2d1d8 5610 bool is_idiv_op = false;
e440a328 5611 switch (this->op_)
5612 {
5613 case OPERATOR_EQEQ:
5614 case OPERATOR_NOTEQ:
5615 case OPERATOR_LT:
5616 case OPERATOR_LE:
5617 case OPERATOR_GT:
5618 case OPERATOR_GE:
ea664253 5619 return Expression::comparison(context, this->type_, this->op_,
5620 this->left_, this->right_, loc);
e440a328 5621
5622 case OPERATOR_OROR:
e440a328 5623 case OPERATOR_ANDAND:
e440a328 5624 use_left_type = false;
5625 break;
5626 case OPERATOR_PLUS:
e440a328 5627 case OPERATOR_MINUS:
e440a328 5628 case OPERATOR_OR:
e440a328 5629 case OPERATOR_XOR:
e440a328 5630 case OPERATOR_MULT:
e440a328 5631 break;
5632 case OPERATOR_DIV:
a32698ee 5633 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5634 break;
e440a328 5635 case OPERATOR_MOD:
29a2d1d8 5636 is_idiv_op = true;
e440a328 5637 break;
5638 case OPERATOR_LSHIFT:
e440a328 5639 case OPERATOR_RSHIFT:
e440a328 5640 is_shift_op = true;
5641 break;
e440a328 5642 case OPERATOR_BITCLEAR:
a32698ee 5643 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5644 case OPERATOR_AND:
e440a328 5645 break;
5646 default:
c3e6f413 5647 go_unreachable();
e440a328 5648 }
5649
a32698ee 5650 if (left_type->is_string_type())
e440a328 5651 {
c484d925 5652 go_assert(this->op_ == OPERATOR_PLUS);
a32698ee 5653 Expression* string_plus =
5654 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5655 this->left_, this->right_);
ea664253 5656 return string_plus->get_backend(context);
a32698ee 5657 }
5658
5659 // For complex division Go might want slightly different results than the
5660 // backend implementation provides, so we have our own runtime routine.
1850e20c 5661 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5662 {
a32698ee 5663 Runtime::Function complex_code;
1850e20c 5664 switch (this->left_->type()->complex_type()->bits())
5665 {
5666 case 64:
a32698ee 5667 complex_code = Runtime::COMPLEX64_DIV;
1850e20c 5668 break;
5669 case 128:
a32698ee 5670 complex_code = Runtime::COMPLEX128_DIV;
1850e20c 5671 break;
5672 default:
5673 go_unreachable();
5674 }
a32698ee 5675 Expression* complex_div =
5676 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
ea664253 5677 return complex_div->get_backend(context);
1850e20c 5678 }
5679
ea664253 5680 Bexpression* left = this->left_->get_backend(context);
5681 Bexpression* right = this->right_->get_backend(context);
e440a328 5682
a32698ee 5683 Type* type = use_left_type ? left_type : right_type;
5684 Btype* btype = type->get_backend(gogo);
5685
5686 Bexpression* ret =
5687 gogo->backend()->binary_expression(this->op_, left, right, loc);
5688 ret = gogo->backend()->convert_expression(btype, ret, loc);
e440a328 5689
a32698ee 5690 // Initialize overflow constants.
5691 Bexpression* overflow;
5692 mpz_t zero;
5693 mpz_init_set_ui(zero, 0UL);
5694 mpz_t one;
5695 mpz_init_set_ui(one, 1UL);
5696 mpz_t neg_one;
5697 mpz_init_set_si(neg_one, -1);
e440a328 5698
a32698ee 5699 Btype* left_btype = left_type->get_backend(gogo);
5700 Btype* right_btype = right_type->get_backend(gogo);
e440a328 5701
5702 // In Go, a shift larger than the size of the type is well-defined.
a32698ee 5703 // This is not true in C, so we need to insert a conditional.
e440a328 5704 if (is_shift_op)
5705 {
a32698ee 5706 go_assert(left_type->integer_type() != NULL);
e440a328 5707
a32698ee 5708 mpz_t bitsval;
5709 int bits = left_type->integer_type()->bits();
5710 mpz_init_set_ui(bitsval, bits);
5711 Bexpression* bits_expr =
5712 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5713 Bexpression* compare =
5714 gogo->backend()->binary_expression(OPERATOR_LT,
5715 right, bits_expr, loc);
e440a328 5716
a32698ee 5717 Bexpression* zero_expr =
5718 gogo->backend()->integer_constant_expression(left_btype, zero);
5719 overflow = zero_expr;
e440a328 5720 if (this->op_ == OPERATOR_RSHIFT
a32698ee 5721 && !left_type->integer_type()->is_unsigned())
e440a328 5722 {
a32698ee 5723 Bexpression* neg_expr =
5724 gogo->backend()->binary_expression(OPERATOR_LT, left,
5725 zero_expr, loc);
5726 Bexpression* neg_one_expr =
5727 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5728 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5729 neg_one_expr,
5730 zero_expr, loc);
29a2d1d8 5731 }
a32698ee 5732 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5733 overflow, loc);
5734 mpz_clear(bitsval);
29a2d1d8 5735 }
5736
5737 // Add checks for division by zero and division overflow as needed.
5738 if (is_idiv_op)
5739 {
5c3f3470 5740 if (gogo->check_divide_by_zero())
29a2d1d8 5741 {
5742 // right == 0
a32698ee 5743 Bexpression* zero_expr =
5744 gogo->backend()->integer_constant_expression(right_btype, zero);
5745 Bexpression* check =
5746 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5747 right, zero_expr, loc);
29a2d1d8 5748
a32698ee 5749 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
29a2d1d8 5750 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
ea664253 5751 Bexpression* crash = gogo->runtime_error(errcode,
5752 loc)->get_backend(context);
29a2d1d8 5753
5754 // right == 0 ? (__go_runtime_error(...), 0) : ret
ea664253 5755 ret = gogo->backend()->conditional_expression(btype, check, crash,
5756 ret, loc);
b13c66cd 5757 }
5758
5c3f3470 5759 if (gogo->check_divide_overflow())
29a2d1d8 5760 {
5761 // right == -1
5762 // FIXME: It would be nice to say that this test is expected
5763 // to return false.
a32698ee 5764
5765 Bexpression* neg_one_expr =
5766 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5767 Bexpression* check =
5768 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5769 right, neg_one_expr, loc);
5770
5771 Bexpression* zero_expr =
5772 gogo->backend()->integer_constant_expression(btype, zero);
5773 Bexpression* one_expr =
5774 gogo->backend()->integer_constant_expression(btype, one);
5775
5776 if (type->integer_type()->is_unsigned())
29a2d1d8 5777 {
5778 // An unsigned -1 is the largest possible number, so
5779 // dividing is always 1 or 0.
a32698ee 5780
5781 Bexpression* cmp =
5782 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5783 left, right, loc);
29a2d1d8 5784 if (this->op_ == OPERATOR_DIV)
a32698ee 5785 overflow =
5786 gogo->backend()->conditional_expression(btype, cmp,
5787 one_expr, zero_expr,
5788 loc);
29a2d1d8 5789 else
a32698ee 5790 overflow =
5791 gogo->backend()->conditional_expression(btype, cmp,
5792 zero_expr, left,
5793 loc);
29a2d1d8 5794 }
5795 else
5796 {
5797 // Computing left / -1 is the same as computing - left,
5798 // which does not overflow since Go sets -fwrapv.
5799 if (this->op_ == OPERATOR_DIV)
a32698ee 5800 {
5801 Expression* negate_expr =
5802 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
ea664253 5803 overflow = negate_expr->get_backend(context);
a32698ee 5804 }
29a2d1d8 5805 else
a32698ee 5806 overflow = zero_expr;
29a2d1d8 5807 }
a32698ee 5808 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
29a2d1d8 5809
5810 // right == -1 ? - left : ret
a32698ee 5811 ret = gogo->backend()->conditional_expression(btype, check, overflow,
5812 ret, loc);
29a2d1d8 5813 }
e440a328 5814 }
5815
a32698ee 5816 mpz_clear(zero);
5817 mpz_clear(one);
5818 mpz_clear(neg_one);
ea664253 5819 return ret;
e440a328 5820}
5821
5822// Export a binary expression.
5823
5824void
5825Binary_expression::do_export(Export* exp) const
5826{
5827 exp->write_c_string("(");
5828 this->left_->export_expression(exp);
5829 switch (this->op_)
5830 {
5831 case OPERATOR_OROR:
5832 exp->write_c_string(" || ");
5833 break;
5834 case OPERATOR_ANDAND:
5835 exp->write_c_string(" && ");
5836 break;
5837 case OPERATOR_EQEQ:
5838 exp->write_c_string(" == ");
5839 break;
5840 case OPERATOR_NOTEQ:
5841 exp->write_c_string(" != ");
5842 break;
5843 case OPERATOR_LT:
5844 exp->write_c_string(" < ");
5845 break;
5846 case OPERATOR_LE:
5847 exp->write_c_string(" <= ");
5848 break;
5849 case OPERATOR_GT:
5850 exp->write_c_string(" > ");
5851 break;
5852 case OPERATOR_GE:
5853 exp->write_c_string(" >= ");
5854 break;
5855 case OPERATOR_PLUS:
5856 exp->write_c_string(" + ");
5857 break;
5858 case OPERATOR_MINUS:
5859 exp->write_c_string(" - ");
5860 break;
5861 case OPERATOR_OR:
5862 exp->write_c_string(" | ");
5863 break;
5864 case OPERATOR_XOR:
5865 exp->write_c_string(" ^ ");
5866 break;
5867 case OPERATOR_MULT:
5868 exp->write_c_string(" * ");
5869 break;
5870 case OPERATOR_DIV:
5871 exp->write_c_string(" / ");
5872 break;
5873 case OPERATOR_MOD:
5874 exp->write_c_string(" % ");
5875 break;
5876 case OPERATOR_LSHIFT:
5877 exp->write_c_string(" << ");
5878 break;
5879 case OPERATOR_RSHIFT:
5880 exp->write_c_string(" >> ");
5881 break;
5882 case OPERATOR_AND:
5883 exp->write_c_string(" & ");
5884 break;
5885 case OPERATOR_BITCLEAR:
5886 exp->write_c_string(" &^ ");
5887 break;
5888 default:
c3e6f413 5889 go_unreachable();
e440a328 5890 }
5891 this->right_->export_expression(exp);
5892 exp->write_c_string(")");
5893}
5894
5895// Import a binary expression.
5896
5897Expression*
5898Binary_expression::do_import(Import* imp)
5899{
5900 imp->require_c_string("(");
5901
5902 Expression* left = Expression::import_expression(imp);
5903
5904 Operator op;
5905 if (imp->match_c_string(" || "))
5906 {
5907 op = OPERATOR_OROR;
5908 imp->advance(4);
5909 }
5910 else if (imp->match_c_string(" && "))
5911 {
5912 op = OPERATOR_ANDAND;
5913 imp->advance(4);
5914 }
5915 else if (imp->match_c_string(" == "))
5916 {
5917 op = OPERATOR_EQEQ;
5918 imp->advance(4);
5919 }
5920 else if (imp->match_c_string(" != "))
5921 {
5922 op = OPERATOR_NOTEQ;
5923 imp->advance(4);
5924 }
5925 else if (imp->match_c_string(" < "))
5926 {
5927 op = OPERATOR_LT;
5928 imp->advance(3);
5929 }
5930 else if (imp->match_c_string(" <= "))
5931 {
5932 op = OPERATOR_LE;
5933 imp->advance(4);
5934 }
5935 else if (imp->match_c_string(" > "))
5936 {
5937 op = OPERATOR_GT;
5938 imp->advance(3);
5939 }
5940 else if (imp->match_c_string(" >= "))
5941 {
5942 op = OPERATOR_GE;
5943 imp->advance(4);
5944 }
5945 else if (imp->match_c_string(" + "))
5946 {
5947 op = OPERATOR_PLUS;
5948 imp->advance(3);
5949 }
5950 else if (imp->match_c_string(" - "))
5951 {
5952 op = OPERATOR_MINUS;
5953 imp->advance(3);
5954 }
5955 else if (imp->match_c_string(" | "))
5956 {
5957 op = OPERATOR_OR;
5958 imp->advance(3);
5959 }
5960 else if (imp->match_c_string(" ^ "))
5961 {
5962 op = OPERATOR_XOR;
5963 imp->advance(3);
5964 }
5965 else if (imp->match_c_string(" * "))
5966 {
5967 op = OPERATOR_MULT;
5968 imp->advance(3);
5969 }
5970 else if (imp->match_c_string(" / "))
5971 {
5972 op = OPERATOR_DIV;
5973 imp->advance(3);
5974 }
5975 else if (imp->match_c_string(" % "))
5976 {
5977 op = OPERATOR_MOD;
5978 imp->advance(3);
5979 }
5980 else if (imp->match_c_string(" << "))
5981 {
5982 op = OPERATOR_LSHIFT;
5983 imp->advance(4);
5984 }
5985 else if (imp->match_c_string(" >> "))
5986 {
5987 op = OPERATOR_RSHIFT;
5988 imp->advance(4);
5989 }
5990 else if (imp->match_c_string(" & "))
5991 {
5992 op = OPERATOR_AND;
5993 imp->advance(3);
5994 }
5995 else if (imp->match_c_string(" &^ "))
5996 {
5997 op = OPERATOR_BITCLEAR;
5998 imp->advance(4);
5999 }
6000 else
6001 {
6002 error_at(imp->location(), "unrecognized binary operator");
6003 return Expression::make_error(imp->location());
6004 }
6005
6006 Expression* right = Expression::import_expression(imp);
6007
6008 imp->require_c_string(")");
6009
6010 return Expression::make_binary(op, left, right, imp->location());
6011}
6012
d751bb78 6013// Dump ast representation of a binary expression.
6014
6015void
6016Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6017{
6018 ast_dump_context->ostream() << "(";
6019 ast_dump_context->dump_expression(this->left_);
6020 ast_dump_context->ostream() << " ";
6021 ast_dump_context->dump_operator(this->op_);
6022 ast_dump_context->ostream() << " ";
6023 ast_dump_context->dump_expression(this->right_);
6024 ast_dump_context->ostream() << ") ";
6025}
6026
e440a328 6027// Make a binary expression.
6028
6029Expression*
6030Expression::make_binary(Operator op, Expression* left, Expression* right,
b13c66cd 6031 Location location)
e440a328 6032{
6033 return new Binary_expression(op, left, right, location);
6034}
6035
6036// Implement a comparison.
6037
a32698ee 6038Bexpression*
6039Expression::comparison(Translate_context* context, Type* result_type,
6040 Operator op, Expression* left, Expression* right,
6041 Location location)
e440a328 6042{
2387f644 6043 Type* left_type = left->type();
6044 Type* right_type = right->type();
ceeb12d7 6045
e67508fa 6046 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
1b1f2abf 6047
15c67ee2 6048 if (left_type->is_string_type() && right_type->is_string_type())
e440a328 6049 {
2387f644 6050 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6051 left, right);
6052 right = zexpr;
e440a328 6053 }
15c67ee2 6054 else if ((left_type->interface_type() != NULL
6055 && right_type->interface_type() == NULL
6056 && !right_type->is_nil_type())
6057 || (left_type->interface_type() == NULL
6058 && !left_type->is_nil_type()
6059 && right_type->interface_type() != NULL))
e440a328 6060 {
6061 // Comparing an interface value to a non-interface value.
6062 if (left_type->interface_type() == NULL)
6063 {
6064 std::swap(left_type, right_type);
2387f644 6065 std::swap(left, right);
e440a328 6066 }
6067
6068 // The right operand is not an interface. We need to take its
6069 // address if it is not a pointer.
ceeb12d7 6070 Expression* pointer_arg = NULL;
e440a328 6071 if (right_type->points_to() != NULL)
2387f644 6072 pointer_arg = right;
e440a328 6073 else
6074 {
2387f644 6075 go_assert(right->is_addressable());
6076 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
ceeb12d7 6077 location);
e440a328 6078 }
e440a328 6079
2387f644 6080 Expression* descriptor =
6081 Expression::make_type_descriptor(right_type, location);
6082 left =
ceeb12d7 6083 Runtime::make_call((left_type->interface_type()->is_empty()
6084 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6085 : Runtime::INTERFACE_VALUE_COMPARE),
2387f644 6086 location, 3, left, descriptor,
ceeb12d7 6087 pointer_arg);
2387f644 6088 right = zexpr;
e440a328 6089 }
6090 else if (left_type->interface_type() != NULL
6091 && right_type->interface_type() != NULL)
6092 {
ceeb12d7 6093 Runtime::Function compare_function;
739bad04 6094 if (left_type->interface_type()->is_empty()
6095 && right_type->interface_type()->is_empty())
ceeb12d7 6096 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
739bad04 6097 else if (!left_type->interface_type()->is_empty()
6098 && !right_type->interface_type()->is_empty())
ceeb12d7 6099 compare_function = Runtime::INTERFACE_COMPARE;
739bad04 6100 else
6101 {
6102 if (left_type->interface_type()->is_empty())
6103 {
c484d925 6104 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
739bad04 6105 std::swap(left_type, right_type);
2387f644 6106 std::swap(left, right);
739bad04 6107 }
c484d925 6108 go_assert(!left_type->interface_type()->is_empty());
6109 go_assert(right_type->interface_type()->is_empty());
ceeb12d7 6110 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
739bad04 6111 }
6112
2387f644 6113 left = Runtime::make_call(compare_function, location, 2, left, right);
6114 right = zexpr;
e440a328 6115 }
6116
6117 if (left_type->is_nil_type()
6118 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6119 {
6120 std::swap(left_type, right_type);
2387f644 6121 std::swap(left, right);
e440a328 6122 }
6123
6124 if (right_type->is_nil_type())
6125 {
2387f644 6126 right = Expression::make_nil(location);
e440a328 6127 if (left_type->array_type() != NULL
6128 && left_type->array_type()->length() == NULL)
6129 {
6130 Array_type* at = left_type->array_type();
2387f644 6131 left = at->get_value_pointer(context->gogo(), left);
e440a328 6132 }
6133 else if (left_type->interface_type() != NULL)
6134 {
6135 // An interface is nil if the first field is nil.
2387f644 6136 left = Expression::make_field_reference(left, 0, location);
e440a328 6137 }
6138 }
6139
ea664253 6140 Bexpression* left_bexpr = left->get_backend(context);
6141 Bexpression* right_bexpr = right->get_backend(context);
e90c9dfc 6142
a32698ee 6143 Gogo* gogo = context->gogo();
6144 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6145 right_bexpr, location);
6146 if (result_type != NULL)
6147 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6148 ret, location);
e440a328 6149 return ret;
6150}
6151
6152// Class Bound_method_expression.
6153
6154// Traversal.
6155
6156int
6157Bound_method_expression::do_traverse(Traverse* traverse)
6158{
e0659c9e 6159 return Expression::traverse(&this->expr_, traverse);
e440a328 6160}
6161
0afbb937 6162// Lower the expression. If this is a method value rather than being
6163// called, and the method is accessed via a pointer, we may need to
6164// add nil checks. Introduce a temporary variable so that those nil
6165// checks do not cause multiple evaluation.
6166
6167Expression*
6168Bound_method_expression::do_lower(Gogo*, Named_object*,
6169 Statement_inserter* inserter, int)
6170{
6171 // For simplicity we use a temporary for every call to an embedded
6172 // method, even though some of them might be pure value methods and
6173 // not require a temporary.
6174 if (this->expr_->var_expression() == NULL
6175 && this->expr_->temporary_reference_expression() == NULL
6176 && this->expr_->set_and_use_temporary_expression() == NULL
6177 && (this->method_->field_indexes() != NULL
6178 || (this->method_->is_value_method()
6179 && this->expr_->type()->points_to() != NULL)))
6180 {
6181 Temporary_statement* temp =
6182 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6183 inserter->insert(temp);
6184 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6185 this->location());
6186 }
6187 return this;
6188}
6189
e440a328 6190// Return the type of a bound method expression. The type of this
0afbb937 6191// object is simply the type of the method with no receiver.
e440a328 6192
6193Type*
6194Bound_method_expression::do_type()
6195{
0afbb937 6196 Named_object* fn = this->method_->named_object();
6197 Function_type* fntype;
6198 if (fn->is_function())
6199 fntype = fn->func_value()->type();
6200 else if (fn->is_function_declaration())
6201 fntype = fn->func_declaration_value()->type();
e0659c9e 6202 else
6203 return Type::make_error_type();
0afbb937 6204 return fntype->copy_without_receiver();
e440a328 6205}
6206
6207// Determine the types of a method expression.
6208
6209void
6210Bound_method_expression::do_determine_type(const Type_context*)
6211{
0afbb937 6212 Named_object* fn = this->method_->named_object();
6213 Function_type* fntype;
6214 if (fn->is_function())
6215 fntype = fn->func_value()->type();
6216 else if (fn->is_function_declaration())
6217 fntype = fn->func_declaration_value()->type();
6218 else
6219 fntype = NULL;
e440a328 6220 if (fntype == NULL || !fntype->is_method())
6221 this->expr_->determine_type_no_context();
6222 else
6223 {
6224 Type_context subcontext(fntype->receiver()->type(), false);
6225 this->expr_->determine_type(&subcontext);
6226 }
6227}
6228
6229// Check the types of a method expression.
6230
6231void
6232Bound_method_expression::do_check_types(Gogo*)
6233{
0afbb937 6234 Named_object* fn = this->method_->named_object();
6235 if (!fn->is_function() && !fn->is_function_declaration())
6236 {
6237 this->report_error(_("object is not a method"));
6238 return;
6239 }
6240
6241 Function_type* fntype;
6242 if (fn->is_function())
6243 fntype = fn->func_value()->type();
6244 else if (fn->is_function_declaration())
6245 fntype = fn->func_declaration_value()->type();
e440a328 6246 else
0afbb937 6247 go_unreachable();
6248 Type* rtype = fntype->receiver()->type()->deref();
6249 Type* etype = (this->expr_type_ != NULL
6250 ? this->expr_type_
6251 : this->expr_->type());
6252 etype = etype->deref();
6253 if (!Type::are_identical(rtype, etype, true, NULL))
6254 this->report_error(_("method type does not match object type"));
6255}
6256
6257// If a bound method expression is not simply called, then it is
6258// represented as a closure. The closure will hold a single variable,
6259// the receiver to pass to the method. The function will be a simple
6260// thunk that pulls that value from the closure and calls the method
6261// with the remaining arguments.
6262//
6263// Because method values are not common, we don't build all thunks for
6264// every methods, but instead only build them as we need them. In
6265// particular, we even build them on demand for methods defined in
6266// other packages.
6267
6268Bound_method_expression::Method_value_thunks
6269 Bound_method_expression::method_value_thunks;
6270
6271// Find or create the thunk for METHOD.
6272
6273Named_object*
6274Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6275 Named_object* fn)
6276{
6277 std::pair<Named_object*, Named_object*> val(fn, NULL);
6278 std::pair<Method_value_thunks::iterator, bool> ins =
6279 Bound_method_expression::method_value_thunks.insert(val);
6280 if (!ins.second)
6281 {
6282 // We have seen this method before.
6283 go_assert(ins.first->second != NULL);
6284 return ins.first->second;
6285 }
6286
6287 Location loc = fn->location();
6288
6289 Function_type* orig_fntype;
6290 if (fn->is_function())
6291 orig_fntype = fn->func_value()->type();
6292 else if (fn->is_function_declaration())
6293 orig_fntype = fn->func_declaration_value()->type();
6294 else
6295 orig_fntype = NULL;
6296
6297 if (orig_fntype == NULL || !orig_fntype->is_method())
e440a328 6298 {
0afbb937 6299 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6300 return ins.first->second;
e440a328 6301 }
0afbb937 6302
6303 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 6304 // The type here is wrong--it should be the C function type. But it
6305 // doesn't really matter.
0afbb937 6306 Type* vt = Type::make_pointer_type(Type::make_void_type());
6307 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6308 sfl->push_back(Struct_field(Typed_identifier("val.1",
6309 orig_fntype->receiver()->type(),
6310 loc)));
6311 Type* closure_type = Type::make_struct_type(sfl, loc);
6312 closure_type = Type::make_pointer_type(closure_type);
6313
f8bdf81a 6314 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 6315
6316 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6317 false, loc);
6318
f8bdf81a 6319 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6320 cvar->set_is_used();
6321 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6322 new_no->func_value()->set_closure_var(cp);
0afbb937 6323
f8bdf81a 6324 gogo->start_block(loc);
0afbb937 6325
6326 // Field 0 of the closure is the function code pointer, field 1 is
6327 // the value on which to invoke the method.
6328 Expression* arg = Expression::make_var_reference(cp, loc);
6329 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6330 arg = Expression::make_field_reference(arg, 1, loc);
6331
6332 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6333
6334 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6335 Expression_list* args;
6336 if (orig_params == NULL || orig_params->empty())
6337 args = NULL;
6338 else
6339 {
6340 const Typed_identifier_list* new_params = new_fntype->parameters();
6341 args = new Expression_list();
6342 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 6343 p != new_params->end();
0afbb937 6344 ++p)
6345 {
6346 Named_object* p_no = gogo->lookup(p->name(), NULL);
6347 go_assert(p_no != NULL
6348 && p_no->is_variable()
6349 && p_no->var_value()->is_parameter());
6350 args->push_back(Expression::make_var_reference(p_no, loc));
6351 }
6352 }
6353
6354 Call_expression* call = Expression::make_call(bme, args,
6355 orig_fntype->is_varargs(),
6356 loc);
6357 call->set_varargs_are_lowered();
6358
6359 Statement* s = Statement::make_return_from_call(call, loc);
6360 gogo->add_statement(s);
6361 Block* b = gogo->finish_block(loc);
6362 gogo->add_block(b, loc);
6363 gogo->lower_block(new_no, b);
a32698ee 6364 gogo->flatten_block(new_no, b);
0afbb937 6365 gogo->finish_function(loc);
6366
6367 ins.first->second = new_no;
6368 return new_no;
6369}
6370
6371// Return an expression to check *REF for nil while dereferencing
6372// according to FIELD_INDEXES. Update *REF to build up the field
6373// reference. This is a static function so that we don't have to
6374// worry about declaring Field_indexes in expressions.h.
6375
6376static Expression*
6377bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6378 Expression** ref)
6379{
6380 if (field_indexes == NULL)
6381 return Expression::make_boolean(false, loc);
6382 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6383 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6384 go_assert(stype != NULL
6385 && field_indexes->field_index < stype->field_count());
6386 if ((*ref)->type()->struct_type() == NULL)
6387 {
6388 go_assert((*ref)->type()->points_to() != NULL);
6389 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6390 Expression::make_nil(loc),
6391 loc);
6392 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6393 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6394 go_assert((*ref)->type()->struct_type() == stype);
6395 }
6396 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6397 loc);
6398 return cond;
e440a328 6399}
6400
ea664253 6401// Get the backend representation for a method value.
e440a328 6402
ea664253 6403Bexpression*
6404Bound_method_expression::do_get_backend(Translate_context* context)
e440a328 6405{
0afbb937 6406 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6407 this->method_,
6408 this->function_);
6409 if (thunk->is_erroneous())
6410 {
6411 go_assert(saw_errors());
ea664253 6412 return context->backend()->error_expression();
0afbb937 6413 }
6414
6415 // FIXME: We should lower this earlier, but we can't lower it in the
6416 // lowering pass because at that point we don't know whether we need
6417 // to create the thunk or not. If the expression is called, we
6418 // don't need the thunk.
6419
6420 Location loc = this->location();
6421
6422 // If the method expects a value, and we have a pointer, we need to
6423 // dereference the pointer.
6424
6425 Named_object* fn = this->method_->named_object();
6426 Function_type* fntype;
6427 if (fn->is_function())
6428 fntype = fn->func_value()->type();
6429 else if (fn->is_function_declaration())
6430 fntype = fn->func_declaration_value()->type();
6431 else
6432 go_unreachable();
6433
6434 Expression* val = this->expr_;
6435 if (fntype->receiver()->type()->points_to() == NULL
6436 && val->type()->points_to() != NULL)
6437 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6438
6439 // Note that we are ignoring this->expr_type_ here. The thunk will
6440 // expect a closure whose second field has type this->expr_type_ (if
6441 // that is not NULL). We are going to pass it a closure whose
6442 // second field has type this->expr_->type(). Since
6443 // this->expr_type_ is only not-NULL for pointer types, we can get
6444 // away with this.
6445
6446 Struct_field_list* fields = new Struct_field_list();
6447 fields->push_back(Struct_field(Typed_identifier("fn.0",
6448 thunk->func_value()->type(),
6449 loc)));
6450 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6451 Struct_type* st = Type::make_struct_type(fields, loc);
6452
6453 Expression_list* vals = new Expression_list();
6454 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6455 vals->push_back(val);
6456
6457 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
2c809f8f 6458 ret = Expression::make_heap_expression(ret, loc);
0afbb937 6459
0afbb937 6460 // See whether the expression or any embedded pointers are nil.
6461
df7ef1fd 6462 Expression* nil_check = NULL;
0afbb937 6463 Expression* expr = this->expr_;
6464 if (this->method_->field_indexes() != NULL)
6465 {
6466 // Note that we are evaluating this->expr_ twice, but that is OK
6467 // because in the lowering pass we forced it into a temporary
6468 // variable.
6469 Expression* ref = expr;
6470 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6471 expr = ref;
6472 }
6473
6474 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6475 {
6476 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6477 Expression::make_nil(loc),
6478 loc);
6479 if (nil_check == NULL)
6480 nil_check = n;
6481 else
6482 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6483 }
6484
ea664253 6485 Bexpression* bme = ret->get_backend(context);
0afbb937 6486 if (nil_check != NULL)
6487 {
df7ef1fd 6488 Gogo* gogo = context->gogo();
ea664253 6489 Bexpression* crash =
6490 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6491 loc)->get_backend(context);
df7ef1fd 6492 Btype* btype = ret->type()->get_backend(gogo);
ea664253 6493 Bexpression* bcheck = nil_check->get_backend(context);
6494 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
df7ef1fd 6495 bme, loc);
6496 }
ea664253 6497 return bme;
e440a328 6498}
6499
d751bb78 6500// Dump ast representation of a bound method expression.
6501
6502void
6503Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6504 const
6505{
6506 if (this->expr_type_ != NULL)
6507 ast_dump_context->ostream() << "(";
6508 ast_dump_context->dump_expression(this->expr_);
6509 if (this->expr_type_ != NULL)
6510 {
6511 ast_dump_context->ostream() << ":";
6512 ast_dump_context->dump_type(this->expr_type_);
6513 ast_dump_context->ostream() << ")";
6514 }
6515
0afbb937 6516 ast_dump_context->ostream() << "." << this->function_->name();
d751bb78 6517}
6518
e440a328 6519// Make a method expression.
6520
6521Bound_method_expression*
0afbb937 6522Expression::make_bound_method(Expression* expr, const Method* method,
6523 Named_object* function, Location location)
e440a328 6524{
0afbb937 6525 return new Bound_method_expression(expr, method, function, location);
e440a328 6526}
6527
6528// Class Builtin_call_expression. This is used for a call to a
6529// builtin function.
6530
6531class Builtin_call_expression : public Call_expression
6532{
6533 public:
6534 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
b13c66cd 6535 bool is_varargs, Location location);
e440a328 6536
6537 protected:
6538 // This overrides Call_expression::do_lower.
6539 Expression*
ceeb4318 6540 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 6541
35a54f17 6542 Expression*
6543 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6544
e440a328 6545 bool
6546 do_is_constant() const;
6547
6548 bool
0c77715b 6549 do_numeric_constant_value(Numeric_constant*) const;
e440a328 6550
4f2138d7 6551 bool
a7549a6a 6552 do_discarding_value();
6553
e440a328 6554 Type*
6555 do_type();
6556
6557 void
6558 do_determine_type(const Type_context*);
6559
6560 void
6561 do_check_types(Gogo*);
6562
6563 Expression*
72666aed 6564 do_copy();
e440a328 6565
ea664253 6566 Bexpression*
6567 do_get_backend(Translate_context*);
e440a328 6568
6569 void
6570 do_export(Export*) const;
6571
6572 virtual bool
6573 do_is_recover_call() const;
6574
6575 virtual void
6576 do_set_recover_arg(Expression*);
6577
6578 private:
6579 // The builtin functions.
6580 enum Builtin_function_code
6581 {
6582 BUILTIN_INVALID,
6583
6584 // Predeclared builtin functions.
6585 BUILTIN_APPEND,
6586 BUILTIN_CAP,
6587 BUILTIN_CLOSE,
48080209 6588 BUILTIN_COMPLEX,
e440a328 6589 BUILTIN_COPY,
1cce762f 6590 BUILTIN_DELETE,
e440a328 6591 BUILTIN_IMAG,
6592 BUILTIN_LEN,
6593 BUILTIN_MAKE,
6594 BUILTIN_NEW,
6595 BUILTIN_PANIC,
6596 BUILTIN_PRINT,
6597 BUILTIN_PRINTLN,
6598 BUILTIN_REAL,
6599 BUILTIN_RECOVER,
6600
6601 // Builtin functions from the unsafe package.
6602 BUILTIN_ALIGNOF,
6603 BUILTIN_OFFSETOF,
6604 BUILTIN_SIZEOF
6605 };
6606
6607 Expression*
6608 one_arg() const;
6609
6610 bool
6611 check_one_arg();
6612
6613 static Type*
6614 real_imag_type(Type*);
6615
6616 static Type*
48080209 6617 complex_type(Type*);
e440a328 6618
a9182619 6619 Expression*
6620 lower_make();
6621
6622 bool
1ad00fd4 6623 check_int_value(Expression*, bool is_length);
a9182619 6624
e440a328 6625 // A pointer back to the general IR structure. This avoids a global
6626 // variable, or passing it around everywhere.
6627 Gogo* gogo_;
6628 // The builtin function being called.
6629 Builtin_function_code code_;
0f914071 6630 // Used to stop endless loops when the length of an array uses len
6631 // or cap of the array itself.
6632 mutable bool seen_;
6334270b 6633 // Whether the argument is set for calls to BUILTIN_RECOVER.
6634 bool recover_arg_is_set_;
e440a328 6635};
6636
6637Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6638 Expression* fn,
6639 Expression_list* args,
6640 bool is_varargs,
b13c66cd 6641 Location location)
e440a328 6642 : Call_expression(fn, args, is_varargs, location),
6334270b 6643 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
6644 recover_arg_is_set_(false)
e440a328 6645{
6646 Func_expression* fnexp = this->fn()->func_expression();
c484d925 6647 go_assert(fnexp != NULL);
e440a328 6648 const std::string& name(fnexp->named_object()->name());
6649 if (name == "append")
6650 this->code_ = BUILTIN_APPEND;
6651 else if (name == "cap")
6652 this->code_ = BUILTIN_CAP;
6653 else if (name == "close")
6654 this->code_ = BUILTIN_CLOSE;
48080209 6655 else if (name == "complex")
6656 this->code_ = BUILTIN_COMPLEX;
e440a328 6657 else if (name == "copy")
6658 this->code_ = BUILTIN_COPY;
1cce762f 6659 else if (name == "delete")
6660 this->code_ = BUILTIN_DELETE;
e440a328 6661 else if (name == "imag")
6662 this->code_ = BUILTIN_IMAG;
6663 else if (name == "len")
6664 this->code_ = BUILTIN_LEN;
6665 else if (name == "make")
6666 this->code_ = BUILTIN_MAKE;
6667 else if (name == "new")
6668 this->code_ = BUILTIN_NEW;
6669 else if (name == "panic")
6670 this->code_ = BUILTIN_PANIC;
6671 else if (name == "print")
6672 this->code_ = BUILTIN_PRINT;
6673 else if (name == "println")
6674 this->code_ = BUILTIN_PRINTLN;
6675 else if (name == "real")
6676 this->code_ = BUILTIN_REAL;
6677 else if (name == "recover")
6678 this->code_ = BUILTIN_RECOVER;
6679 else if (name == "Alignof")
6680 this->code_ = BUILTIN_ALIGNOF;
6681 else if (name == "Offsetof")
6682 this->code_ = BUILTIN_OFFSETOF;
6683 else if (name == "Sizeof")
6684 this->code_ = BUILTIN_SIZEOF;
6685 else
c3e6f413 6686 go_unreachable();
e440a328 6687}
6688
6689// Return whether this is a call to recover. This is a virtual
6690// function called from the parent class.
6691
6692bool
6693Builtin_call_expression::do_is_recover_call() const
6694{
6695 if (this->classification() == EXPRESSION_ERROR)
6696 return false;
6697 return this->code_ == BUILTIN_RECOVER;
6698}
6699
6700// Set the argument for a call to recover.
6701
6702void
6703Builtin_call_expression::do_set_recover_arg(Expression* arg)
6704{
6705 const Expression_list* args = this->args();
c484d925 6706 go_assert(args == NULL || args->empty());
e440a328 6707 Expression_list* new_args = new Expression_list();
6708 new_args->push_back(arg);
6709 this->set_args(new_args);
6334270b 6710 this->recover_arg_is_set_ = true;
e440a328 6711}
6712
e440a328 6713// Lower a builtin call expression. This turns new and make into
6714// specific expressions. We also convert to a constant if we can.
6715
6716Expression*
ceeb4318 6717Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6718 Statement_inserter* inserter, int)
e440a328 6719{
a9182619 6720 if (this->classification() == EXPRESSION_ERROR)
6721 return this;
6722
b13c66cd 6723 Location loc = this->location();
1cce762f 6724
a8725655 6725 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6726 {
6727 this->report_error(_("invalid use of %<...%> with builtin function"));
1cce762f 6728 return Expression::make_error(loc);
a8725655 6729 }
6730
393ba00b 6731 if (this->code_ == BUILTIN_OFFSETOF)
6732 {
6733 Expression* arg = this->one_arg();
12e69faa 6734
6735 if (arg->bound_method_expression() != NULL
6736 || arg->interface_field_reference_expression() != NULL)
6737 {
6738 this->report_error(_("invalid use of method value as argument "
6739 "of Offsetof"));
6740 return this;
6741 }
6742
393ba00b 6743 Field_reference_expression* farg = arg->field_reference_expression();
6744 while (farg != NULL)
6745 {
6746 if (!farg->implicit())
6747 break;
6748 // When the selector refers to an embedded field,
6749 // it must not be reached through pointer indirections.
6750 if (farg->expr()->deref() != farg->expr())
6751 {
12e69faa 6752 this->report_error(_("argument of Offsetof implies "
6753 "indirection of an embedded field"));
393ba00b 6754 return this;
6755 }
6756 // Go up until we reach the original base.
6757 farg = farg->expr()->field_reference_expression();
6758 }
6759 }
6760
1cce762f 6761 if (this->is_constant())
e440a328 6762 {
0c77715b 6763 Numeric_constant nc;
6764 if (this->numeric_constant_value(&nc))
6765 return nc.expression(loc);
e440a328 6766 }
1cce762f 6767
6768 switch (this->code_)
e440a328 6769 {
1cce762f 6770 default:
6771 break;
6772
6773 case BUILTIN_NEW:
6774 {
6775 const Expression_list* args = this->args();
6776 if (args == NULL || args->size() < 1)
6777 this->report_error(_("not enough arguments"));
6778 else if (args->size() > 1)
6779 this->report_error(_("too many arguments"));
6780 else
6781 {
6782 Expression* arg = args->front();
6783 if (!arg->is_type_expression())
6784 {
6785 error_at(arg->location(), "expected type");
6786 this->set_is_error();
6787 }
6788 else
6789 return Expression::make_allocation(arg->type(), loc);
6790 }
6791 }
6792 break;
6793
6794 case BUILTIN_MAKE:
6795 return this->lower_make();
6796
6797 case BUILTIN_RECOVER:
e440a328 6798 if (function != NULL)
6799 function->func_value()->set_calls_recover();
6800 else
6801 {
6802 // Calling recover outside of a function always returns the
6803 // nil empty interface.
823c7e3d 6804 Type* eface = Type::make_empty_interface_type(loc);
1cce762f 6805 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
e440a328 6806 }
1cce762f 6807 break;
6808
6809 case BUILTIN_APPEND:
6810 {
6811 // Lower the varargs.
6812 const Expression_list* args = this->args();
6813 if (args == NULL || args->empty())
e440a328 6814 return this;
1cce762f 6815 Type* slice_type = args->front()->type();
6816 if (!slice_type->is_slice_type())
6817 {
3ff4863b 6818 if (slice_type->is_nil_type())
6819 error_at(args->front()->location(), "use of untyped nil");
6820 else
6821 error_at(args->front()->location(),
6822 "argument 1 must be a slice");
1cce762f 6823 this->set_is_error();
6824 return this;
6825 }
19fd40c3 6826 Type* element_type = slice_type->array_type()->element_type();
6827 this->lower_varargs(gogo, function, inserter,
6828 Type::make_array_type(element_type, NULL),
6829 2);
1cce762f 6830 }
6831 break;
6832
6833 case BUILTIN_DELETE:
6834 {
6835 // Lower to a runtime function call.
6836 const Expression_list* args = this->args();
6837 if (args == NULL || args->size() < 2)
6838 this->report_error(_("not enough arguments"));
6839 else if (args->size() > 2)
6840 this->report_error(_("too many arguments"));
6841 else if (args->front()->type()->map_type() == NULL)
6842 this->report_error(_("argument 1 must be a map"));
6843 else
6844 {
6845 // Since this function returns no value it must appear in
6846 // a statement by itself, so we don't have to worry about
6847 // order of evaluation of values around it. Evaluate the
6848 // map first to get order of evaluation right.
6849 Map_type* mt = args->front()->type()->map_type();
6850 Temporary_statement* map_temp =
6851 Statement::make_temporary(mt, args->front(), loc);
6852 inserter->insert(map_temp);
6853
6854 Temporary_statement* key_temp =
6855 Statement::make_temporary(mt->key_type(), args->back(), loc);
6856 inserter->insert(key_temp);
6857
6858 Expression* e1 = Expression::make_temporary_reference(map_temp,
6859 loc);
6860 Expression* e2 = Expression::make_temporary_reference(key_temp,
6861 loc);
6862 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6863 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6864 2, e1, e2);
6865 }
6866 }
6867 break;
e440a328 6868 }
6869
6870 return this;
6871}
6872
35a54f17 6873// Flatten a builtin call expression. This turns the arguments of copy and
6874// append into temporary expressions.
6875
6876Expression*
6877Builtin_call_expression::do_flatten(Gogo*, Named_object*,
6878 Statement_inserter* inserter)
6879{
6880 if (this->code_ == BUILTIN_APPEND
6881 || this->code_ == BUILTIN_COPY)
6882 {
6883 Location loc = this->location();
6884 Type* at = this->args()->front()->type();
6885 for (Expression_list::iterator pa = this->args()->begin();
6886 pa != this->args()->end();
6887 ++pa)
6888 {
6889 if ((*pa)->is_nil_expression())
55e8ba6a 6890 {
6891 Expression* nil = Expression::make_nil(loc);
6892 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
6893 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
6894 }
35a54f17 6895 if (!(*pa)->is_variable())
6896 {
6897 Temporary_statement* temp =
6898 Statement::make_temporary(NULL, *pa, loc);
6899 inserter->insert(temp);
6900 *pa = Expression::make_temporary_reference(temp, loc);
6901 }
6902 }
6903 }
6904 return this;
6905}
6906
a9182619 6907// Lower a make expression.
6908
6909Expression*
6910Builtin_call_expression::lower_make()
6911{
b13c66cd 6912 Location loc = this->location();
a9182619 6913
6914 const Expression_list* args = this->args();
6915 if (args == NULL || args->size() < 1)
6916 {
6917 this->report_error(_("not enough arguments"));
6918 return Expression::make_error(this->location());
6919 }
6920
6921 Expression_list::const_iterator parg = args->begin();
6922
6923 Expression* first_arg = *parg;
6924 if (!first_arg->is_type_expression())
6925 {
6926 error_at(first_arg->location(), "expected type");
6927 this->set_is_error();
6928 return Expression::make_error(this->location());
6929 }
6930 Type* type = first_arg->type();
6931
6932 bool is_slice = false;
6933 bool is_map = false;
6934 bool is_chan = false;
411eb89e 6935 if (type->is_slice_type())
a9182619 6936 is_slice = true;
6937 else if (type->map_type() != NULL)
6938 is_map = true;
6939 else if (type->channel_type() != NULL)
6940 is_chan = true;
6941 else
6942 {
6943 this->report_error(_("invalid type for make function"));
6944 return Expression::make_error(this->location());
6945 }
6946
ac84c822 6947 bool have_big_args = false;
6948 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6949 int uintptr_bits = uintptr_type->integer_type()->bits();
6950
f6bc81e6 6951 Type_context int_context(Type::lookup_integer_type("int"), false);
6952
a9182619 6953 ++parg;
6954 Expression* len_arg;
6955 if (parg == args->end())
6956 {
6957 if (is_slice)
6958 {
6959 this->report_error(_("length required when allocating a slice"));
6960 return Expression::make_error(this->location());
6961 }
e67508fa 6962 len_arg = Expression::make_integer_ul(0, NULL, loc);
a9182619 6963 }
6964 else
6965 {
6966 len_arg = *parg;
f6bc81e6 6967 len_arg->determine_type(&int_context);
1ad00fd4 6968 if (!this->check_int_value(len_arg, true))
6969 return Expression::make_error(this->location());
ac84c822 6970 if (len_arg->type()->integer_type() != NULL
6971 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6972 have_big_args = true;
a9182619 6973 ++parg;
6974 }
6975
6976 Expression* cap_arg = NULL;
6977 if (is_slice && parg != args->end())
6978 {
6979 cap_arg = *parg;
f6bc81e6 6980 cap_arg->determine_type(&int_context);
1ad00fd4 6981 if (!this->check_int_value(cap_arg, false))
6982 return Expression::make_error(this->location());
6983
6984 Numeric_constant nclen;
6985 Numeric_constant nccap;
6986 unsigned long vlen;
6987 unsigned long vcap;
6988 if (len_arg->numeric_constant_value(&nclen)
6989 && cap_arg->numeric_constant_value(&nccap)
6990 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
6991 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
6992 && vlen > vcap)
a9182619 6993 {
1ad00fd4 6994 this->report_error(_("len larger than cap"));
a9182619 6995 return Expression::make_error(this->location());
6996 }
1ad00fd4 6997
ac84c822 6998 if (cap_arg->type()->integer_type() != NULL
6999 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7000 have_big_args = true;
a9182619 7001 ++parg;
7002 }
7003
7004 if (parg != args->end())
7005 {
7006 this->report_error(_("too many arguments to make"));
7007 return Expression::make_error(this->location());
7008 }
7009
b13c66cd 7010 Location type_loc = first_arg->location();
a9182619 7011 Expression* type_arg;
7012 if (is_slice || is_chan)
7013 type_arg = Expression::make_type_descriptor(type, type_loc);
7014 else if (is_map)
7015 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7016 else
7017 go_unreachable();
7018
7019 Expression* call;
7020 if (is_slice)
7021 {
7022 if (cap_arg == NULL)
ac84c822 7023 call = Runtime::make_call((have_big_args
7024 ? Runtime::MAKESLICE1BIG
7025 : Runtime::MAKESLICE1),
7026 loc, 2, type_arg, len_arg);
a9182619 7027 else
ac84c822 7028 call = Runtime::make_call((have_big_args
7029 ? Runtime::MAKESLICE2BIG
7030 : Runtime::MAKESLICE2),
7031 loc, 3, type_arg, len_arg, cap_arg);
a9182619 7032 }
7033 else if (is_map)
ac84c822 7034 call = Runtime::make_call((have_big_args
7035 ? Runtime::MAKEMAPBIG
7036 : Runtime::MAKEMAP),
7037 loc, 2, type_arg, len_arg);
a9182619 7038 else if (is_chan)
ac84c822 7039 call = Runtime::make_call((have_big_args
7040 ? Runtime::MAKECHANBIG
7041 : Runtime::MAKECHAN),
7042 loc, 2, type_arg, len_arg);
a9182619 7043 else
7044 go_unreachable();
7045
7046 return Expression::make_unsafe_cast(type, call, loc);
7047}
7048
7049// Return whether an expression has an integer value. Report an error
7050// if not. This is used when handling calls to the predeclared make
7051// function.
7052
7053bool
1ad00fd4 7054Builtin_call_expression::check_int_value(Expression* e, bool is_length)
a9182619 7055{
0c77715b 7056 Numeric_constant nc;
1ad00fd4 7057 if (e->numeric_constant_value(&nc))
a9182619 7058 {
1ad00fd4 7059 unsigned long v;
7060 switch (nc.to_unsigned_long(&v))
7061 {
7062 case Numeric_constant::NC_UL_VALID:
1b10c5e7 7063 break;
1ad00fd4 7064 case Numeric_constant::NC_UL_NOTINT:
7065 error_at(e->location(), "non-integer %s argument to make",
7066 is_length ? "len" : "cap");
7067 return false;
7068 case Numeric_constant::NC_UL_NEGATIVE:
7069 error_at(e->location(), "negative %s argument to make",
7070 is_length ? "len" : "cap");
7071 return false;
7072 case Numeric_constant::NC_UL_BIG:
7073 // We don't want to give a compile-time error for a 64-bit
7074 // value on a 32-bit target.
1b10c5e7 7075 break;
1ad00fd4 7076 }
1b10c5e7 7077
7078 mpz_t val;
7079 if (!nc.to_int(&val))
7080 go_unreachable();
7081 int bits = mpz_sizeinbase(val, 2);
7082 mpz_clear(val);
7083 Type* int_type = Type::lookup_integer_type("int");
7084 if (bits >= int_type->integer_type()->bits())
7085 {
7086 error_at(e->location(), "%s argument too large for make",
7087 is_length ? "len" : "cap");
7088 return false;
7089 }
7090
7091 return true;
a9182619 7092 }
7093
1ad00fd4 7094 if (e->type()->integer_type() != NULL)
7095 return true;
7096
7097 error_at(e->location(), "non-integer %s argument to make",
7098 is_length ? "len" : "cap");
a9182619 7099 return false;
7100}
7101
e440a328 7102// Return the type of the real or imag functions, given the type of
fcbea5e4 7103// the argument. We need to map complex64 to float32 and complex128
7104// to float64, so it has to be done by name. This returns NULL if it
7105// can't figure out the type.
e440a328 7106
7107Type*
7108Builtin_call_expression::real_imag_type(Type* arg_type)
7109{
7110 if (arg_type == NULL || arg_type->is_abstract())
7111 return NULL;
7112 Named_type* nt = arg_type->named_type();
7113 if (nt == NULL)
7114 return NULL;
7115 while (nt->real_type()->named_type() != NULL)
7116 nt = nt->real_type()->named_type();
48080209 7117 if (nt->name() == "complex64")
e440a328 7118 return Type::lookup_float_type("float32");
7119 else if (nt->name() == "complex128")
7120 return Type::lookup_float_type("float64");
7121 else
7122 return NULL;
7123}
7124
48080209 7125// Return the type of the complex function, given the type of one of the
e440a328 7126// argments. Like real_imag_type, we have to map by name.
7127
7128Type*
48080209 7129Builtin_call_expression::complex_type(Type* arg_type)
e440a328 7130{
7131 if (arg_type == NULL || arg_type->is_abstract())
7132 return NULL;
7133 Named_type* nt = arg_type->named_type();
7134 if (nt == NULL)
7135 return NULL;
7136 while (nt->real_type()->named_type() != NULL)
7137 nt = nt->real_type()->named_type();
48080209 7138 if (nt->name() == "float32")
e440a328 7139 return Type::lookup_complex_type("complex64");
7140 else if (nt->name() == "float64")
7141 return Type::lookup_complex_type("complex128");
7142 else
7143 return NULL;
7144}
7145
7146// Return a single argument, or NULL if there isn't one.
7147
7148Expression*
7149Builtin_call_expression::one_arg() const
7150{
7151 const Expression_list* args = this->args();
aa615cb3 7152 if (args == NULL || args->size() != 1)
e440a328 7153 return NULL;
7154 return args->front();
7155}
7156
83921647 7157// A traversal class which looks for a call or receive expression.
7158
7159class Find_call_expression : public Traverse
7160{
7161 public:
7162 Find_call_expression()
7163 : Traverse(traverse_expressions),
7164 found_(false)
7165 { }
7166
7167 int
7168 expression(Expression**);
7169
7170 bool
7171 found()
7172 { return this->found_; }
7173
7174 private:
7175 bool found_;
7176};
7177
7178int
7179Find_call_expression::expression(Expression** pexpr)
7180{
7181 if ((*pexpr)->call_expression() != NULL
7182 || (*pexpr)->receive_expression() != NULL)
7183 {
7184 this->found_ = true;
7185 return TRAVERSE_EXIT;
7186 }
7187 return TRAVERSE_CONTINUE;
7188}
7189
7190// Return whether this is constant: len of a string constant, or len
7191// or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7192// unsafe.Alignof.
e440a328 7193
7194bool
7195Builtin_call_expression::do_is_constant() const
7196{
12e69faa 7197 if (this->is_error_expression())
7198 return true;
e440a328 7199 switch (this->code_)
7200 {
7201 case BUILTIN_LEN:
7202 case BUILTIN_CAP:
7203 {
0f914071 7204 if (this->seen_)
7205 return false;
7206
e440a328 7207 Expression* arg = this->one_arg();
7208 if (arg == NULL)
7209 return false;
7210 Type* arg_type = arg->type();
7211
7212 if (arg_type->points_to() != NULL
7213 && arg_type->points_to()->array_type() != NULL
411eb89e 7214 && !arg_type->points_to()->is_slice_type())
e440a328 7215 arg_type = arg_type->points_to();
7216
83921647 7217 // The len and cap functions are only constant if there are no
7218 // function calls or channel operations in the arguments.
7219 // Otherwise we have to make the call.
7220 if (!arg->is_constant())
7221 {
7222 Find_call_expression find_call;
7223 Expression::traverse(&arg, &find_call);
7224 if (find_call.found())
7225 return false;
7226 }
7227
e440a328 7228 if (arg_type->array_type() != NULL
7229 && arg_type->array_type()->length() != NULL)
0f914071 7230 return true;
e440a328 7231
7232 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
0f914071 7233 {
7234 this->seen_ = true;
7235 bool ret = arg->is_constant();
7236 this->seen_ = false;
7237 return ret;
7238 }
e440a328 7239 }
7240 break;
7241
7242 case BUILTIN_SIZEOF:
7243 case BUILTIN_ALIGNOF:
7244 return this->one_arg() != NULL;
7245
7246 case BUILTIN_OFFSETOF:
7247 {
7248 Expression* arg = this->one_arg();
7249 if (arg == NULL)
7250 return false;
7251 return arg->field_reference_expression() != NULL;
7252 }
7253
48080209 7254 case BUILTIN_COMPLEX:
e440a328 7255 {
7256 const Expression_list* args = this->args();
7257 if (args != NULL && args->size() == 2)
7258 return args->front()->is_constant() && args->back()->is_constant();
7259 }
7260 break;
7261
7262 case BUILTIN_REAL:
7263 case BUILTIN_IMAG:
7264 {
7265 Expression* arg = this->one_arg();
7266 return arg != NULL && arg->is_constant();
7267 }
7268
7269 default:
7270 break;
7271 }
7272
7273 return false;
7274}
7275
0c77715b 7276// Return a numeric constant if possible.
e440a328 7277
7278bool
0c77715b 7279Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
e440a328 7280{
7281 if (this->code_ == BUILTIN_LEN
7282 || this->code_ == BUILTIN_CAP)
7283 {
7284 Expression* arg = this->one_arg();
7285 if (arg == NULL)
7286 return false;
7287 Type* arg_type = arg->type();
7288
7289 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7290 {
7291 std::string sval;
7292 if (arg->string_constant_value(&sval))
7293 {
0c77715b 7294 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7295 sval.length());
e440a328 7296 return true;
7297 }
7298 }
7299
7300 if (arg_type->points_to() != NULL
7301 && arg_type->points_to()->array_type() != NULL
411eb89e 7302 && !arg_type->points_to()->is_slice_type())
e440a328 7303 arg_type = arg_type->points_to();
7304
7305 if (arg_type->array_type() != NULL
7306 && arg_type->array_type()->length() != NULL)
7307 {
0f914071 7308 if (this->seen_)
7309 return false;
e440a328 7310 Expression* e = arg_type->array_type()->length();
0f914071 7311 this->seen_ = true;
0c77715b 7312 bool r = e->numeric_constant_value(nc);
0f914071 7313 this->seen_ = false;
7314 if (r)
e440a328 7315 {
0c77715b 7316 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7317 this->location()))
7318 r = false;
e440a328 7319 }
0c77715b 7320 return r;
e440a328 7321 }
7322 }
7323 else if (this->code_ == BUILTIN_SIZEOF
7324 || this->code_ == BUILTIN_ALIGNOF)
7325 {
7326 Expression* arg = this->one_arg();
7327 if (arg == NULL)
7328 return false;
7329 Type* arg_type = arg->type();
5c13bd80 7330 if (arg_type->is_error())
e440a328 7331 return false;
7332 if (arg_type->is_abstract())
7333 return false;
2c809f8f 7334 if (this->seen_)
7335 return false;
927a01eb 7336
5892f89f 7337 unsigned long ret;
e440a328 7338 if (this->code_ == BUILTIN_SIZEOF)
7339 {
2c809f8f 7340 this->seen_ = true;
7341 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7342 this->seen_ = false;
7343 if (!ok)
e440a328 7344 return false;
7345 }
7346 else if (this->code_ == BUILTIN_ALIGNOF)
7347 {
2c809f8f 7348 bool ok;
7349 this->seen_ = true;
637bd3af 7350 if (arg->field_reference_expression() == NULL)
2c809f8f 7351 ok = arg_type->backend_type_align(this->gogo_, &ret);
637bd3af 7352 else
e440a328 7353 {
7354 // Calling unsafe.Alignof(s.f) returns the alignment of
7355 // the type of f when it is used as a field in a struct.
2c809f8f 7356 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
e440a328 7357 }
2c809f8f 7358 this->seen_ = false;
7359 if (!ok)
7360 return false;
e440a328 7361 }
7362 else
c3e6f413 7363 go_unreachable();
927a01eb 7364
5892f89f 7365 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"), ret);
e440a328 7366 return true;
7367 }
7368 else if (this->code_ == BUILTIN_OFFSETOF)
7369 {
7370 Expression* arg = this->one_arg();
7371 if (arg == NULL)
7372 return false;
7373 Field_reference_expression* farg = arg->field_reference_expression();
7374 if (farg == NULL)
7375 return false;
2c809f8f 7376 if (this->seen_)
7377 return false;
7378
9a4bd570 7379 unsigned int total_offset = 0;
7380 while (true)
7381 {
7382 Expression* struct_expr = farg->expr();
7383 Type* st = struct_expr->type();
7384 if (st->struct_type() == NULL)
7385 return false;
7386 if (st->named_type() != NULL)
7387 st->named_type()->convert(this->gogo_);
7388 unsigned int offset;
2c809f8f 7389 this->seen_ = true;
7390 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7391 farg->field_index(),
7392 &offset);
7393 this->seen_ = false;
7394 if (!ok)
7395 return false;
9a4bd570 7396 total_offset += offset;
7397 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7398 {
7399 // Go up until we reach the original base.
7400 farg = struct_expr->field_reference_expression();
7401 continue;
7402 }
7403 break;
7404 }
7ba86326 7405 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
9a4bd570 7406 static_cast<unsigned long>(total_offset));
e440a328 7407 return true;
7408 }
0c77715b 7409 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
e440a328 7410 {
7411 Expression* arg = this->one_arg();
7412 if (arg == NULL)
7413 return false;
7414
0c77715b 7415 Numeric_constant argnc;
7416 if (!arg->numeric_constant_value(&argnc))
7417 return false;
7418
fcbea5e4 7419 mpc_t val;
7420 if (!argnc.to_complex(&val))
0c77715b 7421 return false;
e440a328 7422
0c77715b 7423 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7424 if (this->code_ == BUILTIN_REAL)
fcbea5e4 7425 nc->set_float(type, mpc_realref(val));
0c77715b 7426 else
fcbea5e4 7427 nc->set_float(type, mpc_imagref(val));
7428 mpc_clear(val);
0c77715b 7429 return true;
e440a328 7430 }
0c77715b 7431 else if (this->code_ == BUILTIN_COMPLEX)
e440a328 7432 {
7433 const Expression_list* args = this->args();
7434 if (args == NULL || args->size() != 2)
7435 return false;
7436
0c77715b 7437 Numeric_constant rnc;
7438 if (!args->front()->numeric_constant_value(&rnc))
7439 return false;
7440 Numeric_constant inc;
7441 if (!args->back()->numeric_constant_value(&inc))
7442 return false;
7443
7444 if (rnc.type() != NULL
7445 && !rnc.type()->is_abstract()
7446 && inc.type() != NULL
7447 && !inc.type()->is_abstract()
7448 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7449 return false;
7450
e440a328 7451 mpfr_t r;
0c77715b 7452 if (!rnc.to_float(&r))
7453 return false;
7454 mpfr_t i;
7455 if (!inc.to_float(&i))
e440a328 7456 {
7457 mpfr_clear(r);
7458 return false;
7459 }
7460
0c77715b 7461 Type* arg_type = rnc.type();
7462 if (arg_type == NULL || arg_type->is_abstract())
7463 arg_type = inc.type();
e440a328 7464
fcbea5e4 7465 mpc_t val;
7466 mpc_init2(val, mpc_precision);
7467 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
e440a328 7468 mpfr_clear(r);
7469 mpfr_clear(i);
7470
fcbea5e4 7471 Type* type = Builtin_call_expression::complex_type(arg_type);
7472 nc->set_complex(type, val);
7473
7474 mpc_clear(val);
7475
0c77715b 7476 return true;
e440a328 7477 }
7478
7479 return false;
7480}
7481
a7549a6a 7482// Give an error if we are discarding the value of an expression which
7483// should not normally be discarded. We don't give an error for
7484// discarding the value of an ordinary function call, but we do for
7485// builtin functions, purely for consistency with the gc compiler.
7486
4f2138d7 7487bool
a7549a6a 7488Builtin_call_expression::do_discarding_value()
7489{
7490 switch (this->code_)
7491 {
7492 case BUILTIN_INVALID:
7493 default:
7494 go_unreachable();
7495
7496 case BUILTIN_APPEND:
7497 case BUILTIN_CAP:
7498 case BUILTIN_COMPLEX:
7499 case BUILTIN_IMAG:
7500 case BUILTIN_LEN:
7501 case BUILTIN_MAKE:
7502 case BUILTIN_NEW:
7503 case BUILTIN_REAL:
7504 case BUILTIN_ALIGNOF:
7505 case BUILTIN_OFFSETOF:
7506 case BUILTIN_SIZEOF:
7507 this->unused_value_error();
4f2138d7 7508 return false;
a7549a6a 7509
7510 case BUILTIN_CLOSE:
7511 case BUILTIN_COPY:
1cce762f 7512 case BUILTIN_DELETE:
a7549a6a 7513 case BUILTIN_PANIC:
7514 case BUILTIN_PRINT:
7515 case BUILTIN_PRINTLN:
7516 case BUILTIN_RECOVER:
4f2138d7 7517 return true;
a7549a6a 7518 }
7519}
7520
e440a328 7521// Return the type.
7522
7523Type*
7524Builtin_call_expression::do_type()
7525{
7526 switch (this->code_)
7527 {
7528 case BUILTIN_INVALID:
7529 default:
c3e6f413 7530 go_unreachable();
e440a328 7531
7532 case BUILTIN_NEW:
7533 case BUILTIN_MAKE:
7534 {
7535 const Expression_list* args = this->args();
7536 if (args == NULL || args->empty())
7537 return Type::make_error_type();
7538 return Type::make_pointer_type(args->front()->type());
7539 }
7540
7541 case BUILTIN_CAP:
7542 case BUILTIN_COPY:
7543 case BUILTIN_LEN:
7ba86326 7544 return Type::lookup_integer_type("int");
7545
e440a328 7546 case BUILTIN_ALIGNOF:
7547 case BUILTIN_OFFSETOF:
7548 case BUILTIN_SIZEOF:
7ba86326 7549 return Type::lookup_integer_type("uintptr");
e440a328 7550
7551 case BUILTIN_CLOSE:
1cce762f 7552 case BUILTIN_DELETE:
e440a328 7553 case BUILTIN_PANIC:
7554 case BUILTIN_PRINT:
7555 case BUILTIN_PRINTLN:
7556 return Type::make_void_type();
7557
e440a328 7558 case BUILTIN_RECOVER:
823c7e3d 7559 return Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 7560
7561 case BUILTIN_APPEND:
7562 {
7563 const Expression_list* args = this->args();
7564 if (args == NULL || args->empty())
7565 return Type::make_error_type();
3ff4863b 7566 Type *ret = args->front()->type();
7567 if (!ret->is_slice_type())
7568 return Type::make_error_type();
7569 return ret;
e440a328 7570 }
7571
7572 case BUILTIN_REAL:
7573 case BUILTIN_IMAG:
7574 {
7575 Expression* arg = this->one_arg();
7576 if (arg == NULL)
7577 return Type::make_error_type();
7578 Type* t = arg->type();
7579 if (t->is_abstract())
7580 t = t->make_non_abstract_type();
7581 t = Builtin_call_expression::real_imag_type(t);
7582 if (t == NULL)
7583 t = Type::make_error_type();
7584 return t;
7585 }
7586
48080209 7587 case BUILTIN_COMPLEX:
e440a328 7588 {
7589 const Expression_list* args = this->args();
7590 if (args == NULL || args->size() != 2)
7591 return Type::make_error_type();
7592 Type* t = args->front()->type();
7593 if (t->is_abstract())
7594 {
7595 t = args->back()->type();
7596 if (t->is_abstract())
7597 t = t->make_non_abstract_type();
7598 }
48080209 7599 t = Builtin_call_expression::complex_type(t);
e440a328 7600 if (t == NULL)
7601 t = Type::make_error_type();
7602 return t;
7603 }
7604 }
7605}
7606
7607// Determine the type.
7608
7609void
7610Builtin_call_expression::do_determine_type(const Type_context* context)
7611{
fb94b0ca 7612 if (!this->determining_types())
7613 return;
7614
e440a328 7615 this->fn()->determine_type_no_context();
7616
7617 const Expression_list* args = this->args();
7618
7619 bool is_print;
7620 Type* arg_type = NULL;
7621 switch (this->code_)
7622 {
7623 case BUILTIN_PRINT:
7624 case BUILTIN_PRINTLN:
7625 // Do not force a large integer constant to "int".
7626 is_print = true;
7627 break;
7628
7629 case BUILTIN_REAL:
7630 case BUILTIN_IMAG:
48080209 7631 arg_type = Builtin_call_expression::complex_type(context->type);
f6bc81e6 7632 if (arg_type == NULL)
7633 arg_type = Type::lookup_complex_type("complex128");
e440a328 7634 is_print = false;
7635 break;
7636
48080209 7637 case BUILTIN_COMPLEX:
e440a328 7638 {
48080209 7639 // For the complex function the type of one operand can
e440a328 7640 // determine the type of the other, as in a binary expression.
7641 arg_type = Builtin_call_expression::real_imag_type(context->type);
f6bc81e6 7642 if (arg_type == NULL)
7643 arg_type = Type::lookup_float_type("float64");
e440a328 7644 if (args != NULL && args->size() == 2)
7645 {
7646 Type* t1 = args->front()->type();
c849bb59 7647 Type* t2 = args->back()->type();
e440a328 7648 if (!t1->is_abstract())
7649 arg_type = t1;
7650 else if (!t2->is_abstract())
7651 arg_type = t2;
7652 }
7653 is_print = false;
7654 }
7655 break;
7656
7657 default:
7658 is_print = false;
7659 break;
7660 }
7661
7662 if (args != NULL)
7663 {
7664 for (Expression_list::const_iterator pa = args->begin();
7665 pa != args->end();
7666 ++pa)
7667 {
7668 Type_context subcontext;
7669 subcontext.type = arg_type;
7670
7671 if (is_print)
7672 {
7673 // We want to print large constants, we so can't just
7674 // use the appropriate nonabstract type. Use uint64 for
7675 // an integer if we know it is nonnegative, otherwise
7676 // use int64 for a integer, otherwise use float64 for a
7677 // float or complex128 for a complex.
7678 Type* want_type = NULL;
7679 Type* atype = (*pa)->type();
7680 if (atype->is_abstract())
7681 {
7682 if (atype->integer_type() != NULL)
7683 {
0c77715b 7684 Numeric_constant nc;
7685 if (this->numeric_constant_value(&nc))
7686 {
7687 mpz_t val;
7688 if (nc.to_int(&val))
7689 {
7690 if (mpz_sgn(val) >= 0)
7691 want_type = Type::lookup_integer_type("uint64");
7692 mpz_clear(val);
7693 }
7694 }
7695 if (want_type == NULL)
e440a328 7696 want_type = Type::lookup_integer_type("int64");
e440a328 7697 }
7698 else if (atype->float_type() != NULL)
7699 want_type = Type::lookup_float_type("float64");
7700 else if (atype->complex_type() != NULL)
7701 want_type = Type::lookup_complex_type("complex128");
7702 else if (atype->is_abstract_string_type())
7703 want_type = Type::lookup_string_type();
7704 else if (atype->is_abstract_boolean_type())
7705 want_type = Type::lookup_bool_type();
7706 else
c3e6f413 7707 go_unreachable();
e440a328 7708 subcontext.type = want_type;
7709 }
7710 }
7711
7712 (*pa)->determine_type(&subcontext);
7713 }
7714 }
7715}
7716
7717// If there is exactly one argument, return true. Otherwise give an
7718// error message and return false.
7719
7720bool
7721Builtin_call_expression::check_one_arg()
7722{
7723 const Expression_list* args = this->args();
7724 if (args == NULL || args->size() < 1)
7725 {
7726 this->report_error(_("not enough arguments"));
7727 return false;
7728 }
7729 else if (args->size() > 1)
7730 {
7731 this->report_error(_("too many arguments"));
7732 return false;
7733 }
7734 if (args->front()->is_error_expression()
5c13bd80 7735 || args->front()->type()->is_error())
e440a328 7736 {
7737 this->set_is_error();
7738 return false;
7739 }
7740 return true;
7741}
7742
7743// Check argument types for a builtin function.
7744
7745void
7746Builtin_call_expression::do_check_types(Gogo*)
7747{
375646ea 7748 if (this->is_error_expression())
7749 return;
e440a328 7750 switch (this->code_)
7751 {
7752 case BUILTIN_INVALID:
7753 case BUILTIN_NEW:
7754 case BUILTIN_MAKE:
cd238b8d 7755 case BUILTIN_DELETE:
e440a328 7756 return;
7757
7758 case BUILTIN_LEN:
7759 case BUILTIN_CAP:
7760 {
7761 // The single argument may be either a string or an array or a
7762 // map or a channel, or a pointer to a closed array.
7763 if (this->check_one_arg())
7764 {
7765 Type* arg_type = this->one_arg()->type();
7766 if (arg_type->points_to() != NULL
7767 && arg_type->points_to()->array_type() != NULL
411eb89e 7768 && !arg_type->points_to()->is_slice_type())
e440a328 7769 arg_type = arg_type->points_to();
7770 if (this->code_ == BUILTIN_CAP)
7771 {
5c13bd80 7772 if (!arg_type->is_error()
e440a328 7773 && arg_type->array_type() == NULL
7774 && arg_type->channel_type() == NULL)
7775 this->report_error(_("argument must be array or slice "
7776 "or channel"));
7777 }
7778 else
7779 {
5c13bd80 7780 if (!arg_type->is_error()
e440a328 7781 && !arg_type->is_string_type()
7782 && arg_type->array_type() == NULL
7783 && arg_type->map_type() == NULL
7784 && arg_type->channel_type() == NULL)
7785 this->report_error(_("argument must be string or "
7786 "array or slice or map or channel"));
7787 }
7788 }
7789 }
7790 break;
7791
7792 case BUILTIN_PRINT:
7793 case BUILTIN_PRINTLN:
7794 {
7795 const Expression_list* args = this->args();
7796 if (args == NULL)
7797 {
7798 if (this->code_ == BUILTIN_PRINT)
7799 warning_at(this->location(), 0,
7800 "no arguments for builtin function %<%s%>",
7801 (this->code_ == BUILTIN_PRINT
7802 ? "print"
7803 : "println"));
7804 }
7805 else
7806 {
7807 for (Expression_list::const_iterator p = args->begin();
7808 p != args->end();
7809 ++p)
7810 {
7811 Type* type = (*p)->type();
5c13bd80 7812 if (type->is_error()
e440a328 7813 || type->is_string_type()
7814 || type->integer_type() != NULL
7815 || type->float_type() != NULL
7816 || type->complex_type() != NULL
7817 || type->is_boolean_type()
7818 || type->points_to() != NULL
7819 || type->interface_type() != NULL
7820 || type->channel_type() != NULL
7821 || type->map_type() != NULL
7822 || type->function_type() != NULL
411eb89e 7823 || type->is_slice_type())
e440a328 7824 ;
acf8e158 7825 else if ((*p)->is_type_expression())
7826 {
7827 // If this is a type expression it's going to give
7828 // an error anyhow, so we don't need one here.
7829 }
e440a328 7830 else
7831 this->report_error(_("unsupported argument type to "
7832 "builtin function"));
7833 }
7834 }
7835 }
7836 break;
7837
7838 case BUILTIN_CLOSE:
e440a328 7839 if (this->check_one_arg())
7840 {
7841 if (this->one_arg()->type()->channel_type() == NULL)
7842 this->report_error(_("argument must be channel"));
5202d986 7843 else if (!this->one_arg()->type()->channel_type()->may_send())
7844 this->report_error(_("cannot close receive-only channel"));
e440a328 7845 }
7846 break;
7847
7848 case BUILTIN_PANIC:
7849 case BUILTIN_SIZEOF:
7850 case BUILTIN_ALIGNOF:
7851 this->check_one_arg();
7852 break;
7853
7854 case BUILTIN_RECOVER:
6334270b 7855 if (this->args() != NULL
7856 && !this->args()->empty()
7857 && !this->recover_arg_is_set_)
e440a328 7858 this->report_error(_("too many arguments"));
7859 break;
7860
7861 case BUILTIN_OFFSETOF:
7862 if (this->check_one_arg())
7863 {
7864 Expression* arg = this->one_arg();
7865 if (arg->field_reference_expression() == NULL)
7866 this->report_error(_("argument must be a field reference"));
7867 }
7868 break;
7869
7870 case BUILTIN_COPY:
7871 {
7872 const Expression_list* args = this->args();
7873 if (args == NULL || args->size() < 2)
7874 {
7875 this->report_error(_("not enough arguments"));
7876 break;
7877 }
7878 else if (args->size() > 2)
7879 {
7880 this->report_error(_("too many arguments"));
7881 break;
7882 }
7883 Type* arg1_type = args->front()->type();
7884 Type* arg2_type = args->back()->type();
5c13bd80 7885 if (arg1_type->is_error() || arg2_type->is_error())
e440a328 7886 break;
7887
7888 Type* e1;
411eb89e 7889 if (arg1_type->is_slice_type())
e440a328 7890 e1 = arg1_type->array_type()->element_type();
7891 else
7892 {
7893 this->report_error(_("left argument must be a slice"));
7894 break;
7895 }
7896
411eb89e 7897 if (arg2_type->is_slice_type())
60963afd 7898 {
7899 Type* e2 = arg2_type->array_type()->element_type();
7900 if (!Type::are_identical(e1, e2, true, NULL))
7901 this->report_error(_("element types must be the same"));
7902 }
e440a328 7903 else if (arg2_type->is_string_type())
e440a328 7904 {
60963afd 7905 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7906 this->report_error(_("first argument must be []byte"));
e440a328 7907 }
60963afd 7908 else
7909 this->report_error(_("second argument must be slice or string"));
e440a328 7910 }
7911 break;
7912
7913 case BUILTIN_APPEND:
7914 {
7915 const Expression_list* args = this->args();
b0d311a1 7916 if (args == NULL || args->size() < 2)
e440a328 7917 {
7918 this->report_error(_("not enough arguments"));
7919 break;
7920 }
0b7755ec 7921 if (args->size() > 2)
7922 {
7923 this->report_error(_("too many arguments"));
7924 break;
7925 }
cd238b8d 7926 if (args->front()->type()->is_error()
7927 || args->back()->type()->is_error())
7928 break;
7929
7930 Array_type* at = args->front()->type()->array_type();
7931 Type* e = at->element_type();
4fd4fcf4 7932
7933 // The language permits appending a string to a []byte, as a
7934 // special case.
7935 if (args->back()->type()->is_string_type())
7936 {
60963afd 7937 if (e->integer_type() != NULL && e->integer_type()->is_byte())
4fd4fcf4 7938 break;
7939 }
7940
19fd40c3 7941 // The language says that the second argument must be
7942 // assignable to a slice of the element type of the first
7943 // argument. We already know the first argument is a slice
7944 // type.
cd238b8d 7945 Type* arg2_type = Type::make_array_type(e, NULL);
e440a328 7946 std::string reason;
19fd40c3 7947 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
e440a328 7948 {
7949 if (reason.empty())
19fd40c3 7950 this->report_error(_("argument 2 has invalid type"));
e440a328 7951 else
7952 {
19fd40c3 7953 error_at(this->location(), "argument 2 has invalid type (%s)",
e440a328 7954 reason.c_str());
7955 this->set_is_error();
7956 }
7957 }
7958 break;
7959 }
7960
7961 case BUILTIN_REAL:
7962 case BUILTIN_IMAG:
7963 if (this->check_one_arg())
7964 {
7965 if (this->one_arg()->type()->complex_type() == NULL)
7966 this->report_error(_("argument must have complex type"));
7967 }
7968 break;
7969
48080209 7970 case BUILTIN_COMPLEX:
e440a328 7971 {
7972 const Expression_list* args = this->args();
7973 if (args == NULL || args->size() < 2)
7974 this->report_error(_("not enough arguments"));
7975 else if (args->size() > 2)
7976 this->report_error(_("too many arguments"));
7977 else if (args->front()->is_error_expression()
5c13bd80 7978 || args->front()->type()->is_error()
e440a328 7979 || args->back()->is_error_expression()
5c13bd80 7980 || args->back()->type()->is_error())
e440a328 7981 this->set_is_error();
7982 else if (!Type::are_identical(args->front()->type(),
07ba8be5 7983 args->back()->type(), true, NULL))
48080209 7984 this->report_error(_("complex arguments must have identical types"));
e440a328 7985 else if (args->front()->type()->float_type() == NULL)
48080209 7986 this->report_error(_("complex arguments must have "
e440a328 7987 "floating-point type"));
7988 }
7989 break;
7990
7991 default:
c3e6f413 7992 go_unreachable();
e440a328 7993 }
7994}
7995
72666aed 7996Expression*
7997Builtin_call_expression::do_copy()
7998{
7999 Call_expression* bce =
8000 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8001 this->args()->copy(),
8002 this->is_varargs(),
8003 this->location());
8004
8005 if (this->varargs_are_lowered())
8006 bce->set_varargs_are_lowered();
8007 return bce;
8008}
8009
ea664253 8010// Return the backend representation for a builtin function.
e440a328 8011
ea664253 8012Bexpression*
8013Builtin_call_expression::do_get_backend(Translate_context* context)
e440a328 8014{
8015 Gogo* gogo = context->gogo();
b13c66cd 8016 Location location = this->location();
e440a328 8017 switch (this->code_)
8018 {
8019 case BUILTIN_INVALID:
8020 case BUILTIN_NEW:
8021 case BUILTIN_MAKE:
c3e6f413 8022 go_unreachable();
e440a328 8023
8024 case BUILTIN_LEN:
8025 case BUILTIN_CAP:
8026 {
8027 const Expression_list* args = this->args();
c484d925 8028 go_assert(args != NULL && args->size() == 1);
2c809f8f 8029 Expression* arg = args->front();
e440a328 8030 Type* arg_type = arg->type();
0f914071 8031
8032 if (this->seen_)
8033 {
c484d925 8034 go_assert(saw_errors());
ea664253 8035 return context->backend()->error_expression();
0f914071 8036 }
8037 this->seen_ = true;
0f914071 8038 this->seen_ = false;
e440a328 8039 if (arg_type->points_to() != NULL)
8040 {
8041 arg_type = arg_type->points_to();
c484d925 8042 go_assert(arg_type->array_type() != NULL
411eb89e 8043 && !arg_type->is_slice_type());
2c809f8f 8044 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
e440a328 8045 }
8046
1b1f2abf 8047 Type* int_type = Type::lookup_integer_type("int");
2c809f8f 8048 Expression* val;
e440a328 8049 if (this->code_ == BUILTIN_LEN)
8050 {
8051 if (arg_type->is_string_type())
2c809f8f 8052 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8053 location);
e440a328 8054 else if (arg_type->array_type() != NULL)
0f914071 8055 {
8056 if (this->seen_)
8057 {
c484d925 8058 go_assert(saw_errors());
ea664253 8059 return context->backend()->error_expression();
0f914071 8060 }
8061 this->seen_ = true;
2c809f8f 8062 val = arg_type->array_type()->get_length(gogo, arg);
0f914071 8063 this->seen_ = false;
8064 }
e440a328 8065 else if (arg_type->map_type() != NULL)
2c809f8f 8066 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
e440a328 8067 else if (arg_type->channel_type() != NULL)
2c809f8f 8068 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
e440a328 8069 else
c3e6f413 8070 go_unreachable();
e440a328 8071 }
8072 else
8073 {
8074 if (arg_type->array_type() != NULL)
0f914071 8075 {
8076 if (this->seen_)
8077 {
c484d925 8078 go_assert(saw_errors());
ea664253 8079 return context->backend()->error_expression();
0f914071 8080 }
8081 this->seen_ = true;
2c809f8f 8082 val = arg_type->array_type()->get_capacity(gogo, arg);
0f914071 8083 this->seen_ = false;
8084 }
e440a328 8085 else if (arg_type->channel_type() != NULL)
2c809f8f 8086 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
e440a328 8087 else
c3e6f413 8088 go_unreachable();
e440a328 8089 }
8090
2c809f8f 8091 return Expression::make_cast(int_type, val,
ea664253 8092 location)->get_backend(context);
e440a328 8093 }
8094
8095 case BUILTIN_PRINT:
8096 case BUILTIN_PRINTLN:
8097 {
8098 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
2c809f8f 8099 Expression* print_stmts = NULL;
e440a328 8100
8101 const Expression_list* call_args = this->args();
8102 if (call_args != NULL)
8103 {
8104 for (Expression_list::const_iterator p = call_args->begin();
8105 p != call_args->end();
8106 ++p)
8107 {
8108 if (is_ln && p != call_args->begin())
8109 {
2c809f8f 8110 Expression* print_space =
8111 Runtime::make_call(Runtime::PRINT_SPACE,
8112 this->location(), 0);
e440a328 8113
2c809f8f 8114 print_stmts =
8115 Expression::make_compound(print_stmts, print_space,
8116 location);
8117 }
e440a328 8118
2c809f8f 8119 Expression* arg = *p;
8120 Type* type = arg->type();
8121 Runtime::Function code;
e440a328 8122 if (type->is_string_type())
2c809f8f 8123 code = Runtime::PRINT_STRING;
e440a328 8124 else if (type->integer_type() != NULL
8125 && type->integer_type()->is_unsigned())
8126 {
e440a328 8127 Type* itype = Type::lookup_integer_type("uint64");
2c809f8f 8128 arg = Expression::make_cast(itype, arg, location);
8129 code = Runtime::PRINT_UINT64;
e440a328 8130 }
8131 else if (type->integer_type() != NULL)
8132 {
e440a328 8133 Type* itype = Type::lookup_integer_type("int64");
2c809f8f 8134 arg = Expression::make_cast(itype, arg, location);
8135 code = Runtime::PRINT_INT64;
e440a328 8136 }
8137 else if (type->float_type() != NULL)
8138 {
2c809f8f 8139 Type* dtype = Type::lookup_float_type("float64");
8140 arg = Expression::make_cast(dtype, arg, location);
8141 code = Runtime::PRINT_DOUBLE;
e440a328 8142 }
8143 else if (type->complex_type() != NULL)
8144 {
2c809f8f 8145 Type* ctype = Type::lookup_complex_type("complex128");
8146 arg = Expression::make_cast(ctype, arg, location);
8147 code = Runtime::PRINT_COMPLEX;
e440a328 8148 }
8149 else if (type->is_boolean_type())
2c809f8f 8150 code = Runtime::PRINT_BOOL;
e440a328 8151 else if (type->points_to() != NULL
8152 || type->channel_type() != NULL
8153 || type->map_type() != NULL
8154 || type->function_type() != NULL)
8155 {
2c809f8f 8156 arg = Expression::make_cast(type, arg, location);
8157 code = Runtime::PRINT_POINTER;
e440a328 8158 }
8159 else if (type->interface_type() != NULL)
8160 {
8161 if (type->interface_type()->is_empty())
2c809f8f 8162 code = Runtime::PRINT_EMPTY_INTERFACE;
e440a328 8163 else
2c809f8f 8164 code = Runtime::PRINT_INTERFACE;
e440a328 8165 }
411eb89e 8166 else if (type->is_slice_type())
2c809f8f 8167 code = Runtime::PRINT_SLICE;
e440a328 8168 else
cd238b8d 8169 {
8170 go_assert(saw_errors());
ea664253 8171 return context->backend()->error_expression();
cd238b8d 8172 }
e440a328 8173
2c809f8f 8174 Expression* call = Runtime::make_call(code, location, 1, arg);
8175 if (print_stmts == NULL)
8176 print_stmts = call;
8177 else
8178 print_stmts = Expression::make_compound(print_stmts, call,
8179 location);
e440a328 8180 }
8181 }
8182
8183 if (is_ln)
8184 {
2c809f8f 8185 Expression* print_nl =
8186 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8187 if (print_stmts == NULL)
8188 print_stmts = print_nl;
8189 else
8190 print_stmts = Expression::make_compound(print_stmts, print_nl,
8191 location);
e440a328 8192 }
8193
ea664253 8194 return print_stmts->get_backend(context);
e440a328 8195 }
8196
8197 case BUILTIN_PANIC:
8198 {
8199 const Expression_list* args = this->args();
c484d925 8200 go_assert(args != NULL && args->size() == 1);
e440a328 8201 Expression* arg = args->front();
b13c66cd 8202 Type *empty =
823c7e3d 8203 Type::make_empty_interface_type(Linemap::predeclared_location());
2c809f8f 8204 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8205
8206 Expression* panic =
8207 Runtime::make_call(Runtime::PANIC, location, 1, arg);
ea664253 8208 return panic->get_backend(context);
e440a328 8209 }
8210
8211 case BUILTIN_RECOVER:
8212 {
8213 // The argument is set when building recover thunks. It's a
8214 // boolean value which is true if we can recover a value now.
8215 const Expression_list* args = this->args();
c484d925 8216 go_assert(args != NULL && args->size() == 1);
e440a328 8217 Expression* arg = args->front();
b13c66cd 8218 Type *empty =
823c7e3d 8219 Type::make_empty_interface_type(Linemap::predeclared_location());
e440a328 8220
e440a328 8221 Expression* nil = Expression::make_nil(location);
2c809f8f 8222 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
e440a328 8223
8224 // We need to handle a deferred call to recover specially,
8225 // because it changes whether it can recover a panic or not.
8226 // See test7 in test/recover1.go.
2c809f8f 8227 Expression* recover = Runtime::make_call((this->is_deferred()
8228 ? Runtime::DEFERRED_RECOVER
8229 : Runtime::RECOVER),
8230 location, 0);
8231 Expression* cond =
8232 Expression::make_conditional(arg, recover, nil, location);
ea664253 8233 return cond->get_backend(context);
e440a328 8234 }
8235
8236 case BUILTIN_CLOSE:
e440a328 8237 {
8238 const Expression_list* args = this->args();
c484d925 8239 go_assert(args != NULL && args->size() == 1);
e440a328 8240 Expression* arg = args->front();
2c809f8f 8241 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8242 1, arg);
ea664253 8243 return close->get_backend(context);
e440a328 8244 }
8245
8246 case BUILTIN_SIZEOF:
8247 case BUILTIN_OFFSETOF:
8248 case BUILTIN_ALIGNOF:
8249 {
0c77715b 8250 Numeric_constant nc;
8251 unsigned long val;
8252 if (!this->numeric_constant_value(&nc)
8253 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
7f1d9abd 8254 {
c484d925 8255 go_assert(saw_errors());
ea664253 8256 return context->backend()->error_expression();
7f1d9abd 8257 }
7ba86326 8258 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2c809f8f 8259 mpz_t ival;
8260 nc.get_int(&ival);
8261 Expression* int_cst =
e67508fa 8262 Expression::make_integer_z(&ival, uintptr_type, location);
2c809f8f 8263 mpz_clear(ival);
ea664253 8264 return int_cst->get_backend(context);
e440a328 8265 }
8266
8267 case BUILTIN_COPY:
8268 {
8269 const Expression_list* args = this->args();
c484d925 8270 go_assert(args != NULL && args->size() == 2);
e440a328 8271 Expression* arg1 = args->front();
8272 Expression* arg2 = args->back();
8273
e440a328 8274 Type* arg1_type = arg1->type();
8275 Array_type* at = arg1_type->array_type();
35a54f17 8276 go_assert(arg1->is_variable());
2c809f8f 8277 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8278 Expression* arg1_len = at->get_length(gogo, arg1);
e440a328 8279
8280 Type* arg2_type = arg2->type();
2c809f8f 8281 go_assert(arg2->is_variable());
8282 Expression* arg2_val;
8283 Expression* arg2_len;
411eb89e 8284 if (arg2_type->is_slice_type())
e440a328 8285 {
8286 at = arg2_type->array_type();
2c809f8f 8287 arg2_val = at->get_value_pointer(gogo, arg2);
8288 arg2_len = at->get_length(gogo, arg2);
e440a328 8289 }
8290 else
8291 {
2c809f8f 8292 go_assert(arg2->is_variable());
8293 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8294 location);
8295 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8296 location);
e440a328 8297 }
2c809f8f 8298 Expression* cond =
8299 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8300 Expression* length =
8301 Expression::make_conditional(cond, arg1_len, arg2_len, location);
e440a328 8302
8303 Type* element_type = at->element_type();
9f0e0513 8304 Btype* element_btype = element_type->get_backend(gogo);
e67508fa 8305 size_t element_size = gogo->backend()->type_size(element_btype);
8306 Expression* size_expr = Expression::make_integer_ul(element_size,
8307 length->type(),
8308 location);
2c809f8f 8309 Expression* bytecount =
8310 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8311 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8312 arg1_val, arg2_val, bytecount);
8313
8314 Expression* compound = Expression::make_compound(copy, length, location);
ea664253 8315 return compound->get_backend(context);
e440a328 8316 }
8317
8318 case BUILTIN_APPEND:
8319 {
8320 const Expression_list* args = this->args();
c484d925 8321 go_assert(args != NULL && args->size() == 2);
e440a328 8322 Expression* arg1 = args->front();
8323 Expression* arg2 = args->back();
8324
9d44fbe3 8325 Array_type* at = arg1->type()->array_type();
4fd4fcf4 8326 Type* element_type = at->element_type()->forwarded();
9d44fbe3 8327
2c809f8f 8328 go_assert(arg2->is_variable());
8329 Expression* arg2_val;
8330 Expression* arg2_len;
e67508fa 8331 unsigned long size;
4fd4fcf4 8332 if (arg2->type()->is_string_type()
60963afd 8333 && element_type->integer_type() != NULL
8334 && element_type->integer_type()->is_byte())
4fd4fcf4 8335 {
2c809f8f 8336 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8337 location);
8338 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8339 location);
e67508fa 8340 size = 1;
4fd4fcf4 8341 }
8342 else
8343 {
2c809f8f 8344 arg2_val = at->get_value_pointer(gogo, arg2);
8345 arg2_len = at->get_length(gogo, arg2);
35a54f17 8346 Btype* element_btype = element_type->get_backend(gogo);
e67508fa 8347 size = gogo->backend()->type_size(element_btype);
4fd4fcf4 8348 }
2c809f8f 8349 Expression* element_size =
e67508fa 8350 Expression::make_integer_ul(size, NULL, location);
2c809f8f 8351
8352 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8353 arg1, arg2_val, arg2_len,
8354 element_size);
8355 append = Expression::make_unsafe_cast(arg1->type(), append, location);
ea664253 8356 return append->get_backend(context);
e440a328 8357 }
8358
8359 case BUILTIN_REAL:
8360 case BUILTIN_IMAG:
8361 {
8362 const Expression_list* args = this->args();
c484d925 8363 go_assert(args != NULL && args->size() == 1);
2c809f8f 8364
8365 Bexpression* ret;
ea664253 8366 Bexpression* bcomplex = args->front()->get_backend(context);
2c809f8f 8367 if (this->code_ == BUILTIN_REAL)
8368 ret = gogo->backend()->real_part_expression(bcomplex, location);
8369 else
8370 ret = gogo->backend()->imag_part_expression(bcomplex, location);
ea664253 8371 return ret;
e440a328 8372 }
8373
48080209 8374 case BUILTIN_COMPLEX:
e440a328 8375 {
8376 const Expression_list* args = this->args();
c484d925 8377 go_assert(args != NULL && args->size() == 2);
ea664253 8378 Bexpression* breal = args->front()->get_backend(context);
8379 Bexpression* bimag = args->back()->get_backend(context);
8380 return gogo->backend()->complex_expression(breal, bimag, location);
e440a328 8381 }
8382
8383 default:
c3e6f413 8384 go_unreachable();
e440a328 8385 }
8386}
8387
8388// We have to support exporting a builtin call expression, because
8389// code can set a constant to the result of a builtin expression.
8390
8391void
8392Builtin_call_expression::do_export(Export* exp) const
8393{
0c77715b 8394 Numeric_constant nc;
8395 if (!this->numeric_constant_value(&nc))
8396 {
8397 error_at(this->location(), "value is not constant");
8398 return;
8399 }
e440a328 8400
0c77715b 8401 if (nc.is_int())
e440a328 8402 {
0c77715b 8403 mpz_t val;
8404 nc.get_int(&val);
e440a328 8405 Integer_expression::export_integer(exp, val);
0c77715b 8406 mpz_clear(val);
e440a328 8407 }
0c77715b 8408 else if (nc.is_float())
e440a328 8409 {
8410 mpfr_t fval;
0c77715b 8411 nc.get_float(&fval);
8412 Float_expression::export_float(exp, fval);
e440a328 8413 mpfr_clear(fval);
8414 }
0c77715b 8415 else if (nc.is_complex())
e440a328 8416 {
fcbea5e4 8417 mpc_t cval;
8418 nc.get_complex(&cval);
8419 Complex_expression::export_complex(exp, cval);
8420 mpc_clear(cval);
e440a328 8421 }
0c77715b 8422 else
8423 go_unreachable();
e440a328 8424
8425 // A trailing space lets us reliably identify the end of the number.
8426 exp->write_c_string(" ");
8427}
8428
8429// Class Call_expression.
8430
8381eda7 8431// A Go function can be viewed in a couple of different ways. The
8432// code of a Go function becomes a backend function with parameters
8433// whose types are simply the backend representation of the Go types.
8434// If there are multiple results, they are returned as a backend
8435// struct.
8436
8437// However, when Go code refers to a function other than simply
8438// calling it, the backend type of that function is actually a struct.
8439// The first field of the struct points to the Go function code
8440// (sometimes a wrapper as described below). The remaining fields
8441// hold addresses of closed-over variables. This struct is called a
8442// closure.
8443
8444// There are a few cases to consider.
8445
8446// A direct function call of a known function in package scope. In
8447// this case there are no closed-over variables, and we know the name
8448// of the function code. We can simply produce a backend call to the
8449// function directly, and not worry about the closure.
8450
8451// A direct function call of a known function literal. In this case
8452// we know the function code and we know the closure. We generate the
8453// function code such that it expects an additional final argument of
8454// the closure type. We pass the closure as the last argument, after
8455// the other arguments.
8456
8457// An indirect function call. In this case we have a closure. We
8458// load the pointer to the function code from the first field of the
8459// closure. We pass the address of the closure as the last argument.
8460
8461// A call to a method of an interface. Type methods are always at
8462// package scope, so we call the function directly, and don't worry
8463// about the closure.
8464
8465// This means that for a function at package scope we have two cases.
8466// One is the direct call, which has no closure. The other is the
8467// indirect call, which does have a closure. We can't simply ignore
8468// the closure, even though it is the last argument, because that will
8469// fail on targets where the function pops its arguments. So when
8470// generating a closure for a package-scope function we set the
8471// function code pointer in the closure to point to a wrapper
8472// function. This wrapper function accepts a final argument that
8473// points to the closure, ignores it, and calls the real function as a
8474// direct function call. This wrapper will normally be efficient, and
8475// can often simply be a tail call to the real function.
8476
8477// We don't use GCC's static chain pointer because 1) we don't need
8478// it; 2) GCC only permits using a static chain to call a known
8479// function, so we can't use it for an indirect call anyhow. Since we
8480// can't use it for an indirect call, we may as well not worry about
8481// using it for a direct call either.
8482
8483// We pass the closure last rather than first because it means that
8484// the function wrapper we put into a closure for a package-scope
8485// function can normally just be a tail call to the real function.
8486
8487// For method expressions we generate a wrapper that loads the
8488// receiver from the closure and then calls the method. This
8489// unfortunately forces reshuffling the arguments, since there is a
8490// new first argument, but we can't avoid reshuffling either for
8491// method expressions or for indirect calls of package-scope
8492// functions, and since the latter are more common we reshuffle for
8493// method expressions.
8494
8495// Note that the Go code retains the Go types. The extra final
8496// argument only appears when we convert to the backend
8497// representation.
8498
e440a328 8499// Traversal.
8500
8501int
8502Call_expression::do_traverse(Traverse* traverse)
8503{
8504 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8505 return TRAVERSE_EXIT;
8506 if (this->args_ != NULL)
8507 {
8508 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8509 return TRAVERSE_EXIT;
8510 }
8511 return TRAVERSE_CONTINUE;
8512}
8513
8514// Lower a call statement.
8515
8516Expression*
ceeb4318 8517Call_expression::do_lower(Gogo* gogo, Named_object* function,
8518 Statement_inserter* inserter, int)
e440a328 8519{
b13c66cd 8520 Location loc = this->location();
09ea332d 8521
ceeb4318 8522 // A type cast can look like a function call.
e440a328 8523 if (this->fn_->is_type_expression()
8524 && this->args_ != NULL
8525 && this->args_->size() == 1)
8526 return Expression::make_cast(this->fn_->type(), this->args_->front(),
09ea332d 8527 loc);
e440a328 8528
88f06749 8529 // Because do_type will return an error type and thus prevent future
8530 // errors, check for that case now to ensure that the error gets
8531 // reported.
37448b10 8532 Function_type* fntype = this->get_function_type();
8533 if (fntype == NULL)
88f06749 8534 {
8535 if (!this->fn_->type()->is_error())
8536 this->report_error(_("expected function"));
8537 return Expression::make_error(loc);
8538 }
8539
e440a328 8540 // Handle an argument which is a call to a function which returns
8541 // multiple results.
8542 if (this->args_ != NULL
8543 && this->args_->size() == 1
37448b10 8544 && this->args_->front()->call_expression() != NULL)
e440a328 8545 {
e440a328 8546 size_t rc = this->args_->front()->call_expression()->result_count();
8547 if (rc > 1
37448b10 8548 && ((fntype->parameters() != NULL
8549 && (fntype->parameters()->size() == rc
8550 || (fntype->is_varargs()
8551 && fntype->parameters()->size() - 1 <= rc)))
8552 || fntype->is_builtin()))
e440a328 8553 {
8554 Call_expression* call = this->args_->front()->call_expression();
e90ecd2d 8555 call->set_is_multi_value_arg();
e440a328 8556 Expression_list* args = new Expression_list;
8557 for (size_t i = 0; i < rc; ++i)
8558 args->push_back(Expression::make_call_result(call, i));
8559 // We can't return a new call expression here, because this
42535814 8560 // one may be referenced by Call_result expressions. We
8561 // also can't delete the old arguments, because we may still
8562 // traverse them somewhere up the call stack. FIXME.
e440a328 8563 this->args_ = args;
8564 }
8565 }
8566
37448b10 8567 // Recognize a call to a builtin function.
8568 if (fntype->is_builtin())
8569 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8570 this->is_varargs_, loc);
8571
ceeb4318 8572 // If this call returns multiple results, create a temporary
8573 // variable for each result.
8574 size_t rc = this->result_count();
8575 if (rc > 1 && this->results_ == NULL)
8576 {
8577 std::vector<Temporary_statement*>* temps =
8578 new std::vector<Temporary_statement*>;
8579 temps->reserve(rc);
37448b10 8580 const Typed_identifier_list* results = fntype->results();
ceeb4318 8581 for (Typed_identifier_list::const_iterator p = results->begin();
8582 p != results->end();
8583 ++p)
8584 {
8585 Temporary_statement* temp = Statement::make_temporary(p->type(),
09ea332d 8586 NULL, loc);
ceeb4318 8587 inserter->insert(temp);
8588 temps->push_back(temp);
8589 }
8590 this->results_ = temps;
8591 }
8592
e440a328 8593 // Handle a call to a varargs function by packaging up the extra
8594 // parameters.
37448b10 8595 if (fntype->is_varargs())
e440a328 8596 {
e440a328 8597 const Typed_identifier_list* parameters = fntype->parameters();
c484d925 8598 go_assert(parameters != NULL && !parameters->empty());
e440a328 8599 Type* varargs_type = parameters->back().type();
09ea332d 8600 this->lower_varargs(gogo, function, inserter, varargs_type,
8601 parameters->size());
8602 }
8603
8604 // If this is call to a method, call the method directly passing the
8605 // object as the first parameter.
8606 Bound_method_expression* bme = this->fn_->bound_method_expression();
8607 if (bme != NULL)
8608 {
0afbb937 8609 Named_object* methodfn = bme->function();
09ea332d 8610 Expression* first_arg = bme->first_argument();
8611
8612 // We always pass a pointer when calling a method.
8613 if (first_arg->type()->points_to() == NULL
8614 && !first_arg->type()->is_error())
8615 {
8616 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8617 // We may need to create a temporary variable so that we can
8618 // take the address. We can't do that here because it will
8619 // mess up the order of evaluation.
8620 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8621 ue->set_create_temp();
8622 }
8623
8624 // If we are calling a method which was inherited from an
8625 // embedded struct, and the method did not get a stub, then the
8626 // first type may be wrong.
8627 Type* fatype = bme->first_argument_type();
8628 if (fatype != NULL)
8629 {
8630 if (fatype->points_to() == NULL)
8631 fatype = Type::make_pointer_type(fatype);
8632 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8633 }
8634
8635 Expression_list* new_args = new Expression_list();
8636 new_args->push_back(first_arg);
8637 if (this->args_ != NULL)
8638 {
8639 for (Expression_list::const_iterator p = this->args_->begin();
8640 p != this->args_->end();
8641 ++p)
8642 new_args->push_back(*p);
8643 }
8644
8645 // We have to change in place because this structure may be
8646 // referenced by Call_result_expressions. We can't delete the
8647 // old arguments, because we may be traversing them up in some
8648 // caller. FIXME.
8649 this->args_ = new_args;
0afbb937 8650 this->fn_ = Expression::make_func_reference(methodfn, NULL,
09ea332d 8651 bme->location());
e440a328 8652 }
8653
8654 return this;
8655}
8656
8657// Lower a call to a varargs function. FUNCTION is the function in
8658// which the call occurs--it's not the function we are calling.
8659// VARARGS_TYPE is the type of the varargs parameter, a slice type.
8660// PARAM_COUNT is the number of parameters of the function we are
8661// calling; the last of these parameters will be the varargs
8662// parameter.
8663
09ea332d 8664void
e440a328 8665Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
ceeb4318 8666 Statement_inserter* inserter,
e440a328 8667 Type* varargs_type, size_t param_count)
8668{
8669 if (this->varargs_are_lowered_)
09ea332d 8670 return;
e440a328 8671
b13c66cd 8672 Location loc = this->location();
e440a328 8673
c484d925 8674 go_assert(param_count > 0);
411eb89e 8675 go_assert(varargs_type->is_slice_type());
e440a328 8676
8677 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8678 if (arg_count < param_count - 1)
8679 {
8680 // Not enough arguments; will be caught in check_types.
09ea332d 8681 return;
e440a328 8682 }
8683
8684 Expression_list* old_args = this->args_;
8685 Expression_list* new_args = new Expression_list();
8686 bool push_empty_arg = false;
8687 if (old_args == NULL || old_args->empty())
8688 {
c484d925 8689 go_assert(param_count == 1);
e440a328 8690 push_empty_arg = true;
8691 }
8692 else
8693 {
8694 Expression_list::const_iterator pa;
8695 int i = 1;
8696 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8697 {
8698 if (static_cast<size_t>(i) == param_count)
8699 break;
8700 new_args->push_back(*pa);
8701 }
8702
8703 // We have reached the varargs parameter.
8704
8705 bool issued_error = false;
8706 if (pa == old_args->end())
8707 push_empty_arg = true;
8708 else if (pa + 1 == old_args->end() && this->is_varargs_)
8709 new_args->push_back(*pa);
8710 else if (this->is_varargs_)
8711 {
a6645f74 8712 if ((*pa)->type()->is_slice_type())
8713 this->report_error(_("too many arguments"));
8714 else
8715 {
8716 error_at(this->location(),
8717 _("invalid use of %<...%> with non-slice"));
8718 this->set_is_error();
8719 }
09ea332d 8720 return;
e440a328 8721 }
e440a328 8722 else
8723 {
8724 Type* element_type = varargs_type->array_type()->element_type();
8725 Expression_list* vals = new Expression_list;
8726 for (; pa != old_args->end(); ++pa, ++i)
8727 {
8728 // Check types here so that we get a better message.
8729 Type* patype = (*pa)->type();
b13c66cd 8730 Location paloc = (*pa)->location();
e440a328 8731 if (!this->check_argument_type(i, element_type, patype,
8732 paloc, issued_error))
8733 continue;
8734 vals->push_back(*pa);
8735 }
8736 Expression* val =
8737 Expression::make_slice_composite_literal(varargs_type, vals, loc);
09ea332d 8738 gogo->lower_expression(function, inserter, &val);
e440a328 8739 new_args->push_back(val);
8740 }
8741 }
8742
8743 if (push_empty_arg)
8744 new_args->push_back(Expression::make_nil(loc));
8745
8746 // We can't return a new call expression here, because this one may
6d4c2432 8747 // be referenced by Call_result expressions. FIXME. We can't
8748 // delete OLD_ARGS because we may have both a Call_expression and a
8749 // Builtin_call_expression which refer to them. FIXME.
e440a328 8750 this->args_ = new_args;
8751 this->varargs_are_lowered_ = true;
e440a328 8752}
8753
2c809f8f 8754// Flatten a call with multiple results into a temporary.
8755
8756Expression*
b8e86a51 8757Call_expression::do_flatten(Gogo* gogo, Named_object*,
8758 Statement_inserter* inserter)
2c809f8f 8759{
b8e86a51 8760 if (this->classification() == EXPRESSION_ERROR)
8761 return this;
8762
8763 // Add temporary variables for all arguments that require type
8764 // conversion.
8765 Function_type* fntype = this->get_function_type();
9782d556 8766 if (fntype == NULL)
8767 {
8768 go_assert(saw_errors());
8769 return this;
8770 }
b8e86a51 8771 if (this->args_ != NULL && !this->args_->empty()
8772 && fntype->parameters() != NULL && !fntype->parameters()->empty())
8773 {
8774 bool is_interface_method =
8775 this->fn_->interface_field_reference_expression() != NULL;
8776
8777 Expression_list *args = new Expression_list();
8778 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
8779 Expression_list::const_iterator pa = this->args_->begin();
8780 if (!is_interface_method && fntype->is_method())
8781 {
8782 // The receiver argument.
8783 args->push_back(*pa);
8784 ++pa;
8785 }
8786 for (; pa != this->args_->end(); ++pa, ++pp)
8787 {
8788 go_assert(pp != fntype->parameters()->end());
8789 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
8790 args->push_back(*pa);
8791 else
8792 {
8793 Location loc = (*pa)->location();
8ba8cc87 8794 Expression* arg = *pa;
8795 if (!arg->is_variable())
8796 {
8797 Temporary_statement *temp =
8798 Statement::make_temporary(NULL, arg, loc);
8799 inserter->insert(temp);
8800 arg = Expression::make_temporary_reference(temp, loc);
8801 }
8802 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
8803 loc);
8804 args->push_back(arg);
b8e86a51 8805 }
8806 }
8807 delete this->args_;
8808 this->args_ = args;
8809 }
8810
2c809f8f 8811 size_t rc = this->result_count();
8812 if (rc > 1 && this->call_temp_ == NULL)
8813 {
8814 Struct_field_list* sfl = new Struct_field_list();
8815 Function_type* fntype = this->get_function_type();
8816 const Typed_identifier_list* results = fntype->results();
8817 Location loc = this->location();
8818
8819 int i = 0;
8820 char buf[10];
8821 for (Typed_identifier_list::const_iterator p = results->begin();
8822 p != results->end();
8823 ++p, ++i)
8824 {
8825 snprintf(buf, sizeof buf, "res%d", i);
8826 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
8827 }
8828
8829 Struct_type* st = Type::make_struct_type(sfl, loc);
8830 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
8831 inserter->insert(this->call_temp_);
8832 }
8833
8834 return this;
8835}
8836
ceeb4318 8837// Get the function type. This can return NULL in error cases.
e440a328 8838
8839Function_type*
8840Call_expression::get_function_type() const
8841{
8842 return this->fn_->type()->function_type();
8843}
8844
8845// Return the number of values which this call will return.
8846
8847size_t
8848Call_expression::result_count() const
8849{
8850 const Function_type* fntype = this->get_function_type();
8851 if (fntype == NULL)
8852 return 0;
8853 if (fntype->results() == NULL)
8854 return 0;
8855 return fntype->results()->size();
8856}
8857
ceeb4318 8858// Return the temporary which holds a result.
8859
8860Temporary_statement*
8861Call_expression::result(size_t i) const
8862{
cd238b8d 8863 if (this->results_ == NULL || this->results_->size() <= i)
8864 {
8865 go_assert(saw_errors());
8866 return NULL;
8867 }
ceeb4318 8868 return (*this->results_)[i];
8869}
8870
1373401e 8871// Set the number of results expected from a call expression.
8872
8873void
8874Call_expression::set_expected_result_count(size_t count)
8875{
8876 go_assert(this->expected_result_count_ == 0);
8877 this->expected_result_count_ = count;
8878}
8879
e440a328 8880// Return whether this is a call to the predeclared function recover.
8881
8882bool
8883Call_expression::is_recover_call() const
8884{
8885 return this->do_is_recover_call();
8886}
8887
8888// Set the argument to the recover function.
8889
8890void
8891Call_expression::set_recover_arg(Expression* arg)
8892{
8893 this->do_set_recover_arg(arg);
8894}
8895
8896// Virtual functions also implemented by Builtin_call_expression.
8897
8898bool
8899Call_expression::do_is_recover_call() const
8900{
8901 return false;
8902}
8903
8904void
8905Call_expression::do_set_recover_arg(Expression*)
8906{
c3e6f413 8907 go_unreachable();
e440a328 8908}
8909
ceeb4318 8910// We have found an error with this call expression; return true if
8911// we should report it.
8912
8913bool
8914Call_expression::issue_error()
8915{
8916 if (this->issued_error_)
8917 return false;
8918 else
8919 {
8920 this->issued_error_ = true;
8921 return true;
8922 }
8923}
8924
e440a328 8925// Get the type.
8926
8927Type*
8928Call_expression::do_type()
8929{
8930 if (this->type_ != NULL)
8931 return this->type_;
8932
8933 Type* ret;
8934 Function_type* fntype = this->get_function_type();
8935 if (fntype == NULL)
8936 return Type::make_error_type();
8937
8938 const Typed_identifier_list* results = fntype->results();
8939 if (results == NULL)
8940 ret = Type::make_void_type();
8941 else if (results->size() == 1)
8942 ret = results->begin()->type();
8943 else
8944 ret = Type::make_call_multiple_result_type(this);
8945
8946 this->type_ = ret;
8947
8948 return this->type_;
8949}
8950
8951// Determine types for a call expression. We can use the function
8952// parameter types to set the types of the arguments.
8953
8954void
8955Call_expression::do_determine_type(const Type_context*)
8956{
fb94b0ca 8957 if (!this->determining_types())
8958 return;
8959
e440a328 8960 this->fn_->determine_type_no_context();
8961 Function_type* fntype = this->get_function_type();
8962 const Typed_identifier_list* parameters = NULL;
8963 if (fntype != NULL)
8964 parameters = fntype->parameters();
8965 if (this->args_ != NULL)
8966 {
8967 Typed_identifier_list::const_iterator pt;
8968 if (parameters != NULL)
8969 pt = parameters->begin();
09ea332d 8970 bool first = true;
e440a328 8971 for (Expression_list::const_iterator pa = this->args_->begin();
8972 pa != this->args_->end();
8973 ++pa)
8974 {
09ea332d 8975 if (first)
8976 {
8977 first = false;
8978 // If this is a method, the first argument is the
8979 // receiver.
8980 if (fntype != NULL && fntype->is_method())
8981 {
8982 Type* rtype = fntype->receiver()->type();
8983 // The receiver is always passed as a pointer.
8984 if (rtype->points_to() == NULL)
8985 rtype = Type::make_pointer_type(rtype);
8986 Type_context subcontext(rtype, false);
8987 (*pa)->determine_type(&subcontext);
8988 continue;
8989 }
8990 }
8991
e440a328 8992 if (parameters != NULL && pt != parameters->end())
8993 {
8994 Type_context subcontext(pt->type(), false);
8995 (*pa)->determine_type(&subcontext);
8996 ++pt;
8997 }
8998 else
8999 (*pa)->determine_type_no_context();
9000 }
9001 }
9002}
9003
fb94b0ca 9004// Called when determining types for a Call_expression. Return true
9005// if we should go ahead, false if they have already been determined.
9006
9007bool
9008Call_expression::determining_types()
9009{
9010 if (this->types_are_determined_)
9011 return false;
9012 else
9013 {
9014 this->types_are_determined_ = true;
9015 return true;
9016 }
9017}
9018
e440a328 9019// Check types for parameter I.
9020
9021bool
9022Call_expression::check_argument_type(int i, const Type* parameter_type,
9023 const Type* argument_type,
b13c66cd 9024 Location argument_location,
e440a328 9025 bool issued_error)
9026{
9027 std::string reason;
1eae365b 9028 if (!Type::are_assignable(parameter_type, argument_type, &reason))
e440a328 9029 {
9030 if (!issued_error)
9031 {
9032 if (reason.empty())
9033 error_at(argument_location, "argument %d has incompatible type", i);
9034 else
9035 error_at(argument_location,
9036 "argument %d has incompatible type (%s)",
9037 i, reason.c_str());
9038 }
9039 this->set_is_error();
9040 return false;
9041 }
9042 return true;
9043}
9044
9045// Check types.
9046
9047void
9048Call_expression::do_check_types(Gogo*)
9049{
a6645f74 9050 if (this->classification() == EXPRESSION_ERROR)
9051 return;
9052
e440a328 9053 Function_type* fntype = this->get_function_type();
9054 if (fntype == NULL)
9055 {
5c13bd80 9056 if (!this->fn_->type()->is_error())
e440a328 9057 this->report_error(_("expected function"));
9058 return;
9059 }
9060
1373401e 9061 if (this->expected_result_count_ != 0
9062 && this->expected_result_count_ != this->result_count())
9063 {
9064 if (this->issue_error())
9065 this->report_error(_("function result count mismatch"));
9066 this->set_is_error();
9067 return;
9068 }
9069
09ea332d 9070 bool is_method = fntype->is_method();
9071 if (is_method)
e440a328 9072 {
09ea332d 9073 go_assert(this->args_ != NULL && !this->args_->empty());
9074 Type* rtype = fntype->receiver()->type();
9075 Expression* first_arg = this->args_->front();
1eae365b 9076 // We dereference the values since receivers are always passed
9077 // as pointers.
09ea332d 9078 std::string reason;
1eae365b 9079 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9080 &reason))
e440a328 9081 {
09ea332d 9082 if (reason.empty())
9083 this->report_error(_("incompatible type for receiver"));
9084 else
e440a328 9085 {
09ea332d 9086 error_at(this->location(),
9087 "incompatible type for receiver (%s)",
9088 reason.c_str());
9089 this->set_is_error();
e440a328 9090 }
9091 }
9092 }
9093
9094 // Note that varargs was handled by the lower_varargs() method, so
a6645f74 9095 // we don't have to worry about it here unless something is wrong.
9096 if (this->is_varargs_ && !this->varargs_are_lowered_)
9097 {
9098 if (!fntype->is_varargs())
9099 {
9100 error_at(this->location(),
9101 _("invalid use of %<...%> calling non-variadic function"));
9102 this->set_is_error();
9103 return;
9104 }
9105 }
e440a328 9106
9107 const Typed_identifier_list* parameters = fntype->parameters();
9108 if (this->args_ == NULL)
9109 {
9110 if (parameters != NULL && !parameters->empty())
9111 this->report_error(_("not enough arguments"));
9112 }
9113 else if (parameters == NULL)
09ea332d 9114 {
9115 if (!is_method || this->args_->size() > 1)
9116 this->report_error(_("too many arguments"));
9117 }
1373401e 9118 else if (this->args_->size() == 1
9119 && this->args_->front()->call_expression() != NULL
9120 && this->args_->front()->call_expression()->result_count() > 1)
9121 {
9122 // This is F(G()) when G returns more than one result. If the
9123 // results can be matched to parameters, it would have been
9124 // lowered in do_lower. If we get here we know there is a
9125 // mismatch.
9126 if (this->args_->front()->call_expression()->result_count()
9127 < parameters->size())
9128 this->report_error(_("not enough arguments"));
9129 else
9130 this->report_error(_("too many arguments"));
9131 }
e440a328 9132 else
9133 {
9134 int i = 0;
09ea332d 9135 Expression_list::const_iterator pa = this->args_->begin();
9136 if (is_method)
9137 ++pa;
9138 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9139 pt != parameters->end();
9140 ++pt, ++pa, ++i)
e440a328 9141 {
09ea332d 9142 if (pa == this->args_->end())
e440a328 9143 {
09ea332d 9144 this->report_error(_("not enough arguments"));
e440a328 9145 return;
9146 }
9147 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9148 (*pa)->location(), false);
9149 }
09ea332d 9150 if (pa != this->args_->end())
9151 this->report_error(_("too many arguments"));
e440a328 9152 }
9153}
9154
72666aed 9155Expression*
9156Call_expression::do_copy()
9157{
9158 Call_expression* call =
9159 Expression::make_call(this->fn_->copy(),
9160 (this->args_ == NULL
9161 ? NULL
9162 : this->args_->copy()),
9163 this->is_varargs_, this->location());
9164
9165 if (this->varargs_are_lowered_)
9166 call->set_varargs_are_lowered();
9167 return call;
9168}
9169
e440a328 9170// Return whether we have to use a temporary variable to ensure that
9171// we evaluate this call expression in order. If the call returns no
ceeb4318 9172// results then it will inevitably be executed last.
e440a328 9173
9174bool
9175Call_expression::do_must_eval_in_order() const
9176{
ceeb4318 9177 return this->result_count() > 0;
e440a328 9178}
9179
e440a328 9180// Get the function and the first argument to use when calling an
9181// interface method.
9182
2387f644 9183Expression*
e440a328 9184Call_expression::interface_method_function(
e440a328 9185 Interface_field_reference_expression* interface_method,
2387f644 9186 Expression** first_arg_ptr)
e440a328 9187{
2387f644 9188 *first_arg_ptr = interface_method->get_underlying_object();
9189 return interface_method->get_function();
e440a328 9190}
9191
9192// Build the call expression.
9193
ea664253 9194Bexpression*
9195Call_expression::do_get_backend(Translate_context* context)
e440a328 9196{
2c809f8f 9197 if (this->call_ != NULL)
ea664253 9198 return this->call_;
e440a328 9199
9200 Function_type* fntype = this->get_function_type();
9201 if (fntype == NULL)
ea664253 9202 return context->backend()->error_expression();
e440a328 9203
9204 if (this->fn_->is_error_expression())
ea664253 9205 return context->backend()->error_expression();
e440a328 9206
9207 Gogo* gogo = context->gogo();
b13c66cd 9208 Location location = this->location();
e440a328 9209
9210 Func_expression* func = this->fn_->func_expression();
e440a328 9211 Interface_field_reference_expression* interface_method =
9212 this->fn_->interface_field_reference_expression();
9213 const bool has_closure = func != NULL && func->closure() != NULL;
09ea332d 9214 const bool is_interface_method = interface_method != NULL;
e440a328 9215
f8bdf81a 9216 bool has_closure_arg;
8381eda7 9217 if (has_closure)
f8bdf81a 9218 has_closure_arg = true;
8381eda7 9219 else if (func != NULL)
f8bdf81a 9220 has_closure_arg = false;
8381eda7 9221 else if (is_interface_method)
f8bdf81a 9222 has_closure_arg = false;
8381eda7 9223 else
f8bdf81a 9224 has_closure_arg = true;
8381eda7 9225
e440a328 9226 int nargs;
2c809f8f 9227 std::vector<Bexpression*> fn_args;
e440a328 9228 if (this->args_ == NULL || this->args_->empty())
9229 {
f8bdf81a 9230 nargs = is_interface_method ? 1 : 0;
2c809f8f 9231 if (nargs > 0)
9232 fn_args.resize(1);
e440a328 9233 }
09ea332d 9234 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9235 {
9236 // Passing a receiver parameter.
9237 go_assert(!is_interface_method
9238 && fntype->is_method()
9239 && this->args_->size() == 1);
f8bdf81a 9240 nargs = 1;
2c809f8f 9241 fn_args.resize(1);
ea664253 9242 fn_args[0] = this->args_->front()->get_backend(context);
09ea332d 9243 }
e440a328 9244 else
9245 {
9246 const Typed_identifier_list* params = fntype->parameters();
e440a328 9247
9248 nargs = this->args_->size();
09ea332d 9249 int i = is_interface_method ? 1 : 0;
e440a328 9250 nargs += i;
2c809f8f 9251 fn_args.resize(nargs);
e440a328 9252
9253 Typed_identifier_list::const_iterator pp = params->begin();
09ea332d 9254 Expression_list::const_iterator pe = this->args_->begin();
9255 if (!is_interface_method && fntype->is_method())
9256 {
ea664253 9257 fn_args[i] = (*pe)->get_backend(context);
09ea332d 9258 ++pe;
9259 ++i;
9260 }
9261 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
e440a328 9262 {
c484d925 9263 go_assert(pp != params->end());
2c809f8f 9264 Expression* arg =
9265 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9266 location);
ea664253 9267 fn_args[i] = arg->get_backend(context);
e440a328 9268 }
c484d925 9269 go_assert(pp == params->end());
f8bdf81a 9270 go_assert(i == nargs);
e440a328 9271 }
9272
2c809f8f 9273 Expression* fn;
9274 Expression* closure = NULL;
8381eda7 9275 if (func != NULL)
9276 {
9277 Named_object* no = func->named_object();
2c809f8f 9278 fn = Expression::make_func_code_reference(no, location);
9279 if (has_closure)
9280 closure = func->closure();
8381eda7 9281 }
09ea332d 9282 else if (!is_interface_method)
8381eda7 9283 {
2c809f8f 9284 closure = this->fn_;
9285
9286 // The backend representation of this function type is a pointer
9287 // to a struct whose first field is the actual function to call.
9288 Type* pfntype =
9289 Type::make_pointer_type(
9290 Type::make_pointer_type(Type::make_void_type()));
9291 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9292 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9293 }
e440a328 9294 else
cf609de4 9295 {
2387f644 9296 Expression* first_arg;
2c809f8f 9297 fn = this->interface_method_function(interface_method, &first_arg);
ea664253 9298 fn_args[0] = first_arg->get_backend(context);
e440a328 9299 }
9300
f8bdf81a 9301 if (!has_closure_arg)
2c809f8f 9302 go_assert(closure == NULL);
f8bdf81a 9303 else
9304 {
9305 // Pass the closure argument by calling the function function
9306 // __go_set_closure. In the order_evaluations pass we have
9307 // ensured that if any parameters contain call expressions, they
9308 // will have been moved out to temporary variables.
2c809f8f 9309 go_assert(closure != NULL);
9310 Expression* set_closure =
9311 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9312 fn = Expression::make_compound(set_closure, fn, location);
f8bdf81a 9313 }
9314
ea664253 9315 Bexpression* bfn = fn->get_backend(context);
80d1e1a8 9316
9317 // When not calling a named function directly, use a type conversion
9318 // in case the type of the function is a recursive type which refers
9319 // to itself. We don't do this for an interface method because 1)
9320 // an interface method never refers to itself, so we always have a
9321 // function type here; 2) we pass an extra first argument to an
9322 // interface method, so fntype is not correct.
9323 if (func == NULL && !is_interface_method)
9324 {
9325 Btype* bft = fntype->get_backend_fntype(gogo);
9326 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9327 }
9328
2c809f8f 9329 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
e440a328 9330
2c809f8f 9331 if (this->results_ != NULL)
e440a328 9332 {
2c809f8f 9333 go_assert(this->call_temp_ != NULL);
9334 Expression* call_ref =
9335 Expression::make_temporary_reference(this->call_temp_, location);
ea664253 9336 Bexpression* bcall_ref = call_ref->get_backend(context);
2c809f8f 9337 Bstatement* assn_stmt =
9338 gogo->backend()->assignment_statement(bcall_ref, call, location);
e440a328 9339
2c809f8f 9340 this->call_ = this->set_results(context, bcall_ref);
e440a328 9341
2c809f8f 9342 Bexpression* set_and_call =
9343 gogo->backend()->compound_expression(assn_stmt, this->call_,
9344 location);
ea664253 9345 return set_and_call;
2c809f8f 9346 }
e440a328 9347
2c809f8f 9348 this->call_ = call;
ea664253 9349 return this->call_;
e440a328 9350}
9351
ceeb4318 9352// Set the result variables if this call returns multiple results.
9353
2c809f8f 9354Bexpression*
9355Call_expression::set_results(Translate_context* context, Bexpression* call)
ceeb4318 9356{
2c809f8f 9357 Gogo* gogo = context->gogo();
ceeb4318 9358
2c809f8f 9359 Bexpression* results = NULL;
b13c66cd 9360 Location loc = this->location();
2c809f8f 9361
ceeb4318 9362 size_t rc = this->result_count();
2c809f8f 9363 for (size_t i = 0; i < rc; ++i)
ceeb4318 9364 {
ceeb4318 9365 Temporary_statement* temp = this->result(i);
cd238b8d 9366 if (temp == NULL)
9367 {
9368 go_assert(saw_errors());
2c809f8f 9369 return gogo->backend()->error_expression();
cd238b8d 9370 }
ceeb4318 9371 Temporary_reference_expression* ref =
9372 Expression::make_temporary_reference(temp, loc);
9373 ref->set_is_lvalue();
ceeb4318 9374
ea664253 9375 Bexpression* result_ref = ref->get_backend(context);
2c809f8f 9376 Bexpression* call_result =
9377 gogo->backend()->struct_field_expression(call, i, loc);
9378 Bstatement* assn_stmt =
9379 gogo->backend()->assignment_statement(result_ref, call_result, loc);
ceeb4318 9380
2c809f8f 9381 Bexpression* result =
9382 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
ceeb4318 9383
2c809f8f 9384 if (results == NULL)
9385 results = result;
9386 else
9387 {
9388 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9389 results =
9390 gogo->backend()->compound_expression(expr_stmt, results, loc);
9391 }
9392 }
9393 return results;
ceeb4318 9394}
9395
d751bb78 9396// Dump ast representation for a call expressin.
9397
9398void
9399Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9400{
9401 this->fn_->dump_expression(ast_dump_context);
9402 ast_dump_context->ostream() << "(";
9403 if (args_ != NULL)
9404 ast_dump_context->dump_expression_list(this->args_);
9405
9406 ast_dump_context->ostream() << ") ";
9407}
9408
e440a328 9409// Make a call expression.
9410
9411Call_expression*
9412Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
b13c66cd 9413 Location location)
e440a328 9414{
9415 return new Call_expression(fn, args, is_varargs, location);
9416}
9417
9418// A single result from a call which returns multiple results.
9419
9420class Call_result_expression : public Expression
9421{
9422 public:
9423 Call_result_expression(Call_expression* call, unsigned int index)
9424 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9425 call_(call), index_(index)
9426 { }
9427
9428 protected:
9429 int
9430 do_traverse(Traverse*);
9431
9432 Type*
9433 do_type();
9434
9435 void
9436 do_determine_type(const Type_context*);
9437
9438 void
9439 do_check_types(Gogo*);
9440
9441 Expression*
9442 do_copy()
9443 {
9444 return new Call_result_expression(this->call_->call_expression(),
9445 this->index_);
9446 }
9447
9448 bool
9449 do_must_eval_in_order() const
9450 { return true; }
9451
ea664253 9452 Bexpression*
9453 do_get_backend(Translate_context*);
e440a328 9454
d751bb78 9455 void
9456 do_dump_expression(Ast_dump_context*) const;
9457
e440a328 9458 private:
9459 // The underlying call expression.
9460 Expression* call_;
9461 // Which result we want.
9462 unsigned int index_;
9463};
9464
9465// Traverse a call result.
9466
9467int
9468Call_result_expression::do_traverse(Traverse* traverse)
9469{
9470 if (traverse->remember_expression(this->call_))
9471 {
9472 // We have already traversed the call expression.
9473 return TRAVERSE_CONTINUE;
9474 }
9475 return Expression::traverse(&this->call_, traverse);
9476}
9477
9478// Get the type.
9479
9480Type*
9481Call_result_expression::do_type()
9482{
425dd051 9483 if (this->classification() == EXPRESSION_ERROR)
9484 return Type::make_error_type();
9485
e440a328 9486 // THIS->CALL_ can be replaced with a temporary reference due to
9487 // Call_expression::do_must_eval_in_order when there is an error.
9488 Call_expression* ce = this->call_->call_expression();
9489 if (ce == NULL)
5e85f268 9490 {
9491 this->set_is_error();
9492 return Type::make_error_type();
9493 }
e440a328 9494 Function_type* fntype = ce->get_function_type();
9495 if (fntype == NULL)
5e85f268 9496 {
e37658e2 9497 if (ce->issue_error())
99b3f06f 9498 {
9499 if (!ce->fn()->type()->is_error())
9500 this->report_error(_("expected function"));
9501 }
5e85f268 9502 this->set_is_error();
9503 return Type::make_error_type();
9504 }
e440a328 9505 const Typed_identifier_list* results = fntype->results();
ceeb4318 9506 if (results == NULL || results->size() < 2)
7b8d861f 9507 {
ceeb4318 9508 if (ce->issue_error())
9509 this->report_error(_("number of results does not match "
9510 "number of values"));
7b8d861f 9511 return Type::make_error_type();
9512 }
e440a328 9513 Typed_identifier_list::const_iterator pr = results->begin();
9514 for (unsigned int i = 0; i < this->index_; ++i)
9515 {
9516 if (pr == results->end())
425dd051 9517 break;
e440a328 9518 ++pr;
9519 }
9520 if (pr == results->end())
425dd051 9521 {
ceeb4318 9522 if (ce->issue_error())
9523 this->report_error(_("number of results does not match "
9524 "number of values"));
425dd051 9525 return Type::make_error_type();
9526 }
e440a328 9527 return pr->type();
9528}
9529
425dd051 9530// Check the type. Just make sure that we trigger the warning in
9531// do_type.
e440a328 9532
9533void
9534Call_result_expression::do_check_types(Gogo*)
9535{
425dd051 9536 this->type();
e440a328 9537}
9538
9539// Determine the type. We have nothing to do here, but the 0 result
9540// needs to pass down to the caller.
9541
9542void
9543Call_result_expression::do_determine_type(const Type_context*)
9544{
fb94b0ca 9545 this->call_->determine_type_no_context();
e440a328 9546}
9547
ea664253 9548// Return the backend representation. We just refer to the temporary set by the
9549// call expression. We don't do this at lowering time because it makes it
ceeb4318 9550// hard to evaluate the call at the right time.
e440a328 9551
ea664253 9552Bexpression*
9553Call_result_expression::do_get_backend(Translate_context* context)
e440a328 9554{
ceeb4318 9555 Call_expression* ce = this->call_->call_expression();
cd238b8d 9556 if (ce == NULL)
9557 {
9558 go_assert(this->call_->is_error_expression());
ea664253 9559 return context->backend()->error_expression();
cd238b8d 9560 }
ceeb4318 9561 Temporary_statement* ts = ce->result(this->index_);
cd238b8d 9562 if (ts == NULL)
9563 {
9564 go_assert(saw_errors());
ea664253 9565 return context->backend()->error_expression();
cd238b8d 9566 }
ceeb4318 9567 Expression* ref = Expression::make_temporary_reference(ts, this->location());
ea664253 9568 return ref->get_backend(context);
e440a328 9569}
9570
d751bb78 9571// Dump ast representation for a call result expression.
9572
9573void
9574Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9575 const
9576{
9577 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9578 // (struct) and the fields are referenced instead.
9579 ast_dump_context->ostream() << this->index_ << "@(";
9580 ast_dump_context->dump_expression(this->call_);
9581 ast_dump_context->ostream() << ")";
9582}
9583
e440a328 9584// Make a reference to a single result of a call which returns
9585// multiple results.
9586
9587Expression*
9588Expression::make_call_result(Call_expression* call, unsigned int index)
9589{
9590 return new Call_result_expression(call, index);
9591}
9592
9593// Class Index_expression.
9594
9595// Traversal.
9596
9597int
9598Index_expression::do_traverse(Traverse* traverse)
9599{
9600 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9601 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9602 || (this->end_ != NULL
acf2b673 9603 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9604 || (this->cap_ != NULL
9605 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
e440a328 9606 return TRAVERSE_EXIT;
9607 return TRAVERSE_CONTINUE;
9608}
9609
9610// Lower an index expression. This converts the generic index
9611// expression into an array index, a string index, or a map index.
9612
9613Expression*
ceeb4318 9614Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
e440a328 9615{
b13c66cd 9616 Location location = this->location();
e440a328 9617 Expression* left = this->left_;
9618 Expression* start = this->start_;
9619 Expression* end = this->end_;
acf2b673 9620 Expression* cap = this->cap_;
e440a328 9621
9622 Type* type = left->type();
5c13bd80 9623 if (type->is_error())
d9f3743a 9624 {
9625 go_assert(saw_errors());
9626 return Expression::make_error(location);
9627 }
b0cf7ddd 9628 else if (left->is_type_expression())
9629 {
9630 error_at(location, "attempt to index type expression");
9631 return Expression::make_error(location);
9632 }
e440a328 9633 else if (type->array_type() != NULL)
acf2b673 9634 return Expression::make_array_index(left, start, end, cap, location);
e440a328 9635 else if (type->points_to() != NULL
9636 && type->points_to()->array_type() != NULL
411eb89e 9637 && !type->points_to()->is_slice_type())
e440a328 9638 {
9639 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9640 location);
38092374 9641
9642 // For an ordinary index into the array, the pointer will be
9643 // dereferenced. For a slice it will not--the resulting slice
9644 // will simply reuse the pointer, which is incorrect if that
9645 // pointer is nil.
9646 if (end != NULL || cap != NULL)
9647 deref->issue_nil_check();
9648
acf2b673 9649 return Expression::make_array_index(deref, start, end, cap, location);
e440a328 9650 }
9651 else if (type->is_string_type())
acf2b673 9652 {
9653 if (cap != NULL)
9654 {
9655 error_at(location, "invalid 3-index slice of string");
9656 return Expression::make_error(location);
9657 }
9658 return Expression::make_string_index(left, start, end, location);
9659 }
e440a328 9660 else if (type->map_type() != NULL)
9661 {
acf2b673 9662 if (end != NULL || cap != NULL)
e440a328 9663 {
9664 error_at(location, "invalid slice of map");
9665 return Expression::make_error(location);
9666 }
6d4c2432 9667 Map_index_expression* ret = Expression::make_map_index(left, start,
9668 location);
e440a328 9669 if (this->is_lvalue_)
9670 ret->set_is_lvalue();
9671 return ret;
9672 }
9673 else
9674 {
9675 error_at(location,
9676 "attempt to index object which is not array, string, or map");
9677 return Expression::make_error(location);
9678 }
9679}
9680
acf2b673 9681// Write an indexed expression
9682// (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
d751bb78 9683
9684void
9685Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9686 const Expression* expr,
9687 const Expression* start,
acf2b673 9688 const Expression* end,
9689 const Expression* cap)
d751bb78 9690{
9691 expr->dump_expression(ast_dump_context);
9692 ast_dump_context->ostream() << "[";
9693 start->dump_expression(ast_dump_context);
9694 if (end != NULL)
9695 {
9696 ast_dump_context->ostream() << ":";
9697 end->dump_expression(ast_dump_context);
9698 }
acf2b673 9699 if (cap != NULL)
9700 {
9701 ast_dump_context->ostream() << ":";
9702 cap->dump_expression(ast_dump_context);
9703 }
d751bb78 9704 ast_dump_context->ostream() << "]";
9705}
9706
9707// Dump ast representation for an index expression.
9708
9709void
9710Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9711 const
9712{
9713 Index_expression::dump_index_expression(ast_dump_context, this->left_,
acf2b673 9714 this->start_, this->end_, this->cap_);
d751bb78 9715}
9716
e440a328 9717// Make an index expression.
9718
9719Expression*
9720Expression::make_index(Expression* left, Expression* start, Expression* end,
acf2b673 9721 Expression* cap, Location location)
e440a328 9722{
acf2b673 9723 return new Index_expression(left, start, end, cap, location);
e440a328 9724}
9725
9726// An array index. This is used for both indexing and slicing.
9727
9728class Array_index_expression : public Expression
9729{
9730 public:
9731 Array_index_expression(Expression* array, Expression* start,
acf2b673 9732 Expression* end, Expression* cap, Location location)
e440a328 9733 : Expression(EXPRESSION_ARRAY_INDEX, location),
acf2b673 9734 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
e440a328 9735 { }
9736
9737 protected:
9738 int
9739 do_traverse(Traverse*);
9740
2c809f8f 9741 Expression*
9742 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9743
e440a328 9744 Type*
9745 do_type();
9746
9747 void
9748 do_determine_type(const Type_context*);
9749
9750 void
9751 do_check_types(Gogo*);
9752
9753 Expression*
9754 do_copy()
9755 {
9756 return Expression::make_array_index(this->array_->copy(),
9757 this->start_->copy(),
9758 (this->end_ == NULL
9759 ? NULL
9760 : this->end_->copy()),
acf2b673 9761 (this->cap_ == NULL
9762 ? NULL
9763 : this->cap_->copy()),
e440a328 9764 this->location());
9765 }
9766
baef9f7a 9767 bool
9768 do_must_eval_subexpressions_in_order(int* skip) const
9769 {
9770 *skip = 1;
9771 return true;
9772 }
9773
e440a328 9774 bool
9775 do_is_addressable() const;
9776
9777 void
9778 do_address_taken(bool escapes)
9779 { this->array_->address_taken(escapes); }
9780
56080003 9781 void
9782 do_issue_nil_check()
9783 { this->array_->issue_nil_check(); }
9784
ea664253 9785 Bexpression*
9786 do_get_backend(Translate_context*);
e440a328 9787
d751bb78 9788 void
9789 do_dump_expression(Ast_dump_context*) const;
9790
e440a328 9791 private:
9792 // The array we are getting a value from.
9793 Expression* array_;
9794 // The start or only index.
9795 Expression* start_;
9796 // The end index of a slice. This may be NULL for a simple array
9797 // index, or it may be a nil expression for the length of the array.
9798 Expression* end_;
acf2b673 9799 // The capacity argument of a slice. This may be NULL for an array index or
9800 // slice.
9801 Expression* cap_;
e440a328 9802 // The type of the expression.
9803 Type* type_;
9804};
9805
9806// Array index traversal.
9807
9808int
9809Array_index_expression::do_traverse(Traverse* traverse)
9810{
9811 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9812 return TRAVERSE_EXIT;
9813 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9814 return TRAVERSE_EXIT;
9815 if (this->end_ != NULL)
9816 {
9817 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9818 return TRAVERSE_EXIT;
9819 }
acf2b673 9820 if (this->cap_ != NULL)
9821 {
9822 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9823 return TRAVERSE_EXIT;
9824 }
e440a328 9825 return TRAVERSE_CONTINUE;
9826}
9827
9828// Return the type of an array index.
9829
9830Type*
9831Array_index_expression::do_type()
9832{
9833 if (this->type_ == NULL)
9834 {
9835 Array_type* type = this->array_->type()->array_type();
9836 if (type == NULL)
9837 this->type_ = Type::make_error_type();
9838 else if (this->end_ == NULL)
9839 this->type_ = type->element_type();
411eb89e 9840 else if (type->is_slice_type())
e440a328 9841 {
9842 // A slice of a slice has the same type as the original
9843 // slice.
9844 this->type_ = this->array_->type()->deref();
9845 }
9846 else
9847 {
9848 // A slice of an array is a slice.
9849 this->type_ = Type::make_array_type(type->element_type(), NULL);
9850 }
9851 }
9852 return this->type_;
9853}
9854
9855// Set the type of an array index.
9856
9857void
9858Array_index_expression::do_determine_type(const Type_context*)
9859{
9860 this->array_->determine_type_no_context();
7917ad68 9861 this->start_->determine_type_no_context();
e440a328 9862 if (this->end_ != NULL)
7917ad68 9863 this->end_->determine_type_no_context();
acf2b673 9864 if (this->cap_ != NULL)
9865 this->cap_->determine_type_no_context();
e440a328 9866}
9867
9868// Check types of an array index.
9869
9870void
9871Array_index_expression::do_check_types(Gogo*)
9872{
f6bc81e6 9873 Numeric_constant nc;
9874 unsigned long v;
9875 if (this->start_->type()->integer_type() == NULL
9876 && !this->start_->type()->is_error()
9877 && (!this->start_->numeric_constant_value(&nc)
9878 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 9879 this->report_error(_("index must be integer"));
9880 if (this->end_ != NULL
9881 && this->end_->type()->integer_type() == NULL
99b3f06f 9882 && !this->end_->type()->is_error()
9883 && !this->end_->is_nil_expression()
f6bc81e6 9884 && !this->end_->is_error_expression()
9885 && (!this->end_->numeric_constant_value(&nc)
9886 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 9887 this->report_error(_("slice end must be integer"));
acf2b673 9888 if (this->cap_ != NULL
9889 && this->cap_->type()->integer_type() == NULL
9890 && !this->cap_->type()->is_error()
9891 && !this->cap_->is_nil_expression()
9892 && !this->cap_->is_error_expression()
9893 && (!this->cap_->numeric_constant_value(&nc)
9894 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9895 this->report_error(_("slice capacity must be integer"));
e440a328 9896
9897 Array_type* array_type = this->array_->type()->array_type();
f9c68f17 9898 if (array_type == NULL)
9899 {
c484d925 9900 go_assert(this->array_->type()->is_error());
f9c68f17 9901 return;
9902 }
e440a328 9903
9904 unsigned int int_bits =
9905 Type::lookup_integer_type("int")->integer_type()->bits();
9906
0c77715b 9907 Numeric_constant lvalnc;
e440a328 9908 mpz_t lval;
e440a328 9909 bool lval_valid = (array_type->length() != NULL
0c77715b 9910 && array_type->length()->numeric_constant_value(&lvalnc)
9911 && lvalnc.to_int(&lval));
9912 Numeric_constant inc;
e440a328 9913 mpz_t ival;
0bd5d859 9914 bool ival_valid = false;
0c77715b 9915 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 9916 {
0bd5d859 9917 ival_valid = true;
e440a328 9918 if (mpz_sgn(ival) < 0
9919 || mpz_sizeinbase(ival, 2) >= int_bits
9920 || (lval_valid
9921 && (this->end_ == NULL
9922 ? mpz_cmp(ival, lval) >= 0
9923 : mpz_cmp(ival, lval) > 0)))
9924 {
9925 error_at(this->start_->location(), "array index out of bounds");
9926 this->set_is_error();
9927 }
9928 }
9929 if (this->end_ != NULL && !this->end_->is_nil_expression())
9930 {
0c77715b 9931 Numeric_constant enc;
9932 mpz_t eval;
acf2b673 9933 bool eval_valid = false;
0c77715b 9934 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 9935 {
acf2b673 9936 eval_valid = true;
0c77715b 9937 if (mpz_sgn(eval) < 0
9938 || mpz_sizeinbase(eval, 2) >= int_bits
9939 || (lval_valid && mpz_cmp(eval, lval) > 0))
e440a328 9940 {
9941 error_at(this->end_->location(), "array index out of bounds");
9942 this->set_is_error();
9943 }
0bd5d859 9944 else if (ival_valid && mpz_cmp(ival, eval) > 0)
9945 this->report_error(_("inverted slice range"));
e440a328 9946 }
acf2b673 9947
9948 Numeric_constant cnc;
9949 mpz_t cval;
9950 if (this->cap_ != NULL
9951 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
9952 {
9953 if (mpz_sgn(cval) < 0
9954 || mpz_sizeinbase(cval, 2) >= int_bits
9955 || (lval_valid && mpz_cmp(cval, lval) > 0))
9956 {
9957 error_at(this->cap_->location(), "array index out of bounds");
9958 this->set_is_error();
9959 }
9960 else if (ival_valid && mpz_cmp(ival, cval) > 0)
9961 {
9962 error_at(this->cap_->location(),
9963 "invalid slice index: capacity less than start");
9964 this->set_is_error();
9965 }
9966 else if (eval_valid && mpz_cmp(eval, cval) > 0)
9967 {
9968 error_at(this->cap_->location(),
9969 "invalid slice index: capacity less than length");
9970 this->set_is_error();
9971 }
9972 mpz_clear(cval);
9973 }
9974
9975 if (eval_valid)
9976 mpz_clear(eval);
e440a328 9977 }
0bd5d859 9978 if (ival_valid)
9979 mpz_clear(ival);
0c77715b 9980 if (lval_valid)
9981 mpz_clear(lval);
e440a328 9982
9983 // A slice of an array requires an addressable array. A slice of a
9984 // slice is always possible.
411eb89e 9985 if (this->end_ != NULL && !array_type->is_slice_type())
88ec30c8 9986 {
9987 if (!this->array_->is_addressable())
8da39c3b 9988 this->report_error(_("slice of unaddressable value"));
88ec30c8 9989 else
9990 this->array_->address_taken(true);
9991 }
e440a328 9992}
9993
2c809f8f 9994// Flatten array indexing by using temporary variables for slices and indexes.
35a54f17 9995
9996Expression*
9997Array_index_expression::do_flatten(Gogo*, Named_object*,
9998 Statement_inserter* inserter)
9999{
10000 Location loc = this->location();
2c809f8f 10001 Temporary_statement* temp;
35a54f17 10002 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10003 {
2c809f8f 10004 temp = Statement::make_temporary(NULL, this->array_, loc);
35a54f17 10005 inserter->insert(temp);
10006 this->array_ = Expression::make_temporary_reference(temp, loc);
10007 }
2c809f8f 10008 if (!this->start_->is_variable())
10009 {
10010 temp = Statement::make_temporary(NULL, this->start_, loc);
10011 inserter->insert(temp);
10012 this->start_ = Expression::make_temporary_reference(temp, loc);
10013 }
10014 if (this->end_ != NULL
10015 && !this->end_->is_nil_expression()
10016 && !this->end_->is_variable())
10017 {
10018 temp = Statement::make_temporary(NULL, this->end_, loc);
10019 inserter->insert(temp);
10020 this->end_ = Expression::make_temporary_reference(temp, loc);
10021 }
10022 if (this->cap_ != NULL && !this->cap_->is_variable())
10023 {
10024 temp = Statement::make_temporary(NULL, this->cap_, loc);
10025 inserter->insert(temp);
10026 this->cap_ = Expression::make_temporary_reference(temp, loc);
10027 }
10028
35a54f17 10029 return this;
10030}
10031
e440a328 10032// Return whether this expression is addressable.
10033
10034bool
10035Array_index_expression::do_is_addressable() const
10036{
10037 // A slice expression is not addressable.
10038 if (this->end_ != NULL)
10039 return false;
10040
10041 // An index into a slice is addressable.
411eb89e 10042 if (this->array_->type()->is_slice_type())
e440a328 10043 return true;
10044
10045 // An index into an array is addressable if the array is
10046 // addressable.
10047 return this->array_->is_addressable();
10048}
10049
ea664253 10050// Get the backend representation for an array index.
e440a328 10051
ea664253 10052Bexpression*
10053Array_index_expression::do_get_backend(Translate_context* context)
e440a328 10054{
e440a328 10055 Array_type* array_type = this->array_->type()->array_type();
d8cd8e2d 10056 if (array_type == NULL)
10057 {
c484d925 10058 go_assert(this->array_->type()->is_error());
ea664253 10059 return context->backend()->error_expression();
d8cd8e2d 10060 }
35a54f17 10061 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
e440a328 10062
2c809f8f 10063 Location loc = this->location();
10064 Gogo* gogo = context->gogo();
10065
6dfedc16 10066 Type* int_type = Type::lookup_integer_type("int");
10067 Btype* int_btype = int_type->get_backend(gogo);
e440a328 10068
2c809f8f 10069 // We need to convert the length and capacity to the Go "int" type here
10070 // because the length of a fixed-length array could be of type "uintptr"
10071 // and gimple disallows binary operations between "uintptr" and other
10072 // integer types. FIXME.
10073 Bexpression* length = NULL;
a04bfdfc 10074 if (this->end_ == NULL || this->end_->is_nil_expression())
10075 {
35a54f17 10076 Expression* len = array_type->get_length(gogo, this->array_);
ea664253 10077 length = len->get_backend(context);
2c809f8f 10078 length = gogo->backend()->convert_expression(int_btype, length, loc);
a04bfdfc 10079 }
10080
2c809f8f 10081 Bexpression* capacity = NULL;
a04bfdfc 10082 if (this->end_ != NULL)
10083 {
35a54f17 10084 Expression* cap = array_type->get_capacity(gogo, this->array_);
ea664253 10085 capacity = cap->get_backend(context);
2c809f8f 10086 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
a04bfdfc 10087 }
10088
2c809f8f 10089 Bexpression* cap_arg = capacity;
acf2b673 10090 if (this->cap_ != NULL)
10091 {
ea664253 10092 cap_arg = this->cap_->get_backend(context);
2c809f8f 10093 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
acf2b673 10094 }
10095
2c809f8f 10096 if (length == NULL)
10097 length = cap_arg;
e440a328 10098
10099 int code = (array_type->length() != NULL
10100 ? (this->end_ == NULL
10101 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10102 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10103 : (this->end_ == NULL
10104 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10105 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
ea664253 10106 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
2c809f8f 10107
6dfedc16 10108 if (this->start_->type()->integer_type() == NULL
10109 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10110 {
10111 go_assert(saw_errors());
10112 return context->backend()->error_expression();
10113 }
d9f3743a 10114
ea664253 10115 Bexpression* bad_index =
d9f3743a 10116 Expression::check_bounds(this->start_, loc)->get_backend(context);
2c809f8f 10117
ea664253 10118 Bexpression* start = this->start_->get_backend(context);
2c809f8f 10119 start = gogo->backend()->convert_expression(int_btype, start, loc);
10120 Bexpression* start_too_large =
10121 gogo->backend()->binary_expression((this->end_ == NULL
10122 ? OPERATOR_GE
10123 : OPERATOR_GT),
10124 start,
10125 (this->end_ == NULL
10126 ? length
10127 : capacity),
10128 loc);
10129 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10130 bad_index, loc);
e440a328 10131
10132 if (this->end_ == NULL)
10133 {
10134 // Simple array indexing. This has to return an l-value, so
2c809f8f 10135 // wrap the index check into START.
10136 start =
10137 gogo->backend()->conditional_expression(int_btype, bad_index,
10138 crash, start, loc);
e440a328 10139
2c809f8f 10140 Bexpression* ret;
e440a328 10141 if (array_type->length() != NULL)
10142 {
ea664253 10143 Bexpression* array = this->array_->get_backend(context);
2c809f8f 10144 ret = gogo->backend()->array_index_expression(array, start, loc);
e440a328 10145 }
10146 else
10147 {
2c809f8f 10148 // Slice.
10149 Expression* valptr =
35a54f17 10150 array_type->get_value_pointer(gogo, this->array_);
ea664253 10151 Bexpression* ptr = valptr->get_backend(context);
2c809f8f 10152 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
9b27b43c 10153
10154 Type* ele_type = this->array_->type()->array_type()->element_type();
10155 Btype* ele_btype = ele_type->get_backend(gogo);
10156 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
e440a328 10157 }
ea664253 10158 return ret;
e440a328 10159 }
10160
10161 // Array slice.
10162
acf2b673 10163 if (this->cap_ != NULL)
10164 {
2c809f8f 10165 Bexpression* bounds_bcheck =
ea664253 10166 Expression::check_bounds(this->cap_, loc)->get_backend(context);
2c809f8f 10167 bad_index =
10168 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10169 bad_index, loc);
10170 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10171
10172 Bexpression* cap_too_small =
10173 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10174 Bexpression* cap_too_large =
10175 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10176 Bexpression* bad_cap =
10177 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10178 cap_too_large, loc);
10179 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10180 bad_index, loc);
10181 }
10182
10183 Bexpression* end;
e440a328 10184 if (this->end_->is_nil_expression())
2c809f8f 10185 end = length;
e440a328 10186 else
10187 {
2c809f8f 10188 Bexpression* bounds_bcheck =
ea664253 10189 Expression::check_bounds(this->end_, loc)->get_backend(context);
e440a328 10190
2c809f8f 10191 bad_index =
10192 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10193 bad_index, loc);
e440a328 10194
ea664253 10195 end = this->end_->get_backend(context);
2c809f8f 10196 end = gogo->backend()->convert_expression(int_btype, end, loc);
10197 Bexpression* end_too_small =
10198 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10199 Bexpression* end_too_large =
10200 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10201 Bexpression* bad_end =
10202 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10203 end_too_large, loc);
10204 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10205 bad_index, loc);
e440a328 10206 }
10207
35a54f17 10208 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
ea664253 10209 Bexpression* val = valptr->get_backend(context);
2c809f8f 10210 val = gogo->backend()->pointer_offset_expression(val, start, loc);
e440a328 10211
2c809f8f 10212 Bexpression* result_length =
10213 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
e440a328 10214
2c809f8f 10215 Bexpression* result_capacity =
10216 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
e440a328 10217
2c809f8f 10218 Btype* struct_btype = this->type()->get_backend(gogo);
10219 std::vector<Bexpression*> init;
10220 init.push_back(val);
10221 init.push_back(result_length);
10222 init.push_back(result_capacity);
e440a328 10223
2c809f8f 10224 Bexpression* ctor =
10225 gogo->backend()->constructor_expression(struct_btype, init, loc);
ea664253 10226 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10227 crash, ctor, loc);
e440a328 10228}
10229
d751bb78 10230// Dump ast representation for an array index expression.
10231
10232void
10233Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10234 const
10235{
10236 Index_expression::dump_index_expression(ast_dump_context, this->array_,
acf2b673 10237 this->start_, this->end_, this->cap_);
d751bb78 10238}
10239
acf2b673 10240// Make an array index expression. END and CAP may be NULL.
e440a328 10241
10242Expression*
10243Expression::make_array_index(Expression* array, Expression* start,
acf2b673 10244 Expression* end, Expression* cap,
10245 Location location)
e440a328 10246{
acf2b673 10247 return new Array_index_expression(array, start, end, cap, location);
e440a328 10248}
10249
10250// A string index. This is used for both indexing and slicing.
10251
10252class String_index_expression : public Expression
10253{
10254 public:
10255 String_index_expression(Expression* string, Expression* start,
b13c66cd 10256 Expression* end, Location location)
e440a328 10257 : Expression(EXPRESSION_STRING_INDEX, location),
10258 string_(string), start_(start), end_(end)
10259 { }
10260
10261 protected:
10262 int
10263 do_traverse(Traverse*);
10264
2c809f8f 10265 Expression*
10266 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10267
e440a328 10268 Type*
10269 do_type();
10270
10271 void
10272 do_determine_type(const Type_context*);
10273
10274 void
10275 do_check_types(Gogo*);
10276
10277 Expression*
10278 do_copy()
10279 {
10280 return Expression::make_string_index(this->string_->copy(),
10281 this->start_->copy(),
10282 (this->end_ == NULL
10283 ? NULL
10284 : this->end_->copy()),
10285 this->location());
10286 }
10287
baef9f7a 10288 bool
10289 do_must_eval_subexpressions_in_order(int* skip) const
10290 {
10291 *skip = 1;
10292 return true;
10293 }
10294
ea664253 10295 Bexpression*
10296 do_get_backend(Translate_context*);
e440a328 10297
d751bb78 10298 void
10299 do_dump_expression(Ast_dump_context*) const;
10300
e440a328 10301 private:
10302 // The string we are getting a value from.
10303 Expression* string_;
10304 // The start or only index.
10305 Expression* start_;
10306 // The end index of a slice. This may be NULL for a single index,
10307 // or it may be a nil expression for the length of the string.
10308 Expression* end_;
10309};
10310
10311// String index traversal.
10312
10313int
10314String_index_expression::do_traverse(Traverse* traverse)
10315{
10316 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10317 return TRAVERSE_EXIT;
10318 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10319 return TRAVERSE_EXIT;
10320 if (this->end_ != NULL)
10321 {
10322 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10323 return TRAVERSE_EXIT;
10324 }
10325 return TRAVERSE_CONTINUE;
10326}
10327
2c809f8f 10328Expression*
10329String_index_expression::do_flatten(Gogo*, Named_object*,
10330 Statement_inserter* inserter)
e440a328 10331{
2c809f8f 10332 Temporary_statement* temp;
10333 Location loc = this->location();
10334 if (!this->string_->is_variable())
10335 {
10336 temp = Statement::make_temporary(NULL, this->string_, loc);
10337 inserter->insert(temp);
10338 this->string_ = Expression::make_temporary_reference(temp, loc);
10339 }
10340 if (!this->start_->is_variable())
10341 {
10342 temp = Statement::make_temporary(NULL, this->start_, loc);
10343 inserter->insert(temp);
10344 this->start_ = Expression::make_temporary_reference(temp, loc);
10345 }
10346 if (this->end_ != NULL
10347 && !this->end_->is_nil_expression()
10348 && !this->end_->is_variable())
10349 {
10350 temp = Statement::make_temporary(NULL, this->end_, loc);
10351 inserter->insert(temp);
10352 this->end_ = Expression::make_temporary_reference(temp, loc);
10353 }
10354
10355 return this;
10356}
10357
10358// Return the type of a string index.
10359
10360Type*
10361String_index_expression::do_type()
10362{
10363 if (this->end_ == NULL)
10364 return Type::lookup_integer_type("uint8");
10365 else
10366 return this->string_->type();
10367}
10368
10369// Determine the type of a string index.
10370
10371void
10372String_index_expression::do_determine_type(const Type_context*)
10373{
10374 this->string_->determine_type_no_context();
10375 this->start_->determine_type_no_context();
e440a328 10376 if (this->end_ != NULL)
93000773 10377 this->end_->determine_type_no_context();
e440a328 10378}
10379
10380// Check types of a string index.
10381
10382void
10383String_index_expression::do_check_types(Gogo*)
10384{
acdc230d 10385 Numeric_constant nc;
10386 unsigned long v;
10387 if (this->start_->type()->integer_type() == NULL
10388 && !this->start_->type()->is_error()
10389 && (!this->start_->numeric_constant_value(&nc)
10390 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10391 this->report_error(_("index must be integer"));
10392 if (this->end_ != NULL
10393 && this->end_->type()->integer_type() == NULL
acdc230d 10394 && !this->end_->type()->is_error()
10395 && !this->end_->is_nil_expression()
10396 && !this->end_->is_error_expression()
10397 && (!this->end_->numeric_constant_value(&nc)
10398 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
e440a328 10399 this->report_error(_("slice end must be integer"));
10400
10401 std::string sval;
10402 bool sval_valid = this->string_->string_constant_value(&sval);
10403
0c77715b 10404 Numeric_constant inc;
e440a328 10405 mpz_t ival;
0bd5d859 10406 bool ival_valid = false;
0c77715b 10407 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
e440a328 10408 {
0bd5d859 10409 ival_valid = true;
e440a328 10410 if (mpz_sgn(ival) < 0
10411 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10412 {
10413 error_at(this->start_->location(), "string index out of bounds");
10414 this->set_is_error();
10415 }
10416 }
10417 if (this->end_ != NULL && !this->end_->is_nil_expression())
10418 {
0c77715b 10419 Numeric_constant enc;
10420 mpz_t eval;
10421 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
e440a328 10422 {
0c77715b 10423 if (mpz_sgn(eval) < 0
10424 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
e440a328 10425 {
10426 error_at(this->end_->location(), "string index out of bounds");
10427 this->set_is_error();
10428 }
0bd5d859 10429 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10430 this->report_error(_("inverted slice range"));
0c77715b 10431 mpz_clear(eval);
e440a328 10432 }
10433 }
0bd5d859 10434 if (ival_valid)
10435 mpz_clear(ival);
e440a328 10436}
10437
ea664253 10438// Get the backend representation for a string index.
e440a328 10439
ea664253 10440Bexpression*
10441String_index_expression::do_get_backend(Translate_context* context)
e440a328 10442{
b13c66cd 10443 Location loc = this->location();
2c809f8f 10444 Expression* string_arg = this->string_;
10445 if (this->string_->type()->points_to() != NULL)
10446 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
e440a328 10447
2c809f8f 10448 Expression* bad_index = Expression::check_bounds(this->start_, loc);
e440a328 10449
2c809f8f 10450 int code = (this->end_ == NULL
10451 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10452 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
e440a328 10453
2c809f8f 10454 Gogo* gogo = context->gogo();
ea664253 10455 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
1b1f2abf 10456
10457 Type* int_type = Type::lookup_integer_type("int");
e440a328 10458
2c809f8f 10459 // It is possible that an error occurred earlier because the start index
10460 // cannot be represented as an integer type. In this case, we shouldn't
10461 // try casting the starting index into an integer since
10462 // Type_conversion_expression will fail to get the backend representation.
10463 // FIXME.
10464 if (this->start_->type()->integer_type() == NULL
10465 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10466 {
10467 go_assert(saw_errors());
ea664253 10468 return context->backend()->error_expression();
2c809f8f 10469 }
e440a328 10470
2c809f8f 10471 Expression* start = Expression::make_cast(int_type, this->start_, loc);
e440a328 10472
2c809f8f 10473 if (this->end_ == NULL)
10474 {
10475 Expression* length =
10476 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
e440a328 10477
2c809f8f 10478 Expression* start_too_large =
10479 Expression::make_binary(OPERATOR_GE, start, length, loc);
10480 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10481 bad_index, loc);
10482 Expression* bytes =
10483 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
e440a328 10484
ea664253 10485 Bexpression* bstart = start->get_backend(context);
10486 Bexpression* ptr = bytes->get_backend(context);
2c809f8f 10487 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
9b27b43c 10488 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10489 Bexpression* index =
10490 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
e440a328 10491
2c809f8f 10492 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
ea664253 10493 Bexpression* index_error = bad_index->get_backend(context);
10494 return gogo->backend()->conditional_expression(byte_btype, index_error,
10495 crash, index, loc);
2c809f8f 10496 }
10497
10498 Expression* end = NULL;
10499 if (this->end_->is_nil_expression())
e67508fa 10500 end = Expression::make_integer_sl(-1, int_type, loc);
e440a328 10501 else
10502 {
2c809f8f 10503 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10504 bad_index =
10505 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10506 end = Expression::make_cast(int_type, this->end_, loc);
e440a328 10507 }
2c809f8f 10508
10509 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10510 string_arg, start, end);
ea664253 10511 Bexpression* bstrslice = strslice->get_backend(context);
2c809f8f 10512
10513 Btype* str_btype = strslice->type()->get_backend(gogo);
ea664253 10514 Bexpression* index_error = bad_index->get_backend(context);
10515 return gogo->backend()->conditional_expression(str_btype, index_error,
10516 crash, bstrslice, loc);
e440a328 10517}
10518
d751bb78 10519// Dump ast representation for a string index expression.
10520
10521void
10522String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10523 const
10524{
acf2b673 10525 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10526 this->start_, this->end_, NULL);
d751bb78 10527}
10528
e440a328 10529// Make a string index expression. END may be NULL.
10530
10531Expression*
10532Expression::make_string_index(Expression* string, Expression* start,
b13c66cd 10533 Expression* end, Location location)
e440a328 10534{
10535 return new String_index_expression(string, start, end, location);
10536}
10537
10538// Class Map_index.
10539
10540// Get the type of the map.
10541
10542Map_type*
10543Map_index_expression::get_map_type() const
10544{
10545 Map_type* mt = this->map_->type()->deref()->map_type();
c7524fae 10546 if (mt == NULL)
c484d925 10547 go_assert(saw_errors());
e440a328 10548 return mt;
10549}
10550
10551// Map index traversal.
10552
10553int
10554Map_index_expression::do_traverse(Traverse* traverse)
10555{
10556 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10557 return TRAVERSE_EXIT;
10558 return Expression::traverse(&this->index_, traverse);
10559}
10560
2c809f8f 10561// We need to pass in a pointer to the key, so flatten the index into a
10562// temporary variable if it isn't already. The value pointer will be
10563// dereferenced and checked for nil, so flatten into a temporary to avoid
10564// recomputation.
10565
10566Expression*
10567Map_index_expression::do_flatten(Gogo*, Named_object*,
10568 Statement_inserter* inserter)
10569{
10570 Map_type* mt = this->get_map_type();
10571 if (this->index_->type() != mt->key_type())
10572 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10573 this->location());
10574
10575 if (!this->index_->is_variable())
10576 {
10577 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10578 this->location());
10579 inserter->insert(temp);
10580 this->index_ = Expression::make_temporary_reference(temp,
10581 this->location());
10582 }
10583
10584 if (this->value_pointer_ == NULL)
10585 this->get_value_pointer(this->is_lvalue_);
10586 if (!this->value_pointer_->is_variable())
10587 {
10588 Temporary_statement* temp =
10589 Statement::make_temporary(NULL, this->value_pointer_,
10590 this->location());
10591 inserter->insert(temp);
10592 this->value_pointer_ =
10593 Expression::make_temporary_reference(temp, this->location());
10594 }
10595
10596 return this;
10597}
10598
e440a328 10599// Return the type of a map index.
10600
10601Type*
10602Map_index_expression::do_type()
10603{
c7524fae 10604 Map_type* mt = this->get_map_type();
10605 if (mt == NULL)
10606 return Type::make_error_type();
10607 Type* type = mt->val_type();
e440a328 10608 // If this map index is in a tuple assignment, we actually return a
10609 // pointer to the value type. Tuple_map_assignment_statement is
10610 // responsible for handling this correctly. We need to get the type
10611 // right in case this gets assigned to a temporary variable.
10612 if (this->is_in_tuple_assignment_)
10613 type = Type::make_pointer_type(type);
10614 return type;
10615}
10616
10617// Fix the type of a map index.
10618
10619void
10620Map_index_expression::do_determine_type(const Type_context*)
10621{
10622 this->map_->determine_type_no_context();
c7524fae 10623 Map_type* mt = this->get_map_type();
10624 Type* key_type = mt == NULL ? NULL : mt->key_type();
10625 Type_context subcontext(key_type, false);
e440a328 10626 this->index_->determine_type(&subcontext);
10627}
10628
10629// Check types of a map index.
10630
10631void
10632Map_index_expression::do_check_types(Gogo*)
10633{
10634 std::string reason;
c7524fae 10635 Map_type* mt = this->get_map_type();
10636 if (mt == NULL)
10637 return;
10638 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
e440a328 10639 {
10640 if (reason.empty())
10641 this->report_error(_("incompatible type for map index"));
10642 else
10643 {
10644 error_at(this->location(), "incompatible type for map index (%s)",
10645 reason.c_str());
10646 this->set_is_error();
10647 }
10648 }
10649}
10650
ea664253 10651// Get the backend representation for a map index.
e440a328 10652
ea664253 10653Bexpression*
10654Map_index_expression::do_get_backend(Translate_context* context)
e440a328 10655{
10656 Map_type* type = this->get_map_type();
c7524fae 10657 if (type == NULL)
2c809f8f 10658 {
10659 go_assert(saw_errors());
ea664253 10660 return context->backend()->error_expression();
2c809f8f 10661 }
e440a328 10662
2c809f8f 10663 go_assert(this->value_pointer_ != NULL
10664 && this->value_pointer_->is_variable());
e440a328 10665
2c809f8f 10666 Bexpression* ret;
e440a328 10667 if (this->is_lvalue_)
2c809f8f 10668 {
10669 Expression* val =
10670 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10671 this->location());
ea664253 10672 ret = val->get_backend(context);
2c809f8f 10673 }
e440a328 10674 else if (this->is_in_tuple_assignment_)
10675 {
10676 // Tuple_map_assignment_statement is responsible for using this
10677 // appropriately.
ea664253 10678 ret = this->value_pointer_->get_backend(context);
e440a328 10679 }
10680 else
10681 {
2c809f8f 10682 Location loc = this->location();
10683
10684 Expression* nil_check =
10685 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10686 Expression::make_nil(loc), loc);
ea664253 10687 Bexpression* bnil_check = nil_check->get_backend(context);
2c809f8f 10688 Expression* val =
10689 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
ea664253 10690 Bexpression* bval = val->get_backend(context);
2c809f8f 10691
63697958 10692 Gogo* gogo = context->gogo();
10693 Btype* val_btype = type->val_type()->get_backend(gogo);
10694 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
2c809f8f 10695 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10696 val_zero, bval, loc);
e440a328 10697 }
ea664253 10698 return ret;
e440a328 10699}
10700
2c809f8f 10701// Get an expression for the map index. This returns an expression which
10702// evaluates to a pointer to a value. The pointer will be NULL if the key is
e440a328 10703// not in the map.
10704
2c809f8f 10705Expression*
10706Map_index_expression::get_value_pointer(bool insert)
e440a328 10707{
2c809f8f 10708 if (this->value_pointer_ == NULL)
746d2e73 10709 {
2c809f8f 10710 Map_type* type = this->get_map_type();
10711 if (type == NULL)
746d2e73 10712 {
2c809f8f 10713 go_assert(saw_errors());
10714 return Expression::make_error(this->location());
746d2e73 10715 }
e440a328 10716
2c809f8f 10717 Location loc = this->location();
10718 Expression* map_ref = this->map_;
10719 if (this->map_->type()->points_to() != NULL)
10720 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
e440a328 10721
2c809f8f 10722 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10723 loc);
10724 Expression* map_index =
10725 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10726 map_ref, index_ptr,
10727 Expression::make_boolean(insert, loc));
10728
10729 Type* val_type = type->val_type();
10730 this->value_pointer_ =
10731 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10732 map_index, this->location());
10733 }
10734 return this->value_pointer_;
e440a328 10735}
10736
d751bb78 10737// Dump ast representation for a map index expression
10738
10739void
10740Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10741 const
10742{
acf2b673 10743 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10744 this->index_, NULL, NULL);
d751bb78 10745}
10746
e440a328 10747// Make a map index expression.
10748
10749Map_index_expression*
10750Expression::make_map_index(Expression* map, Expression* index,
b13c66cd 10751 Location location)
e440a328 10752{
10753 return new Map_index_expression(map, index, location);
10754}
10755
10756// Class Field_reference_expression.
10757
149eabc5 10758// Lower a field reference expression. There is nothing to lower, but
10759// this is where we generate the tracking information for fields with
10760// the magic go:"track" tag.
10761
10762Expression*
10763Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10764 Statement_inserter* inserter, int)
10765{
10766 Struct_type* struct_type = this->expr_->type()->struct_type();
10767 if (struct_type == NULL)
10768 {
10769 // Error will be reported elsewhere.
10770 return this;
10771 }
10772 const Struct_field* field = struct_type->field(this->field_index_);
10773 if (field == NULL)
10774 return this;
10775 if (!field->has_tag())
10776 return this;
10777 if (field->tag().find("go:\"track\"") == std::string::npos)
10778 return this;
10779
604e278d 10780 // References from functions generated by the compiler don't count.
c6292d1d 10781 if (function != NULL && function->func_value()->is_type_specific_function())
604e278d 10782 return this;
10783
149eabc5 10784 // We have found a reference to a tracked field. Build a call to
10785 // the runtime function __go_fieldtrack with a string that describes
10786 // the field. FIXME: We should only call this once per referenced
10787 // field per function, not once for each reference to the field.
10788
10789 if (this->called_fieldtrack_)
10790 return this;
10791 this->called_fieldtrack_ = true;
10792
10793 Location loc = this->location();
10794
10795 std::string s = "fieldtrack \"";
10796 Named_type* nt = this->expr_->type()->named_type();
10797 if (nt == NULL || nt->named_object()->package() == NULL)
10798 s.append(gogo->pkgpath());
10799 else
10800 s.append(nt->named_object()->package()->pkgpath());
10801 s.push_back('.');
10802 if (nt != NULL)
5c29ad36 10803 s.append(Gogo::unpack_hidden_name(nt->name()));
149eabc5 10804 s.push_back('.');
10805 s.append(field->field_name());
10806 s.push_back('"');
10807
10808 // We can't use a string here, because internally a string holds a
10809 // pointer to the actual bytes; when the linker garbage collects the
10810 // string, it won't garbage collect the bytes. So we use a
10811 // [...]byte.
10812
e67508fa 10813 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
149eabc5 10814
10815 Type* byte_type = gogo->lookup_global("byte")->type_value();
10816 Type* array_type = Type::make_array_type(byte_type, length_expr);
10817
10818 Expression_list* bytes = new Expression_list();
10819 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10820 {
e67508fa 10821 unsigned char c = static_cast<unsigned char>(*p);
10822 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
149eabc5 10823 }
10824
10825 Expression* e = Expression::make_composite_literal(array_type, 0, false,
62750cd5 10826 bytes, false, loc);
149eabc5 10827
10828 Variable* var = new Variable(array_type, e, true, false, false, loc);
10829
10830 static int count;
10831 char buf[50];
10832 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
10833 ++count;
10834
10835 Named_object* no = gogo->add_variable(buf, var);
10836 e = Expression::make_var_reference(no, loc);
10837 e = Expression::make_unary(OPERATOR_AND, e, loc);
10838
10839 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
604e278d 10840 gogo->lower_expression(function, inserter, &call);
149eabc5 10841 inserter->insert(Statement::make_statement(call, false));
10842
10843 // Put this function, and the global variable we just created, into
10844 // unique sections. This will permit the linker to garbage collect
10845 // them if they are not referenced. The effect is that the only
10846 // strings, indicating field references, that will wind up in the
10847 // executable will be those for functions that are actually needed.
66a6be58 10848 if (function != NULL)
10849 function->func_value()->set_in_unique_section();
149eabc5 10850 var->set_in_unique_section();
10851
10852 return this;
10853}
10854
e440a328 10855// Return the type of a field reference.
10856
10857Type*
10858Field_reference_expression::do_type()
10859{
b0e628fb 10860 Type* type = this->expr_->type();
5c13bd80 10861 if (type->is_error())
b0e628fb 10862 return type;
10863 Struct_type* struct_type = type->struct_type();
c484d925 10864 go_assert(struct_type != NULL);
e440a328 10865 return struct_type->field(this->field_index_)->type();
10866}
10867
10868// Check the types for a field reference.
10869
10870void
10871Field_reference_expression::do_check_types(Gogo*)
10872{
b0e628fb 10873 Type* type = this->expr_->type();
5c13bd80 10874 if (type->is_error())
b0e628fb 10875 return;
10876 Struct_type* struct_type = type->struct_type();
c484d925 10877 go_assert(struct_type != NULL);
10878 go_assert(struct_type->field(this->field_index_) != NULL);
e440a328 10879}
10880
ea664253 10881// Get the backend representation for a field reference.
e440a328 10882
ea664253 10883Bexpression*
10884Field_reference_expression::do_get_backend(Translate_context* context)
e440a328 10885{
ea664253 10886 Bexpression* bstruct = this->expr_->get_backend(context);
10887 return context->gogo()->backend()->struct_field_expression(bstruct,
10888 this->field_index_,
10889 this->location());
e440a328 10890}
10891
d751bb78 10892// Dump ast representation for a field reference expression.
10893
10894void
10895Field_reference_expression::do_dump_expression(
10896 Ast_dump_context* ast_dump_context) const
10897{
10898 this->expr_->dump_expression(ast_dump_context);
10899 ast_dump_context->ostream() << "." << this->field_index_;
10900}
10901
e440a328 10902// Make a reference to a qualified identifier in an expression.
10903
10904Field_reference_expression*
10905Expression::make_field_reference(Expression* expr, unsigned int field_index,
b13c66cd 10906 Location location)
e440a328 10907{
10908 return new Field_reference_expression(expr, field_index, location);
10909}
10910
10911// Class Interface_field_reference_expression.
10912
2387f644 10913// Return an expression for the pointer to the function to call.
e440a328 10914
2387f644 10915Expression*
10916Interface_field_reference_expression::get_function()
e440a328 10917{
2387f644 10918 Expression* ref = this->expr_;
10919 Location loc = this->location();
10920 if (ref->type()->points_to() != NULL)
10921 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
e440a328 10922
2387f644 10923 Expression* mtable =
10924 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
10925 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
e440a328 10926
10927 std::string name = Gogo::unpack_hidden_name(this->name_);
2387f644 10928 unsigned int index;
10929 const Struct_field* field = mtable_type->find_local_field(name, &index);
10930 go_assert(field != NULL);
10931 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
10932 return Expression::make_field_reference(mtable, index, loc);
e440a328 10933}
10934
2387f644 10935// Return an expression for the first argument to pass to the interface
e440a328 10936// function.
10937
2387f644 10938Expression*
10939Interface_field_reference_expression::get_underlying_object()
e440a328 10940{
2387f644 10941 Expression* expr = this->expr_;
10942 if (expr->type()->points_to() != NULL)
10943 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
10944 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
10945 this->location());
e440a328 10946}
10947
10948// Traversal.
10949
10950int
10951Interface_field_reference_expression::do_traverse(Traverse* traverse)
10952{
10953 return Expression::traverse(&this->expr_, traverse);
10954}
10955
0afbb937 10956// Lower the expression. If this expression is not called, we need to
10957// evaluate the expression twice when converting to the backend
10958// interface. So introduce a temporary variable if necessary.
10959
10960Expression*
9782d556 10961Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
10962 Statement_inserter* inserter)
0afbb937 10963{
2387f644 10964 if (!this->expr_->is_variable())
0afbb937 10965 {
10966 Temporary_statement* temp =
10967 Statement::make_temporary(this->expr_->type(), NULL, this->location());
10968 inserter->insert(temp);
10969 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
10970 this->location());
10971 }
10972 return this;
10973}
10974
e440a328 10975// Return the type of an interface field reference.
10976
10977Type*
10978Interface_field_reference_expression::do_type()
10979{
10980 Type* expr_type = this->expr_->type();
10981
10982 Type* points_to = expr_type->points_to();
10983 if (points_to != NULL)
10984 expr_type = points_to;
10985
10986 Interface_type* interface_type = expr_type->interface_type();
10987 if (interface_type == NULL)
10988 return Type::make_error_type();
10989
10990 const Typed_identifier* method = interface_type->find_method(this->name_);
10991 if (method == NULL)
10992 return Type::make_error_type();
10993
10994 return method->type();
10995}
10996
10997// Determine types.
10998
10999void
11000Interface_field_reference_expression::do_determine_type(const Type_context*)
11001{
11002 this->expr_->determine_type_no_context();
11003}
11004
11005// Check the types for an interface field reference.
11006
11007void
11008Interface_field_reference_expression::do_check_types(Gogo*)
11009{
11010 Type* type = this->expr_->type();
11011
11012 Type* points_to = type->points_to();
11013 if (points_to != NULL)
11014 type = points_to;
11015
11016 Interface_type* interface_type = type->interface_type();
11017 if (interface_type == NULL)
5c491127 11018 {
11019 if (!type->is_error_type())
11020 this->report_error(_("expected interface or pointer to interface"));
11021 }
e440a328 11022 else
11023 {
11024 const Typed_identifier* method =
11025 interface_type->find_method(this->name_);
11026 if (method == NULL)
11027 {
11028 error_at(this->location(), "method %qs not in interface",
11029 Gogo::message_name(this->name_).c_str());
11030 this->set_is_error();
11031 }
11032 }
11033}
11034
0afbb937 11035// If an interface field reference is not simply called, then it is
11036// represented as a closure. The closure will hold a single variable,
11037// the value of the interface on which the method should be called.
11038// The function will be a simple thunk that pulls the value from the
11039// closure and calls the method with the remaining arguments.
11040
11041// Because method values are not common, we don't build all thunks for
11042// all possible interface methods, but instead only build them as we
11043// need them. In particular, we even build them on demand for
11044// interface methods defined in other packages.
11045
11046Interface_field_reference_expression::Interface_method_thunks
11047 Interface_field_reference_expression::interface_method_thunks;
11048
11049// Find or create the thunk to call method NAME on TYPE.
11050
11051Named_object*
11052Interface_field_reference_expression::create_thunk(Gogo* gogo,
11053 Interface_type* type,
11054 const std::string& name)
11055{
11056 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11057 std::pair<Interface_method_thunks::iterator, bool> ins =
11058 Interface_field_reference_expression::interface_method_thunks.insert(val);
11059 if (ins.second)
11060 {
11061 // This is the first time we have seen this interface.
11062 ins.first->second = new Method_thunks();
11063 }
11064
11065 for (Method_thunks::const_iterator p = ins.first->second->begin();
11066 p != ins.first->second->end();
11067 p++)
11068 if (p->first == name)
11069 return p->second;
11070
11071 Location loc = type->location();
11072
11073 const Typed_identifier* method_id = type->find_method(name);
11074 if (method_id == NULL)
11075 return Named_object::make_erroneous_name(Gogo::thunk_name());
11076
11077 Function_type* orig_fntype = method_id->type()->function_type();
11078 if (orig_fntype == NULL)
11079 return Named_object::make_erroneous_name(Gogo::thunk_name());
11080
11081 Struct_field_list* sfl = new Struct_field_list();
f8bdf81a 11082 // The type here is wrong--it should be the C function type. But it
11083 // doesn't really matter.
0afbb937 11084 Type* vt = Type::make_pointer_type(Type::make_void_type());
11085 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11086 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11087 Type* closure_type = Type::make_struct_type(sfl, loc);
11088 closure_type = Type::make_pointer_type(closure_type);
11089
f8bdf81a 11090 Function_type* new_fntype = orig_fntype->copy_with_names();
0afbb937 11091
11092 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11093 false, loc);
11094
f8bdf81a 11095 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11096 cvar->set_is_used();
11097 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11098 new_no->func_value()->set_closure_var(cp);
0afbb937 11099
f8bdf81a 11100 gogo->start_block(loc);
0afbb937 11101
11102 // Field 0 of the closure is the function code pointer, field 1 is
11103 // the value on which to invoke the method.
11104 Expression* arg = Expression::make_var_reference(cp, loc);
11105 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11106 arg = Expression::make_field_reference(arg, 1, loc);
11107
11108 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11109 loc);
11110
11111 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11112 Expression_list* args;
11113 if (orig_params == NULL || orig_params->empty())
11114 args = NULL;
11115 else
11116 {
11117 const Typed_identifier_list* new_params = new_fntype->parameters();
11118 args = new Expression_list();
11119 for (Typed_identifier_list::const_iterator p = new_params->begin();
f8bdf81a 11120 p != new_params->end();
0afbb937 11121 ++p)
11122 {
11123 Named_object* p_no = gogo->lookup(p->name(), NULL);
11124 go_assert(p_no != NULL
11125 && p_no->is_variable()
11126 && p_no->var_value()->is_parameter());
11127 args->push_back(Expression::make_var_reference(p_no, loc));
11128 }
11129 }
11130
11131 Call_expression* call = Expression::make_call(ifre, args,
11132 orig_fntype->is_varargs(),
11133 loc);
11134 call->set_varargs_are_lowered();
11135
11136 Statement* s = Statement::make_return_from_call(call, loc);
11137 gogo->add_statement(s);
11138 Block* b = gogo->finish_block(loc);
11139 gogo->add_block(b, loc);
11140 gogo->lower_block(new_no, b);
a32698ee 11141 gogo->flatten_block(new_no, b);
0afbb937 11142 gogo->finish_function(loc);
11143
11144 ins.first->second->push_back(std::make_pair(name, new_no));
11145 return new_no;
11146}
11147
ea664253 11148// Get the backend representation for a method value.
e440a328 11149
ea664253 11150Bexpression*
11151Interface_field_reference_expression::do_get_backend(Translate_context* context)
e440a328 11152{
0afbb937 11153 Interface_type* type = this->expr_->type()->interface_type();
11154 if (type == NULL)
11155 {
11156 go_assert(saw_errors());
ea664253 11157 return context->backend()->error_expression();
0afbb937 11158 }
11159
11160 Named_object* thunk =
11161 Interface_field_reference_expression::create_thunk(context->gogo(),
11162 type, this->name_);
11163 if (thunk->is_erroneous())
11164 {
11165 go_assert(saw_errors());
ea664253 11166 return context->backend()->error_expression();
0afbb937 11167 }
11168
11169 // FIXME: We should lower this earlier, but we can't it lower it in
11170 // the lowering pass because at that point we don't know whether we
11171 // need to create the thunk or not. If the expression is called, we
11172 // don't need the thunk.
11173
11174 Location loc = this->location();
11175
11176 Struct_field_list* fields = new Struct_field_list();
11177 fields->push_back(Struct_field(Typed_identifier("fn.0",
11178 thunk->func_value()->type(),
11179 loc)));
11180 fields->push_back(Struct_field(Typed_identifier("val.1",
11181 this->expr_->type(),
11182 loc)));
11183 Struct_type* st = Type::make_struct_type(fields, loc);
11184
11185 Expression_list* vals = new Expression_list();
11186 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11187 vals->push_back(this->expr_);
11188
11189 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
ea664253 11190 Bexpression* bclosure =
11191 Expression::make_heap_expression(expr, loc)->get_backend(context);
0afbb937 11192
2387f644 11193 Expression* nil_check =
11194 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11195 Expression::make_nil(loc), loc);
ea664253 11196 Bexpression* bnil_check = nil_check->get_backend(context);
0afbb937 11197
2387f644 11198 Gogo* gogo = context->gogo();
ea664253 11199 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11200 loc)->get_backend(context);
2387f644 11201
11202 Bexpression* bcond =
a32698ee 11203 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
2387f644 11204 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
ea664253 11205 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
e440a328 11206}
11207
d751bb78 11208// Dump ast representation for an interface field reference.
11209
11210void
11211Interface_field_reference_expression::do_dump_expression(
11212 Ast_dump_context* ast_dump_context) const
11213{
11214 this->expr_->dump_expression(ast_dump_context);
11215 ast_dump_context->ostream() << "." << this->name_;
11216}
11217
e440a328 11218// Make a reference to a field in an interface.
11219
11220Expression*
11221Expression::make_interface_field_reference(Expression* expr,
11222 const std::string& field,
b13c66cd 11223 Location location)
e440a328 11224{
11225 return new Interface_field_reference_expression(expr, field, location);
11226}
11227
11228// A general selector. This is a Parser_expression for LEFT.NAME. It
11229// is lowered after we know the type of the left hand side.
11230
11231class Selector_expression : public Parser_expression
11232{
11233 public:
11234 Selector_expression(Expression* left, const std::string& name,
b13c66cd 11235 Location location)
e440a328 11236 : Parser_expression(EXPRESSION_SELECTOR, location),
11237 left_(left), name_(name)
11238 { }
11239
11240 protected:
11241 int
11242 do_traverse(Traverse* traverse)
11243 { return Expression::traverse(&this->left_, traverse); }
11244
11245 Expression*
ceeb4318 11246 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 11247
11248 Expression*
11249 do_copy()
11250 {
11251 return new Selector_expression(this->left_->copy(), this->name_,
11252 this->location());
11253 }
11254
d751bb78 11255 void
11256 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11257
e440a328 11258 private:
11259 Expression*
11260 lower_method_expression(Gogo*);
11261
11262 // The expression on the left hand side.
11263 Expression* left_;
11264 // The name on the right hand side.
11265 std::string name_;
11266};
11267
11268// Lower a selector expression once we know the real type of the left
11269// hand side.
11270
11271Expression*
ceeb4318 11272Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11273 int)
e440a328 11274{
11275 Expression* left = this->left_;
11276 if (left->is_type_expression())
11277 return this->lower_method_expression(gogo);
11278 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11279 this->location());
11280}
11281
11282// Lower a method expression T.M or (*T).M. We turn this into a
11283// function literal.
11284
11285Expression*
11286Selector_expression::lower_method_expression(Gogo* gogo)
11287{
b13c66cd 11288 Location location = this->location();
e440a328 11289 Type* type = this->left_->type();
11290 const std::string& name(this->name_);
11291
11292 bool is_pointer;
11293 if (type->points_to() == NULL)
11294 is_pointer = false;
11295 else
11296 {
11297 is_pointer = true;
11298 type = type->points_to();
11299 }
11300 Named_type* nt = type->named_type();
11301 if (nt == NULL)
11302 {
11303 error_at(location,
11304 ("method expression requires named type or "
11305 "pointer to named type"));
11306 return Expression::make_error(location);
11307 }
11308
11309 bool is_ambiguous;
11310 Method* method = nt->method_function(name, &is_ambiguous);
ab1468c3 11311 const Typed_identifier* imethod = NULL;
dcc8506b 11312 if (method == NULL && !is_pointer)
ab1468c3 11313 {
11314 Interface_type* it = nt->interface_type();
11315 if (it != NULL)
11316 imethod = it->find_method(name);
11317 }
11318
11319 if (method == NULL && imethod == NULL)
e440a328 11320 {
11321 if (!is_ambiguous)
dcc8506b 11322 error_at(location, "type %<%s%s%> has no method %<%s%>",
11323 is_pointer ? "*" : "",
e440a328 11324 nt->message_name().c_str(),
11325 Gogo::message_name(name).c_str());
11326 else
dcc8506b 11327 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
e440a328 11328 Gogo::message_name(name).c_str(),
dcc8506b 11329 is_pointer ? "*" : "",
e440a328 11330 nt->message_name().c_str());
11331 return Expression::make_error(location);
11332 }
11333
ab1468c3 11334 if (method != NULL && !is_pointer && !method->is_value_method())
e440a328 11335 {
11336 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11337 nt->message_name().c_str(),
11338 Gogo::message_name(name).c_str());
11339 return Expression::make_error(location);
11340 }
11341
11342 // Build a new function type in which the receiver becomes the first
11343 // argument.
ab1468c3 11344 Function_type* method_type;
11345 if (method != NULL)
11346 {
11347 method_type = method->type();
c484d925 11348 go_assert(method_type->is_method());
ab1468c3 11349 }
11350 else
11351 {
11352 method_type = imethod->type()->function_type();
c484d925 11353 go_assert(method_type != NULL && !method_type->is_method());
ab1468c3 11354 }
e440a328 11355
11356 const char* const receiver_name = "$this";
11357 Typed_identifier_list* parameters = new Typed_identifier_list();
11358 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11359 location));
11360
11361 const Typed_identifier_list* method_parameters = method_type->parameters();
11362 if (method_parameters != NULL)
11363 {
f470da59 11364 int i = 0;
e440a328 11365 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11366 p != method_parameters->end();
f470da59 11367 ++p, ++i)
11368 {
68883531 11369 if (!p->name().empty())
f470da59 11370 parameters->push_back(*p);
11371 else
11372 {
11373 char buf[20];
11374 snprintf(buf, sizeof buf, "$param%d", i);
11375 parameters->push_back(Typed_identifier(buf, p->type(),
11376 p->location()));
11377 }
11378 }
e440a328 11379 }
11380
11381 const Typed_identifier_list* method_results = method_type->results();
11382 Typed_identifier_list* results;
11383 if (method_results == NULL)
11384 results = NULL;
11385 else
11386 {
11387 results = new Typed_identifier_list();
11388 for (Typed_identifier_list::const_iterator p = method_results->begin();
11389 p != method_results->end();
11390 ++p)
11391 results->push_back(*p);
11392 }
11393
11394 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11395 location);
11396 if (method_type->is_varargs())
11397 fntype->set_is_varargs();
11398
11399 // We generate methods which always takes a pointer to the receiver
11400 // as their first argument. If this is for a pointer type, we can
11401 // simply reuse the existing function. We use an internal hack to
11402 // get the right type.
8381eda7 11403 // FIXME: This optimization is disabled because it doesn't yet work
11404 // with function descriptors when the method expression is not
11405 // directly called.
11406 if (method != NULL && is_pointer && false)
e440a328 11407 {
11408 Named_object* mno = (method->needs_stub_method()
11409 ? method->stub_object()
11410 : method->named_object());
11411 Expression* f = Expression::make_func_reference(mno, NULL, location);
11412 f = Expression::make_cast(fntype, f, location);
11413 Type_conversion_expression* tce =
11414 static_cast<Type_conversion_expression*>(f);
11415 tce->set_may_convert_function_types();
11416 return f;
11417 }
11418
11419 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11420 location);
11421
11422 Named_object* vno = gogo->lookup(receiver_name, NULL);
c484d925 11423 go_assert(vno != NULL);
e440a328 11424 Expression* ve = Expression::make_var_reference(vno, location);
ab1468c3 11425 Expression* bm;
11426 if (method != NULL)
11427 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11428 else
11429 bm = Expression::make_interface_field_reference(ve, name, location);
f690b0bb 11430
11431 // Even though we found the method above, if it has an error type we
11432 // may see an error here.
11433 if (bm->is_error_expression())
463fe805 11434 {
11435 gogo->finish_function(location);
11436 return bm;
11437 }
e440a328 11438
11439 Expression_list* args;
f470da59 11440 if (parameters->size() <= 1)
e440a328 11441 args = NULL;
11442 else
11443 {
11444 args = new Expression_list();
f470da59 11445 Typed_identifier_list::const_iterator p = parameters->begin();
11446 ++p;
11447 for (; p != parameters->end(); ++p)
e440a328 11448 {
11449 vno = gogo->lookup(p->name(), NULL);
c484d925 11450 go_assert(vno != NULL);
e440a328 11451 args->push_back(Expression::make_var_reference(vno, location));
11452 }
11453 }
11454
ceeb4318 11455 gogo->start_block(location);
11456
e440a328 11457 Call_expression* call = Expression::make_call(bm, args,
11458 method_type->is_varargs(),
11459 location);
11460
0afbb937 11461 Statement* s = Statement::make_return_from_call(call, location);
e440a328 11462 gogo->add_statement(s);
11463
ceeb4318 11464 Block* b = gogo->finish_block(location);
11465
11466 gogo->add_block(b, location);
11467
11468 // Lower the call in case there are multiple results.
11469 gogo->lower_block(no, b);
a32698ee 11470 gogo->flatten_block(no, b);
ceeb4318 11471
e440a328 11472 gogo->finish_function(location);
11473
11474 return Expression::make_func_reference(no, NULL, location);
11475}
11476
d751bb78 11477// Dump the ast for a selector expression.
11478
11479void
11480Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11481 const
11482{
11483 ast_dump_context->dump_expression(this->left_);
11484 ast_dump_context->ostream() << ".";
11485 ast_dump_context->ostream() << this->name_;
11486}
11487
e440a328 11488// Make a selector expression.
11489
11490Expression*
11491Expression::make_selector(Expression* left, const std::string& name,
b13c66cd 11492 Location location)
e440a328 11493{
11494 return new Selector_expression(left, name, location);
11495}
11496
11497// Implement the builtin function new.
11498
11499class Allocation_expression : public Expression
11500{
11501 public:
b13c66cd 11502 Allocation_expression(Type* type, Location location)
e440a328 11503 : Expression(EXPRESSION_ALLOCATION, location),
11504 type_(type)
11505 { }
11506
11507 protected:
11508 int
11509 do_traverse(Traverse* traverse)
11510 { return Type::traverse(this->type_, traverse); }
11511
11512 Type*
11513 do_type()
11514 { return Type::make_pointer_type(this->type_); }
11515
11516 void
11517 do_determine_type(const Type_context*)
11518 { }
11519
e440a328 11520 Expression*
11521 do_copy()
11522 { return new Allocation_expression(this->type_, this->location()); }
11523
ea664253 11524 Bexpression*
11525 do_get_backend(Translate_context*);
e440a328 11526
d751bb78 11527 void
11528 do_dump_expression(Ast_dump_context*) const;
11529
e440a328 11530 private:
11531 // The type we are allocating.
11532 Type* type_;
11533};
11534
ea664253 11535// Return the backend representation for an allocation expression.
e440a328 11536
ea664253 11537Bexpression*
11538Allocation_expression::do_get_backend(Translate_context* context)
e440a328 11539{
2c809f8f 11540 Gogo* gogo = context->gogo();
11541 Location loc = this->location();
ea664253 11542 Bexpression* space =
11543 gogo->allocate_memory(this->type_, loc)->get_backend(context);
2c809f8f 11544 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
ea664253 11545 return gogo->backend()->convert_expression(pbtype, space, loc);
e440a328 11546}
11547
d751bb78 11548// Dump ast representation for an allocation expression.
11549
11550void
11551Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11552 const
11553{
11554 ast_dump_context->ostream() << "new(";
11555 ast_dump_context->dump_type(this->type_);
11556 ast_dump_context->ostream() << ")";
11557}
11558
e440a328 11559// Make an allocation expression.
11560
11561Expression*
b13c66cd 11562Expression::make_allocation(Type* type, Location location)
e440a328 11563{
11564 return new Allocation_expression(type, location);
11565}
11566
e440a328 11567// Construct a struct.
11568
11569class Struct_construction_expression : public Expression
11570{
11571 public:
11572 Struct_construction_expression(Type* type, Expression_list* vals,
b13c66cd 11573 Location location)
e440a328 11574 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
0c4f5a19 11575 type_(type), vals_(vals), traverse_order_(NULL)
e440a328 11576 { }
11577
0c4f5a19 11578 // Set the traversal order, used to ensure that we implement the
11579 // order of evaluation rules. Takes ownership of the argument.
11580 void
11581 set_traverse_order(std::vector<int>* traverse_order)
11582 { this->traverse_order_ = traverse_order; }
11583
e440a328 11584 // Return whether this is a constant initializer.
11585 bool
11586 is_constant_struct() const;
11587
11588 protected:
11589 int
11590 do_traverse(Traverse* traverse);
11591
f9ca30f9 11592 bool
11593 do_is_immutable() const;
11594
e440a328 11595 Type*
11596 do_type()
11597 { return this->type_; }
11598
11599 void
11600 do_determine_type(const Type_context*);
11601
11602 void
11603 do_check_types(Gogo*);
11604
11605 Expression*
11606 do_copy()
11607 {
0c4f5a19 11608 Struct_construction_expression* ret =
0f87b2f8 11609 new Struct_construction_expression(this->type_,
11610 (this->vals_ == NULL
11611 ? NULL
11612 : this->vals_->copy()),
0c4f5a19 11613 this->location());
11614 if (this->traverse_order_ != NULL)
11615 ret->set_traverse_order(this->traverse_order_);
11616 return ret;
e440a328 11617 }
11618
8ba8cc87 11619 Expression*
11620 do_flatten(Gogo*, Named_object*, Statement_inserter*);
11621
ea664253 11622 Bexpression*
11623 do_get_backend(Translate_context*);
e440a328 11624
11625 void
11626 do_export(Export*) const;
11627
d751bb78 11628 void
11629 do_dump_expression(Ast_dump_context*) const;
11630
e440a328 11631 private:
11632 // The type of the struct to construct.
11633 Type* type_;
11634 // The list of values, in order of the fields in the struct. A NULL
11635 // entry means that the field should be zero-initialized.
11636 Expression_list* vals_;
0c4f5a19 11637 // If not NULL, the order in which to traverse vals_. This is used
11638 // so that we implement the order of evaluation rules correctly.
11639 std::vector<int>* traverse_order_;
e440a328 11640};
11641
11642// Traversal.
11643
11644int
11645Struct_construction_expression::do_traverse(Traverse* traverse)
11646{
0c4f5a19 11647 if (this->vals_ != NULL)
11648 {
11649 if (this->traverse_order_ == NULL)
11650 {
11651 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11652 return TRAVERSE_EXIT;
11653 }
11654 else
11655 {
11656 for (std::vector<int>::const_iterator p =
11657 this->traverse_order_->begin();
11658 p != this->traverse_order_->end();
11659 ++p)
11660 {
11661 if (Expression::traverse(&this->vals_->at(*p), traverse)
11662 == TRAVERSE_EXIT)
11663 return TRAVERSE_EXIT;
11664 }
11665 }
11666 }
e440a328 11667 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11668 return TRAVERSE_EXIT;
11669 return TRAVERSE_CONTINUE;
11670}
11671
11672// Return whether this is a constant initializer.
11673
11674bool
11675Struct_construction_expression::is_constant_struct() const
11676{
11677 if (this->vals_ == NULL)
11678 return true;
11679 for (Expression_list::const_iterator pv = this->vals_->begin();
11680 pv != this->vals_->end();
11681 ++pv)
11682 {
11683 if (*pv != NULL
11684 && !(*pv)->is_constant()
11685 && (!(*pv)->is_composite_literal()
11686 || (*pv)->is_nonconstant_composite_literal()))
11687 return false;
11688 }
11689
11690 const Struct_field_list* fields = this->type_->struct_type()->fields();
11691 for (Struct_field_list::const_iterator pf = fields->begin();
11692 pf != fields->end();
11693 ++pf)
11694 {
11695 // There are no constant constructors for interfaces.
11696 if (pf->type()->interface_type() != NULL)
11697 return false;
11698 }
11699
11700 return true;
11701}
11702
f9ca30f9 11703// Return whether this struct is immutable.
11704
11705bool
11706Struct_construction_expression::do_is_immutable() const
11707{
11708 if (this->vals_ == NULL)
11709 return true;
11710 for (Expression_list::const_iterator pv = this->vals_->begin();
11711 pv != this->vals_->end();
11712 ++pv)
11713 {
11714 if (*pv != NULL && !(*pv)->is_immutable())
11715 return false;
11716 }
11717 return true;
11718}
11719
e440a328 11720// Final type determination.
11721
11722void
11723Struct_construction_expression::do_determine_type(const Type_context*)
11724{
11725 if (this->vals_ == NULL)
11726 return;
11727 const Struct_field_list* fields = this->type_->struct_type()->fields();
11728 Expression_list::const_iterator pv = this->vals_->begin();
11729 for (Struct_field_list::const_iterator pf = fields->begin();
11730 pf != fields->end();
11731 ++pf, ++pv)
11732 {
11733 if (pv == this->vals_->end())
11734 return;
11735 if (*pv != NULL)
11736 {
11737 Type_context subcontext(pf->type(), false);
11738 (*pv)->determine_type(&subcontext);
11739 }
11740 }
a6cb4c0e 11741 // Extra values are an error we will report elsewhere; we still want
11742 // to determine the type to avoid knockon errors.
11743 for (; pv != this->vals_->end(); ++pv)
11744 (*pv)->determine_type_no_context();
e440a328 11745}
11746
11747// Check types.
11748
11749void
11750Struct_construction_expression::do_check_types(Gogo*)
11751{
11752 if (this->vals_ == NULL)
11753 return;
11754
11755 Struct_type* st = this->type_->struct_type();
11756 if (this->vals_->size() > st->field_count())
11757 {
11758 this->report_error(_("too many expressions for struct"));
11759 return;
11760 }
11761
11762 const Struct_field_list* fields = st->fields();
11763 Expression_list::const_iterator pv = this->vals_->begin();
11764 int i = 0;
11765 for (Struct_field_list::const_iterator pf = fields->begin();
11766 pf != fields->end();
11767 ++pf, ++pv, ++i)
11768 {
11769 if (pv == this->vals_->end())
11770 {
11771 this->report_error(_("too few expressions for struct"));
11772 break;
11773 }
11774
11775 if (*pv == NULL)
11776 continue;
11777
11778 std::string reason;
11779 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11780 {
11781 if (reason.empty())
11782 error_at((*pv)->location(),
11783 "incompatible type for field %d in struct construction",
11784 i + 1);
11785 else
11786 error_at((*pv)->location(),
11787 ("incompatible type for field %d in "
11788 "struct construction (%s)"),
11789 i + 1, reason.c_str());
11790 this->set_is_error();
11791 }
11792 }
c484d925 11793 go_assert(pv == this->vals_->end());
e440a328 11794}
11795
8ba8cc87 11796// Flatten a struct construction expression. Store the values into
11797// temporaries in case they need interface conversion.
11798
11799Expression*
11800Struct_construction_expression::do_flatten(Gogo*, Named_object*,
11801 Statement_inserter* inserter)
11802{
11803 if (this->vals_ == NULL)
11804 return this;
11805
11806 // If this is a constant struct, we don't need temporaries.
11807 if (this->is_constant_struct())
11808 return this;
11809
11810 Location loc = this->location();
11811 for (Expression_list::iterator pv = this->vals_->begin();
11812 pv != this->vals_->end();
11813 ++pv)
11814 {
11815 if (*pv != NULL)
11816 {
11817 if (!(*pv)->is_variable())
11818 {
11819 Temporary_statement* temp =
11820 Statement::make_temporary(NULL, *pv, loc);
11821 inserter->insert(temp);
11822 *pv = Expression::make_temporary_reference(temp, loc);
11823 }
11824 }
11825 }
11826 return this;
11827}
11828
ea664253 11829// Return the backend representation for constructing a struct.
e440a328 11830
ea664253 11831Bexpression*
11832Struct_construction_expression::do_get_backend(Translate_context* context)
e440a328 11833{
11834 Gogo* gogo = context->gogo();
11835
2c809f8f 11836 Btype* btype = this->type_->get_backend(gogo);
e440a328 11837 if (this->vals_ == NULL)
ea664253 11838 return gogo->backend()->zero_expression(btype);
e440a328 11839
e440a328 11840 const Struct_field_list* fields = this->type_->struct_type()->fields();
e440a328 11841 Expression_list::const_iterator pv = this->vals_->begin();
2c809f8f 11842 std::vector<Bexpression*> init;
11843 for (Struct_field_list::const_iterator pf = fields->begin();
11844 pf != fields->end();
11845 ++pf)
e440a328 11846 {
63697958 11847 Btype* fbtype = pf->type()->get_backend(gogo);
e440a328 11848 if (pv == this->vals_->end())
2c809f8f 11849 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 11850 else if (*pv == NULL)
11851 {
2c809f8f 11852 init.push_back(gogo->backend()->zero_expression(fbtype));
e440a328 11853 ++pv;
11854 }
11855 else
11856 {
2c809f8f 11857 Expression* val =
11858 Expression::convert_for_assignment(gogo, pf->type(),
11859 *pv, this->location());
ea664253 11860 init.push_back(val->get_backend(context));
e440a328 11861 ++pv;
11862 }
e440a328 11863 }
ea664253 11864 return gogo->backend()->constructor_expression(btype, init, this->location());
e440a328 11865}
11866
11867// Export a struct construction.
11868
11869void
11870Struct_construction_expression::do_export(Export* exp) const
11871{
11872 exp->write_c_string("convert(");
11873 exp->write_type(this->type_);
11874 for (Expression_list::const_iterator pv = this->vals_->begin();
11875 pv != this->vals_->end();
11876 ++pv)
11877 {
11878 exp->write_c_string(", ");
11879 if (*pv != NULL)
11880 (*pv)->export_expression(exp);
11881 }
11882 exp->write_c_string(")");
11883}
11884
d751bb78 11885// Dump ast representation of a struct construction expression.
11886
11887void
11888Struct_construction_expression::do_dump_expression(
11889 Ast_dump_context* ast_dump_context) const
11890{
d751bb78 11891 ast_dump_context->dump_type(this->type_);
11892 ast_dump_context->ostream() << "{";
11893 ast_dump_context->dump_expression_list(this->vals_);
11894 ast_dump_context->ostream() << "}";
11895}
11896
e440a328 11897// Make a struct composite literal. This used by the thunk code.
11898
11899Expression*
11900Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
b13c66cd 11901 Location location)
e440a328 11902{
c484d925 11903 go_assert(type->struct_type() != NULL);
e440a328 11904 return new Struct_construction_expression(type, vals, location);
11905}
11906
11907// Construct an array. This class is not used directly; instead we
11908// use the child classes, Fixed_array_construction_expression and
2c809f8f 11909// Slice_construction_expression.
e440a328 11910
11911class Array_construction_expression : public Expression
11912{
11913 protected:
11914 Array_construction_expression(Expression_classification classification,
ffe743ca 11915 Type* type,
11916 const std::vector<unsigned long>* indexes,
11917 Expression_list* vals, Location location)
e440a328 11918 : Expression(classification, location),
ffe743ca 11919 type_(type), indexes_(indexes), vals_(vals)
11920 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
e440a328 11921
11922 public:
11923 // Return whether this is a constant initializer.
11924 bool
11925 is_constant_array() const;
11926
11927 // Return the number of elements.
11928 size_t
11929 element_count() const
11930 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11931
11932protected:
23d77f91 11933 virtual int
e440a328 11934 do_traverse(Traverse* traverse);
11935
f9ca30f9 11936 bool
11937 do_is_immutable() const;
11938
e440a328 11939 Type*
11940 do_type()
11941 { return this->type_; }
11942
11943 void
11944 do_determine_type(const Type_context*);
11945
11946 void
11947 do_check_types(Gogo*);
11948
e440a328 11949 void
11950 do_export(Export*) const;
11951
ffe743ca 11952 // The indexes.
11953 const std::vector<unsigned long>*
11954 indexes()
11955 { return this->indexes_; }
11956
e440a328 11957 // The list of values.
11958 Expression_list*
11959 vals()
11960 { return this->vals_; }
11961
8ba8cc87 11962 Expression*
11963 do_flatten(Gogo*, Named_object*, Statement_inserter*);
11964
2c809f8f 11965 // Get the backend constructor for the array values.
11966 Bexpression*
11967 get_constructor(Translate_context* context, Btype* btype);
e440a328 11968
d751bb78 11969 void
11970 do_dump_expression(Ast_dump_context*) const;
11971
e440a328 11972 private:
11973 // The type of the array to construct.
11974 Type* type_;
ffe743ca 11975 // The list of indexes into the array, one for each value. This may
11976 // be NULL, in which case the indexes start at zero and increment.
11977 const std::vector<unsigned long>* indexes_;
11978 // The list of values. This may be NULL if there are no values.
e440a328 11979 Expression_list* vals_;
11980};
11981
11982// Traversal.
11983
11984int
11985Array_construction_expression::do_traverse(Traverse* traverse)
11986{
11987 if (this->vals_ != NULL
11988 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11989 return TRAVERSE_EXIT;
11990 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11991 return TRAVERSE_EXIT;
11992 return TRAVERSE_CONTINUE;
11993}
11994
11995// Return whether this is a constant initializer.
11996
11997bool
11998Array_construction_expression::is_constant_array() const
11999{
12000 if (this->vals_ == NULL)
12001 return true;
12002
12003 // There are no constant constructors for interfaces.
12004 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12005 return false;
12006
12007 for (Expression_list::const_iterator pv = this->vals_->begin();
12008 pv != this->vals_->end();
12009 ++pv)
12010 {
12011 if (*pv != NULL
12012 && !(*pv)->is_constant()
12013 && (!(*pv)->is_composite_literal()
12014 || (*pv)->is_nonconstant_composite_literal()))
12015 return false;
12016 }
12017 return true;
12018}
12019
f9ca30f9 12020// Return whether this is an immutable array initializer.
12021
12022bool
12023Array_construction_expression::do_is_immutable() const
12024{
12025 if (this->vals_ == NULL)
12026 return true;
12027 for (Expression_list::const_iterator pv = this->vals_->begin();
12028 pv != this->vals_->end();
12029 ++pv)
12030 {
12031 if (*pv != NULL && !(*pv)->is_immutable())
12032 return false;
12033 }
12034 return true;
12035}
12036
e440a328 12037// Final type determination.
12038
12039void
12040Array_construction_expression::do_determine_type(const Type_context*)
12041{
12042 if (this->vals_ == NULL)
12043 return;
12044 Type_context subcontext(this->type_->array_type()->element_type(), false);
12045 for (Expression_list::const_iterator pv = this->vals_->begin();
12046 pv != this->vals_->end();
12047 ++pv)
12048 {
12049 if (*pv != NULL)
12050 (*pv)->determine_type(&subcontext);
12051 }
12052}
12053
12054// Check types.
12055
12056void
12057Array_construction_expression::do_check_types(Gogo*)
12058{
12059 if (this->vals_ == NULL)
12060 return;
12061
12062 Array_type* at = this->type_->array_type();
12063 int i = 0;
12064 Type* element_type = at->element_type();
12065 for (Expression_list::const_iterator pv = this->vals_->begin();
12066 pv != this->vals_->end();
12067 ++pv, ++i)
12068 {
12069 if (*pv != NULL
12070 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12071 {
12072 error_at((*pv)->location(),
12073 "incompatible type for element %d in composite literal",
12074 i + 1);
12075 this->set_is_error();
12076 }
12077 }
e440a328 12078}
12079
8ba8cc87 12080// Flatten an array construction expression. Store the values into
12081// temporaries in case they need interface conversion.
12082
12083Expression*
12084Array_construction_expression::do_flatten(Gogo*, Named_object*,
12085 Statement_inserter* inserter)
12086{
12087 if (this->vals_ == NULL)
12088 return this;
12089
12090 // If this is a constant array, we don't need temporaries.
12091 if (this->is_constant_array())
12092 return this;
12093
12094 Location loc = this->location();
12095 for (Expression_list::iterator pv = this->vals_->begin();
12096 pv != this->vals_->end();
12097 ++pv)
12098 {
12099 if (*pv != NULL)
12100 {
12101 if (!(*pv)->is_variable())
12102 {
12103 Temporary_statement* temp =
12104 Statement::make_temporary(NULL, *pv, loc);
12105 inserter->insert(temp);
12106 *pv = Expression::make_temporary_reference(temp, loc);
12107 }
12108 }
12109 }
12110 return this;
12111}
12112
2c809f8f 12113// Get a constructor expression for the array values.
e440a328 12114
2c809f8f 12115Bexpression*
12116Array_construction_expression::get_constructor(Translate_context* context,
12117 Btype* array_btype)
e440a328 12118{
e440a328 12119 Type* element_type = this->type_->array_type()->element_type();
2c809f8f 12120
12121 std::vector<unsigned long> indexes;
12122 std::vector<Bexpression*> vals;
12123 Gogo* gogo = context->gogo();
e440a328 12124 if (this->vals_ != NULL)
12125 {
12126 size_t i = 0;
ffe743ca 12127 std::vector<unsigned long>::const_iterator pi;
12128 if (this->indexes_ != NULL)
12129 pi = this->indexes_->begin();
e440a328 12130 for (Expression_list::const_iterator pv = this->vals_->begin();
12131 pv != this->vals_->end();
12132 ++pv, ++i)
12133 {
ffe743ca 12134 if (this->indexes_ != NULL)
12135 go_assert(pi != this->indexes_->end());
ffe743ca 12136
12137 if (this->indexes_ == NULL)
2c809f8f 12138 indexes.push_back(i);
ffe743ca 12139 else
2c809f8f 12140 indexes.push_back(*pi);
e440a328 12141 if (*pv == NULL)
63697958 12142 {
63697958 12143 Btype* ebtype = element_type->get_backend(gogo);
12144 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
2c809f8f 12145 vals.push_back(zv);
63697958 12146 }
e440a328 12147 else
12148 {
2c809f8f 12149 Expression* val_expr =
12150 Expression::convert_for_assignment(gogo, element_type, *pv,
12151 this->location());
ea664253 12152 vals.push_back(val_expr->get_backend(context));
e440a328 12153 }
ffe743ca 12154 if (this->indexes_ != NULL)
12155 ++pi;
e440a328 12156 }
ffe743ca 12157 if (this->indexes_ != NULL)
12158 go_assert(pi == this->indexes_->end());
e440a328 12159 }
2c809f8f 12160 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12161 vals, this->location());
e440a328 12162}
12163
12164// Export an array construction.
12165
12166void
12167Array_construction_expression::do_export(Export* exp) const
12168{
12169 exp->write_c_string("convert(");
12170 exp->write_type(this->type_);
12171 if (this->vals_ != NULL)
12172 {
ffe743ca 12173 std::vector<unsigned long>::const_iterator pi;
12174 if (this->indexes_ != NULL)
12175 pi = this->indexes_->begin();
e440a328 12176 for (Expression_list::const_iterator pv = this->vals_->begin();
12177 pv != this->vals_->end();
12178 ++pv)
12179 {
12180 exp->write_c_string(", ");
ffe743ca 12181
12182 if (this->indexes_ != NULL)
12183 {
12184 char buf[100];
12185 snprintf(buf, sizeof buf, "%lu", *pi);
12186 exp->write_c_string(buf);
12187 exp->write_c_string(":");
12188 }
12189
e440a328 12190 if (*pv != NULL)
12191 (*pv)->export_expression(exp);
ffe743ca 12192
12193 if (this->indexes_ != NULL)
12194 ++pi;
e440a328 12195 }
12196 }
12197 exp->write_c_string(")");
12198}
12199
d751bb78 12200// Dump ast representation of an array construction expressin.
12201
12202void
12203Array_construction_expression::do_dump_expression(
12204 Ast_dump_context* ast_dump_context) const
12205{
ffe743ca 12206 Expression* length = this->type_->array_type()->length();
8b1c301d 12207
12208 ast_dump_context->ostream() << "[" ;
12209 if (length != NULL)
12210 {
12211 ast_dump_context->dump_expression(length);
12212 }
12213 ast_dump_context->ostream() << "]" ;
d751bb78 12214 ast_dump_context->dump_type(this->type_);
12215 ast_dump_context->ostream() << "{" ;
ffe743ca 12216 if (this->indexes_ == NULL)
12217 ast_dump_context->dump_expression_list(this->vals_);
12218 else
12219 {
12220 Expression_list::const_iterator pv = this->vals_->begin();
12221 for (std::vector<unsigned long>::const_iterator pi =
12222 this->indexes_->begin();
12223 pi != this->indexes_->end();
12224 ++pi, ++pv)
12225 {
12226 if (pi != this->indexes_->begin())
12227 ast_dump_context->ostream() << ", ";
12228 ast_dump_context->ostream() << *pi << ':';
12229 ast_dump_context->dump_expression(*pv);
12230 }
12231 }
d751bb78 12232 ast_dump_context->ostream() << "}" ;
12233
12234}
12235
e440a328 12236// Construct a fixed array.
12237
12238class Fixed_array_construction_expression :
12239 public Array_construction_expression
12240{
12241 public:
ffe743ca 12242 Fixed_array_construction_expression(Type* type,
12243 const std::vector<unsigned long>* indexes,
12244 Expression_list* vals, Location location)
e440a328 12245 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
ffe743ca 12246 type, indexes, vals, location)
12247 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
e440a328 12248
12249 protected:
12250 Expression*
12251 do_copy()
12252 {
12253 return new Fixed_array_construction_expression(this->type(),
ffe743ca 12254 this->indexes(),
e440a328 12255 (this->vals() == NULL
12256 ? NULL
12257 : this->vals()->copy()),
12258 this->location());
12259 }
12260
ea664253 12261 Bexpression*
12262 do_get_backend(Translate_context*);
e440a328 12263};
12264
ea664253 12265// Return the backend representation for constructing a fixed array.
e440a328 12266
ea664253 12267Bexpression*
12268Fixed_array_construction_expression::do_get_backend(Translate_context* context)
e440a328 12269{
9f0e0513 12270 Type* type = this->type();
12271 Btype* btype = type->get_backend(context->gogo());
ea664253 12272 return this->get_constructor(context, btype);
e440a328 12273}
12274
76f85fd6 12275Expression*
12276Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12277 Location location)
12278{
12279 go_assert(type->array_type() != NULL && !type->is_slice_type());
12280 return new Fixed_array_construction_expression(type, NULL, vals, location);
12281}
12282
2c809f8f 12283// Construct a slice.
e440a328 12284
2c809f8f 12285class Slice_construction_expression : public Array_construction_expression
e440a328 12286{
12287 public:
2c809f8f 12288 Slice_construction_expression(Type* type,
12289 const std::vector<unsigned long>* indexes,
12290 Expression_list* vals, Location location)
12291 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12292 type, indexes, vals, location),
12293 valtype_(NULL)
23d77f91 12294 {
12295 go_assert(type->is_slice_type());
12296
e67508fa 12297 unsigned long lenval;
23d77f91 12298 Expression* length;
12299 if (vals == NULL || vals->empty())
e67508fa 12300 lenval = 0;
23d77f91 12301 else
12302 {
12303 if (this->indexes() == NULL)
e67508fa 12304 lenval = vals->size();
23d77f91 12305 else
e67508fa 12306 lenval = indexes->back() + 1;
23d77f91 12307 }
12308 Type* int_type = Type::lookup_integer_type("int");
e67508fa 12309 length = Expression::make_integer_ul(lenval, int_type, location);
23d77f91 12310 Type* element_type = type->array_type()->element_type();
12311 this->valtype_ = Type::make_array_type(element_type, length);
12312 }
e440a328 12313
12314 protected:
2c809f8f 12315 // Note that taking the address of a slice literal is invalid.
e440a328 12316
23d77f91 12317 int
12318 do_traverse(Traverse* traverse);
12319
e440a328 12320 Expression*
12321 do_copy()
12322 {
2c809f8f 12323 return new Slice_construction_expression(this->type(), this->indexes(),
12324 (this->vals() == NULL
12325 ? NULL
12326 : this->vals()->copy()),
12327 this->location());
e440a328 12328 }
12329
ea664253 12330 Bexpression*
12331 do_get_backend(Translate_context*);
2c809f8f 12332
12333 private:
12334 // The type of the values in this slice.
12335 Type* valtype_;
e440a328 12336};
12337
23d77f91 12338// Traversal.
12339
12340int
12341Slice_construction_expression::do_traverse(Traverse* traverse)
12342{
12343 if (this->Array_construction_expression::do_traverse(traverse)
12344 == TRAVERSE_EXIT)
12345 return TRAVERSE_EXIT;
12346 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12347 return TRAVERSE_EXIT;
12348 return TRAVERSE_CONTINUE;
12349}
12350
ea664253 12351// Return the backend representation for constructing a slice.
e440a328 12352
ea664253 12353Bexpression*
12354Slice_construction_expression::do_get_backend(Translate_context* context)
e440a328 12355{
f9c68f17 12356 Array_type* array_type = this->type()->array_type();
12357 if (array_type == NULL)
12358 {
c484d925 12359 go_assert(this->type()->is_error());
ea664253 12360 return context->backend()->error_expression();
f9c68f17 12361 }
12362
f23d7786 12363 Location loc = this->location();
f9c68f17 12364 Type* element_type = array_type->element_type();
23d77f91 12365 go_assert(this->valtype_ != NULL);
3d60812e 12366
f23d7786 12367 Expression_list* vals = this->vals();
e440a328 12368 if (this->vals() == NULL || this->vals()->empty())
12369 {
f23d7786 12370 // We need to create a unique value for the empty array literal.
12371 vals = new Expression_list;
12372 vals->push_back(NULL);
e440a328 12373 }
f23d7786 12374 Expression* array_val =
12375 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12376 vals, loc);
e440a328 12377
f23d7786 12378 bool is_constant_initializer = array_val->is_immutable();
d8829beb 12379
12380 // We have to copy the initial values into heap memory if we are in
12381 // a function or if the values are not constants. We also have to
12382 // copy them if they may contain pointers in a non-constant context,
12383 // as otherwise the garbage collector won't see them.
12384 bool copy_to_heap = (context->function() != NULL
12385 || !is_constant_initializer
12386 || (element_type->has_pointer()
12387 && !context->is_const()));
e440a328 12388
f23d7786 12389 Expression* space;
d8829beb 12390 if (!copy_to_heap)
e440a328 12391 {
f23d7786 12392 // The initializer will only run once.
12393 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12394 space->unary_expression()->set_is_slice_init();
e440a328 12395 }
12396 else
f23d7786 12397 space = Expression::make_heap_expression(array_val, loc);
e440a328 12398
2c809f8f 12399 // Build a constructor for the slice.
e440a328 12400
f23d7786 12401 Expression* len = this->valtype_->array_type()->length();
12402 Expression* slice_val =
12403 Expression::make_slice_value(this->type(), space, len, len, loc);
ea664253 12404 return slice_val->get_backend(context);
e440a328 12405}
12406
12407// Make a slice composite literal. This is used by the type
12408// descriptor code.
12409
12410Expression*
12411Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
b13c66cd 12412 Location location)
e440a328 12413{
411eb89e 12414 go_assert(type->is_slice_type());
2c809f8f 12415 return new Slice_construction_expression(type, NULL, vals, location);
e440a328 12416}
12417
12418// Construct a map.
12419
12420class Map_construction_expression : public Expression
12421{
12422 public:
12423 Map_construction_expression(Type* type, Expression_list* vals,
b13c66cd 12424 Location location)
e440a328 12425 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
2c809f8f 12426 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
c484d925 12427 { go_assert(vals == NULL || vals->size() % 2 == 0); }
e440a328 12428
12429 protected:
12430 int
12431 do_traverse(Traverse* traverse);
12432
2c809f8f 12433 Expression*
12434 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12435
e440a328 12436 Type*
12437 do_type()
12438 { return this->type_; }
12439
12440 void
12441 do_determine_type(const Type_context*);
12442
12443 void
12444 do_check_types(Gogo*);
12445
12446 Expression*
12447 do_copy()
12448 {
0f87b2f8 12449 return new Map_construction_expression(this->type_,
12450 (this->vals_ == NULL
12451 ? NULL
12452 : this->vals_->copy()),
e440a328 12453 this->location());
12454 }
12455
ea664253 12456 Bexpression*
12457 do_get_backend(Translate_context*);
e440a328 12458
12459 void
12460 do_export(Export*) const;
12461
d751bb78 12462 void
12463 do_dump_expression(Ast_dump_context*) const;
12464
e440a328 12465 private:
12466 // The type of the map to construct.
12467 Type* type_;
12468 // The list of values.
12469 Expression_list* vals_;
2c809f8f 12470 // The type of the key-value pair struct for each map element.
12471 Struct_type* element_type_;
12472 // A temporary reference to the variable storing the constructor initializer.
12473 Temporary_statement* constructor_temp_;
e440a328 12474};
12475
12476// Traversal.
12477
12478int
12479Map_construction_expression::do_traverse(Traverse* traverse)
12480{
12481 if (this->vals_ != NULL
12482 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12483 return TRAVERSE_EXIT;
12484 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12485 return TRAVERSE_EXIT;
12486 return TRAVERSE_CONTINUE;
12487}
12488
2c809f8f 12489// Flatten constructor initializer into a temporary variable since
12490// we need to take its address for __go_construct_map.
12491
12492Expression*
12493Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12494 Statement_inserter* inserter)
12495{
12496 if (!this->is_error_expression()
12497 && this->vals_ != NULL
12498 && !this->vals_->empty()
12499 && this->constructor_temp_ == NULL)
12500 {
12501 Map_type* mt = this->type_->map_type();
12502 Type* key_type = mt->key_type();
12503 Type* val_type = mt->val_type();
12504 this->element_type_ = Type::make_builtin_struct_type(2,
12505 "__key", key_type,
12506 "__val", val_type);
12507
12508 Expression_list* value_pairs = new Expression_list();
12509 Location loc = this->location();
12510
12511 size_t i = 0;
12512 for (Expression_list::const_iterator pv = this->vals_->begin();
12513 pv != this->vals_->end();
12514 ++pv, ++i)
12515 {
12516 Expression_list* key_value_pair = new Expression_list();
12517 Expression* key =
12518 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12519
12520 ++pv;
12521 Expression* val =
12522 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12523
12524 key_value_pair->push_back(key);
12525 key_value_pair->push_back(val);
12526 value_pairs->push_back(
12527 Expression::make_struct_composite_literal(this->element_type_,
12528 key_value_pair, loc));
12529 }
12530
e67508fa 12531 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
2c809f8f 12532 Type* ctor_type =
12533 Type::make_array_type(this->element_type_, element_count);
12534 Expression* constructor =
12535 new Fixed_array_construction_expression(ctor_type, NULL,
12536 value_pairs, loc);
12537
12538 this->constructor_temp_ =
12539 Statement::make_temporary(NULL, constructor, loc);
12540 constructor->issue_nil_check();
12541 this->constructor_temp_->set_is_address_taken();
12542 inserter->insert(this->constructor_temp_);
12543 }
12544
12545 return this;
12546}
12547
e440a328 12548// Final type determination.
12549
12550void
12551Map_construction_expression::do_determine_type(const Type_context*)
12552{
12553 if (this->vals_ == NULL)
12554 return;
12555
12556 Map_type* mt = this->type_->map_type();
12557 Type_context key_context(mt->key_type(), false);
12558 Type_context val_context(mt->val_type(), false);
12559 for (Expression_list::const_iterator pv = this->vals_->begin();
12560 pv != this->vals_->end();
12561 ++pv)
12562 {
12563 (*pv)->determine_type(&key_context);
12564 ++pv;
12565 (*pv)->determine_type(&val_context);
12566 }
12567}
12568
12569// Check types.
12570
12571void
12572Map_construction_expression::do_check_types(Gogo*)
12573{
12574 if (this->vals_ == NULL)
12575 return;
12576
12577 Map_type* mt = this->type_->map_type();
12578 int i = 0;
12579 Type* key_type = mt->key_type();
12580 Type* val_type = mt->val_type();
12581 for (Expression_list::const_iterator pv = this->vals_->begin();
12582 pv != this->vals_->end();
12583 ++pv, ++i)
12584 {
12585 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12586 {
12587 error_at((*pv)->location(),
12588 "incompatible type for element %d key in map construction",
12589 i + 1);
12590 this->set_is_error();
12591 }
12592 ++pv;
12593 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12594 {
12595 error_at((*pv)->location(),
12596 ("incompatible type for element %d value "
12597 "in map construction"),
12598 i + 1);
12599 this->set_is_error();
12600 }
12601 }
12602}
12603
ea664253 12604// Return the backend representation for constructing a map.
e440a328 12605
ea664253 12606Bexpression*
12607Map_construction_expression::do_get_backend(Translate_context* context)
e440a328 12608{
2c809f8f 12609 if (this->is_error_expression())
ea664253 12610 return context->backend()->error_expression();
2c809f8f 12611 Location loc = this->location();
e440a328 12612
e440a328 12613 size_t i = 0;
2c809f8f 12614 Expression* ventries;
e440a328 12615 if (this->vals_ == NULL || this->vals_->empty())
2c809f8f 12616 ventries = Expression::make_nil(loc);
e440a328 12617 else
12618 {
2c809f8f 12619 go_assert(this->constructor_temp_ != NULL);
12620 i = this->vals_->size() / 2;
e440a328 12621
2c809f8f 12622 Expression* ctor_ref =
12623 Expression::make_temporary_reference(this->constructor_temp_, loc);
12624 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12625 }
e440a328 12626
2c809f8f 12627 Map_type* mt = this->type_->map_type();
12628 if (this->element_type_ == NULL)
12629 this->element_type_ =
12630 Type::make_builtin_struct_type(2,
12631 "__key", mt->key_type(),
12632 "__val", mt->val_type());
12633 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12634
12635 Type* uintptr_t = Type::lookup_integer_type("uintptr");
e67508fa 12636 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
2c809f8f 12637
12638 Expression* entry_size =
12639 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12640
12641 unsigned int field_index;
12642 const Struct_field* valfield =
12643 this->element_type_->find_local_field("__val", &field_index);
12644 Expression* val_offset =
12645 Expression::make_struct_field_offset(this->element_type_, valfield);
12646 Expression* val_size =
12647 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12648
12649 Expression* map_ctor =
12650 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12651 entry_size, val_offset, val_size, ventries);
ea664253 12652 return map_ctor->get_backend(context);
2c809f8f 12653}
e440a328 12654
2c809f8f 12655// Export an array construction.
e440a328 12656
2c809f8f 12657void
12658Map_construction_expression::do_export(Export* exp) const
12659{
12660 exp->write_c_string("convert(");
12661 exp->write_type(this->type_);
12662 for (Expression_list::const_iterator pv = this->vals_->begin();
12663 pv != this->vals_->end();
12664 ++pv)
12665 {
12666 exp->write_c_string(", ");
12667 (*pv)->export_expression(exp);
12668 }
12669 exp->write_c_string(")");
12670}
e440a328 12671
2c809f8f 12672// Dump ast representation for a map construction expression.
d751bb78 12673
12674void
12675Map_construction_expression::do_dump_expression(
12676 Ast_dump_context* ast_dump_context) const
12677{
d751bb78 12678 ast_dump_context->ostream() << "{" ;
8b1c301d 12679 ast_dump_context->dump_expression_list(this->vals_, true);
d751bb78 12680 ast_dump_context->ostream() << "}";
12681}
12682
e440a328 12683// A general composite literal. This is lowered to a type specific
12684// version.
12685
12686class Composite_literal_expression : public Parser_expression
12687{
12688 public:
12689 Composite_literal_expression(Type* type, int depth, bool has_keys,
62750cd5 12690 Expression_list* vals, bool all_are_names,
12691 Location location)
e440a328 12692 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
62750cd5 12693 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12694 all_are_names_(all_are_names)
e440a328 12695 { }
12696
12697 protected:
12698 int
12699 do_traverse(Traverse* traverse);
12700
12701 Expression*
ceeb4318 12702 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
e440a328 12703
12704 Expression*
12705 do_copy()
12706 {
12707 return new Composite_literal_expression(this->type_, this->depth_,
12708 this->has_keys_,
12709 (this->vals_ == NULL
12710 ? NULL
12711 : this->vals_->copy()),
62750cd5 12712 this->all_are_names_,
e440a328 12713 this->location());
12714 }
12715
d751bb78 12716 void
12717 do_dump_expression(Ast_dump_context*) const;
12718
e440a328 12719 private:
12720 Expression*
81c4b26b 12721 lower_struct(Gogo*, Type*);
e440a328 12722
12723 Expression*
113ef6a5 12724 lower_array(Type*);
e440a328 12725
12726 Expression*
ffe743ca 12727 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
e440a328 12728
12729 Expression*
ceeb4318 12730 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
e440a328 12731
12732 // The type of the composite literal.
12733 Type* type_;
12734 // The depth within a list of composite literals within a composite
12735 // literal, when the type is omitted.
12736 int depth_;
12737 // The values to put in the composite literal.
12738 Expression_list* vals_;
12739 // If this is true, then VALS_ is a list of pairs: a key and a
12740 // value. In an array initializer, a missing key will be NULL.
12741 bool has_keys_;
62750cd5 12742 // If this is true, then HAS_KEYS_ is true, and every key is a
12743 // simple identifier.
12744 bool all_are_names_;
e440a328 12745};
12746
12747// Traversal.
12748
12749int
12750Composite_literal_expression::do_traverse(Traverse* traverse)
12751{
dbffccfc 12752 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
e440a328 12753 return TRAVERSE_EXIT;
dbffccfc 12754
12755 // If this is a struct composite literal with keys, then the keys
12756 // are field names, not expressions. We don't want to traverse them
12757 // in that case. If we do, we can give an erroneous error "variable
12758 // initializer refers to itself." See bug482.go in the testsuite.
12759 if (this->has_keys_ && this->vals_ != NULL)
12760 {
12761 // The type may not be resolvable at this point.
12762 Type* type = this->type_;
a01f2481 12763
12764 for (int depth = this->depth_; depth > 0; --depth)
12765 {
12766 if (type->array_type() != NULL)
12767 type = type->array_type()->element_type();
12768 else if (type->map_type() != NULL)
12769 type = type->map_type()->val_type();
12770 else
12771 {
12772 // This error will be reported during lowering.
12773 return TRAVERSE_CONTINUE;
12774 }
12775 }
12776
dbffccfc 12777 while (true)
12778 {
12779 if (type->classification() == Type::TYPE_NAMED)
12780 type = type->named_type()->real_type();
12781 else if (type->classification() == Type::TYPE_FORWARD)
12782 {
12783 Type* t = type->forwarded();
12784 if (t == type)
12785 break;
12786 type = t;
12787 }
12788 else
12789 break;
12790 }
12791
12792 if (type->classification() == Type::TYPE_STRUCT)
12793 {
12794 Expression_list::iterator p = this->vals_->begin();
12795 while (p != this->vals_->end())
12796 {
12797 // Skip key.
12798 ++p;
12799 go_assert(p != this->vals_->end());
12800 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12801 return TRAVERSE_EXIT;
12802 ++p;
12803 }
12804 return TRAVERSE_CONTINUE;
12805 }
12806 }
12807
12808 if (this->vals_ != NULL)
12809 return this->vals_->traverse(traverse);
12810
12811 return TRAVERSE_CONTINUE;
e440a328 12812}
12813
12814// Lower a generic composite literal into a specific version based on
12815// the type.
12816
12817Expression*
ceeb4318 12818Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12819 Statement_inserter* inserter, int)
e440a328 12820{
12821 Type* type = this->type_;
12822
12823 for (int depth = this->depth_; depth > 0; --depth)
12824 {
12825 if (type->array_type() != NULL)
12826 type = type->array_type()->element_type();
12827 else if (type->map_type() != NULL)
12828 type = type->map_type()->val_type();
12829 else
12830 {
5c13bd80 12831 if (!type->is_error())
e440a328 12832 error_at(this->location(),
12833 ("may only omit types within composite literals "
12834 "of slice, array, or map type"));
12835 return Expression::make_error(this->location());
12836 }
12837 }
12838
e00772b3 12839 Type *pt = type->points_to();
12840 bool is_pointer = false;
12841 if (pt != NULL)
12842 {
12843 is_pointer = true;
12844 type = pt;
12845 }
12846
12847 Expression* ret;
5c13bd80 12848 if (type->is_error())
e440a328 12849 return Expression::make_error(this->location());
12850 else if (type->struct_type() != NULL)
e00772b3 12851 ret = this->lower_struct(gogo, type);
e440a328 12852 else if (type->array_type() != NULL)
113ef6a5 12853 ret = this->lower_array(type);
e440a328 12854 else if (type->map_type() != NULL)
e00772b3 12855 ret = this->lower_map(gogo, function, inserter, type);
e440a328 12856 else
12857 {
12858 error_at(this->location(),
12859 ("expected struct, slice, array, or map type "
12860 "for composite literal"));
12861 return Expression::make_error(this->location());
12862 }
e00772b3 12863
12864 if (is_pointer)
2c809f8f 12865 ret = Expression::make_heap_expression(ret, this->location());
e00772b3 12866
12867 return ret;
e440a328 12868}
12869
12870// Lower a struct composite literal.
12871
12872Expression*
81c4b26b 12873Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
e440a328 12874{
b13c66cd 12875 Location location = this->location();
e440a328 12876 Struct_type* st = type->struct_type();
12877 if (this->vals_ == NULL || !this->has_keys_)
07daa4e7 12878 {
e6013c28 12879 if (this->vals_ != NULL
12880 && !this->vals_->empty()
12881 && type->named_type() != NULL
12882 && type->named_type()->named_object()->package() != NULL)
12883 {
12884 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12885 pf != st->fields()->end();
12886 ++pf)
07daa4e7 12887 {
e6013c28 12888 if (Gogo::is_hidden_name(pf->field_name()))
07daa4e7 12889 error_at(this->location(),
e6013c28 12890 "assignment of unexported field %qs in %qs literal",
12891 Gogo::message_name(pf->field_name()).c_str(),
12892 type->named_type()->message_name().c_str());
07daa4e7 12893 }
12894 }
12895
12896 return new Struct_construction_expression(type, this->vals_, location);
12897 }
e440a328 12898
12899 size_t field_count = st->field_count();
12900 std::vector<Expression*> vals(field_count);
0c4f5a19 12901 std::vector<int>* traverse_order = new(std::vector<int>);
e440a328 12902 Expression_list::const_iterator p = this->vals_->begin();
62750cd5 12903 Expression* external_expr = NULL;
12904 const Named_object* external_no = NULL;
e440a328 12905 while (p != this->vals_->end())
12906 {
12907 Expression* name_expr = *p;
12908
12909 ++p;
c484d925 12910 go_assert(p != this->vals_->end());
e440a328 12911 Expression* val = *p;
12912
12913 ++p;
12914
12915 if (name_expr == NULL)
12916 {
12917 error_at(val->location(), "mixture of field and value initializers");
12918 return Expression::make_error(location);
12919 }
12920
12921 bool bad_key = false;
12922 std::string name;
81c4b26b 12923 const Named_object* no = NULL;
e440a328 12924 switch (name_expr->classification())
12925 {
12926 case EXPRESSION_UNKNOWN_REFERENCE:
12927 name = name_expr->unknown_expression()->name();
7f7ce694 12928 if (type->named_type() != NULL)
12929 {
12930 // If the named object found for this field name comes from a
12931 // different package than the struct it is a part of, do not count
12932 // this incorrect lookup as a usage of the object's package.
12933 no = name_expr->unknown_expression()->named_object();
12934 if (no->package() != NULL
12935 && no->package() != type->named_type()->named_object()->package())
12936 no->package()->forget_usage(name_expr);
12937 }
e440a328 12938 break;
12939
12940 case EXPRESSION_CONST_REFERENCE:
81c4b26b 12941 no = static_cast<Const_expression*>(name_expr)->named_object();
e440a328 12942 break;
12943
12944 case EXPRESSION_TYPE:
12945 {
12946 Type* t = name_expr->type();
12947 Named_type* nt = t->named_type();
12948 if (nt == NULL)
12949 bad_key = true;
12950 else
81c4b26b 12951 no = nt->named_object();
e440a328 12952 }
12953 break;
12954
12955 case EXPRESSION_VAR_REFERENCE:
81c4b26b 12956 no = name_expr->var_expression()->named_object();
e440a328 12957 break;
12958
12959 case EXPRESSION_FUNC_REFERENCE:
81c4b26b 12960 no = name_expr->func_expression()->named_object();
e440a328 12961 break;
12962
12963 case EXPRESSION_UNARY:
12964 // If there is a local variable around with the same name as
12965 // the field, and this occurs in the closure, then the
12966 // parser may turn the field reference into an indirection
12967 // through the closure. FIXME: This is a mess.
12968 {
12969 bad_key = true;
12970 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12971 if (ue->op() == OPERATOR_MULT)
12972 {
12973 Field_reference_expression* fre =
12974 ue->operand()->field_reference_expression();
12975 if (fre != NULL)
12976 {
12977 Struct_type* st =
12978 fre->expr()->type()->deref()->struct_type();
12979 if (st != NULL)
12980 {
12981 const Struct_field* sf = st->field(fre->field_index());
12982 name = sf->field_name();
2d29d278 12983
12984 // See below. FIXME.
12985 if (!Gogo::is_hidden_name(name)
12986 && name[0] >= 'a'
12987 && name[0] <= 'z')
12988 {
12989 if (gogo->lookup_global(name.c_str()) != NULL)
12990 name = gogo->pack_hidden_name(name, false);
12991 }
12992
e440a328 12993 char buf[20];
12994 snprintf(buf, sizeof buf, "%u", fre->field_index());
12995 size_t buflen = strlen(buf);
12996 if (name.compare(name.length() - buflen, buflen, buf)
12997 == 0)
12998 {
12999 name = name.substr(0, name.length() - buflen);
13000 bad_key = false;
13001 }
13002 }
13003 }
13004 }
13005 }
13006 break;
13007
13008 default:
13009 bad_key = true;
13010 break;
13011 }
13012 if (bad_key)
13013 {
13014 error_at(name_expr->location(), "expected struct field name");
13015 return Expression::make_error(location);
13016 }
13017
81c4b26b 13018 if (no != NULL)
13019 {
62750cd5 13020 if (no->package() != NULL && external_expr == NULL)
13021 {
13022 external_expr = name_expr;
13023 external_no = no;
13024 }
13025
81c4b26b 13026 name = no->name();
13027
13028 // A predefined name won't be packed. If it starts with a
13029 // lower case letter we need to check for that case, because
2d29d278 13030 // the field name will be packed. FIXME.
81c4b26b 13031 if (!Gogo::is_hidden_name(name)
13032 && name[0] >= 'a'
13033 && name[0] <= 'z')
13034 {
13035 Named_object* gno = gogo->lookup_global(name.c_str());
13036 if (gno == no)
13037 name = gogo->pack_hidden_name(name, false);
13038 }
13039 }
13040
e440a328 13041 unsigned int index;
13042 const Struct_field* sf = st->find_local_field(name, &index);
13043 if (sf == NULL)
13044 {
13045 error_at(name_expr->location(), "unknown field %qs in %qs",
13046 Gogo::message_name(name).c_str(),
13047 (type->named_type() != NULL
13048 ? type->named_type()->message_name().c_str()
13049 : "unnamed struct"));
13050 return Expression::make_error(location);
13051 }
13052 if (vals[index] != NULL)
13053 {
13054 error_at(name_expr->location(),
13055 "duplicate value for field %qs in %qs",
13056 Gogo::message_name(name).c_str(),
13057 (type->named_type() != NULL
13058 ? type->named_type()->message_name().c_str()
13059 : "unnamed struct"));
13060 return Expression::make_error(location);
13061 }
13062
07daa4e7 13063 if (type->named_type() != NULL
13064 && type->named_type()->named_object()->package() != NULL
13065 && Gogo::is_hidden_name(sf->field_name()))
13066 error_at(name_expr->location(),
13067 "assignment of unexported field %qs in %qs literal",
13068 Gogo::message_name(sf->field_name()).c_str(),
13069 type->named_type()->message_name().c_str());
07daa4e7 13070
e440a328 13071 vals[index] = val;
0c4f5a19 13072 traverse_order->push_back(index);
e440a328 13073 }
13074
62750cd5 13075 if (!this->all_are_names_)
13076 {
13077 // This is a weird case like bug462 in the testsuite.
13078 if (external_expr == NULL)
13079 error_at(this->location(), "unknown field in %qs literal",
13080 (type->named_type() != NULL
13081 ? type->named_type()->message_name().c_str()
13082 : "unnamed struct"));
13083 else
13084 error_at(external_expr->location(), "unknown field %qs in %qs",
13085 external_no->message_name().c_str(),
13086 (type->named_type() != NULL
13087 ? type->named_type()->message_name().c_str()
13088 : "unnamed struct"));
13089 return Expression::make_error(location);
13090 }
13091
e440a328 13092 Expression_list* list = new Expression_list;
13093 list->reserve(field_count);
13094 for (size_t i = 0; i < field_count; ++i)
13095 list->push_back(vals[i]);
13096
0c4f5a19 13097 Struct_construction_expression* ret =
13098 new Struct_construction_expression(type, list, location);
13099 ret->set_traverse_order(traverse_order);
13100 return ret;
e440a328 13101}
13102
00773463 13103// Used to sort an index/value array.
13104
13105class Index_value_compare
13106{
13107 public:
13108 bool
13109 operator()(const std::pair<unsigned long, Expression*>& a,
13110 const std::pair<unsigned long, Expression*>& b)
13111 { return a.first < b.first; }
13112};
13113
e440a328 13114// Lower an array composite literal.
13115
13116Expression*
113ef6a5 13117Composite_literal_expression::lower_array(Type* type)
e440a328 13118{
b13c66cd 13119 Location location = this->location();
e440a328 13120 if (this->vals_ == NULL || !this->has_keys_)
ffe743ca 13121 return this->make_array(type, NULL, this->vals_);
e440a328 13122
ffe743ca 13123 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13124 indexes->reserve(this->vals_->size());
00773463 13125 bool indexes_out_of_order = false;
ffe743ca 13126 Expression_list* vals = new Expression_list();
13127 vals->reserve(this->vals_->size());
e440a328 13128 unsigned long index = 0;
13129 Expression_list::const_iterator p = this->vals_->begin();
13130 while (p != this->vals_->end())
13131 {
13132 Expression* index_expr = *p;
13133
13134 ++p;
c484d925 13135 go_assert(p != this->vals_->end());
e440a328 13136 Expression* val = *p;
13137
13138 ++p;
13139
ffe743ca 13140 if (index_expr == NULL)
13141 {
13142 if (!indexes->empty())
13143 indexes->push_back(index);
13144 }
13145 else
e440a328 13146 {
ffe743ca 13147 if (indexes->empty() && !vals->empty())
13148 {
13149 for (size_t i = 0; i < vals->size(); ++i)
13150 indexes->push_back(i);
13151 }
13152
0c77715b 13153 Numeric_constant nc;
13154 if (!index_expr->numeric_constant_value(&nc))
e440a328 13155 {
e440a328 13156 error_at(index_expr->location(),
13157 "index expression is not integer constant");
13158 return Expression::make_error(location);
13159 }
6f6d9955 13160
0c77715b 13161 switch (nc.to_unsigned_long(&index))
e440a328 13162 {
0c77715b 13163 case Numeric_constant::NC_UL_VALID:
13164 break;
13165 case Numeric_constant::NC_UL_NOTINT:
13166 error_at(index_expr->location(),
13167 "index expression is not integer constant");
13168 return Expression::make_error(location);
13169 case Numeric_constant::NC_UL_NEGATIVE:
e440a328 13170 error_at(index_expr->location(), "index expression is negative");
13171 return Expression::make_error(location);
0c77715b 13172 case Numeric_constant::NC_UL_BIG:
e440a328 13173 error_at(index_expr->location(), "index value overflow");
13174 return Expression::make_error(location);
0c77715b 13175 default:
13176 go_unreachable();
e440a328 13177 }
6f6d9955 13178
13179 Named_type* ntype = Type::lookup_integer_type("int");
13180 Integer_type* inttype = ntype->integer_type();
0c77715b 13181 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13182 && index >> (inttype->bits() - 1) != 0)
6f6d9955 13183 {
6f6d9955 13184 error_at(index_expr->location(), "index value overflow");
13185 return Expression::make_error(location);
13186 }
13187
ffe743ca 13188 if (std::find(indexes->begin(), indexes->end(), index)
13189 != indexes->end())
e440a328 13190 {
ffe743ca 13191 error_at(index_expr->location(), "duplicate value for index %lu",
e440a328 13192 index);
13193 return Expression::make_error(location);
13194 }
ffe743ca 13195
00773463 13196 if (!indexes->empty() && index < indexes->back())
13197 indexes_out_of_order = true;
13198
ffe743ca 13199 indexes->push_back(index);
e440a328 13200 }
13201
ffe743ca 13202 vals->push_back(val);
13203
e440a328 13204 ++index;
13205 }
13206
ffe743ca 13207 if (indexes->empty())
13208 {
13209 delete indexes;
13210 indexes = NULL;
13211 }
e440a328 13212
00773463 13213 if (indexes_out_of_order)
13214 {
13215 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13216
13217 V v;
13218 v.reserve(indexes->size());
13219 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13220 for (Expression_list::const_iterator pe = vals->begin();
13221 pe != vals->end();
13222 ++pe, ++pi)
13223 v.push_back(std::make_pair(*pi, *pe));
13224
13225 std::sort(v.begin(), v.end(), Index_value_compare());
13226
13227 delete indexes;
13228 delete vals;
13229 indexes = new std::vector<unsigned long>();
13230 indexes->reserve(v.size());
13231 vals = new Expression_list();
13232 vals->reserve(v.size());
13233
13234 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13235 {
13236 indexes->push_back(p->first);
13237 vals->push_back(p->second);
13238 }
13239 }
13240
ffe743ca 13241 return this->make_array(type, indexes, vals);
e440a328 13242}
13243
13244// Actually build the array composite literal. This handles
13245// [...]{...}.
13246
13247Expression*
ffe743ca 13248Composite_literal_expression::make_array(
13249 Type* type,
13250 const std::vector<unsigned long>* indexes,
13251 Expression_list* vals)
e440a328 13252{
b13c66cd 13253 Location location = this->location();
e440a328 13254 Array_type* at = type->array_type();
ffe743ca 13255
e440a328 13256 if (at->length() != NULL && at->length()->is_nil_expression())
13257 {
ffe743ca 13258 size_t size;
13259 if (vals == NULL)
13260 size = 0;
00773463 13261 else if (indexes != NULL)
13262 size = indexes->back() + 1;
13263 else
ffe743ca 13264 {
13265 size = vals->size();
13266 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13267 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13268 && size >> (it->bits() - 1) != 0)
13269 {
13270 error_at(location, "too many elements in composite literal");
13271 return Expression::make_error(location);
13272 }
13273 }
ffe743ca 13274
e67508fa 13275 Expression* elen = Expression::make_integer_ul(size, NULL, location);
e440a328 13276 at = Type::make_array_type(at->element_type(), elen);
13277 type = at;
13278 }
ffe743ca 13279 else if (at->length() != NULL
13280 && !at->length()->is_error_expression()
13281 && this->vals_ != NULL)
13282 {
13283 Numeric_constant nc;
13284 unsigned long val;
13285 if (at->length()->numeric_constant_value(&nc)
13286 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13287 {
13288 if (indexes == NULL)
13289 {
13290 if (this->vals_->size() > val)
13291 {
13292 error_at(location, "too many elements in composite literal");
13293 return Expression::make_error(location);
13294 }
13295 }
13296 else
13297 {
00773463 13298 unsigned long max = indexes->back();
ffe743ca 13299 if (max >= val)
13300 {
13301 error_at(location,
13302 ("some element keys in composite literal "
13303 "are out of range"));
13304 return Expression::make_error(location);
13305 }
13306 }
13307 }
13308 }
13309
e440a328 13310 if (at->length() != NULL)
ffe743ca 13311 return new Fixed_array_construction_expression(type, indexes, vals,
13312 location);
e440a328 13313 else
2c809f8f 13314 return new Slice_construction_expression(type, indexes, vals, location);
e440a328 13315}
13316
13317// Lower a map composite literal.
13318
13319Expression*
a287720d 13320Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
ceeb4318 13321 Statement_inserter* inserter,
a287720d 13322 Type* type)
e440a328 13323{
b13c66cd 13324 Location location = this->location();
e440a328 13325 if (this->vals_ != NULL)
13326 {
13327 if (!this->has_keys_)
13328 {
13329 error_at(location, "map composite literal must have keys");
13330 return Expression::make_error(location);
13331 }
13332
a287720d 13333 for (Expression_list::iterator p = this->vals_->begin();
e440a328 13334 p != this->vals_->end();
13335 p += 2)
13336 {
13337 if (*p == NULL)
13338 {
13339 ++p;
13340 error_at((*p)->location(),
13341 "map composite literal must have keys for every value");
13342 return Expression::make_error(location);
13343 }
a287720d 13344 // Make sure we have lowered the key; it may not have been
13345 // lowered in order to handle keys for struct composite
13346 // literals. Lower it now to get the right error message.
13347 if ((*p)->unknown_expression() != NULL)
13348 {
13349 (*p)->unknown_expression()->clear_is_composite_literal_key();
ceeb4318 13350 gogo->lower_expression(function, inserter, &*p);
c484d925 13351 go_assert((*p)->is_error_expression());
a287720d 13352 return Expression::make_error(location);
13353 }
e440a328 13354 }
13355 }
13356
13357 return new Map_construction_expression(type, this->vals_, location);
13358}
13359
d751bb78 13360// Dump ast representation for a composite literal expression.
13361
13362void
13363Composite_literal_expression::do_dump_expression(
13364 Ast_dump_context* ast_dump_context) const
13365{
8b1c301d 13366 ast_dump_context->ostream() << "composite(";
d751bb78 13367 ast_dump_context->dump_type(this->type_);
13368 ast_dump_context->ostream() << ", {";
8b1c301d 13369 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
d751bb78 13370 ast_dump_context->ostream() << "})";
13371}
13372
e440a328 13373// Make a composite literal expression.
13374
13375Expression*
13376Expression::make_composite_literal(Type* type, int depth, bool has_keys,
62750cd5 13377 Expression_list* vals, bool all_are_names,
b13c66cd 13378 Location location)
e440a328 13379{
13380 return new Composite_literal_expression(type, depth, has_keys, vals,
62750cd5 13381 all_are_names, location);
e440a328 13382}
13383
13384// Return whether this expression is a composite literal.
13385
13386bool
13387Expression::is_composite_literal() const
13388{
13389 switch (this->classification_)
13390 {
13391 case EXPRESSION_COMPOSITE_LITERAL:
13392 case EXPRESSION_STRUCT_CONSTRUCTION:
13393 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
2c809f8f 13394 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13395 case EXPRESSION_MAP_CONSTRUCTION:
13396 return true;
13397 default:
13398 return false;
13399 }
13400}
13401
13402// Return whether this expression is a composite literal which is not
13403// constant.
13404
13405bool
13406Expression::is_nonconstant_composite_literal() const
13407{
13408 switch (this->classification_)
13409 {
13410 case EXPRESSION_STRUCT_CONSTRUCTION:
13411 {
13412 const Struct_construction_expression *psce =
13413 static_cast<const Struct_construction_expression*>(this);
13414 return !psce->is_constant_struct();
13415 }
13416 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13417 {
13418 const Fixed_array_construction_expression *pace =
13419 static_cast<const Fixed_array_construction_expression*>(this);
13420 return !pace->is_constant_array();
13421 }
2c809f8f 13422 case EXPRESSION_SLICE_CONSTRUCTION:
e440a328 13423 {
2c809f8f 13424 const Slice_construction_expression *pace =
13425 static_cast<const Slice_construction_expression*>(this);
e440a328 13426 return !pace->is_constant_array();
13427 }
13428 case EXPRESSION_MAP_CONSTRUCTION:
13429 return true;
13430 default:
13431 return false;
13432 }
13433}
13434
35a54f17 13435// Return true if this is a variable or temporary_variable.
13436
13437bool
13438Expression::is_variable() const
13439{
13440 switch (this->classification_)
13441 {
13442 case EXPRESSION_VAR_REFERENCE:
13443 case EXPRESSION_TEMPORARY_REFERENCE:
13444 case EXPRESSION_SET_AND_USE_TEMPORARY:
13445 return true;
13446 default:
13447 return false;
13448 }
13449}
13450
e440a328 13451// Return true if this is a reference to a local variable.
13452
13453bool
13454Expression::is_local_variable() const
13455{
13456 const Var_expression* ve = this->var_expression();
13457 if (ve == NULL)
13458 return false;
13459 const Named_object* no = ve->named_object();
13460 return (no->is_result_variable()
13461 || (no->is_variable() && !no->var_value()->is_global()));
13462}
13463
13464// Class Type_guard_expression.
13465
13466// Traversal.
13467
13468int
13469Type_guard_expression::do_traverse(Traverse* traverse)
13470{
13471 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13472 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13473 return TRAVERSE_EXIT;
13474 return TRAVERSE_CONTINUE;
13475}
13476
2c809f8f 13477Expression*
13478Type_guard_expression::do_flatten(Gogo*, Named_object*,
13479 Statement_inserter* inserter)
13480{
13481 if (!this->expr_->is_variable())
13482 {
13483 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13484 this->location());
13485 inserter->insert(temp);
13486 this->expr_ =
13487 Expression::make_temporary_reference(temp, this->location());
13488 }
13489 return this;
13490}
13491
e440a328 13492// Check types of a type guard expression. The expression must have
13493// an interface type, but the actual type conversion is checked at run
13494// time.
13495
13496void
13497Type_guard_expression::do_check_types(Gogo*)
13498{
e440a328 13499 Type* expr_type = this->expr_->type();
7e9da23f 13500 if (expr_type->interface_type() == NULL)
f725ade8 13501 {
5c13bd80 13502 if (!expr_type->is_error() && !this->type_->is_error())
f725ade8 13503 this->report_error(_("type assertion only valid for interface types"));
13504 this->set_is_error();
13505 }
e440a328 13506 else if (this->type_->interface_type() == NULL)
13507 {
13508 std::string reason;
13509 if (!expr_type->interface_type()->implements_interface(this->type_,
13510 &reason))
13511 {
5c13bd80 13512 if (!this->type_->is_error())
e440a328 13513 {
f725ade8 13514 if (reason.empty())
13515 this->report_error(_("impossible type assertion: "
13516 "type does not implement interface"));
13517 else
13518 error_at(this->location(),
13519 ("impossible type assertion: "
13520 "type does not implement interface (%s)"),
13521 reason.c_str());
e440a328 13522 }
f725ade8 13523 this->set_is_error();
e440a328 13524 }
13525 }
13526}
13527
ea664253 13528// Return the backend representation for a type guard expression.
e440a328 13529
ea664253 13530Bexpression*
13531Type_guard_expression::do_get_backend(Translate_context* context)
e440a328 13532{
2c809f8f 13533 Expression* conversion;
7e9da23f 13534 if (this->type_->interface_type() != NULL)
2c809f8f 13535 conversion =
13536 Expression::convert_interface_to_interface(this->type_, this->expr_,
13537 true, this->location());
e440a328 13538 else
2c809f8f 13539 conversion =
13540 Expression::convert_for_assignment(context->gogo(), this->type_,
13541 this->expr_, this->location());
13542
ea664253 13543 return conversion->get_backend(context);
e440a328 13544}
13545
d751bb78 13546// Dump ast representation for a type guard expression.
13547
13548void
2c809f8f 13549Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
d751bb78 13550 const
13551{
13552 this->expr_->dump_expression(ast_dump_context);
13553 ast_dump_context->ostream() << ".";
13554 ast_dump_context->dump_type(this->type_);
13555}
13556
e440a328 13557// Make a type guard expression.
13558
13559Expression*
13560Expression::make_type_guard(Expression* expr, Type* type,
b13c66cd 13561 Location location)
e440a328 13562{
13563 return new Type_guard_expression(expr, type, location);
13564}
13565
2c809f8f 13566// Class Heap_expression.
e440a328 13567
2c809f8f 13568// When you take the address of an escaping expression, it is allocated
e440a328 13569// on the heap. This class implements that.
13570
2c809f8f 13571class Heap_expression : public Expression
e440a328 13572{
13573 public:
2c809f8f 13574 Heap_expression(Expression* expr, Location location)
13575 : Expression(EXPRESSION_HEAP, location),
e440a328 13576 expr_(expr)
13577 { }
13578
13579 protected:
13580 int
13581 do_traverse(Traverse* traverse)
13582 { return Expression::traverse(&this->expr_, traverse); }
13583
13584 Type*
13585 do_type()
13586 { return Type::make_pointer_type(this->expr_->type()); }
13587
13588 void
13589 do_determine_type(const Type_context*)
13590 { this->expr_->determine_type_no_context(); }
13591
13592 Expression*
13593 do_copy()
13594 {
2c809f8f 13595 return Expression::make_heap_expression(this->expr_->copy(),
13596 this->location());
e440a328 13597 }
13598
ea664253 13599 Bexpression*
13600 do_get_backend(Translate_context*);
e440a328 13601
13602 // We only export global objects, and the parser does not generate
13603 // this in global scope.
13604 void
13605 do_export(Export*) const
c3e6f413 13606 { go_unreachable(); }
e440a328 13607
d751bb78 13608 void
13609 do_dump_expression(Ast_dump_context*) const;
13610
e440a328 13611 private:
2c809f8f 13612 // The expression which is being put on the heap.
e440a328 13613 Expression* expr_;
13614};
13615
ea664253 13616// Return the backend representation for allocating an expression on the heap.
e440a328 13617
ea664253 13618Bexpression*
13619Heap_expression::do_get_backend(Translate_context* context)
e440a328 13620{
02c19a1a 13621 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
ea664253 13622 return context->backend()->error_expression();
2c809f8f 13623
02c19a1a 13624 Location loc = this->location();
2c809f8f 13625 Gogo* gogo = context->gogo();
02c19a1a 13626 Btype* btype = this->type()->get_backend(gogo);
ea664253 13627 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13628 loc)->get_backend(context);
02c19a1a 13629
13630 Bstatement* decl;
13631 Named_object* fn = context->function();
13632 go_assert(fn != NULL);
13633 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13634 Bvariable* space_temp =
13635 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13636 space, true, loc, &decl);
13637 space = gogo->backend()->var_expression(space_temp, loc);
9b27b43c 13638 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13639 Bexpression* ref =
13640 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
02c19a1a 13641
ea664253 13642 Bexpression* bexpr = this->expr_->get_backend(context);
02c19a1a 13643 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13644 decl = gogo->backend()->compound_statement(decl, assn);
13645 space = gogo->backend()->var_expression(space_temp, loc);
ea664253 13646 return gogo->backend()->compound_expression(decl, space, loc);
e440a328 13647}
13648
2c809f8f 13649// Dump ast representation for a heap expression.
d751bb78 13650
13651void
2c809f8f 13652Heap_expression::do_dump_expression(
d751bb78 13653 Ast_dump_context* ast_dump_context) const
13654{
13655 ast_dump_context->ostream() << "&(";
13656 ast_dump_context->dump_expression(this->expr_);
13657 ast_dump_context->ostream() << ")";
13658}
13659
2c809f8f 13660// Allocate an expression on the heap.
e440a328 13661
13662Expression*
2c809f8f 13663Expression::make_heap_expression(Expression* expr, Location location)
e440a328 13664{
2c809f8f 13665 return new Heap_expression(expr, location);
e440a328 13666}
13667
13668// Class Receive_expression.
13669
13670// Return the type of a receive expression.
13671
13672Type*
13673Receive_expression::do_type()
13674{
13675 Channel_type* channel_type = this->channel_->type()->channel_type();
13676 if (channel_type == NULL)
13677 return Type::make_error_type();
13678 return channel_type->element_type();
13679}
13680
13681// Check types for a receive expression.
13682
13683void
13684Receive_expression::do_check_types(Gogo*)
13685{
13686 Type* type = this->channel_->type();
5c13bd80 13687 if (type->is_error())
e440a328 13688 {
13689 this->set_is_error();
13690 return;
13691 }
13692 if (type->channel_type() == NULL)
13693 {
13694 this->report_error(_("expected channel"));
13695 return;
13696 }
13697 if (!type->channel_type()->may_receive())
13698 {
13699 this->report_error(_("invalid receive on send-only channel"));
13700 return;
13701 }
13702}
13703
2c809f8f 13704// Flattening for receive expressions creates a temporary variable to store
13705// received data in for receives.
13706
13707Expression*
13708Receive_expression::do_flatten(Gogo*, Named_object*,
13709 Statement_inserter* inserter)
13710{
13711 Channel_type* channel_type = this->channel_->type()->channel_type();
13712 if (channel_type == NULL)
13713 {
13714 go_assert(saw_errors());
13715 return this;
13716 }
13717
13718 Type* element_type = channel_type->element_type();
13719 if (this->temp_receiver_ == NULL)
13720 {
13721 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13722 this->location());
13723 this->temp_receiver_->set_is_address_taken();
13724 inserter->insert(this->temp_receiver_);
13725 }
13726
13727 return this;
13728}
13729
ea664253 13730// Get the backend representation for a receive expression.
e440a328 13731
ea664253 13732Bexpression*
13733Receive_expression::do_get_backend(Translate_context* context)
e440a328 13734{
f24f10bb 13735 Location loc = this->location();
13736
e440a328 13737 Channel_type* channel_type = this->channel_->type()->channel_type();
5b8368f4 13738 if (channel_type == NULL)
13739 {
c484d925 13740 go_assert(this->channel_->type()->is_error());
ea664253 13741 return context->backend()->error_expression();
5b8368f4 13742 }
f24f10bb 13743 Expression* td = Expression::make_type_descriptor(channel_type, loc);
e440a328 13744
2c809f8f 13745 Expression* recv_ref =
13746 Expression::make_temporary_reference(this->temp_receiver_, loc);
13747 Expression* recv_addr =
13748 Expression::make_temporary_reference(this->temp_receiver_, loc);
13749 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13750 Expression* recv =
13751 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13752 td, this->channel_, recv_addr);
ea664253 13753 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
e440a328 13754}
13755
d751bb78 13756// Dump ast representation for a receive expression.
13757
13758void
13759Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13760{
13761 ast_dump_context->ostream() << " <- " ;
13762 ast_dump_context->dump_expression(channel_);
13763}
13764
e440a328 13765// Make a receive expression.
13766
13767Receive_expression*
b13c66cd 13768Expression::make_receive(Expression* channel, Location location)
e440a328 13769{
13770 return new Receive_expression(channel, location);
13771}
13772
e440a328 13773// An expression which evaluates to a pointer to the type descriptor
13774// of a type.
13775
13776class Type_descriptor_expression : public Expression
13777{
13778 public:
b13c66cd 13779 Type_descriptor_expression(Type* type, Location location)
e440a328 13780 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13781 type_(type)
13782 { }
13783
13784 protected:
4b686186 13785 int
13786 do_traverse(Traverse*);
13787
e440a328 13788 Type*
13789 do_type()
13790 { return Type::make_type_descriptor_ptr_type(); }
13791
f9ca30f9 13792 bool
13793 do_is_immutable() const
13794 { return true; }
13795
e440a328 13796 void
13797 do_determine_type(const Type_context*)
13798 { }
13799
13800 Expression*
13801 do_copy()
13802 { return this; }
13803
ea664253 13804 Bexpression*
13805 do_get_backend(Translate_context* context)
a1d23b41 13806 {
ea664253 13807 return this->type_->type_descriptor_pointer(context->gogo(),
13808 this->location());
a1d23b41 13809 }
e440a328 13810
d751bb78 13811 void
13812 do_dump_expression(Ast_dump_context*) const;
13813
e440a328 13814 private:
13815 // The type for which this is the descriptor.
13816 Type* type_;
13817};
13818
4b686186 13819int
13820Type_descriptor_expression::do_traverse(Traverse* traverse)
13821{
13822 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13823 return TRAVERSE_EXIT;
13824 return TRAVERSE_CONTINUE;
13825}
13826
d751bb78 13827// Dump ast representation for a type descriptor expression.
13828
13829void
13830Type_descriptor_expression::do_dump_expression(
13831 Ast_dump_context* ast_dump_context) const
13832{
13833 ast_dump_context->dump_type(this->type_);
13834}
13835
e440a328 13836// Make a type descriptor expression.
13837
13838Expression*
b13c66cd 13839Expression::make_type_descriptor(Type* type, Location location)
e440a328 13840{
13841 return new Type_descriptor_expression(type, location);
13842}
13843
aa5ae575 13844// An expression which evaluates to a pointer to the Garbage Collection symbol
13845// of a type.
13846
13847class GC_symbol_expression : public Expression
13848{
13849 public:
13850 GC_symbol_expression(Type* type)
13851 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
13852 type_(type)
13853 {}
13854
13855 protected:
13856 Type*
13857 do_type()
23d77f91 13858 { return Type::lookup_integer_type("uintptr"); }
aa5ae575 13859
13860 bool
13861 do_is_immutable() const
13862 { return true; }
13863
13864 void
13865 do_determine_type(const Type_context*)
13866 { }
13867
13868 Expression*
13869 do_copy()
13870 { return this; }
13871
13872 Bexpression*
13873 do_get_backend(Translate_context* context)
13874 { return this->type_->gc_symbol_pointer(context->gogo()); }
13875
13876 void
13877 do_dump_expression(Ast_dump_context*) const;
13878
13879 private:
13880 // The type which this gc symbol describes.
13881 Type* type_;
13882};
13883
13884// Dump ast representation for a gc symbol expression.
13885
13886void
13887GC_symbol_expression::do_dump_expression(
13888 Ast_dump_context* ast_dump_context) const
13889{
13890 ast_dump_context->ostream() << "gcdata(";
13891 ast_dump_context->dump_type(this->type_);
13892 ast_dump_context->ostream() << ")";
13893}
13894
13895// Make a gc symbol expression.
13896
13897Expression*
13898Expression::make_gc_symbol(Type* type)
13899{
13900 return new GC_symbol_expression(type);
13901}
13902
e440a328 13903// An expression which evaluates to some characteristic of a type.
13904// This is only used to initialize fields of a type descriptor. Using
13905// a new expression class is slightly inefficient but gives us a good
13906// separation between the frontend and the middle-end with regard to
13907// how types are laid out.
13908
13909class Type_info_expression : public Expression
13910{
13911 public:
13912 Type_info_expression(Type* type, Type_info type_info)
b13c66cd 13913 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
e440a328 13914 type_(type), type_info_(type_info)
13915 { }
13916
13917 protected:
0e168074 13918 bool
13919 do_is_immutable() const
13920 { return true; }
13921
e440a328 13922 Type*
13923 do_type();
13924
13925 void
13926 do_determine_type(const Type_context*)
13927 { }
13928
13929 Expression*
13930 do_copy()
13931 { return this; }
13932
ea664253 13933 Bexpression*
13934 do_get_backend(Translate_context* context);
e440a328 13935
d751bb78 13936 void
13937 do_dump_expression(Ast_dump_context*) const;
13938
e440a328 13939 private:
13940 // The type for which we are getting information.
13941 Type* type_;
13942 // What information we want.
13943 Type_info type_info_;
13944};
13945
13946// The type is chosen to match what the type descriptor struct
13947// expects.
13948
13949Type*
13950Type_info_expression::do_type()
13951{
13952 switch (this->type_info_)
13953 {
13954 case TYPE_INFO_SIZE:
13955 return Type::lookup_integer_type("uintptr");
13956 case TYPE_INFO_ALIGNMENT:
13957 case TYPE_INFO_FIELD_ALIGNMENT:
13958 return Type::lookup_integer_type("uint8");
13959 default:
c3e6f413 13960 go_unreachable();
e440a328 13961 }
13962}
13963
ea664253 13964// Return the backend representation for type information.
e440a328 13965
ea664253 13966Bexpression*
13967Type_info_expression::do_get_backend(Translate_context* context)
e440a328 13968{
927a01eb 13969 Btype* btype = this->type_->get_backend(context->gogo());
13970 Gogo* gogo = context->gogo();
13971 size_t val;
13972 switch (this->type_info_)
e440a328 13973 {
927a01eb 13974 case TYPE_INFO_SIZE:
13975 val = gogo->backend()->type_size(btype);
13976 break;
13977 case TYPE_INFO_ALIGNMENT:
13978 val = gogo->backend()->type_alignment(btype);
13979 break;
13980 case TYPE_INFO_FIELD_ALIGNMENT:
13981 val = gogo->backend()->type_field_alignment(btype);
13982 break;
13983 default:
13984 go_unreachable();
e440a328 13985 }
287cdcf4 13986 mpz_t cst;
13987 mpz_init_set_ui(cst, val);
13988 Btype* int_btype = this->type()->get_backend(gogo);
13989 Bexpression* ret =
13990 gogo->backend()->integer_constant_expression(int_btype, cst);
13991 mpz_clear(cst);
ea664253 13992 return ret;
e440a328 13993}
13994
d751bb78 13995// Dump ast representation for a type info expression.
13996
13997void
13998Type_info_expression::do_dump_expression(
13999 Ast_dump_context* ast_dump_context) const
14000{
14001 ast_dump_context->ostream() << "typeinfo(";
14002 ast_dump_context->dump_type(this->type_);
14003 ast_dump_context->ostream() << ",";
14004 ast_dump_context->ostream() <<
14005 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14006 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14007 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14008 : "unknown");
14009 ast_dump_context->ostream() << ")";
14010}
14011
e440a328 14012// Make a type info expression.
14013
14014Expression*
14015Expression::make_type_info(Type* type, Type_info type_info)
14016{
14017 return new Type_info_expression(type, type_info);
14018}
14019
35a54f17 14020// An expression that evaluates to some characteristic of a slice.
14021// This is used when indexing, bound-checking, or nil checking a slice.
14022
14023class Slice_info_expression : public Expression
14024{
14025 public:
14026 Slice_info_expression(Expression* slice, Slice_info slice_info,
14027 Location location)
14028 : Expression(EXPRESSION_SLICE_INFO, location),
14029 slice_(slice), slice_info_(slice_info)
14030 { }
14031
14032 protected:
14033 Type*
14034 do_type();
14035
14036 void
14037 do_determine_type(const Type_context*)
14038 { }
14039
14040 Expression*
14041 do_copy()
14042 {
14043 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14044 this->location());
14045 }
14046
ea664253 14047 Bexpression*
14048 do_get_backend(Translate_context* context);
35a54f17 14049
14050 void
14051 do_dump_expression(Ast_dump_context*) const;
14052
14053 void
14054 do_issue_nil_check()
14055 { this->slice_->issue_nil_check(); }
14056
14057 private:
14058 // The slice for which we are getting information.
14059 Expression* slice_;
14060 // What information we want.
14061 Slice_info slice_info_;
14062};
14063
14064// Return the type of the slice info.
14065
14066Type*
14067Slice_info_expression::do_type()
14068{
14069 switch (this->slice_info_)
14070 {
14071 case SLICE_INFO_VALUE_POINTER:
14072 return Type::make_pointer_type(
14073 this->slice_->type()->array_type()->element_type());
14074 case SLICE_INFO_LENGTH:
14075 case SLICE_INFO_CAPACITY:
14076 return Type::lookup_integer_type("int");
14077 default:
14078 go_unreachable();
14079 }
14080}
14081
ea664253 14082// Return the backend information for slice information.
35a54f17 14083
ea664253 14084Bexpression*
14085Slice_info_expression::do_get_backend(Translate_context* context)
35a54f17 14086{
14087 Gogo* gogo = context->gogo();
ea664253 14088 Bexpression* bslice = this->slice_->get_backend(context);
35a54f17 14089 switch (this->slice_info_)
14090 {
14091 case SLICE_INFO_VALUE_POINTER:
14092 case SLICE_INFO_LENGTH:
14093 case SLICE_INFO_CAPACITY:
ea664253 14094 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14095 this->location());
35a54f17 14096 break;
14097 default:
14098 go_unreachable();
14099 }
35a54f17 14100}
14101
14102// Dump ast representation for a type info expression.
14103
14104void
14105Slice_info_expression::do_dump_expression(
14106 Ast_dump_context* ast_dump_context) const
14107{
14108 ast_dump_context->ostream() << "sliceinfo(";
14109 this->slice_->dump_expression(ast_dump_context);
14110 ast_dump_context->ostream() << ",";
14111 ast_dump_context->ostream() <<
14112 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14113 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14114 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14115 : "unknown");
14116 ast_dump_context->ostream() << ")";
14117}
14118
14119// Make a slice info expression.
14120
14121Expression*
14122Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14123 Location location)
14124{
14125 return new Slice_info_expression(slice, slice_info, location);
14126}
14127
2c809f8f 14128// An expression that represents a slice value: a struct with value pointer,
14129// length, and capacity fields.
14130
14131class Slice_value_expression : public Expression
14132{
14133 public:
14134 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14135 Expression* cap, Location location)
14136 : Expression(EXPRESSION_SLICE_VALUE, location),
14137 type_(type), valptr_(valptr), len_(len), cap_(cap)
14138 { }
14139
14140 protected:
14141 int
14142 do_traverse(Traverse*);
14143
14144 Type*
14145 do_type()
14146 { return this->type_; }
14147
14148 void
14149 do_determine_type(const Type_context*)
14150 { go_unreachable(); }
14151
14152 Expression*
14153 do_copy()
14154 {
14155 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14156 this->len_->copy(), this->cap_->copy(),
14157 this->location());
14158 }
14159
ea664253 14160 Bexpression*
14161 do_get_backend(Translate_context* context);
2c809f8f 14162
14163 void
14164 do_dump_expression(Ast_dump_context*) const;
14165
14166 private:
14167 // The type of the slice value.
14168 Type* type_;
14169 // The pointer to the values in the slice.
14170 Expression* valptr_;
14171 // The length of the slice.
14172 Expression* len_;
14173 // The capacity of the slice.
14174 Expression* cap_;
14175};
14176
14177int
14178Slice_value_expression::do_traverse(Traverse* traverse)
14179{
55e8ba6a 14180 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14181 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
2c809f8f 14182 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14183 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14184 return TRAVERSE_EXIT;
14185 return TRAVERSE_CONTINUE;
14186}
14187
ea664253 14188Bexpression*
14189Slice_value_expression::do_get_backend(Translate_context* context)
2c809f8f 14190{
14191 std::vector<Bexpression*> vals(3);
ea664253 14192 vals[0] = this->valptr_->get_backend(context);
14193 vals[1] = this->len_->get_backend(context);
14194 vals[2] = this->cap_->get_backend(context);
2c809f8f 14195
14196 Gogo* gogo = context->gogo();
14197 Btype* btype = this->type_->get_backend(gogo);
ea664253 14198 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 14199}
14200
14201void
14202Slice_value_expression::do_dump_expression(
14203 Ast_dump_context* ast_dump_context) const
14204{
14205 ast_dump_context->ostream() << "slicevalue(";
14206 ast_dump_context->ostream() << "values: ";
14207 this->valptr_->dump_expression(ast_dump_context);
14208 ast_dump_context->ostream() << ", length: ";
14209 this->len_->dump_expression(ast_dump_context);
14210 ast_dump_context->ostream() << ", capacity: ";
14211 this->cap_->dump_expression(ast_dump_context);
14212 ast_dump_context->ostream() << ")";
14213}
14214
14215Expression*
14216Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14217 Expression* cap, Location location)
14218{
14219 go_assert(at->is_slice_type());
14220 return new Slice_value_expression(at, valptr, len, cap, location);
14221}
2387f644 14222
14223// An expression that evaluates to some characteristic of a non-empty interface.
14224// This is used to access the method table or underlying object of an interface.
14225
14226class Interface_info_expression : public Expression
14227{
14228 public:
14229 Interface_info_expression(Expression* iface, Interface_info iface_info,
2c809f8f 14230 Location location)
2387f644 14231 : Expression(EXPRESSION_INTERFACE_INFO, location),
14232 iface_(iface), iface_info_(iface_info)
14233 { }
14234
14235 protected:
14236 Type*
14237 do_type();
14238
14239 void
14240 do_determine_type(const Type_context*)
14241 { }
14242
14243 Expression*
14244 do_copy()
14245 {
14246 return new Interface_info_expression(this->iface_->copy(),
14247 this->iface_info_, this->location());
14248 }
14249
ea664253 14250 Bexpression*
14251 do_get_backend(Translate_context* context);
2387f644 14252
14253 void
14254 do_dump_expression(Ast_dump_context*) const;
14255
14256 void
14257 do_issue_nil_check()
14258 { this->iface_->issue_nil_check(); }
14259
14260 private:
14261 // The interface for which we are getting information.
14262 Expression* iface_;
14263 // What information we want.
14264 Interface_info iface_info_;
14265};
14266
14267// Return the type of the interface info.
14268
14269Type*
14270Interface_info_expression::do_type()
14271{
14272 switch (this->iface_info_)
14273 {
14274 case INTERFACE_INFO_METHODS:
14275 {
2c809f8f 14276 Type* pdt = Type::make_type_descriptor_ptr_type();
14277 if (this->iface_->type()->interface_type()->is_empty())
14278 return pdt;
14279
2387f644 14280 Location loc = this->location();
14281 Struct_field_list* sfl = new Struct_field_list();
2387f644 14282 sfl->push_back(
14283 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14284
14285 Interface_type* itype = this->iface_->type()->interface_type();
14286 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14287 p != itype->methods()->end();
14288 ++p)
14289 {
14290 Function_type* ft = p->type()->function_type();
14291 go_assert(ft->receiver() == NULL);
14292
14293 const Typed_identifier_list* params = ft->parameters();
14294 Typed_identifier_list* mparams = new Typed_identifier_list();
14295 if (params != NULL)
14296 mparams->reserve(params->size() + 1);
14297 Type* vt = Type::make_pointer_type(Type::make_void_type());
14298 mparams->push_back(Typed_identifier("", vt, ft->location()));
14299 if (params != NULL)
14300 {
14301 for (Typed_identifier_list::const_iterator pp = params->begin();
14302 pp != params->end();
14303 ++pp)
14304 mparams->push_back(*pp);
14305 }
14306
14307 Typed_identifier_list* mresults = (ft->results() == NULL
14308 ? NULL
14309 : ft->results()->copy());
14310 Backend_function_type* mft =
14311 Type::make_backend_function_type(NULL, mparams, mresults,
14312 ft->location());
14313
14314 std::string fname = Gogo::unpack_hidden_name(p->name());
14315 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14316 }
14317
14318 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14319 }
14320 case INTERFACE_INFO_OBJECT:
14321 return Type::make_pointer_type(Type::make_void_type());
14322 default:
14323 go_unreachable();
14324 }
14325}
14326
ea664253 14327// Return the backend representation for interface information.
2387f644 14328
ea664253 14329Bexpression*
14330Interface_info_expression::do_get_backend(Translate_context* context)
2387f644 14331{
14332 Gogo* gogo = context->gogo();
ea664253 14333 Bexpression* biface = this->iface_->get_backend(context);
2387f644 14334 switch (this->iface_info_)
14335 {
14336 case INTERFACE_INFO_METHODS:
14337 case INTERFACE_INFO_OBJECT:
ea664253 14338 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14339 this->location());
2387f644 14340 break;
14341 default:
14342 go_unreachable();
14343 }
2387f644 14344}
14345
14346// Dump ast representation for an interface info expression.
14347
14348void
14349Interface_info_expression::do_dump_expression(
14350 Ast_dump_context* ast_dump_context) const
14351{
2c809f8f 14352 bool is_empty = this->iface_->type()->interface_type()->is_empty();
2387f644 14353 ast_dump_context->ostream() << "interfaceinfo(";
14354 this->iface_->dump_expression(ast_dump_context);
14355 ast_dump_context->ostream() << ",";
14356 ast_dump_context->ostream() <<
2c809f8f 14357 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14358 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
2387f644 14359 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14360 : "unknown");
14361 ast_dump_context->ostream() << ")";
14362}
14363
14364// Make an interface info expression.
14365
14366Expression*
14367Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14368 Location location)
14369{
14370 return new Interface_info_expression(iface, iface_info, location);
14371}
14372
2c809f8f 14373// An expression that represents an interface value. The first field is either
14374// a type descriptor for an empty interface or a pointer to the interface method
14375// table for a non-empty interface. The second field is always the object.
14376
14377class Interface_value_expression : public Expression
14378{
14379 public:
14380 Interface_value_expression(Type* type, Expression* first_field,
14381 Expression* obj, Location location)
14382 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14383 type_(type), first_field_(first_field), obj_(obj)
14384 { }
14385
14386 protected:
14387 int
14388 do_traverse(Traverse*);
14389
14390 Type*
14391 do_type()
14392 { return this->type_; }
14393
14394 void
14395 do_determine_type(const Type_context*)
14396 { go_unreachable(); }
14397
14398 Expression*
14399 do_copy()
14400 {
14401 return new Interface_value_expression(this->type_,
14402 this->first_field_->copy(),
14403 this->obj_->copy(), this->location());
14404 }
14405
ea664253 14406 Bexpression*
14407 do_get_backend(Translate_context* context);
2c809f8f 14408
14409 void
14410 do_dump_expression(Ast_dump_context*) const;
14411
14412 private:
14413 // The type of the interface value.
14414 Type* type_;
14415 // The first field of the interface (either a type descriptor or a pointer
14416 // to the method table.
14417 Expression* first_field_;
14418 // The underlying object of the interface.
14419 Expression* obj_;
14420};
14421
14422int
14423Interface_value_expression::do_traverse(Traverse* traverse)
14424{
14425 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14426 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14427 return TRAVERSE_EXIT;
14428 return TRAVERSE_CONTINUE;
14429}
14430
ea664253 14431Bexpression*
14432Interface_value_expression::do_get_backend(Translate_context* context)
2c809f8f 14433{
14434 std::vector<Bexpression*> vals(2);
ea664253 14435 vals[0] = this->first_field_->get_backend(context);
14436 vals[1] = this->obj_->get_backend(context);
2c809f8f 14437
14438 Gogo* gogo = context->gogo();
14439 Btype* btype = this->type_->get_backend(gogo);
ea664253 14440 return gogo->backend()->constructor_expression(btype, vals, this->location());
2c809f8f 14441}
14442
14443void
14444Interface_value_expression::do_dump_expression(
14445 Ast_dump_context* ast_dump_context) const
14446{
14447 ast_dump_context->ostream() << "interfacevalue(";
14448 ast_dump_context->ostream() <<
14449 (this->type_->interface_type()->is_empty()
14450 ? "type_descriptor: "
14451 : "methods: ");
14452 this->first_field_->dump_expression(ast_dump_context);
14453 ast_dump_context->ostream() << ", object: ";
14454 this->obj_->dump_expression(ast_dump_context);
14455 ast_dump_context->ostream() << ")";
14456}
14457
14458Expression*
14459Expression::make_interface_value(Type* type, Expression* first_value,
14460 Expression* object, Location location)
14461{
14462 return new Interface_value_expression(type, first_value, object, location);
14463}
14464
14465// An interface method table for a pair of types: an interface type and a type
14466// that implements that interface.
14467
14468class Interface_mtable_expression : public Expression
14469{
14470 public:
14471 Interface_mtable_expression(Interface_type* itype, Type* type,
14472 bool is_pointer, Location location)
14473 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14474 itype_(itype), type_(type), is_pointer_(is_pointer),
14475 method_table_type_(NULL), bvar_(NULL)
14476 { }
14477
14478 protected:
14479 int
14480 do_traverse(Traverse*);
14481
14482 Type*
14483 do_type();
14484
14485 bool
14486 is_immutable() const
14487 { return true; }
14488
14489 void
14490 do_determine_type(const Type_context*)
14491 { go_unreachable(); }
14492
14493 Expression*
14494 do_copy()
14495 {
14496 return new Interface_mtable_expression(this->itype_, this->type_,
14497 this->is_pointer_, this->location());
14498 }
14499
14500 bool
14501 do_is_addressable() const
14502 { return true; }
14503
ea664253 14504 Bexpression*
14505 do_get_backend(Translate_context* context);
2c809f8f 14506
14507 void
14508 do_dump_expression(Ast_dump_context*) const;
14509
14510 private:
14511 // The interface type for which the methods are defined.
14512 Interface_type* itype_;
14513 // The type to construct the interface method table for.
14514 Type* type_;
14515 // Whether this table contains the method set for the receiver type or the
14516 // pointer receiver type.
14517 bool is_pointer_;
14518 // The type of the method table.
14519 Type* method_table_type_;
14520 // The backend variable that refers to the interface method table.
14521 Bvariable* bvar_;
14522};
14523
14524int
14525Interface_mtable_expression::do_traverse(Traverse* traverse)
14526{
14527 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14528 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14529 return TRAVERSE_EXIT;
14530 return TRAVERSE_CONTINUE;
14531}
14532
14533Type*
14534Interface_mtable_expression::do_type()
14535{
14536 if (this->method_table_type_ != NULL)
14537 return this->method_table_type_;
14538
14539 const Typed_identifier_list* interface_methods = this->itype_->methods();
14540 go_assert(!interface_methods->empty());
14541
14542 Struct_field_list* sfl = new Struct_field_list;
14543 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14544 this->location());
14545 sfl->push_back(Struct_field(tid));
14546 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14547 p != interface_methods->end();
14548 ++p)
14549 sfl->push_back(Struct_field(*p));
14550 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14551 return this->method_table_type_;
14552}
14553
ea664253 14554Bexpression*
14555Interface_mtable_expression::do_get_backend(Translate_context* context)
2c809f8f 14556{
14557 Gogo* gogo = context->gogo();
2c809f8f 14558 Location loc = Linemap::predeclared_location();
14559 if (this->bvar_ != NULL)
ea664253 14560 return gogo->backend()->var_expression(this->bvar_, this->location());
2c809f8f 14561
14562 const Typed_identifier_list* interface_methods = this->itype_->methods();
14563 go_assert(!interface_methods->empty());
14564
14565 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14566 + this->itype_->mangled_name(gogo)
14567 + "__"
14568 + this->type_->mangled_name(gogo));
14569
14570 // See whether this interface has any hidden methods.
14571 bool has_hidden_methods = false;
14572 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14573 p != interface_methods->end();
14574 ++p)
14575 {
14576 if (Gogo::is_hidden_name(p->name()))
14577 {
14578 has_hidden_methods = true;
14579 break;
14580 }
14581 }
14582
14583 // We already know that the named type is convertible to the
14584 // interface. If the interface has hidden methods, and the named
14585 // type is defined in a different package, then the interface
14586 // conversion table will be defined by that other package.
14587 if (has_hidden_methods
14588 && this->type_->named_type() != NULL
14589 && this->type_->named_type()->named_object()->package() != NULL)
14590 {
14591 Btype* btype = this->type()->get_backend(gogo);
14592 this->bvar_ =
14593 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
ea664253 14594 return gogo->backend()->var_expression(this->bvar_, this->location());
2c809f8f 14595 }
14596
14597 // The first element is the type descriptor.
14598 Type* td_type;
14599 if (!this->is_pointer_)
14600 td_type = this->type_;
14601 else
14602 td_type = Type::make_pointer_type(this->type_);
14603
14604 // Build an interface method table for a type: a type descriptor followed by a
14605 // list of function pointers, one for each interface method. This is used for
14606 // interfaces.
14607 Expression_list* svals = new Expression_list();
14608 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14609
14610 Named_type* nt = this->type_->named_type();
14611 Struct_type* st = this->type_->struct_type();
14612 go_assert(nt != NULL || st != NULL);
14613
14614 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14615 p != interface_methods->end();
14616 ++p)
14617 {
14618 bool is_ambiguous;
14619 Method* m;
14620 if (nt != NULL)
14621 m = nt->method_function(p->name(), &is_ambiguous);
14622 else
14623 m = st->method_function(p->name(), &is_ambiguous);
14624 go_assert(m != NULL);
14625 Named_object* no = m->named_object();
14626
14627 go_assert(no->is_function() || no->is_function_declaration());
14628 svals->push_back(Expression::make_func_code_reference(no, loc));
14629 }
14630
14631 Btype* btype = this->type()->get_backend(gogo);
14632 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14633 svals, loc);
ea664253 14634 Bexpression* ctor = mtable->get_backend(context);
2c809f8f 14635
14636 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14637 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14638 !is_public, btype, loc);
14639 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14640 !is_public, btype, loc, ctor);
ea664253 14641 return gogo->backend()->var_expression(this->bvar_, loc);
2c809f8f 14642}
14643
14644void
14645Interface_mtable_expression::do_dump_expression(
14646 Ast_dump_context* ast_dump_context) const
14647{
14648 ast_dump_context->ostream() << "__go_"
14649 << (this->is_pointer_ ? "pimt__" : "imt_");
14650 ast_dump_context->dump_type(this->itype_);
14651 ast_dump_context->ostream() << "__";
14652 ast_dump_context->dump_type(this->type_);
14653}
14654
14655Expression*
14656Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14657 bool is_pointer, Location location)
14658{
14659 return new Interface_mtable_expression(itype, type, is_pointer, location);
14660}
14661
e440a328 14662// An expression which evaluates to the offset of a field within a
14663// struct. This, like Type_info_expression, q.v., is only used to
14664// initialize fields of a type descriptor.
14665
14666class Struct_field_offset_expression : public Expression
14667{
14668 public:
14669 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
b13c66cd 14670 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14671 Linemap::predeclared_location()),
e440a328 14672 type_(type), field_(field)
14673 { }
14674
14675 protected:
f23d7786 14676 bool
14677 do_is_immutable() const
14678 { return true; }
14679
e440a328 14680 Type*
14681 do_type()
14682 { return Type::lookup_integer_type("uintptr"); }
14683
14684 void
14685 do_determine_type(const Type_context*)
14686 { }
14687
14688 Expression*
14689 do_copy()
14690 { return this; }
14691
ea664253 14692 Bexpression*
14693 do_get_backend(Translate_context* context);
e440a328 14694
d751bb78 14695 void
14696 do_dump_expression(Ast_dump_context*) const;
14697
e440a328 14698 private:
14699 // The type of the struct.
14700 Struct_type* type_;
14701 // The field.
14702 const Struct_field* field_;
14703};
14704
ea664253 14705// Return the backend representation for a struct field offset.
e440a328 14706
ea664253 14707Bexpression*
14708Struct_field_offset_expression::do_get_backend(Translate_context* context)
e440a328 14709{
e440a328 14710 const Struct_field_list* fields = this->type_->fields();
e440a328 14711 Struct_field_list::const_iterator p;
2c8bda43 14712 unsigned i = 0;
e440a328 14713 for (p = fields->begin();
14714 p != fields->end();
2c8bda43 14715 ++p, ++i)
14716 if (&*p == this->field_)
14717 break;
c484d925 14718 go_assert(&*p == this->field_);
e440a328 14719
2c8bda43 14720 Gogo* gogo = context->gogo();
14721 Btype* btype = this->type_->get_backend(gogo);
14722
14723 size_t offset = gogo->backend()->type_field_offset(btype, i);
2c8bda43 14724 Type* uptr_type = Type::lookup_integer_type("uintptr");
e67508fa 14725 Expression* ret =
14726 Expression::make_integer_ul(offset, uptr_type,
14727 Linemap::predeclared_location());
ea664253 14728 return ret->get_backend(context);
e440a328 14729}
14730
d751bb78 14731// Dump ast representation for a struct field offset expression.
14732
14733void
14734Struct_field_offset_expression::do_dump_expression(
14735 Ast_dump_context* ast_dump_context) const
14736{
14737 ast_dump_context->ostream() << "unsafe.Offsetof(";
2d29d278 14738 ast_dump_context->dump_type(this->type_);
14739 ast_dump_context->ostream() << '.';
14740 ast_dump_context->ostream() <<
14741 Gogo::message_name(this->field_->field_name());
d751bb78 14742 ast_dump_context->ostream() << ")";
14743}
14744
e440a328 14745// Make an expression for a struct field offset.
14746
14747Expression*
14748Expression::make_struct_field_offset(Struct_type* type,
14749 const Struct_field* field)
14750{
14751 return new Struct_field_offset_expression(type, field);
14752}
14753
a9182619 14754// An expression which evaluates to a pointer to the map descriptor of
14755// a map type.
14756
14757class Map_descriptor_expression : public Expression
14758{
14759 public:
b13c66cd 14760 Map_descriptor_expression(Map_type* type, Location location)
a9182619 14761 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14762 type_(type)
14763 { }
14764
14765 protected:
14766 Type*
14767 do_type()
14768 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14769
14770 void
14771 do_determine_type(const Type_context*)
14772 { }
14773
14774 Expression*
14775 do_copy()
14776 { return this; }
14777
ea664253 14778 Bexpression*
14779 do_get_backend(Translate_context* context)
a9182619 14780 {
ea664253 14781 return this->type_->map_descriptor_pointer(context->gogo(),
14782 this->location());
a9182619 14783 }
14784
d751bb78 14785 void
14786 do_dump_expression(Ast_dump_context*) const;
14787
a9182619 14788 private:
14789 // The type for which this is the descriptor.
14790 Map_type* type_;
14791};
14792
d751bb78 14793// Dump ast representation for a map descriptor expression.
14794
14795void
14796Map_descriptor_expression::do_dump_expression(
14797 Ast_dump_context* ast_dump_context) const
14798{
14799 ast_dump_context->ostream() << "map_descriptor(";
14800 ast_dump_context->dump_type(this->type_);
14801 ast_dump_context->ostream() << ")";
14802}
14803
a9182619 14804// Make a map descriptor expression.
14805
14806Expression*
b13c66cd 14807Expression::make_map_descriptor(Map_type* type, Location location)
a9182619 14808{
14809 return new Map_descriptor_expression(type, location);
14810}
14811
e440a328 14812// An expression which evaluates to the address of an unnamed label.
14813
14814class Label_addr_expression : public Expression
14815{
14816 public:
b13c66cd 14817 Label_addr_expression(Label* label, Location location)
e440a328 14818 : Expression(EXPRESSION_LABEL_ADDR, location),
14819 label_(label)
14820 { }
14821
14822 protected:
14823 Type*
14824 do_type()
14825 { return Type::make_pointer_type(Type::make_void_type()); }
14826
14827 void
14828 do_determine_type(const Type_context*)
14829 { }
14830
14831 Expression*
14832 do_copy()
14833 { return new Label_addr_expression(this->label_, this->location()); }
14834
ea664253 14835 Bexpression*
14836 do_get_backend(Translate_context* context)
14837 { return this->label_->get_addr(context, this->location()); }
e440a328 14838
d751bb78 14839 void
14840 do_dump_expression(Ast_dump_context* ast_dump_context) const
14841 { ast_dump_context->ostream() << this->label_->name(); }
14842
e440a328 14843 private:
14844 // The label whose address we are taking.
14845 Label* label_;
14846};
14847
14848// Make an expression for the address of an unnamed label.
14849
14850Expression*
b13c66cd 14851Expression::make_label_addr(Label* label, Location location)
e440a328 14852{
14853 return new Label_addr_expression(label, location);
14854}
14855
283a177b 14856// Conditional expressions.
14857
14858class Conditional_expression : public Expression
14859{
14860 public:
14861 Conditional_expression(Expression* cond, Expression* then_expr,
14862 Expression* else_expr, Location location)
14863 : Expression(EXPRESSION_CONDITIONAL, location),
14864 cond_(cond), then_(then_expr), else_(else_expr)
14865 {}
14866
14867 protected:
2c809f8f 14868 int
14869 do_traverse(Traverse*);
14870
283a177b 14871 Type*
14872 do_type();
14873
14874 void
2c809f8f 14875 do_determine_type(const Type_context*);
283a177b 14876
14877 Expression*
14878 do_copy()
14879 {
14880 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
14881 this->else_->copy(), this->location());
14882 }
14883
ea664253 14884 Bexpression*
14885 do_get_backend(Translate_context* context);
283a177b 14886
14887 void
14888 do_dump_expression(Ast_dump_context*) const;
14889
14890 private:
14891 // The condition to be checked.
14892 Expression* cond_;
14893 // The expression to execute if the condition is true.
14894 Expression* then_;
14895 // The expression to execute if the condition is false.
14896 Expression* else_;
14897};
14898
2c809f8f 14899// Traversal.
14900
14901int
14902Conditional_expression::do_traverse(Traverse* traverse)
14903{
14904 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14905 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14906 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14907 return TRAVERSE_EXIT;
14908 return TRAVERSE_CONTINUE;
14909}
14910
283a177b 14911// Return the type of the conditional expression.
14912
14913Type*
14914Conditional_expression::do_type()
14915{
14916 Type* result_type = Type::make_void_type();
2c809f8f 14917 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
14918 NULL))
283a177b 14919 result_type = this->then_->type();
14920 else if (this->then_->is_nil_expression()
14921 || this->else_->is_nil_expression())
14922 result_type = (!this->then_->is_nil_expression()
14923 ? this->then_->type()
14924 : this->else_->type());
14925 return result_type;
14926}
14927
2c809f8f 14928// Determine type for a conditional expression.
14929
14930void
14931Conditional_expression::do_determine_type(const Type_context* context)
14932{
14933 this->cond_->determine_type_no_context();
14934 this->then_->determine_type(context);
14935 this->else_->determine_type(context);
14936}
14937
283a177b 14938// Get the backend representation of a conditional expression.
14939
ea664253 14940Bexpression*
14941Conditional_expression::do_get_backend(Translate_context* context)
283a177b 14942{
14943 Gogo* gogo = context->gogo();
14944 Btype* result_btype = this->type()->get_backend(gogo);
ea664253 14945 Bexpression* cond = this->cond_->get_backend(context);
14946 Bexpression* then = this->then_->get_backend(context);
14947 Bexpression* belse = this->else_->get_backend(context);
14948 return gogo->backend()->conditional_expression(result_btype, cond, then,
14949 belse, this->location());
283a177b 14950}
14951
14952// Dump ast representation of a conditional expression.
14953
14954void
14955Conditional_expression::do_dump_expression(
14956 Ast_dump_context* ast_dump_context) const
14957{
14958 ast_dump_context->ostream() << "(";
14959 ast_dump_context->dump_expression(this->cond_);
14960 ast_dump_context->ostream() << " ? ";
14961 ast_dump_context->dump_expression(this->then_);
14962 ast_dump_context->ostream() << " : ";
14963 ast_dump_context->dump_expression(this->else_);
14964 ast_dump_context->ostream() << ") ";
14965}
14966
14967// Make a conditional expression.
14968
14969Expression*
14970Expression::make_conditional(Expression* cond, Expression* then,
14971 Expression* else_expr, Location location)
14972{
14973 return new Conditional_expression(cond, then, else_expr, location);
14974}
14975
2c809f8f 14976// Compound expressions.
14977
14978class Compound_expression : public Expression
14979{
14980 public:
14981 Compound_expression(Expression* init, Expression* expr, Location location)
14982 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
14983 {}
14984
14985 protected:
14986 int
14987 do_traverse(Traverse*);
14988
14989 Type*
14990 do_type();
14991
14992 void
14993 do_determine_type(const Type_context*);
14994
14995 Expression*
14996 do_copy()
14997 {
14998 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
14999 this->location());
15000 }
15001
ea664253 15002 Bexpression*
15003 do_get_backend(Translate_context* context);
2c809f8f 15004
15005 void
15006 do_dump_expression(Ast_dump_context*) const;
15007
15008 private:
15009 // The expression that is evaluated first and discarded.
15010 Expression* init_;
15011 // The expression that is evaluated and returned.
15012 Expression* expr_;
15013};
15014
15015// Traversal.
15016
15017int
15018Compound_expression::do_traverse(Traverse* traverse)
15019{
15020 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15021 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15022 return TRAVERSE_EXIT;
15023 return TRAVERSE_CONTINUE;
15024}
15025
15026// Return the type of the compound expression.
15027
15028Type*
15029Compound_expression::do_type()
15030{
15031 return this->expr_->type();
15032}
15033
15034// Determine type for a compound expression.
15035
15036void
15037Compound_expression::do_determine_type(const Type_context* context)
15038{
15039 this->init_->determine_type_no_context();
15040 this->expr_->determine_type(context);
15041}
15042
15043// Get the backend representation of a compound expression.
15044
ea664253 15045Bexpression*
15046Compound_expression::do_get_backend(Translate_context* context)
2c809f8f 15047{
15048 Gogo* gogo = context->gogo();
ea664253 15049 Bexpression* binit = this->init_->get_backend(context);
2c809f8f 15050 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
ea664253 15051 Bexpression* bexpr = this->expr_->get_backend(context);
15052 return gogo->backend()->compound_expression(init_stmt, bexpr,
15053 this->location());
2c809f8f 15054}
15055
15056// Dump ast representation of a conditional expression.
15057
15058void
15059Compound_expression::do_dump_expression(
15060 Ast_dump_context* ast_dump_context) const
15061{
15062 ast_dump_context->ostream() << "(";
15063 ast_dump_context->dump_expression(this->init_);
15064 ast_dump_context->ostream() << ",";
15065 ast_dump_context->dump_expression(this->expr_);
15066 ast_dump_context->ostream() << ") ";
15067}
15068
15069// Make a compound expression.
15070
15071Expression*
15072Expression::make_compound(Expression* init, Expression* expr, Location location)
15073{
15074 return new Compound_expression(init, expr, location);
15075}
15076
e440a328 15077// Import an expression. This comes at the end in order to see the
15078// various class definitions.
15079
15080Expression*
15081Expression::import_expression(Import* imp)
15082{
15083 int c = imp->peek_char();
15084 if (imp->match_c_string("- ")
15085 || imp->match_c_string("! ")
15086 || imp->match_c_string("^ "))
15087 return Unary_expression::do_import(imp);
15088 else if (c == '(')
15089 return Binary_expression::do_import(imp);
15090 else if (imp->match_c_string("true")
15091 || imp->match_c_string("false"))
15092 return Boolean_expression::do_import(imp);
15093 else if (c == '"')
15094 return String_expression::do_import(imp);
15095 else if (c == '-' || (c >= '0' && c <= '9'))
15096 {
15097 // This handles integers, floats and complex constants.
15098 return Integer_expression::do_import(imp);
15099 }
15100 else if (imp->match_c_string("nil"))
15101 return Nil_expression::do_import(imp);
15102 else if (imp->match_c_string("convert"))
15103 return Type_conversion_expression::do_import(imp);
15104 else
15105 {
15106 error_at(imp->location(), "import error: expected expression");
15107 return Expression::make_error(imp->location());
15108 }
15109}
15110
15111// Class Expression_list.
15112
15113// Traverse the list.
15114
15115int
15116Expression_list::traverse(Traverse* traverse)
15117{
15118 for (Expression_list::iterator p = this->begin();
15119 p != this->end();
15120 ++p)
15121 {
15122 if (*p != NULL)
15123 {
15124 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15125 return TRAVERSE_EXIT;
15126 }
15127 }
15128 return TRAVERSE_CONTINUE;
15129}
15130
15131// Copy the list.
15132
15133Expression_list*
15134Expression_list::copy()
15135{
15136 Expression_list* ret = new Expression_list();
15137 for (Expression_list::iterator p = this->begin();
15138 p != this->end();
15139 ++p)
15140 {
15141 if (*p == NULL)
15142 ret->push_back(NULL);
15143 else
15144 ret->push_back((*p)->copy());
15145 }
15146 return ret;
15147}
15148
15149// Return whether an expression list has an error expression.
15150
15151bool
15152Expression_list::contains_error() const
15153{
15154 for (Expression_list::const_iterator p = this->begin();
15155 p != this->end();
15156 ++p)
15157 if (*p != NULL && (*p)->is_error_expression())
15158 return true;
15159 return false;
15160}
0c77715b 15161
15162// Class Numeric_constant.
15163
15164// Destructor.
15165
15166Numeric_constant::~Numeric_constant()
15167{
15168 this->clear();
15169}
15170
15171// Copy constructor.
15172
15173Numeric_constant::Numeric_constant(const Numeric_constant& a)
15174 : classification_(a.classification_), type_(a.type_)
15175{
15176 switch (a.classification_)
15177 {
15178 case NC_INVALID:
15179 break;
15180 case NC_INT:
15181 case NC_RUNE:
15182 mpz_init_set(this->u_.int_val, a.u_.int_val);
15183 break;
15184 case NC_FLOAT:
15185 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15186 break;
15187 case NC_COMPLEX:
fcbea5e4 15188 mpc_init2(this->u_.complex_val, mpc_precision);
15189 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15190 break;
15191 default:
15192 go_unreachable();
15193 }
15194}
15195
15196// Assignment operator.
15197
15198Numeric_constant&
15199Numeric_constant::operator=(const Numeric_constant& a)
15200{
15201 this->clear();
15202 this->classification_ = a.classification_;
15203 this->type_ = a.type_;
15204 switch (a.classification_)
15205 {
15206 case NC_INVALID:
15207 break;
15208 case NC_INT:
15209 case NC_RUNE:
15210 mpz_init_set(this->u_.int_val, a.u_.int_val);
15211 break;
15212 case NC_FLOAT:
15213 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15214 break;
15215 case NC_COMPLEX:
fcbea5e4 15216 mpc_init2(this->u_.complex_val, mpc_precision);
15217 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
0c77715b 15218 break;
15219 default:
15220 go_unreachable();
15221 }
15222 return *this;
15223}
15224
15225// Clear the contents.
15226
15227void
15228Numeric_constant::clear()
15229{
15230 switch (this->classification_)
15231 {
15232 case NC_INVALID:
15233 break;
15234 case NC_INT:
15235 case NC_RUNE:
15236 mpz_clear(this->u_.int_val);
15237 break;
15238 case NC_FLOAT:
15239 mpfr_clear(this->u_.float_val);
15240 break;
15241 case NC_COMPLEX:
fcbea5e4 15242 mpc_clear(this->u_.complex_val);
0c77715b 15243 break;
15244 default:
15245 go_unreachable();
15246 }
15247 this->classification_ = NC_INVALID;
15248}
15249
15250// Set to an unsigned long value.
15251
15252void
15253Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15254{
15255 this->clear();
15256 this->classification_ = NC_INT;
15257 this->type_ = type;
15258 mpz_init_set_ui(this->u_.int_val, val);
15259}
15260
15261// Set to an integer value.
15262
15263void
15264Numeric_constant::set_int(Type* type, const mpz_t val)
15265{
15266 this->clear();
15267 this->classification_ = NC_INT;
15268 this->type_ = type;
15269 mpz_init_set(this->u_.int_val, val);
15270}
15271
15272// Set to a rune value.
15273
15274void
15275Numeric_constant::set_rune(Type* type, const mpz_t val)
15276{
15277 this->clear();
15278 this->classification_ = NC_RUNE;
15279 this->type_ = type;
15280 mpz_init_set(this->u_.int_val, val);
15281}
15282
15283// Set to a floating point value.
15284
15285void
15286Numeric_constant::set_float(Type* type, const mpfr_t val)
15287{
15288 this->clear();
15289 this->classification_ = NC_FLOAT;
15290 this->type_ = type;
833b523c 15291 // Numeric constants do not have negative zero values, so remove
15292 // them here. They also don't have infinity or NaN values, but we
15293 // should never see them here.
15294 if (mpfr_zero_p(val))
15295 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15296 else
15297 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
0c77715b 15298}
15299
15300// Set to a complex value.
15301
15302void
fcbea5e4 15303Numeric_constant::set_complex(Type* type, const mpc_t val)
0c77715b 15304{
15305 this->clear();
15306 this->classification_ = NC_COMPLEX;
15307 this->type_ = type;
fcbea5e4 15308 mpc_init2(this->u_.complex_val, mpc_precision);
15309 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
0c77715b 15310}
15311
15312// Get an int value.
15313
15314void
15315Numeric_constant::get_int(mpz_t* val) const
15316{
15317 go_assert(this->is_int());
15318 mpz_init_set(*val, this->u_.int_val);
15319}
15320
15321// Get a rune value.
15322
15323void
15324Numeric_constant::get_rune(mpz_t* val) const
15325{
15326 go_assert(this->is_rune());
15327 mpz_init_set(*val, this->u_.int_val);
15328}
15329
15330// Get a floating point value.
15331
15332void
15333Numeric_constant::get_float(mpfr_t* val) const
15334{
15335 go_assert(this->is_float());
15336 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15337}
15338
15339// Get a complex value.
15340
15341void
fcbea5e4 15342Numeric_constant::get_complex(mpc_t* val) const
0c77715b 15343{
15344 go_assert(this->is_complex());
fcbea5e4 15345 mpc_init2(*val, mpc_precision);
15346 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15347}
15348
15349// Express value as unsigned long if possible.
15350
15351Numeric_constant::To_unsigned_long
15352Numeric_constant::to_unsigned_long(unsigned long* val) const
15353{
15354 switch (this->classification_)
15355 {
15356 case NC_INT:
15357 case NC_RUNE:
15358 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15359 case NC_FLOAT:
15360 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15361 case NC_COMPLEX:
fcbea5e4 15362 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15363 return NC_UL_NOTINT;
fcbea5e4 15364 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15365 val);
0c77715b 15366 default:
15367 go_unreachable();
15368 }
15369}
15370
15371// Express integer value as unsigned long if possible.
15372
15373Numeric_constant::To_unsigned_long
15374Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15375 unsigned long *val) const
15376{
15377 if (mpz_sgn(ival) < 0)
15378 return NC_UL_NEGATIVE;
15379 unsigned long ui = mpz_get_ui(ival);
15380 if (mpz_cmp_ui(ival, ui) != 0)
15381 return NC_UL_BIG;
15382 *val = ui;
15383 return NC_UL_VALID;
15384}
15385
15386// Express floating point value as unsigned long if possible.
15387
15388Numeric_constant::To_unsigned_long
15389Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15390 unsigned long *val) const
15391{
15392 if (!mpfr_integer_p(fval))
15393 return NC_UL_NOTINT;
15394 mpz_t ival;
15395 mpz_init(ival);
15396 mpfr_get_z(ival, fval, GMP_RNDN);
15397 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15398 mpz_clear(ival);
15399 return ret;
15400}
15401
15402// Convert value to integer if possible.
15403
15404bool
15405Numeric_constant::to_int(mpz_t* val) const
15406{
15407 switch (this->classification_)
15408 {
15409 case NC_INT:
15410 case NC_RUNE:
15411 mpz_init_set(*val, this->u_.int_val);
15412 return true;
15413 case NC_FLOAT:
15414 if (!mpfr_integer_p(this->u_.float_val))
15415 return false;
15416 mpz_init(*val);
15417 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15418 return true;
15419 case NC_COMPLEX:
fcbea5e4 15420 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15421 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
0c77715b 15422 return false;
15423 mpz_init(*val);
fcbea5e4 15424 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15425 return true;
15426 default:
15427 go_unreachable();
15428 }
15429}
15430
15431// Convert value to floating point if possible.
15432
15433bool
15434Numeric_constant::to_float(mpfr_t* val) const
15435{
15436 switch (this->classification_)
15437 {
15438 case NC_INT:
15439 case NC_RUNE:
15440 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15441 return true;
15442 case NC_FLOAT:
15443 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15444 return true;
15445 case NC_COMPLEX:
fcbea5e4 15446 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15447 return false;
fcbea5e4 15448 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15449 return true;
15450 default:
15451 go_unreachable();
15452 }
15453}
15454
15455// Convert value to complex.
15456
15457bool
fcbea5e4 15458Numeric_constant::to_complex(mpc_t* val) const
0c77715b 15459{
fcbea5e4 15460 mpc_init2(*val, mpc_precision);
0c77715b 15461 switch (this->classification_)
15462 {
15463 case NC_INT:
15464 case NC_RUNE:
fcbea5e4 15465 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
0c77715b 15466 return true;
15467 case NC_FLOAT:
fcbea5e4 15468 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
0c77715b 15469 return true;
15470 case NC_COMPLEX:
fcbea5e4 15471 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15472 return true;
15473 default:
15474 go_unreachable();
15475 }
15476}
15477
15478// Get the type.
15479
15480Type*
15481Numeric_constant::type() const
15482{
15483 if (this->type_ != NULL)
15484 return this->type_;
15485 switch (this->classification_)
15486 {
15487 case NC_INT:
15488 return Type::make_abstract_integer_type();
15489 case NC_RUNE:
15490 return Type::make_abstract_character_type();
15491 case NC_FLOAT:
15492 return Type::make_abstract_float_type();
15493 case NC_COMPLEX:
15494 return Type::make_abstract_complex_type();
15495 default:
15496 go_unreachable();
15497 }
15498}
15499
15500// If the constant can be expressed in TYPE, then set the type of the
15501// constant to TYPE and return true. Otherwise return false, and, if
15502// ISSUE_ERROR is true, report an appropriate error message.
15503
15504bool
15505Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15506{
15507 bool ret;
15508 if (type == NULL)
15509 ret = true;
15510 else if (type->integer_type() != NULL)
15511 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15512 else if (type->float_type() != NULL)
15513 ret = this->check_float_type(type->float_type(), issue_error, loc);
15514 else if (type->complex_type() != NULL)
15515 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15516 else
15517 go_unreachable();
15518 if (ret)
15519 this->type_ = type;
15520 return ret;
15521}
15522
15523// Check whether the constant can be expressed in an integer type.
15524
15525bool
15526Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15527 Location location) const
15528{
15529 mpz_t val;
15530 switch (this->classification_)
15531 {
15532 case NC_INT:
15533 case NC_RUNE:
15534 mpz_init_set(val, this->u_.int_val);
15535 break;
15536
15537 case NC_FLOAT:
15538 if (!mpfr_integer_p(this->u_.float_val))
15539 {
15540 if (issue_error)
15541 error_at(location, "floating point constant truncated to integer");
15542 return false;
15543 }
15544 mpz_init(val);
15545 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15546 break;
15547
15548 case NC_COMPLEX:
fcbea5e4 15549 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15550 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15551 {
15552 if (issue_error)
15553 error_at(location, "complex constant truncated to integer");
15554 return false;
15555 }
15556 mpz_init(val);
fcbea5e4 15557 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15558 break;
15559
15560 default:
15561 go_unreachable();
15562 }
15563
15564 bool ret;
15565 if (type->is_abstract())
15566 ret = true;
15567 else
15568 {
15569 int bits = mpz_sizeinbase(val, 2);
15570 if (type->is_unsigned())
15571 {
15572 // For an unsigned type we can only accept a nonnegative
15573 // number, and we must be able to represents at least BITS.
15574 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15575 }
15576 else
15577 {
15578 // For a signed type we need an extra bit to indicate the
15579 // sign. We have to handle the most negative integer
15580 // specially.
15581 ret = (bits + 1 <= type->bits()
15582 || (bits <= type->bits()
15583 && mpz_sgn(val) < 0
15584 && (mpz_scan1(val, 0)
15585 == static_cast<unsigned long>(type->bits() - 1))
15586 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15587 }
15588 }
15589
15590 if (!ret && issue_error)
15591 error_at(location, "integer constant overflow");
15592
15593 return ret;
15594}
15595
15596// Check whether the constant can be expressed in a floating point
15597// type.
15598
15599bool
15600Numeric_constant::check_float_type(Float_type* type, bool issue_error,
d0bcce51 15601 Location location)
0c77715b 15602{
15603 mpfr_t val;
15604 switch (this->classification_)
15605 {
15606 case NC_INT:
15607 case NC_RUNE:
15608 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15609 break;
15610
15611 case NC_FLOAT:
15612 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15613 break;
15614
15615 case NC_COMPLEX:
fcbea5e4 15616 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
0c77715b 15617 {
15618 if (issue_error)
15619 error_at(location, "complex constant truncated to float");
15620 return false;
15621 }
fcbea5e4 15622 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
0c77715b 15623 break;
15624
15625 default:
15626 go_unreachable();
15627 }
15628
15629 bool ret;
15630 if (type->is_abstract())
15631 ret = true;
15632 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15633 {
15634 // A NaN or Infinity always fits in the range of the type.
15635 ret = true;
15636 }
15637 else
15638 {
15639 mp_exp_t exp = mpfr_get_exp(val);
15640 mp_exp_t max_exp;
15641 switch (type->bits())
15642 {
15643 case 32:
15644 max_exp = 128;
15645 break;
15646 case 64:
15647 max_exp = 1024;
15648 break;
15649 default:
15650 go_unreachable();
15651 }
15652
15653 ret = exp <= max_exp;
d0bcce51 15654
15655 if (ret)
15656 {
15657 // Round the constant to the desired type.
15658 mpfr_t t;
15659 mpfr_init(t);
15660 switch (type->bits())
15661 {
15662 case 32:
15663 mpfr_set_prec(t, 24);
15664 break;
15665 case 64:
15666 mpfr_set_prec(t, 53);
15667 break;
15668 default:
15669 go_unreachable();
15670 }
15671 mpfr_set(t, val, GMP_RNDN);
15672 mpfr_set(val, t, GMP_RNDN);
15673 mpfr_clear(t);
15674
15675 this->set_float(type, val);
15676 }
0c77715b 15677 }
15678
15679 mpfr_clear(val);
15680
15681 if (!ret && issue_error)
15682 error_at(location, "floating point constant overflow");
15683
15684 return ret;
15685}
15686
15687// Check whether the constant can be expressed in a complex type.
15688
15689bool
15690Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
d0bcce51 15691 Location location)
0c77715b 15692{
15693 if (type->is_abstract())
15694 return true;
15695
15696 mp_exp_t max_exp;
15697 switch (type->bits())
15698 {
15699 case 64:
15700 max_exp = 128;
15701 break;
15702 case 128:
15703 max_exp = 1024;
15704 break;
15705 default:
15706 go_unreachable();
15707 }
15708
fcbea5e4 15709 mpc_t val;
15710 mpc_init2(val, mpc_precision);
0c77715b 15711 switch (this->classification_)
15712 {
15713 case NC_INT:
15714 case NC_RUNE:
fcbea5e4 15715 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
0c77715b 15716 break;
15717
15718 case NC_FLOAT:
fcbea5e4 15719 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
0c77715b 15720 break;
15721
15722 case NC_COMPLEX:
fcbea5e4 15723 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
0c77715b 15724 break;
15725
15726 default:
15727 go_unreachable();
15728 }
15729
d0bcce51 15730 bool ret = true;
fcbea5e4 15731 if (!mpfr_nan_p(mpc_realref(val))
15732 && !mpfr_inf_p(mpc_realref(val))
15733 && !mpfr_zero_p(mpc_realref(val))
15734 && mpfr_get_exp(mpc_realref(val)) > max_exp)
d0bcce51 15735 {
15736 if (issue_error)
15737 error_at(location, "complex real part overflow");
15738 ret = false;
15739 }
0c77715b 15740
fcbea5e4 15741 if (!mpfr_nan_p(mpc_imagref(val))
15742 && !mpfr_inf_p(mpc_imagref(val))
15743 && !mpfr_zero_p(mpc_imagref(val))
15744 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
d0bcce51 15745 {
15746 if (issue_error)
15747 error_at(location, "complex imaginary part overflow");
15748 ret = false;
15749 }
0c77715b 15750
d0bcce51 15751 if (ret)
15752 {
15753 // Round the constant to the desired type.
fcbea5e4 15754 mpc_t t;
d0bcce51 15755 switch (type->bits())
15756 {
15757 case 64:
fcbea5e4 15758 mpc_init2(t, 24);
d0bcce51 15759 break;
15760 case 128:
fcbea5e4 15761 mpc_init2(t, 53);
d0bcce51 15762 break;
15763 default:
15764 go_unreachable();
15765 }
fcbea5e4 15766 mpc_set(t, val, MPC_RNDNN);
15767 mpc_set(val, t, MPC_RNDNN);
15768 mpc_clear(t);
d0bcce51 15769
fcbea5e4 15770 this->set_complex(type, val);
d0bcce51 15771 }
15772
fcbea5e4 15773 mpc_clear(val);
0c77715b 15774
15775 return ret;
15776}
15777
15778// Return an Expression for this value.
15779
15780Expression*
15781Numeric_constant::expression(Location loc) const
15782{
15783 switch (this->classification_)
15784 {
15785 case NC_INT:
e67508fa 15786 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
0c77715b 15787 case NC_RUNE:
15788 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15789 case NC_FLOAT:
15790 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15791 case NC_COMPLEX:
fcbea5e4 15792 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
0c77715b 15793 default:
15794 go_unreachable();
15795 }
15796}