OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [gcc/] [go/] [gofrontend/] [expressions.cc] - Blame information for rev 774

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 714 jeremybenn
// expressions.cc -- Go frontend expression handling.
2
 
3
// Copyright 2009 The Go Authors. All rights reserved.
4
// Use of this source code is governed by a BSD-style
5
// license that can be found in the LICENSE file.
6
 
7
#include "go-system.h"
8
 
9
#include <gmp.h>
10
 
11
#ifndef ENABLE_BUILD_WITH_CXX
12
extern "C"
13
{
14
#endif
15
 
16
#include "toplev.h"
17
#include "intl.h"
18
#include "tree.h"
19
#include "gimple.h"
20
#include "tree-iterator.h"
21
#include "convert.h"
22
#include "real.h"
23
#include "realmpfr.h"
24
 
25
#ifndef ENABLE_BUILD_WITH_CXX
26
}
27
#endif
28
 
29
#include "go-c.h"
30
#include "gogo.h"
31
#include "types.h"
32
#include "export.h"
33
#include "import.h"
34
#include "statements.h"
35
#include "lex.h"
36
#include "runtime.h"
37
#include "backend.h"
38
#include "expressions.h"
39
#include "ast-dump.h"
40
 
41
// Class Expression.
42
 
43
Expression::Expression(Expression_classification classification,
44
                       Location location)
45
  : classification_(classification), location_(location)
46
{
47
}
48
 
49
Expression::~Expression()
50
{
51
}
52
 
53
// If this expression has a constant integer value, return it.
54
 
55
bool
56
Expression::integer_constant_value(bool iota_is_constant, mpz_t val,
57
                                   Type** ptype) const
58
{
59
  *ptype = NULL;
60
  return this->do_integer_constant_value(iota_is_constant, val, ptype);
61
}
62
 
63
// If this expression has a constant floating point value, return it.
64
 
65
bool
66
Expression::float_constant_value(mpfr_t val, Type** ptype) const
67
{
68
  *ptype = NULL;
69
  if (this->do_float_constant_value(val, ptype))
70
    return true;
71
  mpz_t ival;
72
  mpz_init(ival);
73
  Type* t;
74
  bool ret;
75
  if (!this->do_integer_constant_value(false, ival, &t))
76
    ret = false;
77
  else
78
    {
79
      mpfr_set_z(val, ival, GMP_RNDN);
80
      ret = true;
81
    }
82
  mpz_clear(ival);
83
  return ret;
84
}
85
 
86
// If this expression has a constant complex value, return it.
87
 
88
bool
89
Expression::complex_constant_value(mpfr_t real, mpfr_t imag,
90
                                   Type** ptype) const
91
{
92
  *ptype = NULL;
93
  if (this->do_complex_constant_value(real, imag, ptype))
94
    return true;
95
  Type *t;
96
  if (this->float_constant_value(real, &t))
97
    {
98
      mpfr_set_ui(imag, 0, GMP_RNDN);
99
      return true;
100
    }
101
  return false;
102
}
103
 
104
// Traverse the expressions.
105
 
106
int
107
Expression::traverse(Expression** pexpr, Traverse* traverse)
108
{
109
  Expression* expr = *pexpr;
110
  if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
111
    {
112
      int t = traverse->expression(pexpr);
113
      if (t == TRAVERSE_EXIT)
114
        return TRAVERSE_EXIT;
115
      else if (t == TRAVERSE_SKIP_COMPONENTS)
116
        return TRAVERSE_CONTINUE;
117
    }
118
  return expr->do_traverse(traverse);
119
}
120
 
121
// Traverse subexpressions of this expression.
122
 
123
int
124
Expression::traverse_subexpressions(Traverse* traverse)
125
{
126
  return this->do_traverse(traverse);
127
}
128
 
129
// Default implementation for do_traverse for child classes.
130
 
131
int
132
Expression::do_traverse(Traverse*)
133
{
134
  return TRAVERSE_CONTINUE;
135
}
136
 
137
// This virtual function is called by the parser if the value of this
138
// expression is being discarded.  By default, we give an error.
139
// Expressions with side effects override.
140
 
141
void
142
Expression::do_discarding_value()
143
{
144
  this->unused_value_error();
145
}
146
 
147
// This virtual function is called to export expressions.  This will
148
// only be used by expressions which may be constant.
149
 
150
void
151
Expression::do_export(Export*) const
152
{
153
  go_unreachable();
154
}
155
 
156
// Give an error saying that the value of the expression is not used.
157
 
158
void
159
Expression::unused_value_error()
160
{
161
  error_at(this->location(), "value computed is not used");
162
}
163
 
164
// Note that this expression is an error.  This is called by children
165
// when they discover an error.
166
 
167
void
168
Expression::set_is_error()
169
{
170
  this->classification_ = EXPRESSION_ERROR;
171
}
172
 
173
// For children to call to report an error conveniently.
174
 
175
void
176
Expression::report_error(const char* msg)
177
{
178
  error_at(this->location_, "%s", msg);
179
  this->set_is_error();
180
}
181
 
182
// Set types of variables and constants.  This is implemented by the
183
// child class.
184
 
185
void
186
Expression::determine_type(const Type_context* context)
187
{
188
  this->do_determine_type(context);
189
}
190
 
191
// Set types when there is no context.
192
 
193
void
194
Expression::determine_type_no_context()
195
{
196
  Type_context context;
197
  this->do_determine_type(&context);
198
}
199
 
200
// Return a tree handling any conversions which must be done during
201
// assignment.
202
 
203
tree
204
Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
205
                                   Type* rhs_type, tree rhs_tree,
206
                                   Location location)
207
{
208
  if (lhs_type == rhs_type)
209
    return rhs_tree;
210
 
211
  if (lhs_type->is_error() || rhs_type->is_error())
212
    return error_mark_node;
213
 
214
  if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
215
    return error_mark_node;
216
 
217
  Gogo* gogo = context->gogo();
218
 
219
  tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
220
  if (lhs_type_tree == error_mark_node)
221
    return error_mark_node;
222
 
223
  if (lhs_type->interface_type() != NULL)
224
    {
225
      if (rhs_type->interface_type() == NULL)
226
        return Expression::convert_type_to_interface(context, lhs_type,
227
                                                     rhs_type, rhs_tree,
228
                                                     location);
229
      else
230
        return Expression::convert_interface_to_interface(context, lhs_type,
231
                                                          rhs_type, rhs_tree,
232
                                                          false, location);
233
    }
234
  else if (rhs_type->interface_type() != NULL)
235
    return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
236
                                                 rhs_tree, location);
237
  else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
238
    {
239
      // Assigning nil to an open array.
240
      go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
241
 
242
      VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
243
 
244
      constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
245
      tree field = TYPE_FIELDS(lhs_type_tree);
246
      go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
247
                        "__values") == 0);
248
      elt->index = field;
249
      elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
250
 
251
      elt = VEC_quick_push(constructor_elt, init, NULL);
252
      field = DECL_CHAIN(field);
253
      go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
254
                        "__count") == 0);
255
      elt->index = field;
256
      elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
257
 
258
      elt = VEC_quick_push(constructor_elt, init, NULL);
259
      field = DECL_CHAIN(field);
260
      go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
261
                        "__capacity") == 0);
262
      elt->index = field;
263
      elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
264
 
265
      tree val = build_constructor(lhs_type_tree, init);
266
      TREE_CONSTANT(val) = 1;
267
 
268
      return val;
269
    }
270
  else if (rhs_type->is_nil_type())
271
    {
272
      // The left hand side should be a pointer type at the tree
273
      // level.
274
      go_assert(POINTER_TYPE_P(lhs_type_tree));
275
      return fold_convert(lhs_type_tree, null_pointer_node);
276
    }
277
  else if (lhs_type_tree == TREE_TYPE(rhs_tree))
278
    {
279
      // No conversion is needed.
280
      return rhs_tree;
281
    }
282
  else if (POINTER_TYPE_P(lhs_type_tree)
283
           || INTEGRAL_TYPE_P(lhs_type_tree)
284
           || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
285
           || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
286
    return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
287
  else if (TREE_CODE(lhs_type_tree) == RECORD_TYPE
288
           && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
289
    {
290
      // This conversion must be permitted by Go, or we wouldn't have
291
      // gotten here.
292
      go_assert(int_size_in_bytes(lhs_type_tree)
293
                 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
294
      return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
295
                             lhs_type_tree, rhs_tree);
296
    }
297
  else
298
    {
299
      go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
300
      return rhs_tree;
301
    }
302
}
303
 
304
// Return a tree for a conversion from a non-interface type to an
305
// interface type.
306
 
307
tree
308
Expression::convert_type_to_interface(Translate_context* context,
309
                                      Type* lhs_type, Type* rhs_type,
310
                                      tree rhs_tree, Location location)
311
{
312
  Gogo* gogo = context->gogo();
313
  Interface_type* lhs_interface_type = lhs_type->interface_type();
314
  bool lhs_is_empty = lhs_interface_type->is_empty();
315
 
316
  // Since RHS_TYPE is a static type, we can create the interface
317
  // method table at compile time.
318
 
319
  // When setting an interface to nil, we just set both fields to
320
  // NULL.
321
  if (rhs_type->is_nil_type())
322
    {
323
      Btype* lhs_btype = lhs_type->get_backend(gogo);
324
      return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
325
    }
326
 
327
  // This should have been checked already.
328
  go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
329
 
330
  tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
331
  if (lhs_type_tree == error_mark_node)
332
    return error_mark_node;
333
 
334
  // An interface is a tuple.  If LHS_TYPE is an empty interface type,
335
  // then the first field is the type descriptor for RHS_TYPE.
336
  // Otherwise it is the interface method table for RHS_TYPE.
337
  tree first_field_value;
338
  if (lhs_is_empty)
339
    first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
340
  else
341
    {
342
      // Build the interface method table for this interface and this
343
      // object type: a list of function pointers for each interface
344
      // method.
345
      Named_type* rhs_named_type = rhs_type->named_type();
346
      bool is_pointer = false;
347
      if (rhs_named_type == NULL)
348
        {
349
          rhs_named_type = rhs_type->deref()->named_type();
350
          is_pointer = true;
351
        }
352
      tree method_table;
353
      if (rhs_named_type == NULL)
354
        method_table = null_pointer_node;
355
      else
356
        method_table =
357
          rhs_named_type->interface_method_table(gogo, lhs_interface_type,
358
                                                 is_pointer);
359
      first_field_value = fold_convert_loc(location.gcc_location(),
360
                                           const_ptr_type_node, method_table);
361
    }
362
  if (first_field_value == error_mark_node)
363
    return error_mark_node;
364
 
365
  // Start building a constructor for the value we will return.
366
 
367
  VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
368
 
369
  constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
370
  tree field = TYPE_FIELDS(lhs_type_tree);
371
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
372
                    (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
373
  elt->index = field;
374
  elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
375
                                first_field_value);
376
 
377
  elt = VEC_quick_push(constructor_elt, init, NULL);
378
  field = DECL_CHAIN(field);
379
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
380
  elt->index = field;
381
 
382
  if (rhs_type->points_to() != NULL)
383
    {
384
      //  We are assigning a pointer to the interface; the interface
385
      // holds the pointer itself.
386
      elt->value = rhs_tree;
387
      return build_constructor(lhs_type_tree, init);
388
    }
389
 
390
  // We are assigning a non-pointer value to the interface; the
391
  // interface gets a copy of the value in the heap.
392
 
393
  tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
394
 
395
  tree space = gogo->allocate_memory(rhs_type, object_size, location);
396
  space = fold_convert_loc(location.gcc_location(),
397
                           build_pointer_type(TREE_TYPE(rhs_tree)), space);
398
  space = save_expr(space);
399
 
400
  tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
401
  TREE_THIS_NOTRAP(ref) = 1;
402
  tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
403
                             void_type_node, ref, rhs_tree);
404
 
405
  elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
406
                                space);
407
 
408
  return build2(COMPOUND_EXPR, lhs_type_tree, set,
409
                build_constructor(lhs_type_tree, init));
410
}
411
 
412
// Return a tree for the type descriptor of RHS_TREE, which has
413
// interface type RHS_TYPE.  If RHS_TREE is nil the result will be
414
// NULL.
415
 
416
tree
417
Expression::get_interface_type_descriptor(Translate_context*,
418
                                          Type* rhs_type, tree rhs_tree,
419
                                          Location location)
420
{
421
  tree rhs_type_tree = TREE_TYPE(rhs_tree);
422
  go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
423
  tree rhs_field = TYPE_FIELDS(rhs_type_tree);
424
  tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
425
                  NULL_TREE);
426
  if (rhs_type->interface_type()->is_empty())
427
    {
428
      go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
429
                        "__type_descriptor") == 0);
430
      return v;
431
    }
432
 
433
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
434
             == 0);
435
  go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
436
  v = save_expr(v);
437
  tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
438
  go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
439
  tree f = TYPE_FIELDS(TREE_TYPE(v1));
440
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
441
             == 0);
442
  v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
443
 
444
  tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
445
                            v, fold_convert_loc(location.gcc_location(),
446
                                                TREE_TYPE(v),
447
                                                null_pointer_node));
448
  tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
449
                            null_pointer_node);
450
  return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
451
                         eq, n, v1);
452
}
453
 
454
// Return a tree for the conversion of an interface type to an
455
// interface type.
456
 
457
tree
458
Expression::convert_interface_to_interface(Translate_context* context,
459
                                           Type *lhs_type, Type *rhs_type,
460
                                           tree rhs_tree, bool for_type_guard,
461
                                           Location location)
462
{
463
  Gogo* gogo = context->gogo();
464
  Interface_type* lhs_interface_type = lhs_type->interface_type();
465
  bool lhs_is_empty = lhs_interface_type->is_empty();
466
 
467
  tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
468
  if (lhs_type_tree == error_mark_node)
469
    return error_mark_node;
470
 
471
  // In the general case this requires runtime examination of the type
472
  // method table to match it up with the interface methods.
473
 
474
  // FIXME: If all of the methods in the right hand side interface
475
  // also appear in the left hand side interface, then we don't need
476
  // to do a runtime check, although we still need to build a new
477
  // method table.
478
 
479
  // Get the type descriptor for the right hand side.  This will be
480
  // NULL for a nil interface.
481
 
482
  if (!DECL_P(rhs_tree))
483
    rhs_tree = save_expr(rhs_tree);
484
 
485
  tree rhs_type_descriptor =
486
    Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
487
                                              location);
488
 
489
  // The result is going to be a two element constructor.
490
 
491
  VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
492
 
493
  constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
494
  tree field = TYPE_FIELDS(lhs_type_tree);
495
  elt->index = field;
496
 
497
  if (for_type_guard)
498
    {
499
      // A type assertion fails when converting a nil interface.
500
      tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
501
                                                                   location);
502
      static tree assert_interface_decl;
503
      tree call = Gogo::call_builtin(&assert_interface_decl,
504
                                     location,
505
                                     "__go_assert_interface",
506
                                     2,
507
                                     ptr_type_node,
508
                                     TREE_TYPE(lhs_type_descriptor),
509
                                     lhs_type_descriptor,
510
                                     TREE_TYPE(rhs_type_descriptor),
511
                                     rhs_type_descriptor);
512
      if (call == error_mark_node)
513
        return error_mark_node;
514
      // This will panic if the interface conversion fails.
515
      TREE_NOTHROW(assert_interface_decl) = 0;
516
      elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
517
                                    call);
518
    }
519
  else if (lhs_is_empty)
520
    {
521
      // A convertion to an empty interface always succeeds, and the
522
      // first field is just the type descriptor of the object.
523
      go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
524
                        "__type_descriptor") == 0);
525
      elt->value = fold_convert_loc(location.gcc_location(),
526
                                    TREE_TYPE(field), rhs_type_descriptor);
527
    }
528
  else
529
    {
530
      // A conversion to a non-empty interface may fail, but unlike a
531
      // type assertion converting nil will always succeed.
532
      go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
533
                 == 0);
534
      tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
535
                                                                   location);
536
      static tree convert_interface_decl;
537
      tree call = Gogo::call_builtin(&convert_interface_decl,
538
                                     location,
539
                                     "__go_convert_interface",
540
                                     2,
541
                                     ptr_type_node,
542
                                     TREE_TYPE(lhs_type_descriptor),
543
                                     lhs_type_descriptor,
544
                                     TREE_TYPE(rhs_type_descriptor),
545
                                     rhs_type_descriptor);
546
      if (call == error_mark_node)
547
        return error_mark_node;
548
      // This will panic if the interface conversion fails.
549
      TREE_NOTHROW(convert_interface_decl) = 0;
550
      elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
551
                                    call);
552
    }
553
 
554
  // The second field is simply the object pointer.
555
 
556
  elt = VEC_quick_push(constructor_elt, init, NULL);
557
  field = DECL_CHAIN(field);
558
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
559
  elt->index = field;
560
 
561
  tree rhs_type_tree = TREE_TYPE(rhs_tree);
562
  go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
563
  tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
564
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
565
  elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
566
                      NULL_TREE);
567
 
568
  return build_constructor(lhs_type_tree, init);
569
}
570
 
571
// Return a tree for the conversion of an interface type to a
572
// non-interface type.
573
 
574
tree
575
Expression::convert_interface_to_type(Translate_context* context,
576
                                      Type *lhs_type, Type* rhs_type,
577
                                      tree rhs_tree, Location location)
578
{
579
  Gogo* gogo = context->gogo();
580
  tree rhs_type_tree = TREE_TYPE(rhs_tree);
581
 
582
  tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
583
  if (lhs_type_tree == error_mark_node)
584
    return error_mark_node;
585
 
586
  // Call a function to check that the type is valid.  The function
587
  // will panic with an appropriate runtime type error if the type is
588
  // not valid.
589
 
590
  tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
591
 
592
  if (!DECL_P(rhs_tree))
593
    rhs_tree = save_expr(rhs_tree);
594
 
595
  tree rhs_type_descriptor =
596
    Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
597
                                              location);
598
 
599
  tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
600
                                                                location);
601
 
602
  static tree check_interface_type_decl;
603
  tree call = Gogo::call_builtin(&check_interface_type_decl,
604
                                 location,
605
                                 "__go_check_interface_type",
606
                                 3,
607
                                 void_type_node,
608
                                 TREE_TYPE(lhs_type_descriptor),
609
                                 lhs_type_descriptor,
610
                                 TREE_TYPE(rhs_type_descriptor),
611
                                 rhs_type_descriptor,
612
                                 TREE_TYPE(rhs_inter_descriptor),
613
                                 rhs_inter_descriptor);
614
  if (call == error_mark_node)
615
    return error_mark_node;
616
  // This call will panic if the conversion is invalid.
617
  TREE_NOTHROW(check_interface_type_decl) = 0;
618
 
619
  // If the call succeeds, pull out the value.
620
  go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
621
  tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
622
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
623
  tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
624
                    NULL_TREE);
625
 
626
  // If the value is a pointer, then it is the value we want.
627
  // Otherwise it points to the value.
628
  if (lhs_type->points_to() == NULL)
629
    {
630
      val = fold_convert_loc(location.gcc_location(),
631
                             build_pointer_type(lhs_type_tree), val);
632
      val = build_fold_indirect_ref_loc(location.gcc_location(), val);
633
    }
634
 
635
  return build2(COMPOUND_EXPR, lhs_type_tree, call,
636
                fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
637
}
638
 
639
// Convert an expression to a tree.  This is implemented by the child
640
// class.  Not that it is not in general safe to call this multiple
641
// times for a single expression, but that we don't catch such errors.
642
 
643
tree
644
Expression::get_tree(Translate_context* context)
645
{
646
  // The child may have marked this expression as having an error.
647
  if (this->classification_ == EXPRESSION_ERROR)
648
    return error_mark_node;
649
 
650
  return this->do_get_tree(context);
651
}
652
 
653
// Return a tree for VAL in TYPE.
654
 
655
tree
656
Expression::integer_constant_tree(mpz_t val, tree type)
657
{
658
  if (type == error_mark_node)
659
    return error_mark_node;
660
  else if (TREE_CODE(type) == INTEGER_TYPE)
661
    return double_int_to_tree(type,
662
                              mpz_get_double_int(type, val, true));
663
  else if (TREE_CODE(type) == REAL_TYPE)
664
    {
665
      mpfr_t fval;
666
      mpfr_init_set_z(fval, val, GMP_RNDN);
667
      tree ret = Expression::float_constant_tree(fval, type);
668
      mpfr_clear(fval);
669
      return ret;
670
    }
671
  else if (TREE_CODE(type) == COMPLEX_TYPE)
672
    {
673
      mpfr_t fval;
674
      mpfr_init_set_z(fval, val, GMP_RNDN);
675
      tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
676
      mpfr_clear(fval);
677
      tree imag = build_real_from_int_cst(TREE_TYPE(type),
678
                                          integer_zero_node);
679
      return build_complex(type, real, imag);
680
    }
681
  else
682
    go_unreachable();
683
}
684
 
685
// Return a tree for VAL in TYPE.
686
 
687
tree
688
Expression::float_constant_tree(mpfr_t val, tree type)
689
{
690
  if (type == error_mark_node)
691
    return error_mark_node;
692
  else if (TREE_CODE(type) == INTEGER_TYPE)
693
    {
694
      mpz_t ival;
695
      mpz_init(ival);
696
      mpfr_get_z(ival, val, GMP_RNDN);
697
      tree ret = Expression::integer_constant_tree(ival, type);
698
      mpz_clear(ival);
699
      return ret;
700
    }
701
  else if (TREE_CODE(type) == REAL_TYPE)
702
    {
703
      REAL_VALUE_TYPE r1;
704
      real_from_mpfr(&r1, val, type, GMP_RNDN);
705
      REAL_VALUE_TYPE r2;
706
      real_convert(&r2, TYPE_MODE(type), &r1);
707
      return build_real(type, r2);
708
    }
709
  else if (TREE_CODE(type) == COMPLEX_TYPE)
710
    {
711
      REAL_VALUE_TYPE r1;
712
      real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
713
      REAL_VALUE_TYPE r2;
714
      real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
715
      tree imag = build_real_from_int_cst(TREE_TYPE(type),
716
                                          integer_zero_node);
717
      return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
718
    }
719
  else
720
    go_unreachable();
721
}
722
 
723
// Return a tree for REAL/IMAG in TYPE.
724
 
725
tree
726
Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
727
{
728
  if (type == error_mark_node)
729
    return error_mark_node;
730
  else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
731
    return Expression::float_constant_tree(real, type);
732
  else if (TREE_CODE(type) == COMPLEX_TYPE)
733
    {
734
      REAL_VALUE_TYPE r1;
735
      real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
736
      REAL_VALUE_TYPE r2;
737
      real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
738
 
739
      REAL_VALUE_TYPE r3;
740
      real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
741
      REAL_VALUE_TYPE r4;
742
      real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
743
 
744
      return build_complex(type, build_real(TREE_TYPE(type), r2),
745
                           build_real(TREE_TYPE(type), r4));
746
    }
747
  else
748
    go_unreachable();
749
}
750
 
751
// Return a tree which evaluates to true if VAL, of arbitrary integer
752
// type, is negative or is more than the maximum value of BOUND_TYPE.
753
// If SOFAR is not NULL, it is or'red into the result.  The return
754
// value may be NULL if SOFAR is NULL.
755
 
756
tree
757
Expression::check_bounds(tree val, tree bound_type, tree sofar,
758
                         Location loc)
759
{
760
  tree val_type = TREE_TYPE(val);
761
  tree ret = NULL_TREE;
762
 
763
  if (!TYPE_UNSIGNED(val_type))
764
    {
765
      ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
766
                            build_int_cst(val_type, 0));
767
      if (ret == boolean_false_node)
768
        ret = NULL_TREE;
769
    }
770
 
771
  HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
772
  HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
773
  go_assert(val_type_size != -1 && bound_type_size != -1);
774
  if (val_type_size > bound_type_size
775
      || (val_type_size == bound_type_size
776
          && TYPE_UNSIGNED(val_type)
777
          && !TYPE_UNSIGNED(bound_type)))
778
    {
779
      tree max = TYPE_MAX_VALUE(bound_type);
780
      tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
781
                                 val, fold_convert_loc(loc.gcc_location(),
782
                                                       val_type, max));
783
      if (big == boolean_false_node)
784
        ;
785
      else if (ret == NULL_TREE)
786
        ret = big;
787
      else
788
        ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
789
                              boolean_type_node, ret, big);
790
    }
791
 
792
  if (ret == NULL_TREE)
793
    return sofar;
794
  else if (sofar == NULL_TREE)
795
    return ret;
796
  else
797
    return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
798
                           sofar, ret);
799
}
800
 
801
void
802
Expression::dump_expression(Ast_dump_context* ast_dump_context) const
803
{
804
  this->do_dump_expression(ast_dump_context);
805
}
806
 
807
// Error expressions.  This are used to avoid cascading errors.
808
 
809
class Error_expression : public Expression
810
{
811
 public:
812
  Error_expression(Location location)
813
    : Expression(EXPRESSION_ERROR, location)
814
  { }
815
 
816
 protected:
817
  bool
818
  do_is_constant() const
819
  { return true; }
820
 
821
  bool
822
  do_integer_constant_value(bool, mpz_t val, Type**) const
823
  {
824
    mpz_set_ui(val, 0);
825
    return true;
826
  }
827
 
828
  bool
829
  do_float_constant_value(mpfr_t val, Type**) const
830
  {
831
    mpfr_set_ui(val, 0, GMP_RNDN);
832
    return true;
833
  }
834
 
835
  bool
836
  do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const
837
  {
838
    mpfr_set_ui(real, 0, GMP_RNDN);
839
    mpfr_set_ui(imag, 0, GMP_RNDN);
840
    return true;
841
  }
842
 
843
  void
844
  do_discarding_value()
845
  { }
846
 
847
  Type*
848
  do_type()
849
  { return Type::make_error_type(); }
850
 
851
  void
852
  do_determine_type(const Type_context*)
853
  { }
854
 
855
  Expression*
856
  do_copy()
857
  { return this; }
858
 
859
  bool
860
  do_is_addressable() const
861
  { return true; }
862
 
863
  tree
864
  do_get_tree(Translate_context*)
865
  { return error_mark_node; }
866
 
867
  void
868
  do_dump_expression(Ast_dump_context*) const;
869
};
870
 
871
// Dump the ast representation for an error expression to a dump context.
872
 
873
void
874
Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
875
{
876
  ast_dump_context->ostream() << "_Error_" ;
877
}
878
 
879
Expression*
880
Expression::make_error(Location location)
881
{
882
  return new Error_expression(location);
883
}
884
 
885
// An expression which is really a type.  This is used during parsing.
886
// It is an error if these survive after lowering.
887
 
888
class
889
Type_expression : public Expression
890
{
891
 public:
892
  Type_expression(Type* type, Location location)
893
    : Expression(EXPRESSION_TYPE, location),
894
      type_(type)
895
  { }
896
 
897
 protected:
898
  int
899
  do_traverse(Traverse* traverse)
900
  { return Type::traverse(this->type_, traverse); }
901
 
902
  Type*
903
  do_type()
904
  { return this->type_; }
905
 
906
  void
907
  do_determine_type(const Type_context*)
908
  { }
909
 
910
  void
911
  do_check_types(Gogo*)
912
  { this->report_error(_("invalid use of type")); }
913
 
914
  Expression*
915
  do_copy()
916
  { return this; }
917
 
918
  tree
919
  do_get_tree(Translate_context*)
920
  { go_unreachable(); }
921
 
922
  void do_dump_expression(Ast_dump_context*) const;
923
 
924
 private:
925
  // The type which we are representing as an expression.
926
  Type* type_;
927
};
928
 
929
void
930
Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
931
{
932
  ast_dump_context->dump_type(this->type_);
933
}
934
 
935
Expression*
936
Expression::make_type(Type* type, Location location)
937
{
938
  return new Type_expression(type, location);
939
}
940
 
941
// Class Parser_expression.
942
 
943
Type*
944
Parser_expression::do_type()
945
{
946
  // We should never really ask for the type of a Parser_expression.
947
  // However, it can happen, at least when we have an invalid const
948
  // whose initializer refers to the const itself.  In that case we
949
  // may ask for the type when lowering the const itself.
950
  go_assert(saw_errors());
951
  return Type::make_error_type();
952
}
953
 
954
// Class Var_expression.
955
 
956
// Lower a variable expression.  Here we just make sure that the
957
// initialization expression of the variable has been lowered.  This
958
// ensures that we will be able to determine the type of the variable
959
// if necessary.
960
 
961
Expression*
962
Var_expression::do_lower(Gogo* gogo, Named_object* function,
963
                         Statement_inserter* inserter, int)
964
{
965
  if (this->variable_->is_variable())
966
    {
967
      Variable* var = this->variable_->var_value();
968
      // This is either a local variable or a global variable.  A
969
      // reference to a variable which is local to an enclosing
970
      // function will be a reference to a field in a closure.
971
      if (var->is_global())
972
        {
973
          function = NULL;
974
          inserter = NULL;
975
        }
976
      var->lower_init_expression(gogo, function, inserter);
977
    }
978
  return this;
979
}
980
 
981
// Return the type of a reference to a variable.
982
 
983
Type*
984
Var_expression::do_type()
985
{
986
  if (this->variable_->is_variable())
987
    return this->variable_->var_value()->type();
988
  else if (this->variable_->is_result_variable())
989
    return this->variable_->result_var_value()->type();
990
  else
991
    go_unreachable();
992
}
993
 
994
// Determine the type of a reference to a variable.
995
 
996
void
997
Var_expression::do_determine_type(const Type_context*)
998
{
999
  if (this->variable_->is_variable())
1000
    this->variable_->var_value()->determine_type();
1001
}
1002
 
1003
// Something takes the address of this variable.  This means that we
1004
// may want to move the variable onto the heap.
1005
 
1006
void
1007
Var_expression::do_address_taken(bool escapes)
1008
{
1009
  if (!escapes)
1010
    {
1011
      if (this->variable_->is_variable())
1012
        this->variable_->var_value()->set_non_escaping_address_taken();
1013
      else if (this->variable_->is_result_variable())
1014
        this->variable_->result_var_value()->set_non_escaping_address_taken();
1015
      else
1016
        go_unreachable();
1017
    }
1018
  else
1019
    {
1020
      if (this->variable_->is_variable())
1021
        this->variable_->var_value()->set_address_taken();
1022
      else if (this->variable_->is_result_variable())
1023
        this->variable_->result_var_value()->set_address_taken();
1024
      else
1025
        go_unreachable();
1026
    }
1027
}
1028
 
1029
// Get the tree for a reference to a variable.
1030
 
1031
tree
1032
Var_expression::do_get_tree(Translate_context* context)
1033
{
1034
  Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
1035
                                                          context->function());
1036
  tree ret = var_to_tree(bvar);
1037
  if (ret == error_mark_node)
1038
    return error_mark_node;
1039
  bool is_in_heap;
1040
  if (this->variable_->is_variable())
1041
    is_in_heap = this->variable_->var_value()->is_in_heap();
1042
  else if (this->variable_->is_result_variable())
1043
    is_in_heap = this->variable_->result_var_value()->is_in_heap();
1044
  else
1045
    go_unreachable();
1046
  if (is_in_heap)
1047
    {
1048
      ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
1049
      TREE_THIS_NOTRAP(ret) = 1;
1050
    }
1051
  return ret;
1052
}
1053
 
1054
// Ast dump for variable expression.
1055
 
1056
void
1057
Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1058
{
1059
  ast_dump_context->ostream() << this->variable_->name() ;
1060
}
1061
 
1062
// Make a reference to a variable in an expression.
1063
 
1064
Expression*
1065
Expression::make_var_reference(Named_object* var, Location location)
1066
{
1067
  if (var->is_sink())
1068
    return Expression::make_sink(location);
1069
 
1070
  // FIXME: Creating a new object for each reference to a variable is
1071
  // wasteful.
1072
  return new Var_expression(var, location);
1073
}
1074
 
1075
// Class Temporary_reference_expression.
1076
 
1077
// The type.
1078
 
1079
Type*
1080
Temporary_reference_expression::do_type()
1081
{
1082
  return this->statement_->type();
1083
}
1084
 
1085
// Called if something takes the address of this temporary variable.
1086
// We never have to move temporary variables to the heap, but we do
1087
// need to know that they must live in the stack rather than in a
1088
// register.
1089
 
1090
void
1091
Temporary_reference_expression::do_address_taken(bool)
1092
{
1093
  this->statement_->set_is_address_taken();
1094
}
1095
 
1096
// Get a tree referring to the variable.
1097
 
1098
tree
1099
Temporary_reference_expression::do_get_tree(Translate_context* context)
1100
{
1101
  Bvariable* bvar = this->statement_->get_backend_variable(context);
1102
 
1103
  // The gcc backend can't represent the same set of recursive types
1104
  // that the Go frontend can.  In some cases this means that a
1105
  // temporary variable won't have the right backend type.  Correct
1106
  // that here by adding a type cast.  We need to use base() to push
1107
  // the circularity down one level.
1108
  tree ret = var_to_tree(bvar);
1109
  if (!this->is_lvalue_
1110
      && POINTER_TYPE_P(TREE_TYPE(ret))
1111
      && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1112
    {
1113
      Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1114
      tree type_tree = type_to_tree(type_btype);
1115
      ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1116
    }
1117
  return ret;
1118
}
1119
 
1120
// Ast dump for temporary reference.
1121
 
1122
void
1123
Temporary_reference_expression::do_dump_expression(
1124
                                Ast_dump_context* ast_dump_context) const
1125
{
1126
  ast_dump_context->dump_temp_variable_name(this->statement_);
1127
}
1128
 
1129
// Make a reference to a temporary variable.
1130
 
1131
Temporary_reference_expression*
1132
Expression::make_temporary_reference(Temporary_statement* statement,
1133
                                     Location location)
1134
{
1135
  return new Temporary_reference_expression(statement, location);
1136
}
1137
 
1138
// Class Set_and_use_temporary_expression.
1139
 
1140
// Return the type.
1141
 
1142
Type*
1143
Set_and_use_temporary_expression::do_type()
1144
{
1145
  return this->statement_->type();
1146
}
1147
 
1148
// Take the address.
1149
 
1150
void
1151
Set_and_use_temporary_expression::do_address_taken(bool)
1152
{
1153
  this->statement_->set_is_address_taken();
1154
}
1155
 
1156
// Return the backend representation.
1157
 
1158
tree
1159
Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1160
{
1161
  Bvariable* bvar = this->statement_->get_backend_variable(context);
1162
  tree var_tree = var_to_tree(bvar);
1163
  tree expr_tree = this->expr_->get_tree(context);
1164
  if (var_tree == error_mark_node || expr_tree == error_mark_node)
1165
    return error_mark_node;
1166
  Location loc = this->location();
1167
  return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1168
                    build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1169
                               var_tree, expr_tree),
1170
                    var_tree);
1171
}
1172
 
1173
// Dump.
1174
 
1175
void
1176
Set_and_use_temporary_expression::do_dump_expression(
1177
    Ast_dump_context* ast_dump_context) const
1178
{
1179
  ast_dump_context->ostream() << '(';
1180
  ast_dump_context->dump_temp_variable_name(this->statement_);
1181
  ast_dump_context->ostream() << " = ";
1182
  this->expr_->dump_expression(ast_dump_context);
1183
  ast_dump_context->ostream() << ')';
1184
}
1185
 
1186
// Make a set-and-use temporary.
1187
 
1188
Set_and_use_temporary_expression*
1189
Expression::make_set_and_use_temporary(Temporary_statement* statement,
1190
                                       Expression* expr, Location location)
1191
{
1192
  return new Set_and_use_temporary_expression(statement, expr, location);
1193
}
1194
 
1195
// A sink expression--a use of the blank identifier _.
1196
 
1197
class Sink_expression : public Expression
1198
{
1199
 public:
1200
  Sink_expression(Location location)
1201
    : Expression(EXPRESSION_SINK, location),
1202
      type_(NULL), var_(NULL_TREE)
1203
  { }
1204
 
1205
 protected:
1206
  void
1207
  do_discarding_value()
1208
  { }
1209
 
1210
  Type*
1211
  do_type();
1212
 
1213
  void
1214
  do_determine_type(const Type_context*);
1215
 
1216
  Expression*
1217
  do_copy()
1218
  { return new Sink_expression(this->location()); }
1219
 
1220
  tree
1221
  do_get_tree(Translate_context*);
1222
 
1223
  void
1224
  do_dump_expression(Ast_dump_context*) const;
1225
 
1226
 private:
1227
  // The type of this sink variable.
1228
  Type* type_;
1229
  // The temporary variable we generate.
1230
  tree var_;
1231
};
1232
 
1233
// Return the type of a sink expression.
1234
 
1235
Type*
1236
Sink_expression::do_type()
1237
{
1238
  if (this->type_ == NULL)
1239
    return Type::make_sink_type();
1240
  return this->type_;
1241
}
1242
 
1243
// Determine the type of a sink expression.
1244
 
1245
void
1246
Sink_expression::do_determine_type(const Type_context* context)
1247
{
1248
  if (context->type != NULL)
1249
    this->type_ = context->type;
1250
}
1251
 
1252
// Return a temporary variable for a sink expression.  This will
1253
// presumably be a write-only variable which the middle-end will drop.
1254
 
1255
tree
1256
Sink_expression::do_get_tree(Translate_context* context)
1257
{
1258
  if (this->var_ == NULL_TREE)
1259
    {
1260
      go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1261
      Btype* bt = this->type_->get_backend(context->gogo());
1262
      this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1263
    }
1264
  return this->var_;
1265
}
1266
 
1267
// Ast dump for sink expression.
1268
 
1269
void
1270
Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1271
{
1272
  ast_dump_context->ostream() << "_" ;
1273
}
1274
 
1275
// Make a sink expression.
1276
 
1277
Expression*
1278
Expression::make_sink(Location location)
1279
{
1280
  return new Sink_expression(location);
1281
}
1282
 
1283
// Class Func_expression.
1284
 
1285
// FIXME: Can a function expression appear in a constant expression?
1286
// The value is unchanging.  Initializing a constant to the address of
1287
// a function seems like it could work, though there might be little
1288
// point to it.
1289
 
1290
// Traversal.
1291
 
1292
int
1293
Func_expression::do_traverse(Traverse* traverse)
1294
{
1295
  return (this->closure_ == NULL
1296
          ? TRAVERSE_CONTINUE
1297
          : Expression::traverse(&this->closure_, traverse));
1298
}
1299
 
1300
// Return the type of a function expression.
1301
 
1302
Type*
1303
Func_expression::do_type()
1304
{
1305
  if (this->function_->is_function())
1306
    return this->function_->func_value()->type();
1307
  else if (this->function_->is_function_declaration())
1308
    return this->function_->func_declaration_value()->type();
1309
  else
1310
    go_unreachable();
1311
}
1312
 
1313
// Get the tree for a function expression without evaluating the
1314
// closure.
1315
 
1316
tree
1317
Func_expression::get_tree_without_closure(Gogo* gogo)
1318
{
1319
  Function_type* fntype;
1320
  if (this->function_->is_function())
1321
    fntype = this->function_->func_value()->type();
1322
  else if (this->function_->is_function_declaration())
1323
    fntype = this->function_->func_declaration_value()->type();
1324
  else
1325
    go_unreachable();
1326
 
1327
  // Builtin functions are handled specially by Call_expression.  We
1328
  // can't take their address.
1329
  if (fntype->is_builtin())
1330
    {
1331
      error_at(this->location(),
1332
               "invalid use of special builtin function %qs; must be called",
1333
               this->function_->name().c_str());
1334
      return error_mark_node;
1335
    }
1336
 
1337
  Named_object* no = this->function_;
1338
 
1339
  tree id = no->get_id(gogo);
1340
  if (id == error_mark_node)
1341
    return error_mark_node;
1342
 
1343
  tree fndecl;
1344
  if (no->is_function())
1345
    fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1346
  else if (no->is_function_declaration())
1347
    fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1348
  else
1349
    go_unreachable();
1350
 
1351
  if (fndecl == error_mark_node)
1352
    return error_mark_node;
1353
 
1354
  return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1355
}
1356
 
1357
// Get the tree for a function expression.  This is used when we take
1358
// the address of a function rather than simply calling it.  If the
1359
// function has a closure, we must use a trampoline.
1360
 
1361
tree
1362
Func_expression::do_get_tree(Translate_context* context)
1363
{
1364
  Gogo* gogo = context->gogo();
1365
 
1366
  tree fnaddr = this->get_tree_without_closure(gogo);
1367
  if (fnaddr == error_mark_node)
1368
    return error_mark_node;
1369
 
1370
  go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1371
             && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1372
  TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1373
 
1374
  // For a normal non-nested function call, that is all we have to do.
1375
  if (!this->function_->is_function()
1376
      || this->function_->func_value()->enclosing() == NULL)
1377
    {
1378
      go_assert(this->closure_ == NULL);
1379
      return fnaddr;
1380
    }
1381
 
1382
  // For a nested function call, we have to always allocate a
1383
  // trampoline.  If we don't always allocate, then closures will not
1384
  // be reliably distinct.
1385
  Expression* closure = this->closure_;
1386
  tree closure_tree;
1387
  if (closure == NULL)
1388
    closure_tree = null_pointer_node;
1389
  else
1390
    {
1391
      // Get the value of the closure.  This will be a pointer to
1392
      // space allocated on the heap.
1393
      closure_tree = closure->get_tree(context);
1394
      if (closure_tree == error_mark_node)
1395
        return error_mark_node;
1396
      go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1397
    }
1398
 
1399
  // Now we need to build some code on the heap.  This code will load
1400
  // the static chain pointer with the closure and then jump to the
1401
  // body of the function.  The normal gcc approach is to build the
1402
  // code on the stack.  Unfortunately we can not do that, as Go
1403
  // permits us to return the function pointer.
1404
 
1405
  return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1406
}
1407
 
1408
// Ast dump for function.
1409
 
1410
void
1411
Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1412
{
1413
  ast_dump_context->ostream() << this->function_->name();
1414
  if (this->closure_ != NULL)
1415
    {
1416
      ast_dump_context->ostream() << " {closure =  ";
1417
      this->closure_->dump_expression(ast_dump_context);
1418
      ast_dump_context->ostream() << "}";
1419
    }
1420
}
1421
 
1422
// Make a reference to a function in an expression.
1423
 
1424
Expression*
1425
Expression::make_func_reference(Named_object* function, Expression* closure,
1426
                                Location location)
1427
{
1428
  return new Func_expression(function, closure, location);
1429
}
1430
 
1431
// Class Unknown_expression.
1432
 
1433
// Return the name of an unknown expression.
1434
 
1435
const std::string&
1436
Unknown_expression::name() const
1437
{
1438
  return this->named_object_->name();
1439
}
1440
 
1441
// Lower a reference to an unknown name.
1442
 
1443
Expression*
1444
Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1445
{
1446
  Location location = this->location();
1447
  Named_object* no = this->named_object_;
1448
  Named_object* real;
1449
  if (!no->is_unknown())
1450
    real = no;
1451
  else
1452
    {
1453
      real = no->unknown_value()->real_named_object();
1454
      if (real == NULL)
1455
        {
1456
          if (this->is_composite_literal_key_)
1457
            return this;
1458
          if (!this->no_error_message_)
1459
            error_at(location, "reference to undefined name %qs",
1460
                     this->named_object_->message_name().c_str());
1461
          return Expression::make_error(location);
1462
        }
1463
    }
1464
  switch (real->classification())
1465
    {
1466
    case Named_object::NAMED_OBJECT_CONST:
1467
      return Expression::make_const_reference(real, location);
1468
    case Named_object::NAMED_OBJECT_TYPE:
1469
      return Expression::make_type(real->type_value(), location);
1470
    case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1471
      if (this->is_composite_literal_key_)
1472
        return this;
1473
      if (!this->no_error_message_)
1474
        error_at(location, "reference to undefined type %qs",
1475
                 real->message_name().c_str());
1476
      return Expression::make_error(location);
1477
    case Named_object::NAMED_OBJECT_VAR:
1478
      real->var_value()->set_is_used();
1479
      return Expression::make_var_reference(real, location);
1480
    case Named_object::NAMED_OBJECT_FUNC:
1481
    case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1482
      return Expression::make_func_reference(real, NULL, location);
1483
    case Named_object::NAMED_OBJECT_PACKAGE:
1484
      if (this->is_composite_literal_key_)
1485
        return this;
1486
      if (!this->no_error_message_)
1487
        error_at(location, "unexpected reference to package");
1488
      return Expression::make_error(location);
1489
    default:
1490
      go_unreachable();
1491
    }
1492
}
1493
 
1494
// Dump the ast representation for an unknown expression to a dump context.
1495
 
1496
void
1497
Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1498
{
1499
  ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1500
                              << ")";
1501
}
1502
 
1503
// Make a reference to an unknown name.
1504
 
1505
Unknown_expression*
1506
Expression::make_unknown_reference(Named_object* no, Location location)
1507
{
1508
  return new Unknown_expression(no, location);
1509
}
1510
 
1511
// A boolean expression.
1512
 
1513
class Boolean_expression : public Expression
1514
{
1515
 public:
1516
  Boolean_expression(bool val, Location location)
1517
    : Expression(EXPRESSION_BOOLEAN, location),
1518
      val_(val), type_(NULL)
1519
  { }
1520
 
1521
  static Expression*
1522
  do_import(Import*);
1523
 
1524
 protected:
1525
  bool
1526
  do_is_constant() const
1527
  { return true; }
1528
 
1529
  Type*
1530
  do_type();
1531
 
1532
  void
1533
  do_determine_type(const Type_context*);
1534
 
1535
  Expression*
1536
  do_copy()
1537
  { return this; }
1538
 
1539
  tree
1540
  do_get_tree(Translate_context*)
1541
  { return this->val_ ? boolean_true_node : boolean_false_node; }
1542
 
1543
  void
1544
  do_export(Export* exp) const
1545
  { exp->write_c_string(this->val_ ? "true" : "false"); }
1546
 
1547
  void
1548
  do_dump_expression(Ast_dump_context* ast_dump_context) const
1549
  { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1550
 
1551
 private:
1552
  // The constant.
1553
  bool val_;
1554
  // The type as determined by context.
1555
  Type* type_;
1556
};
1557
 
1558
// Get the type.
1559
 
1560
Type*
1561
Boolean_expression::do_type()
1562
{
1563
  if (this->type_ == NULL)
1564
    this->type_ = Type::make_boolean_type();
1565
  return this->type_;
1566
}
1567
 
1568
// Set the type from the context.
1569
 
1570
void
1571
Boolean_expression::do_determine_type(const Type_context* context)
1572
{
1573
  if (this->type_ != NULL && !this->type_->is_abstract())
1574
    ;
1575
  else if (context->type != NULL && context->type->is_boolean_type())
1576
    this->type_ = context->type;
1577
  else if (!context->may_be_abstract)
1578
    this->type_ = Type::lookup_bool_type();
1579
}
1580
 
1581
// Import a boolean constant.
1582
 
1583
Expression*
1584
Boolean_expression::do_import(Import* imp)
1585
{
1586
  if (imp->peek_char() == 't')
1587
    {
1588
      imp->require_c_string("true");
1589
      return Expression::make_boolean(true, imp->location());
1590
    }
1591
  else
1592
    {
1593
      imp->require_c_string("false");
1594
      return Expression::make_boolean(false, imp->location());
1595
    }
1596
}
1597
 
1598
// Make a boolean expression.
1599
 
1600
Expression*
1601
Expression::make_boolean(bool val, Location location)
1602
{
1603
  return new Boolean_expression(val, location);
1604
}
1605
 
1606
// Class String_expression.
1607
 
1608
// Get the type.
1609
 
1610
Type*
1611
String_expression::do_type()
1612
{
1613
  if (this->type_ == NULL)
1614
    this->type_ = Type::make_string_type();
1615
  return this->type_;
1616
}
1617
 
1618
// Set the type from the context.
1619
 
1620
void
1621
String_expression::do_determine_type(const Type_context* context)
1622
{
1623
  if (this->type_ != NULL && !this->type_->is_abstract())
1624
    ;
1625
  else if (context->type != NULL && context->type->is_string_type())
1626
    this->type_ = context->type;
1627
  else if (!context->may_be_abstract)
1628
    this->type_ = Type::lookup_string_type();
1629
}
1630
 
1631
// Build a string constant.
1632
 
1633
tree
1634
String_expression::do_get_tree(Translate_context* context)
1635
{
1636
  return context->gogo()->go_string_constant_tree(this->val_);
1637
}
1638
 
1639
 // Write string literal to string dump.
1640
 
1641
void
1642
String_expression::export_string(String_dump* exp,
1643
                                 const String_expression* str)
1644
{
1645
  std::string s;
1646
  s.reserve(str->val_.length() * 4 + 2);
1647
  s += '"';
1648
  for (std::string::const_iterator p = str->val_.begin();
1649
       p != str->val_.end();
1650
       ++p)
1651
    {
1652
      if (*p == '\\' || *p == '"')
1653
        {
1654
          s += '\\';
1655
          s += *p;
1656
        }
1657
      else if (*p >= 0x20 && *p < 0x7f)
1658
        s += *p;
1659
      else if (*p == '\n')
1660
        s += "\\n";
1661
      else if (*p == '\t')
1662
        s += "\\t";
1663
      else
1664
        {
1665
          s += "\\x";
1666
          unsigned char c = *p;
1667
          unsigned int dig = c >> 4;
1668
          s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1669
          dig = c & 0xf;
1670
          s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1671
        }
1672
    }
1673
  s += '"';
1674
  exp->write_string(s);
1675
}
1676
 
1677
// Export a string expression.
1678
 
1679
void
1680
String_expression::do_export(Export* exp) const
1681
{
1682
  String_expression::export_string(exp, this);
1683
}
1684
 
1685
// Import a string expression.
1686
 
1687
Expression*
1688
String_expression::do_import(Import* imp)
1689
{
1690
  imp->require_c_string("\"");
1691
  std::string val;
1692
  while (true)
1693
    {
1694
      int c = imp->get_char();
1695
      if (c == '"' || c == -1)
1696
        break;
1697
      if (c != '\\')
1698
        val += static_cast<char>(c);
1699
      else
1700
        {
1701
          c = imp->get_char();
1702
          if (c == '\\' || c == '"')
1703
            val += static_cast<char>(c);
1704
          else if (c == 'n')
1705
            val += '\n';
1706
          else if (c == 't')
1707
            val += '\t';
1708
          else if (c == 'x')
1709
            {
1710
              c = imp->get_char();
1711
              unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1712
              c = imp->get_char();
1713
              unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1714
              char v = (vh << 4) | vl;
1715
              val += v;
1716
            }
1717
          else
1718
            {
1719
              error_at(imp->location(), "bad string constant");
1720
              return Expression::make_error(imp->location());
1721
            }
1722
        }
1723
    }
1724
  return Expression::make_string(val, imp->location());
1725
}
1726
 
1727
// Ast dump for string expression.
1728
 
1729
void
1730
String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1731
{
1732
  String_expression::export_string(ast_dump_context, this);
1733
}
1734
 
1735
// Make a string expression.
1736
 
1737
Expression*
1738
Expression::make_string(const std::string& val, Location location)
1739
{
1740
  return new String_expression(val, location);
1741
}
1742
 
1743
// Make an integer expression.
1744
 
1745
class Integer_expression : public Expression
1746
{
1747
 public:
1748
  Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1749
                     Location location)
1750
    : Expression(EXPRESSION_INTEGER, location),
1751
      type_(type), is_character_constant_(is_character_constant)
1752
  { mpz_init_set(this->val_, *val); }
1753
 
1754
  static Expression*
1755
  do_import(Import*);
1756
 
1757
  // Return whether VAL fits in the type.
1758
  static bool
1759
  check_constant(mpz_t val, Type*, Location);
1760
 
1761
  // Write VAL to string dump.
1762
  static void
1763
  export_integer(String_dump* exp, const mpz_t val);
1764
 
1765
  // Write VAL to dump context.
1766
  static void
1767
  dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1768
 
1769
 protected:
1770
  bool
1771
  do_is_constant() const
1772
  { return true; }
1773
 
1774
  bool
1775
  do_integer_constant_value(bool, mpz_t val, Type** ptype) const;
1776
 
1777
  Type*
1778
  do_type();
1779
 
1780
  void
1781
  do_determine_type(const Type_context* context);
1782
 
1783
  void
1784
  do_check_types(Gogo*);
1785
 
1786
  tree
1787
  do_get_tree(Translate_context*);
1788
 
1789
  Expression*
1790
  do_copy()
1791
  {
1792
    if (this->is_character_constant_)
1793
      return Expression::make_character(&this->val_, this->type_,
1794
                                        this->location());
1795
    else
1796
      return Expression::make_integer(&this->val_, this->type_,
1797
                                      this->location());
1798
  }
1799
 
1800
  void
1801
  do_export(Export*) const;
1802
 
1803
  void
1804
  do_dump_expression(Ast_dump_context*) const;
1805
 
1806
 private:
1807
  // The integer value.
1808
  mpz_t val_;
1809
  // The type so far.
1810
  Type* type_;
1811
  // Whether this is a character constant.
1812
  bool is_character_constant_;
1813
};
1814
 
1815
// Return an integer constant value.
1816
 
1817
bool
1818
Integer_expression::do_integer_constant_value(bool, mpz_t val,
1819
                                              Type** ptype) const
1820
{
1821
  if (this->type_ != NULL)
1822
    *ptype = this->type_;
1823
  mpz_set(val, this->val_);
1824
  return true;
1825
}
1826
 
1827
// Return the current type.  If we haven't set the type yet, we return
1828
// an abstract integer type.
1829
 
1830
Type*
1831
Integer_expression::do_type()
1832
{
1833
  if (this->type_ == NULL)
1834
    {
1835
      if (this->is_character_constant_)
1836
        this->type_ = Type::make_abstract_character_type();
1837
      else
1838
        this->type_ = Type::make_abstract_integer_type();
1839
    }
1840
  return this->type_;
1841
}
1842
 
1843
// Set the type of the integer value.  Here we may switch from an
1844
// abstract type to a real type.
1845
 
1846
void
1847
Integer_expression::do_determine_type(const Type_context* context)
1848
{
1849
  if (this->type_ != NULL && !this->type_->is_abstract())
1850
    ;
1851
  else if (context->type != NULL
1852
           && (context->type->integer_type() != NULL
1853
               || context->type->float_type() != NULL
1854
               || context->type->complex_type() != NULL))
1855
    this->type_ = context->type;
1856
  else if (!context->may_be_abstract)
1857
    {
1858
      if (this->is_character_constant_)
1859
        this->type_ = Type::lookup_integer_type("int32");
1860
      else
1861
        this->type_ = Type::lookup_integer_type("int");
1862
    }
1863
}
1864
 
1865
// Return true if the integer VAL fits in the range of the type TYPE.
1866
// Otherwise give an error and return false.  TYPE may be NULL.
1867
 
1868
bool
1869
Integer_expression::check_constant(mpz_t val, Type* type,
1870
                                   Location location)
1871
{
1872
  if (type == NULL)
1873
    return true;
1874
  Integer_type* itype = type->integer_type();
1875
  if (itype == NULL || itype->is_abstract())
1876
    return true;
1877
 
1878
  int bits = mpz_sizeinbase(val, 2);
1879
 
1880
  if (itype->is_unsigned())
1881
    {
1882
      // For an unsigned type we can only accept a nonnegative number,
1883
      // and we must be able to represent at least BITS.
1884
      if (mpz_sgn(val) >= 0
1885
          && bits <= itype->bits())
1886
        return true;
1887
    }
1888
  else
1889
    {
1890
      // For a signed type we need an extra bit to indicate the sign.
1891
      // We have to handle the most negative integer specially.
1892
      if (bits + 1 <= itype->bits()
1893
          || (bits <= itype->bits()
1894
              && mpz_sgn(val) < 0
1895
              && (mpz_scan1(val, 0)
1896
                  == static_cast<unsigned long>(itype->bits() - 1))
1897
              && mpz_scan0(val, itype->bits()) == ULONG_MAX))
1898
        return true;
1899
    }
1900
 
1901
  error_at(location, "integer constant overflow");
1902
  return false;
1903
}
1904
 
1905
// Check the type of an integer constant.
1906
 
1907
void
1908
Integer_expression::do_check_types(Gogo*)
1909
{
1910
  if (this->type_ == NULL)
1911
    return;
1912
  if (!Integer_expression::check_constant(this->val_, this->type_,
1913
                                          this->location()))
1914
    this->set_is_error();
1915
}
1916
 
1917
// Get a tree for an integer constant.
1918
 
1919
tree
1920
Integer_expression::do_get_tree(Translate_context* context)
1921
{
1922
  Gogo* gogo = context->gogo();
1923
  tree type;
1924
  if (this->type_ != NULL && !this->type_->is_abstract())
1925
    type = type_to_tree(this->type_->get_backend(gogo));
1926
  else if (this->type_ != NULL && this->type_->float_type() != NULL)
1927
    {
1928
      // We are converting to an abstract floating point type.
1929
      Type* ftype = Type::lookup_float_type("float64");
1930
      type = type_to_tree(ftype->get_backend(gogo));
1931
    }
1932
  else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1933
    {
1934
      // We are converting to an abstract complex type.
1935
      Type* ctype = Type::lookup_complex_type("complex128");
1936
      type = type_to_tree(ctype->get_backend(gogo));
1937
    }
1938
  else
1939
    {
1940
      // If we still have an abstract type here, then this is being
1941
      // used in a constant expression which didn't get reduced for
1942
      // some reason.  Use a type which will fit the value.  We use <,
1943
      // not <=, because we need an extra bit for the sign bit.
1944
      int bits = mpz_sizeinbase(this->val_, 2);
1945
      if (bits < INT_TYPE_SIZE)
1946
        {
1947
          Type* t = Type::lookup_integer_type("int");
1948
          type = type_to_tree(t->get_backend(gogo));
1949
        }
1950
      else if (bits < 64)
1951
        {
1952
          Type* t = Type::lookup_integer_type("int64");
1953
          type = type_to_tree(t->get_backend(gogo));
1954
        }
1955
      else
1956
        type = long_long_integer_type_node;
1957
    }
1958
  return Expression::integer_constant_tree(this->val_, type);
1959
}
1960
 
1961
// Write VAL to export data.
1962
 
1963
void
1964
Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1965
{
1966
  char* s = mpz_get_str(NULL, 10, val);
1967
  exp->write_c_string(s);
1968
  free(s);
1969
}
1970
 
1971
// Export an integer in a constant expression.
1972
 
1973
void
1974
Integer_expression::do_export(Export* exp) const
1975
{
1976
  Integer_expression::export_integer(exp, this->val_);
1977
  if (this->is_character_constant_)
1978
    exp->write_c_string("'");
1979
  // A trailing space lets us reliably identify the end of the number.
1980
  exp->write_c_string(" ");
1981
}
1982
 
1983
// Import an integer, floating point, or complex value.  This handles
1984
// all these types because they all start with digits.
1985
 
1986
Expression*
1987
Integer_expression::do_import(Import* imp)
1988
{
1989
  std::string num = imp->read_identifier();
1990
  imp->require_c_string(" ");
1991
  if (!num.empty() && num[num.length() - 1] == 'i')
1992
    {
1993
      mpfr_t real;
1994
      size_t plus_pos = num.find('+', 1);
1995
      size_t minus_pos = num.find('-', 1);
1996
      size_t pos;
1997
      if (plus_pos == std::string::npos)
1998
        pos = minus_pos;
1999
      else if (minus_pos == std::string::npos)
2000
        pos = plus_pos;
2001
      else
2002
        {
2003
          error_at(imp->location(), "bad number in import data: %qs",
2004
                   num.c_str());
2005
          return Expression::make_error(imp->location());
2006
        }
2007
      if (pos == std::string::npos)
2008
        mpfr_set_ui(real, 0, GMP_RNDN);
2009
      else
2010
        {
2011
          std::string real_str = num.substr(0, pos);
2012
          if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2013
            {
2014
              error_at(imp->location(), "bad number in import data: %qs",
2015
                       real_str.c_str());
2016
              return Expression::make_error(imp->location());
2017
            }
2018
        }
2019
 
2020
      std::string imag_str;
2021
      if (pos == std::string::npos)
2022
        imag_str = num;
2023
      else
2024
        imag_str = num.substr(pos);
2025
      imag_str = imag_str.substr(0, imag_str.size() - 1);
2026
      mpfr_t imag;
2027
      if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2028
        {
2029
          error_at(imp->location(), "bad number in import data: %qs",
2030
                   imag_str.c_str());
2031
          return Expression::make_error(imp->location());
2032
        }
2033
      Expression* ret = Expression::make_complex(&real, &imag, NULL,
2034
                                                 imp->location());
2035
      mpfr_clear(real);
2036
      mpfr_clear(imag);
2037
      return ret;
2038
    }
2039
  else if (num.find('.') == std::string::npos
2040
           && num.find('E') == std::string::npos)
2041
    {
2042
      bool is_character_constant = (!num.empty()
2043
                                    && num[num.length() - 1] == '\'');
2044
      if (is_character_constant)
2045
        num = num.substr(0, num.length() - 1);
2046
      mpz_t val;
2047
      if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2048
        {
2049
          error_at(imp->location(), "bad number in import data: %qs",
2050
                   num.c_str());
2051
          return Expression::make_error(imp->location());
2052
        }
2053
      Expression* ret;
2054
      if (is_character_constant)
2055
        ret = Expression::make_character(&val, NULL, imp->location());
2056
      else
2057
        ret = Expression::make_integer(&val, NULL, imp->location());
2058
      mpz_clear(val);
2059
      return ret;
2060
    }
2061
  else
2062
    {
2063
      mpfr_t val;
2064
      if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2065
        {
2066
          error_at(imp->location(), "bad number in import data: %qs",
2067
                   num.c_str());
2068
          return Expression::make_error(imp->location());
2069
        }
2070
      Expression* ret = Expression::make_float(&val, NULL, imp->location());
2071
      mpfr_clear(val);
2072
      return ret;
2073
    }
2074
}
2075
// Ast dump for integer expression.
2076
 
2077
void
2078
Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2079
{
2080
  if (this->is_character_constant_)
2081
    ast_dump_context->ostream() << '\'';
2082
  Integer_expression::export_integer(ast_dump_context, this->val_);
2083
  if (this->is_character_constant_)
2084
    ast_dump_context->ostream() << '\'';
2085
}
2086
 
2087
// Build a new integer value.
2088
 
2089
Expression*
2090
Expression::make_integer(const mpz_t* val, Type* type, Location location)
2091
{
2092
  return new Integer_expression(val, type, false, location);
2093
}
2094
 
2095
// Build a new character constant value.
2096
 
2097
Expression*
2098
Expression::make_character(const mpz_t* val, Type* type, Location location)
2099
{
2100
  return new Integer_expression(val, type, true, location);
2101
}
2102
 
2103
// Floats.
2104
 
2105
class Float_expression : public Expression
2106
{
2107
 public:
2108
  Float_expression(const mpfr_t* val, Type* type, Location location)
2109
    : Expression(EXPRESSION_FLOAT, location),
2110
      type_(type)
2111
  {
2112
    mpfr_init_set(this->val_, *val, GMP_RNDN);
2113
  }
2114
 
2115
  // Constrain VAL to fit into TYPE.
2116
  static void
2117
  constrain_float(mpfr_t val, Type* type);
2118
 
2119
  // Return whether VAL fits in the type.
2120
  static bool
2121
  check_constant(mpfr_t val, Type*, Location);
2122
 
2123
  // Write VAL to export data.
2124
  static void
2125
  export_float(String_dump* exp, const mpfr_t val);
2126
 
2127
  // Write VAL to dump file.
2128
  static void
2129
  dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2130
 
2131
 protected:
2132
  bool
2133
  do_is_constant() const
2134
  { return true; }
2135
 
2136
  bool
2137
  do_float_constant_value(mpfr_t val, Type**) const;
2138
 
2139
  Type*
2140
  do_type();
2141
 
2142
  void
2143
  do_determine_type(const Type_context*);
2144
 
2145
  void
2146
  do_check_types(Gogo*);
2147
 
2148
  Expression*
2149
  do_copy()
2150
  { return Expression::make_float(&this->val_, this->type_,
2151
                                  this->location()); }
2152
 
2153
  tree
2154
  do_get_tree(Translate_context*);
2155
 
2156
  void
2157
  do_export(Export*) const;
2158
 
2159
  void
2160
  do_dump_expression(Ast_dump_context*) const;
2161
 
2162
 private:
2163
  // The floating point value.
2164
  mpfr_t val_;
2165
  // The type so far.
2166
  Type* type_;
2167
};
2168
 
2169
// Constrain VAL to fit into TYPE.
2170
 
2171
void
2172
Float_expression::constrain_float(mpfr_t val, Type* type)
2173
{
2174
  Float_type* ftype = type->float_type();
2175
  if (ftype != NULL && !ftype->is_abstract())
2176
    mpfr_prec_round(val, ftype->bits(), GMP_RNDN);
2177
}
2178
 
2179
// Return a floating point constant value.
2180
 
2181
bool
2182
Float_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
2183
{
2184
  if (this->type_ != NULL)
2185
    *ptype = this->type_;
2186
  mpfr_set(val, this->val_, GMP_RNDN);
2187
  return true;
2188
}
2189
 
2190
// Return the current type.  If we haven't set the type yet, we return
2191
// an abstract float type.
2192
 
2193
Type*
2194
Float_expression::do_type()
2195
{
2196
  if (this->type_ == NULL)
2197
    this->type_ = Type::make_abstract_float_type();
2198
  return this->type_;
2199
}
2200
 
2201
// Set the type of the float value.  Here we may switch from an
2202
// abstract type to a real type.
2203
 
2204
void
2205
Float_expression::do_determine_type(const Type_context* context)
2206
{
2207
  if (this->type_ != NULL && !this->type_->is_abstract())
2208
    ;
2209
  else if (context->type != NULL
2210
           && (context->type->integer_type() != NULL
2211
               || context->type->float_type() != NULL
2212
               || context->type->complex_type() != NULL))
2213
    this->type_ = context->type;
2214
  else if (!context->may_be_abstract)
2215
    this->type_ = Type::lookup_float_type("float64");
2216
}
2217
 
2218
// Return true if the floating point value VAL fits in the range of
2219
// the type TYPE.  Otherwise give an error and return false.  TYPE may
2220
// be NULL.
2221
 
2222
bool
2223
Float_expression::check_constant(mpfr_t val, Type* type,
2224
                                 Location location)
2225
{
2226
  if (type == NULL)
2227
    return true;
2228
  Float_type* ftype = type->float_type();
2229
  if (ftype == NULL || ftype->is_abstract())
2230
    return true;
2231
 
2232
  // A NaN or Infinity always fits in the range of the type.
2233
  if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
2234
    return true;
2235
 
2236
  mp_exp_t exp = mpfr_get_exp(val);
2237
  mp_exp_t max_exp;
2238
  switch (ftype->bits())
2239
    {
2240
    case 32:
2241
      max_exp = 128;
2242
      break;
2243
    case 64:
2244
      max_exp = 1024;
2245
      break;
2246
    default:
2247
      go_unreachable();
2248
    }
2249
  if (exp > max_exp)
2250
    {
2251
      error_at(location, "floating point constant overflow");
2252
      return false;
2253
    }
2254
  return true;
2255
}
2256
 
2257
// Check the type of a float value.
2258
 
2259
void
2260
Float_expression::do_check_types(Gogo*)
2261
{
2262
  if (this->type_ == NULL)
2263
    return;
2264
 
2265
  if (!Float_expression::check_constant(this->val_, this->type_,
2266
                                        this->location()))
2267
    this->set_is_error();
2268
 
2269
  Integer_type* integer_type = this->type_->integer_type();
2270
  if (integer_type != NULL)
2271
    {
2272
      if (!mpfr_integer_p(this->val_))
2273
        this->report_error(_("floating point constant truncated to integer"));
2274
      else
2275
        {
2276
          go_assert(!integer_type->is_abstract());
2277
          mpz_t ival;
2278
          mpz_init(ival);
2279
          mpfr_get_z(ival, this->val_, GMP_RNDN);
2280
          Integer_expression::check_constant(ival, integer_type,
2281
                                             this->location());
2282
          mpz_clear(ival);
2283
        }
2284
    }
2285
}
2286
 
2287
// Get a tree for a float constant.
2288
 
2289
tree
2290
Float_expression::do_get_tree(Translate_context* context)
2291
{
2292
  Gogo* gogo = context->gogo();
2293
  tree type;
2294
  if (this->type_ != NULL && !this->type_->is_abstract())
2295
    type = type_to_tree(this->type_->get_backend(gogo));
2296
  else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2297
    {
2298
      // We have an abstract integer type.  We just hope for the best.
2299
      type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2300
    }
2301
  else
2302
    {
2303
      // If we still have an abstract type here, then this is being
2304
      // used in a constant expression which didn't get reduced.  We
2305
      // just use float64 and hope for the best.
2306
      Type* ft = Type::lookup_float_type("float64");
2307
      type = type_to_tree(ft->get_backend(gogo));
2308
    }
2309
  return Expression::float_constant_tree(this->val_, type);
2310
}
2311
 
2312
// Write a floating point number to a string dump.
2313
 
2314
void
2315
Float_expression::export_float(String_dump *exp, const mpfr_t val)
2316
{
2317
  mp_exp_t exponent;
2318
  char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2319
  if (*s == '-')
2320
    exp->write_c_string("-");
2321
  exp->write_c_string("0.");
2322
  exp->write_c_string(*s == '-' ? s + 1 : s);
2323
  mpfr_free_str(s);
2324
  char buf[30];
2325
  snprintf(buf, sizeof buf, "E%ld", exponent);
2326
  exp->write_c_string(buf);
2327
}
2328
 
2329
// Export a floating point number in a constant expression.
2330
 
2331
void
2332
Float_expression::do_export(Export* exp) const
2333
{
2334
  Float_expression::export_float(exp, this->val_);
2335
  // A trailing space lets us reliably identify the end of the number.
2336
  exp->write_c_string(" ");
2337
}
2338
 
2339
// Dump a floating point number to the dump file.
2340
 
2341
void
2342
Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2343
{
2344
  Float_expression::export_float(ast_dump_context, this->val_);
2345
}
2346
 
2347
// Make a float expression.
2348
 
2349
Expression*
2350
Expression::make_float(const mpfr_t* val, Type* type, Location location)
2351
{
2352
  return new Float_expression(val, type, location);
2353
}
2354
 
2355
// Complex numbers.
2356
 
2357
class Complex_expression : public Expression
2358
{
2359
 public:
2360
  Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2361
                     Location location)
2362
    : Expression(EXPRESSION_COMPLEX, location),
2363
      type_(type)
2364
  {
2365
    mpfr_init_set(this->real_, *real, GMP_RNDN);
2366
    mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2367
  }
2368
 
2369
  // Constrain REAL/IMAG to fit into TYPE.
2370
  static void
2371
  constrain_complex(mpfr_t real, mpfr_t imag, Type* type);
2372
 
2373
  // Return whether REAL/IMAG fits in the type.
2374
  static bool
2375
  check_constant(mpfr_t real, mpfr_t imag, Type*, Location);
2376
 
2377
  // Write REAL/IMAG to string dump.
2378
  static void
2379
  export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2380
 
2381
  // Write REAL/IMAG to dump context.
2382
  static void
2383
  dump_complex(Ast_dump_context* ast_dump_context,
2384
               const mpfr_t real, const mpfr_t val);
2385
 
2386
 protected:
2387
  bool
2388
  do_is_constant() const
2389
  { return true; }
2390
 
2391
  bool
2392
  do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const;
2393
 
2394
  Type*
2395
  do_type();
2396
 
2397
  void
2398
  do_determine_type(const Type_context*);
2399
 
2400
  void
2401
  do_check_types(Gogo*);
2402
 
2403
  Expression*
2404
  do_copy()
2405
  {
2406
    return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2407
                                    this->location());
2408
  }
2409
 
2410
  tree
2411
  do_get_tree(Translate_context*);
2412
 
2413
  void
2414
  do_export(Export*) const;
2415
 
2416
  void
2417
  do_dump_expression(Ast_dump_context*) const;
2418
 
2419
 private:
2420
  // The real part.
2421
  mpfr_t real_;
2422
  // The imaginary part;
2423
  mpfr_t imag_;
2424
  // The type if known.
2425
  Type* type_;
2426
};
2427
 
2428
// Constrain REAL/IMAG to fit into TYPE.
2429
 
2430
void
2431
Complex_expression::constrain_complex(mpfr_t real, mpfr_t imag, Type* type)
2432
{
2433
  Complex_type* ctype = type->complex_type();
2434
  if (ctype != NULL && !ctype->is_abstract())
2435
    {
2436
      mpfr_prec_round(real, ctype->bits() / 2, GMP_RNDN);
2437
      mpfr_prec_round(imag, ctype->bits() / 2, GMP_RNDN);
2438
    }
2439
}
2440
 
2441
// Return a complex constant value.
2442
 
2443
bool
2444
Complex_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
2445
                                              Type** ptype) const
2446
{
2447
  if (this->type_ != NULL)
2448
    *ptype = this->type_;
2449
  mpfr_set(real, this->real_, GMP_RNDN);
2450
  mpfr_set(imag, this->imag_, GMP_RNDN);
2451
  return true;
2452
}
2453
 
2454
// Return the current type.  If we haven't set the type yet, we return
2455
// an abstract complex type.
2456
 
2457
Type*
2458
Complex_expression::do_type()
2459
{
2460
  if (this->type_ == NULL)
2461
    this->type_ = Type::make_abstract_complex_type();
2462
  return this->type_;
2463
}
2464
 
2465
// Set the type of the complex value.  Here we may switch from an
2466
// abstract type to a real type.
2467
 
2468
void
2469
Complex_expression::do_determine_type(const Type_context* context)
2470
{
2471
  if (this->type_ != NULL && !this->type_->is_abstract())
2472
    ;
2473
  else if (context->type != NULL
2474
           && context->type->complex_type() != NULL)
2475
    this->type_ = context->type;
2476
  else if (!context->may_be_abstract)
2477
    this->type_ = Type::lookup_complex_type("complex128");
2478
}
2479
 
2480
// Return true if the complex value REAL/IMAG fits in the range of the
2481
// type TYPE.  Otherwise give an error and return false.  TYPE may be
2482
// NULL.
2483
 
2484
bool
2485
Complex_expression::check_constant(mpfr_t real, mpfr_t imag, Type* type,
2486
                                   Location location)
2487
{
2488
  if (type == NULL)
2489
    return true;
2490
  Complex_type* ctype = type->complex_type();
2491
  if (ctype == NULL || ctype->is_abstract())
2492
    return true;
2493
 
2494
  mp_exp_t max_exp;
2495
  switch (ctype->bits())
2496
    {
2497
    case 64:
2498
      max_exp = 128;
2499
      break;
2500
    case 128:
2501
      max_exp = 1024;
2502
      break;
2503
    default:
2504
      go_unreachable();
2505
    }
2506
 
2507
  // A NaN or Infinity always fits in the range of the type.
2508
  if (!mpfr_nan_p(real) && !mpfr_inf_p(real) && !mpfr_zero_p(real))
2509
    {
2510
      if (mpfr_get_exp(real) > max_exp)
2511
        {
2512
          error_at(location, "complex real part constant overflow");
2513
          return false;
2514
        }
2515
    }
2516
 
2517
  if (!mpfr_nan_p(imag) && !mpfr_inf_p(imag) && !mpfr_zero_p(imag))
2518
    {
2519
      if (mpfr_get_exp(imag) > max_exp)
2520
        {
2521
          error_at(location, "complex imaginary part constant overflow");
2522
          return false;
2523
        }
2524
    }
2525
 
2526
  return true;
2527
}
2528
 
2529
// Check the type of a complex value.
2530
 
2531
void
2532
Complex_expression::do_check_types(Gogo*)
2533
{
2534
  if (this->type_ == NULL)
2535
    return;
2536
 
2537
  if (!Complex_expression::check_constant(this->real_, this->imag_,
2538
                                          this->type_, this->location()))
2539
    this->set_is_error();
2540
}
2541
 
2542
// Get a tree for a complex constant.
2543
 
2544
tree
2545
Complex_expression::do_get_tree(Translate_context* context)
2546
{
2547
  Gogo* gogo = context->gogo();
2548
  tree type;
2549
  if (this->type_ != NULL && !this->type_->is_abstract())
2550
    type = type_to_tree(this->type_->get_backend(gogo));
2551
  else
2552
    {
2553
      // If we still have an abstract type here, this this is being
2554
      // used in a constant expression which didn't get reduced.  We
2555
      // just use complex128 and hope for the best.
2556
      Type* ct = Type::lookup_complex_type("complex128");
2557
      type = type_to_tree(ct->get_backend(gogo));
2558
    }
2559
  return Expression::complex_constant_tree(this->real_, this->imag_, type);
2560
}
2561
 
2562
// Write REAL/IMAG to export data.
2563
 
2564
void
2565
Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2566
                                   const mpfr_t imag)
2567
{
2568
  if (!mpfr_zero_p(real))
2569
    {
2570
      Float_expression::export_float(exp, real);
2571
      if (mpfr_sgn(imag) > 0)
2572
        exp->write_c_string("+");
2573
    }
2574
  Float_expression::export_float(exp, imag);
2575
  exp->write_c_string("i");
2576
}
2577
 
2578
// Export a complex number in a constant expression.
2579
 
2580
void
2581
Complex_expression::do_export(Export* exp) const
2582
{
2583
  Complex_expression::export_complex(exp, this->real_, this->imag_);
2584
  // A trailing space lets us reliably identify the end of the number.
2585
  exp->write_c_string(" ");
2586
}
2587
 
2588
// Dump a complex expression to the dump file.
2589
 
2590
void
2591
Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2592
{
2593
  Complex_expression::export_complex(ast_dump_context,
2594
                                      this->real_,
2595
                                      this->imag_);
2596
}
2597
 
2598
// Make a complex expression.
2599
 
2600
Expression*
2601
Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2602
                         Location location)
2603
{
2604
  return new Complex_expression(real, imag, type, location);
2605
}
2606
 
2607
// Find a named object in an expression.
2608
 
2609
class Find_named_object : public Traverse
2610
{
2611
 public:
2612
  Find_named_object(Named_object* no)
2613
    : Traverse(traverse_expressions),
2614
      no_(no), found_(false)
2615
  { }
2616
 
2617
  // Whether we found the object.
2618
  bool
2619
  found() const
2620
  { return this->found_; }
2621
 
2622
 protected:
2623
  int
2624
  expression(Expression**);
2625
 
2626
 private:
2627
  // The object we are looking for.
2628
  Named_object* no_;
2629
  // Whether we found it.
2630
  bool found_;
2631
};
2632
 
2633
// A reference to a const in an expression.
2634
 
2635
class Const_expression : public Expression
2636
{
2637
 public:
2638
  Const_expression(Named_object* constant, Location location)
2639
    : Expression(EXPRESSION_CONST_REFERENCE, location),
2640
      constant_(constant), type_(NULL), seen_(false)
2641
  { }
2642
 
2643
  Named_object*
2644
  named_object()
2645
  { return this->constant_; }
2646
 
2647
  // Check that the initializer does not refer to the constant itself.
2648
  void
2649
  check_for_init_loop();
2650
 
2651
 protected:
2652
  int
2653
  do_traverse(Traverse*);
2654
 
2655
  Expression*
2656
  do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2657
 
2658
  bool
2659
  do_is_constant() const
2660
  { return true; }
2661
 
2662
  bool
2663
  do_integer_constant_value(bool, mpz_t val, Type**) const;
2664
 
2665
  bool
2666
  do_float_constant_value(mpfr_t val, Type**) const;
2667
 
2668
  bool
2669
  do_complex_constant_value(mpfr_t real, mpfr_t imag, Type**) const;
2670
 
2671
  bool
2672
  do_string_constant_value(std::string* val) const
2673
  { return this->constant_->const_value()->expr()->string_constant_value(val); }
2674
 
2675
  Type*
2676
  do_type();
2677
 
2678
  // The type of a const is set by the declaration, not the use.
2679
  void
2680
  do_determine_type(const Type_context*);
2681
 
2682
  void
2683
  do_check_types(Gogo*);
2684
 
2685
  Expression*
2686
  do_copy()
2687
  { return this; }
2688
 
2689
  tree
2690
  do_get_tree(Translate_context* context);
2691
 
2692
  // When exporting a reference to a const as part of a const
2693
  // expression, we export the value.  We ignore the fact that it has
2694
  // a name.
2695
  void
2696
  do_export(Export* exp) const
2697
  { this->constant_->const_value()->expr()->export_expression(exp); }
2698
 
2699
  void
2700
  do_dump_expression(Ast_dump_context*) const;
2701
 
2702
 private:
2703
  // The constant.
2704
  Named_object* constant_;
2705
  // The type of this reference.  This is used if the constant has an
2706
  // abstract type.
2707
  Type* type_;
2708
  // Used to prevent infinite recursion when a constant incorrectly
2709
  // refers to itself.
2710
  mutable bool seen_;
2711
};
2712
 
2713
// Traversal.
2714
 
2715
int
2716
Const_expression::do_traverse(Traverse* traverse)
2717
{
2718
  if (this->type_ != NULL)
2719
    return Type::traverse(this->type_, traverse);
2720
  return TRAVERSE_CONTINUE;
2721
}
2722
 
2723
// Lower a constant expression.  This is where we convert the
2724
// predeclared constant iota into an integer value.
2725
 
2726
Expression*
2727
Const_expression::do_lower(Gogo* gogo, Named_object*,
2728
                           Statement_inserter*, int iota_value)
2729
{
2730
  if (this->constant_->const_value()->expr()->classification()
2731
      == EXPRESSION_IOTA)
2732
    {
2733
      if (iota_value == -1)
2734
        {
2735
          error_at(this->location(),
2736
                   "iota is only defined in const declarations");
2737
          iota_value = 0;
2738
        }
2739
      mpz_t val;
2740
      mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2741
      Expression* ret = Expression::make_integer(&val, NULL,
2742
                                                 this->location());
2743
      mpz_clear(val);
2744
      return ret;
2745
    }
2746
 
2747
  // Make sure that the constant itself has been lowered.
2748
  gogo->lower_constant(this->constant_);
2749
 
2750
  return this;
2751
}
2752
 
2753
// Return an integer constant value.
2754
 
2755
bool
2756
Const_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val,
2757
                                            Type** ptype) const
2758
{
2759
  if (this->seen_)
2760
    return false;
2761
 
2762
  Type* ctype;
2763
  if (this->type_ != NULL)
2764
    ctype = this->type_;
2765
  else
2766
    ctype = this->constant_->const_value()->type();
2767
  if (ctype != NULL && ctype->integer_type() == NULL)
2768
    return false;
2769
 
2770
  Expression* e = this->constant_->const_value()->expr();
2771
 
2772
  this->seen_ = true;
2773
 
2774
  Type* t;
2775
  bool r = e->integer_constant_value(iota_is_constant, val, &t);
2776
 
2777
  this->seen_ = false;
2778
 
2779
  if (r
2780
      && ctype != NULL
2781
      && !Integer_expression::check_constant(val, ctype, this->location()))
2782
    return false;
2783
 
2784
  *ptype = ctype != NULL ? ctype : t;
2785
  return r;
2786
}
2787
 
2788
// Return a floating point constant value.
2789
 
2790
bool
2791
Const_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
2792
{
2793
  if (this->seen_)
2794
    return false;
2795
 
2796
  Type* ctype;
2797
  if (this->type_ != NULL)
2798
    ctype = this->type_;
2799
  else
2800
    ctype = this->constant_->const_value()->type();
2801
  if (ctype != NULL && ctype->float_type() == NULL)
2802
    return false;
2803
 
2804
  this->seen_ = true;
2805
 
2806
  Type* t;
2807
  bool r = this->constant_->const_value()->expr()->float_constant_value(val,
2808
                                                                        &t);
2809
 
2810
  this->seen_ = false;
2811
 
2812
  if (r && ctype != NULL)
2813
    {
2814
      if (!Float_expression::check_constant(val, ctype, this->location()))
2815
        return false;
2816
      Float_expression::constrain_float(val, ctype);
2817
    }
2818
  *ptype = ctype != NULL ? ctype : t;
2819
  return r;
2820
}
2821
 
2822
// Return a complex constant value.
2823
 
2824
bool
2825
Const_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
2826
                                            Type **ptype) const
2827
{
2828
  if (this->seen_)
2829
    return false;
2830
 
2831
  Type* ctype;
2832
  if (this->type_ != NULL)
2833
    ctype = this->type_;
2834
  else
2835
    ctype = this->constant_->const_value()->type();
2836
  if (ctype != NULL && ctype->complex_type() == NULL)
2837
    return false;
2838
 
2839
  this->seen_ = true;
2840
 
2841
  Type *t;
2842
  bool r = this->constant_->const_value()->expr()->complex_constant_value(real,
2843
                                                                          imag,
2844
                                                                          &t);
2845
 
2846
  this->seen_ = false;
2847
 
2848
  if (r && ctype != NULL)
2849
    {
2850
      if (!Complex_expression::check_constant(real, imag, ctype,
2851
                                              this->location()))
2852
        return false;
2853
      Complex_expression::constrain_complex(real, imag, ctype);
2854
    }
2855
  *ptype = ctype != NULL ? ctype : t;
2856
  return r;
2857
}
2858
 
2859
// Return the type of the const reference.
2860
 
2861
Type*
2862
Const_expression::do_type()
2863
{
2864
  if (this->type_ != NULL)
2865
    return this->type_;
2866
 
2867
  Named_constant* nc = this->constant_->const_value();
2868
 
2869
  if (this->seen_ || nc->lowering())
2870
    {
2871
      this->report_error(_("constant refers to itself"));
2872
      this->type_ = Type::make_error_type();
2873
      return this->type_;
2874
    }
2875
 
2876
  this->seen_ = true;
2877
 
2878
  Type* ret = nc->type();
2879
 
2880
  if (ret != NULL)
2881
    {
2882
      this->seen_ = false;
2883
      return ret;
2884
    }
2885
 
2886
  // During parsing, a named constant may have a NULL type, but we
2887
  // must not return a NULL type here.
2888
  ret = nc->expr()->type();
2889
 
2890
  this->seen_ = false;
2891
 
2892
  return ret;
2893
}
2894
 
2895
// Set the type of the const reference.
2896
 
2897
void
2898
Const_expression::do_determine_type(const Type_context* context)
2899
{
2900
  Type* ctype = this->constant_->const_value()->type();
2901
  Type* cetype = (ctype != NULL
2902
                  ? ctype
2903
                  : this->constant_->const_value()->expr()->type());
2904
  if (ctype != NULL && !ctype->is_abstract())
2905
    ;
2906
  else if (context->type != NULL
2907
           && (context->type->integer_type() != NULL
2908
               || context->type->float_type() != NULL
2909
               || context->type->complex_type() != NULL)
2910
           && (cetype->integer_type() != NULL
2911
               || cetype->float_type() != NULL
2912
               || cetype->complex_type() != NULL))
2913
    this->type_ = context->type;
2914
  else if (context->type != NULL
2915
           && context->type->is_string_type()
2916
           && cetype->is_string_type())
2917
    this->type_ = context->type;
2918
  else if (context->type != NULL
2919
           && context->type->is_boolean_type()
2920
           && cetype->is_boolean_type())
2921
    this->type_ = context->type;
2922
  else if (!context->may_be_abstract)
2923
    {
2924
      if (cetype->is_abstract())
2925
        cetype = cetype->make_non_abstract_type();
2926
      this->type_ = cetype;
2927
    }
2928
}
2929
 
2930
// Check for a loop in which the initializer of a constant refers to
2931
// the constant itself.
2932
 
2933
void
2934
Const_expression::check_for_init_loop()
2935
{
2936
  if (this->type_ != NULL && this->type_->is_error())
2937
    return;
2938
 
2939
  if (this->seen_)
2940
    {
2941
      this->report_error(_("constant refers to itself"));
2942
      this->type_ = Type::make_error_type();
2943
      return;
2944
    }
2945
 
2946
  Expression* init = this->constant_->const_value()->expr();
2947
  Find_named_object find_named_object(this->constant_);
2948
 
2949
  this->seen_ = true;
2950
  Expression::traverse(&init, &find_named_object);
2951
  this->seen_ = false;
2952
 
2953
  if (find_named_object.found())
2954
    {
2955
      if (this->type_ == NULL || !this->type_->is_error())
2956
        {
2957
          this->report_error(_("constant refers to itself"));
2958
          this->type_ = Type::make_error_type();
2959
        }
2960
      return;
2961
    }
2962
}
2963
 
2964
// Check types of a const reference.
2965
 
2966
void
2967
Const_expression::do_check_types(Gogo*)
2968
{
2969
  if (this->type_ != NULL && this->type_->is_error())
2970
    return;
2971
 
2972
  this->check_for_init_loop();
2973
 
2974
  if (this->type_ == NULL || this->type_->is_abstract())
2975
    return;
2976
 
2977
  // Check for integer overflow.
2978
  if (this->type_->integer_type() != NULL)
2979
    {
2980
      mpz_t ival;
2981
      mpz_init(ival);
2982
      Type* dummy;
2983
      if (!this->integer_constant_value(true, ival, &dummy))
2984
        {
2985
          mpfr_t fval;
2986
          mpfr_init(fval);
2987
          Expression* cexpr = this->constant_->const_value()->expr();
2988
          if (cexpr->float_constant_value(fval, &dummy))
2989
            {
2990
              if (!mpfr_integer_p(fval))
2991
                this->report_error(_("floating point constant "
2992
                                     "truncated to integer"));
2993
              else
2994
                {
2995
                  mpfr_get_z(ival, fval, GMP_RNDN);
2996
                  Integer_expression::check_constant(ival, this->type_,
2997
                                                     this->location());
2998
                }
2999
            }
3000
          mpfr_clear(fval);
3001
        }
3002
      mpz_clear(ival);
3003
    }
3004
}
3005
 
3006
// Return a tree for the const reference.
3007
 
3008
tree
3009
Const_expression::do_get_tree(Translate_context* context)
3010
{
3011
  Gogo* gogo = context->gogo();
3012
  tree type_tree;
3013
  if (this->type_ == NULL)
3014
    type_tree = NULL_TREE;
3015
  else
3016
    {
3017
      type_tree = type_to_tree(this->type_->get_backend(gogo));
3018
      if (type_tree == error_mark_node)
3019
        return error_mark_node;
3020
    }
3021
 
3022
  // If the type has been set for this expression, but the underlying
3023
  // object is an abstract int or float, we try to get the abstract
3024
  // value.  Otherwise we may lose something in the conversion.
3025
  if (this->type_ != NULL
3026
      && (this->constant_->const_value()->type() == NULL
3027
          || this->constant_->const_value()->type()->is_abstract()))
3028
    {
3029
      Expression* expr = this->constant_->const_value()->expr();
3030
      mpz_t ival;
3031
      mpz_init(ival);
3032
      Type* t;
3033
      if (expr->integer_constant_value(true, ival, &t))
3034
        {
3035
          tree ret = Expression::integer_constant_tree(ival, type_tree);
3036
          mpz_clear(ival);
3037
          return ret;
3038
        }
3039
      mpz_clear(ival);
3040
 
3041
      mpfr_t fval;
3042
      mpfr_init(fval);
3043
      if (expr->float_constant_value(fval, &t))
3044
        {
3045
          tree ret = Expression::float_constant_tree(fval, type_tree);
3046
          mpfr_clear(fval);
3047
          return ret;
3048
        }
3049
 
3050
      mpfr_t imag;
3051
      mpfr_init(imag);
3052
      if (expr->complex_constant_value(fval, imag, &t))
3053
        {
3054
          tree ret = Expression::complex_constant_tree(fval, imag, type_tree);
3055
          mpfr_clear(fval);
3056
          mpfr_clear(imag);
3057
          return ret;
3058
        }
3059
      mpfr_clear(imag);
3060
      mpfr_clear(fval);
3061
    }
3062
 
3063
  tree const_tree = this->constant_->get_tree(gogo, context->function());
3064
  if (this->type_ == NULL
3065
      || const_tree == error_mark_node
3066
      || TREE_TYPE(const_tree) == error_mark_node)
3067
    return const_tree;
3068
 
3069
  tree ret;
3070
  if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
3071
    ret = fold_convert(type_tree, const_tree);
3072
  else if (TREE_CODE(type_tree) == INTEGER_TYPE)
3073
    ret = fold(convert_to_integer(type_tree, const_tree));
3074
  else if (TREE_CODE(type_tree) == REAL_TYPE)
3075
    ret = fold(convert_to_real(type_tree, const_tree));
3076
  else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
3077
    ret = fold(convert_to_complex(type_tree, const_tree));
3078
  else
3079
    go_unreachable();
3080
  return ret;
3081
}
3082
 
3083
// Dump ast representation for constant expression.
3084
 
3085
void
3086
Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3087
{
3088
  ast_dump_context->ostream() << this->constant_->name();
3089
}
3090
 
3091
// Make a reference to a constant in an expression.
3092
 
3093
Expression*
3094
Expression::make_const_reference(Named_object* constant,
3095
                                 Location location)
3096
{
3097
  return new Const_expression(constant, location);
3098
}
3099
 
3100
// Find a named object in an expression.
3101
 
3102
int
3103
Find_named_object::expression(Expression** pexpr)
3104
{
3105
  switch ((*pexpr)->classification())
3106
    {
3107
    case Expression::EXPRESSION_CONST_REFERENCE:
3108
      {
3109
        Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3110
        if (ce->named_object() == this->no_)
3111
          break;
3112
 
3113
        // We need to check a constant initializer explicitly, as
3114
        // loops here will not be caught by the loop checking for
3115
        // variable initializers.
3116
        ce->check_for_init_loop();
3117
 
3118
        return TRAVERSE_CONTINUE;
3119
      }
3120
 
3121
    case Expression::EXPRESSION_VAR_REFERENCE:
3122
      if ((*pexpr)->var_expression()->named_object() == this->no_)
3123
        break;
3124
      return TRAVERSE_CONTINUE;
3125
    case Expression::EXPRESSION_FUNC_REFERENCE:
3126
      if ((*pexpr)->func_expression()->named_object() == this->no_)
3127
        break;
3128
      return TRAVERSE_CONTINUE;
3129
    default:
3130
      return TRAVERSE_CONTINUE;
3131
    }
3132
  this->found_ = true;
3133
  return TRAVERSE_EXIT;
3134
}
3135
 
3136
// The nil value.
3137
 
3138
class Nil_expression : public Expression
3139
{
3140
 public:
3141
  Nil_expression(Location location)
3142
    : Expression(EXPRESSION_NIL, location)
3143
  { }
3144
 
3145
  static Expression*
3146
  do_import(Import*);
3147
 
3148
 protected:
3149
  bool
3150
  do_is_constant() const
3151
  { return true; }
3152
 
3153
  Type*
3154
  do_type()
3155
  { return Type::make_nil_type(); }
3156
 
3157
  void
3158
  do_determine_type(const Type_context*)
3159
  { }
3160
 
3161
  Expression*
3162
  do_copy()
3163
  { return this; }
3164
 
3165
  tree
3166
  do_get_tree(Translate_context*)
3167
  { return null_pointer_node; }
3168
 
3169
  void
3170
  do_export(Export* exp) const
3171
  { exp->write_c_string("nil"); }
3172
 
3173
  void
3174
  do_dump_expression(Ast_dump_context* ast_dump_context) const
3175
  { ast_dump_context->ostream() << "nil"; }
3176
};
3177
 
3178
// Import a nil expression.
3179
 
3180
Expression*
3181
Nil_expression::do_import(Import* imp)
3182
{
3183
  imp->require_c_string("nil");
3184
  return Expression::make_nil(imp->location());
3185
}
3186
 
3187
// Make a nil expression.
3188
 
3189
Expression*
3190
Expression::make_nil(Location location)
3191
{
3192
  return new Nil_expression(location);
3193
}
3194
 
3195
// The value of the predeclared constant iota.  This is little more
3196
// than a marker.  This will be lowered to an integer in
3197
// Const_expression::do_lower, which is where we know the value that
3198
// it should have.
3199
 
3200
class Iota_expression : public Parser_expression
3201
{
3202
 public:
3203
  Iota_expression(Location location)
3204
    : Parser_expression(EXPRESSION_IOTA, location)
3205
  { }
3206
 
3207
 protected:
3208
  Expression*
3209
  do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3210
  { go_unreachable(); }
3211
 
3212
  // There should only ever be one of these.
3213
  Expression*
3214
  do_copy()
3215
  { go_unreachable(); }
3216
 
3217
  void
3218
  do_dump_expression(Ast_dump_context* ast_dump_context) const
3219
  { ast_dump_context->ostream() << "iota"; }
3220
};
3221
 
3222
// Make an iota expression.  This is only called for one case: the
3223
// value of the predeclared constant iota.
3224
 
3225
Expression*
3226
Expression::make_iota()
3227
{
3228
  static Iota_expression iota_expression(Linemap::unknown_location());
3229
  return &iota_expression;
3230
}
3231
 
3232
// A type conversion expression.
3233
 
3234
class Type_conversion_expression : public Expression
3235
{
3236
 public:
3237
  Type_conversion_expression(Type* type, Expression* expr,
3238
                             Location location)
3239
    : Expression(EXPRESSION_CONVERSION, location),
3240
      type_(type), expr_(expr), may_convert_function_types_(false)
3241
  { }
3242
 
3243
  // Return the type to which we are converting.
3244
  Type*
3245
  type() const
3246
  { return this->type_; }
3247
 
3248
  // Return the expression which we are converting.
3249
  Expression*
3250
  expr() const
3251
  { return this->expr_; }
3252
 
3253
  // Permit converting from one function type to another.  This is
3254
  // used internally for method expressions.
3255
  void
3256
  set_may_convert_function_types()
3257
  {
3258
    this->may_convert_function_types_ = true;
3259
  }
3260
 
3261
  // Import a type conversion expression.
3262
  static Expression*
3263
  do_import(Import*);
3264
 
3265
 protected:
3266
  int
3267
  do_traverse(Traverse* traverse);
3268
 
3269
  Expression*
3270
  do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3271
 
3272
  bool
3273
  do_is_constant() const
3274
  { return this->expr_->is_constant(); }
3275
 
3276
  bool
3277
  do_integer_constant_value(bool, mpz_t, Type**) const;
3278
 
3279
  bool
3280
  do_float_constant_value(mpfr_t, Type**) const;
3281
 
3282
  bool
3283
  do_complex_constant_value(mpfr_t, mpfr_t, Type**) const;
3284
 
3285
  bool
3286
  do_string_constant_value(std::string*) const;
3287
 
3288
  Type*
3289
  do_type()
3290
  { return this->type_; }
3291
 
3292
  void
3293
  do_determine_type(const Type_context*)
3294
  {
3295
    Type_context subcontext(this->type_, false);
3296
    this->expr_->determine_type(&subcontext);
3297
  }
3298
 
3299
  void
3300
  do_check_types(Gogo*);
3301
 
3302
  Expression*
3303
  do_copy()
3304
  {
3305
    return new Type_conversion_expression(this->type_, this->expr_->copy(),
3306
                                          this->location());
3307
  }
3308
 
3309
  tree
3310
  do_get_tree(Translate_context* context);
3311
 
3312
  void
3313
  do_export(Export*) const;
3314
 
3315
  void
3316
  do_dump_expression(Ast_dump_context*) const;
3317
 
3318
 private:
3319
  // The type to convert to.
3320
  Type* type_;
3321
  // The expression to convert.
3322
  Expression* expr_;
3323
  // True if this is permitted to convert function types.  This is
3324
  // used internally for method expressions.
3325
  bool may_convert_function_types_;
3326
};
3327
 
3328
// Traversal.
3329
 
3330
int
3331
Type_conversion_expression::do_traverse(Traverse* traverse)
3332
{
3333
  if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3334
      || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3335
    return TRAVERSE_EXIT;
3336
  return TRAVERSE_CONTINUE;
3337
}
3338
 
3339
// Convert to a constant at lowering time.
3340
 
3341
Expression*
3342
Type_conversion_expression::do_lower(Gogo*, Named_object*,
3343
                                     Statement_inserter*, int)
3344
{
3345
  Type* type = this->type_;
3346
  Expression* val = this->expr_;
3347
  Location location = this->location();
3348
 
3349
  if (type->integer_type() != NULL)
3350
    {
3351
      mpz_t ival;
3352
      mpz_init(ival);
3353
      Type* dummy;
3354
      if (val->integer_constant_value(false, ival, &dummy))
3355
        {
3356
          if (!Integer_expression::check_constant(ival, type, location))
3357
            mpz_set_ui(ival, 0);
3358
          Expression* ret = Expression::make_integer(&ival, type, location);
3359
          mpz_clear(ival);
3360
          return ret;
3361
        }
3362
 
3363
      mpfr_t fval;
3364
      mpfr_init(fval);
3365
      if (val->float_constant_value(fval, &dummy))
3366
        {
3367
          if (!mpfr_integer_p(fval))
3368
            {
3369
              error_at(location,
3370
                       "floating point constant truncated to integer");
3371
              return Expression::make_error(location);
3372
            }
3373
          mpfr_get_z(ival, fval, GMP_RNDN);
3374
          if (!Integer_expression::check_constant(ival, type, location))
3375
            mpz_set_ui(ival, 0);
3376
          Expression* ret = Expression::make_integer(&ival, type, location);
3377
          mpfr_clear(fval);
3378
          mpz_clear(ival);
3379
          return ret;
3380
        }
3381
      mpfr_clear(fval);
3382
      mpz_clear(ival);
3383
    }
3384
 
3385
  if (type->float_type() != NULL)
3386
    {
3387
      mpfr_t fval;
3388
      mpfr_init(fval);
3389
      Type* dummy;
3390
      if (val->float_constant_value(fval, &dummy))
3391
        {
3392
          if (!Float_expression::check_constant(fval, type, location))
3393
            mpfr_set_ui(fval, 0, GMP_RNDN);
3394
          Float_expression::constrain_float(fval, type);
3395
          Expression *ret = Expression::make_float(&fval, type, location);
3396
          mpfr_clear(fval);
3397
          return ret;
3398
        }
3399
      mpfr_clear(fval);
3400
    }
3401
 
3402
  if (type->complex_type() != NULL)
3403
    {
3404
      mpfr_t real;
3405
      mpfr_t imag;
3406
      mpfr_init(real);
3407
      mpfr_init(imag);
3408
      Type* dummy;
3409
      if (val->complex_constant_value(real, imag, &dummy))
3410
        {
3411
          if (!Complex_expression::check_constant(real, imag, type, location))
3412
            {
3413
              mpfr_set_ui(real, 0, GMP_RNDN);
3414
              mpfr_set_ui(imag, 0, GMP_RNDN);
3415
            }
3416
          Complex_expression::constrain_complex(real, imag, type);
3417
          Expression* ret = Expression::make_complex(&real, &imag, type,
3418
                                                     location);
3419
          mpfr_clear(real);
3420
          mpfr_clear(imag);
3421
          return ret;
3422
        }
3423
      mpfr_clear(real);
3424
      mpfr_clear(imag);
3425
    }
3426
 
3427
  if (type->is_slice_type())
3428
    {
3429
      Type* element_type = type->array_type()->element_type()->forwarded();
3430
      bool is_byte = (element_type->integer_type() != NULL
3431
                      && element_type->integer_type()->is_byte());
3432
      bool is_rune = (element_type->integer_type() != NULL
3433
                      && element_type->integer_type()->is_rune());
3434
      if (is_byte || is_rune)
3435
        {
3436
          std::string s;
3437
          if (val->string_constant_value(&s))
3438
            {
3439
              Expression_list* vals = new Expression_list();
3440
              if (is_byte)
3441
                {
3442
                  for (std::string::const_iterator p = s.begin();
3443
                       p != s.end();
3444
                       p++)
3445
                    {
3446
                      mpz_t val;
3447
                      mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3448
                      Expression* v = Expression::make_integer(&val,
3449
                                                               element_type,
3450
                                                               location);
3451
                      vals->push_back(v);
3452
                      mpz_clear(val);
3453
                    }
3454
                }
3455
              else
3456
                {
3457
                  const char *p = s.data();
3458
                  const char *pend = s.data() + s.length();
3459
                  while (p < pend)
3460
                    {
3461
                      unsigned int c;
3462
                      int adv = Lex::fetch_char(p, &c);
3463
                      if (adv == 0)
3464
                        {
3465
                          warning_at(this->location(), 0,
3466
                                     "invalid UTF-8 encoding");
3467
                          adv = 1;
3468
                        }
3469
                      p += adv;
3470
                      mpz_t val;
3471
                      mpz_init_set_ui(val, c);
3472
                      Expression* v = Expression::make_integer(&val,
3473
                                                               element_type,
3474
                                                               location);
3475
                      vals->push_back(v);
3476
                      mpz_clear(val);
3477
                    }
3478
                }
3479
 
3480
              return Expression::make_slice_composite_literal(type, vals,
3481
                                                              location);
3482
            }
3483
        }
3484
    }
3485
 
3486
  return this;
3487
}
3488
 
3489
// Return the constant integer value if there is one.
3490
 
3491
bool
3492
Type_conversion_expression::do_integer_constant_value(bool iota_is_constant,
3493
                                                      mpz_t val,
3494
                                                      Type** ptype) const
3495
{
3496
  if (this->type_->integer_type() == NULL)
3497
    return false;
3498
 
3499
  mpz_t ival;
3500
  mpz_init(ival);
3501
  Type* dummy;
3502
  if (this->expr_->integer_constant_value(iota_is_constant, ival, &dummy))
3503
    {
3504
      if (!Integer_expression::check_constant(ival, this->type_,
3505
                                              this->location()))
3506
        {
3507
          mpz_clear(ival);
3508
          return false;
3509
        }
3510
      mpz_set(val, ival);
3511
      mpz_clear(ival);
3512
      *ptype = this->type_;
3513
      return true;
3514
    }
3515
  mpz_clear(ival);
3516
 
3517
  mpfr_t fval;
3518
  mpfr_init(fval);
3519
  if (this->expr_->float_constant_value(fval, &dummy))
3520
    {
3521
      mpfr_get_z(val, fval, GMP_RNDN);
3522
      mpfr_clear(fval);
3523
      if (!Integer_expression::check_constant(val, this->type_,
3524
                                              this->location()))
3525
        return false;
3526
      *ptype = this->type_;
3527
      return true;
3528
    }
3529
  mpfr_clear(fval);
3530
 
3531
  return false;
3532
}
3533
 
3534
// Return the constant floating point value if there is one.
3535
 
3536
bool
3537
Type_conversion_expression::do_float_constant_value(mpfr_t val,
3538
                                                    Type** ptype) const
3539
{
3540
  if (this->type_->float_type() == NULL)
3541
    return false;
3542
 
3543
  mpfr_t fval;
3544
  mpfr_init(fval);
3545
  Type* dummy;
3546
  if (this->expr_->float_constant_value(fval, &dummy))
3547
    {
3548
      if (!Float_expression::check_constant(fval, this->type_,
3549
                                            this->location()))
3550
        {
3551
          mpfr_clear(fval);
3552
          return false;
3553
        }
3554
      mpfr_set(val, fval, GMP_RNDN);
3555
      mpfr_clear(fval);
3556
      Float_expression::constrain_float(val, this->type_);
3557
      *ptype = this->type_;
3558
      return true;
3559
    }
3560
  mpfr_clear(fval);
3561
 
3562
  return false;
3563
}
3564
 
3565
// Return the constant complex value if there is one.
3566
 
3567
bool
3568
Type_conversion_expression::do_complex_constant_value(mpfr_t real,
3569
                                                      mpfr_t imag,
3570
                                                      Type **ptype) const
3571
{
3572
  if (this->type_->complex_type() == NULL)
3573
    return false;
3574
 
3575
  mpfr_t rval;
3576
  mpfr_t ival;
3577
  mpfr_init(rval);
3578
  mpfr_init(ival);
3579
  Type* dummy;
3580
  if (this->expr_->complex_constant_value(rval, ival, &dummy))
3581
    {
3582
      if (!Complex_expression::check_constant(rval, ival, this->type_,
3583
                                              this->location()))
3584
        {
3585
          mpfr_clear(rval);
3586
          mpfr_clear(ival);
3587
          return false;
3588
        }
3589
      mpfr_set(real, rval, GMP_RNDN);
3590
      mpfr_set(imag, ival, GMP_RNDN);
3591
      mpfr_clear(rval);
3592
      mpfr_clear(ival);
3593
      Complex_expression::constrain_complex(real, imag, this->type_);
3594
      *ptype = this->type_;
3595
      return true;
3596
    }
3597
  mpfr_clear(rval);
3598
  mpfr_clear(ival);
3599
 
3600
  return false;
3601
}
3602
 
3603
// Return the constant string value if there is one.
3604
 
3605
bool
3606
Type_conversion_expression::do_string_constant_value(std::string* val) const
3607
{
3608
  if (this->type_->is_string_type()
3609
      && this->expr_->type()->integer_type() != NULL)
3610
    {
3611
      mpz_t ival;
3612
      mpz_init(ival);
3613
      Type* dummy;
3614
      if (this->expr_->integer_constant_value(false, ival, &dummy))
3615
        {
3616
          unsigned long ulval = mpz_get_ui(ival);
3617
          if (mpz_cmp_ui(ival, ulval) == 0)
3618
            {
3619
              Lex::append_char(ulval, true, val, this->location());
3620
              mpz_clear(ival);
3621
              return true;
3622
            }
3623
        }
3624
      mpz_clear(ival);
3625
    }
3626
 
3627
  // FIXME: Could handle conversion from const []int here.
3628
 
3629
  return false;
3630
}
3631
 
3632
// Check that types are convertible.
3633
 
3634
void
3635
Type_conversion_expression::do_check_types(Gogo*)
3636
{
3637
  Type* type = this->type_;
3638
  Type* expr_type = this->expr_->type();
3639
  std::string reason;
3640
 
3641
  if (type->is_error() || expr_type->is_error())
3642
    {
3643
      this->set_is_error();
3644
      return;
3645
    }
3646
 
3647
  if (this->may_convert_function_types_
3648
      && type->function_type() != NULL
3649
      && expr_type->function_type() != NULL)
3650
    return;
3651
 
3652
  if (Type::are_convertible(type, expr_type, &reason))
3653
    return;
3654
 
3655
  error_at(this->location(), "%s", reason.c_str());
3656
  this->set_is_error();
3657
}
3658
 
3659
// Get a tree for a type conversion.
3660
 
3661
tree
3662
Type_conversion_expression::do_get_tree(Translate_context* context)
3663
{
3664
  Gogo* gogo = context->gogo();
3665
  tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3666
  tree expr_tree = this->expr_->get_tree(context);
3667
 
3668
  if (type_tree == error_mark_node
3669
      || expr_tree == error_mark_node
3670
      || TREE_TYPE(expr_tree) == error_mark_node)
3671
    return error_mark_node;
3672
 
3673
  if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3674
    return fold_convert(type_tree, expr_tree);
3675
 
3676
  Type* type = this->type_;
3677
  Type* expr_type = this->expr_->type();
3678
  tree ret;
3679
  if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3680
    ret = Expression::convert_for_assignment(context, type, expr_type,
3681
                                             expr_tree, this->location());
3682
  else if (type->integer_type() != NULL)
3683
    {
3684
      if (expr_type->integer_type() != NULL
3685
          || expr_type->float_type() != NULL
3686
          || expr_type->is_unsafe_pointer_type())
3687
        ret = fold(convert_to_integer(type_tree, expr_tree));
3688
      else
3689
        go_unreachable();
3690
    }
3691
  else if (type->float_type() != NULL)
3692
    {
3693
      if (expr_type->integer_type() != NULL
3694
          || expr_type->float_type() != NULL)
3695
        ret = fold(convert_to_real(type_tree, expr_tree));
3696
      else
3697
        go_unreachable();
3698
    }
3699
  else if (type->complex_type() != NULL)
3700
    {
3701
      if (expr_type->complex_type() != NULL)
3702
        ret = fold(convert_to_complex(type_tree, expr_tree));
3703
      else
3704
        go_unreachable();
3705
    }
3706
  else if (type->is_string_type()
3707
           && expr_type->integer_type() != NULL)
3708
    {
3709
      expr_tree = fold_convert(integer_type_node, expr_tree);
3710
      if (host_integerp(expr_tree, 0))
3711
        {
3712
          HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3713
          std::string s;
3714
          Lex::append_char(intval, true, &s, this->location());
3715
          Expression* se = Expression::make_string(s, this->location());
3716
          return se->get_tree(context);
3717
        }
3718
 
3719
      static tree int_to_string_fndecl;
3720
      ret = Gogo::call_builtin(&int_to_string_fndecl,
3721
                               this->location(),
3722
                               "__go_int_to_string",
3723
                               1,
3724
                               type_tree,
3725
                               integer_type_node,
3726
                               fold_convert(integer_type_node, expr_tree));
3727
    }
3728
  else if (type->is_string_type() && expr_type->is_slice_type())
3729
    {
3730
      if (!DECL_P(expr_tree))
3731
        expr_tree = save_expr(expr_tree);
3732
      Array_type* a = expr_type->array_type();
3733
      Type* e = a->element_type()->forwarded();
3734
      go_assert(e->integer_type() != NULL);
3735
      tree valptr = fold_convert(const_ptr_type_node,
3736
                                 a->value_pointer_tree(gogo, expr_tree));
3737
      tree len = a->length_tree(gogo, expr_tree);
3738
      len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3739
                             len);
3740
      if (e->integer_type()->is_byte())
3741
        {
3742
          static tree byte_array_to_string_fndecl;
3743
          ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3744
                                   this->location(),
3745
                                   "__go_byte_array_to_string",
3746
                                   2,
3747
                                   type_tree,
3748
                                   const_ptr_type_node,
3749
                                   valptr,
3750
                                   integer_type_node,
3751
                                   len);
3752
        }
3753
      else
3754
        {
3755
          go_assert(e->integer_type()->is_rune());
3756
          static tree int_array_to_string_fndecl;
3757
          ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3758
                                   this->location(),
3759
                                   "__go_int_array_to_string",
3760
                                   2,
3761
                                   type_tree,
3762
                                   const_ptr_type_node,
3763
                                   valptr,
3764
                                   integer_type_node,
3765
                                   len);
3766
        }
3767
    }
3768
  else if (type->is_slice_type() && expr_type->is_string_type())
3769
    {
3770
      Type* e = type->array_type()->element_type()->forwarded();
3771
      go_assert(e->integer_type() != NULL);
3772
      if (e->integer_type()->is_byte())
3773
        {
3774
          tree string_to_byte_array_fndecl = NULL_TREE;
3775
          ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3776
                                   this->location(),
3777
                                   "__go_string_to_byte_array",
3778
                                   1,
3779
                                   type_tree,
3780
                                   TREE_TYPE(expr_tree),
3781
                                   expr_tree);
3782
        }
3783
      else
3784
        {
3785
          go_assert(e->integer_type()->is_rune());
3786
          tree string_to_int_array_fndecl = NULL_TREE;
3787
          ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3788
                                   this->location(),
3789
                                   "__go_string_to_int_array",
3790
                                   1,
3791
                                   type_tree,
3792
                                   TREE_TYPE(expr_tree),
3793
                                   expr_tree);
3794
        }
3795
    }
3796
  else if ((type->is_unsafe_pointer_type()
3797
            && expr_type->points_to() != NULL)
3798
           || (expr_type->is_unsafe_pointer_type()
3799
               && type->points_to() != NULL))
3800
    ret = fold_convert(type_tree, expr_tree);
3801
  else if (type->is_unsafe_pointer_type()
3802
           && expr_type->integer_type() != NULL)
3803
    ret = convert_to_pointer(type_tree, expr_tree);
3804
  else if (this->may_convert_function_types_
3805
           && type->function_type() != NULL
3806
           && expr_type->function_type() != NULL)
3807
    ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3808
                           expr_tree);
3809
  else
3810
    ret = Expression::convert_for_assignment(context, type, expr_type,
3811
                                             expr_tree, this->location());
3812
 
3813
  return ret;
3814
}
3815
 
3816
// Output a type conversion in a constant expression.
3817
 
3818
void
3819
Type_conversion_expression::do_export(Export* exp) const
3820
{
3821
  exp->write_c_string("convert(");
3822
  exp->write_type(this->type_);
3823
  exp->write_c_string(", ");
3824
  this->expr_->export_expression(exp);
3825
  exp->write_c_string(")");
3826
}
3827
 
3828
// Import a type conversion or a struct construction.
3829
 
3830
Expression*
3831
Type_conversion_expression::do_import(Import* imp)
3832
{
3833
  imp->require_c_string("convert(");
3834
  Type* type = imp->read_type();
3835
  imp->require_c_string(", ");
3836
  Expression* val = Expression::import_expression(imp);
3837
  imp->require_c_string(")");
3838
  return Expression::make_cast(type, val, imp->location());
3839
}
3840
 
3841
// Dump ast representation for a type conversion expression.
3842
 
3843
void
3844
Type_conversion_expression::do_dump_expression(
3845
    Ast_dump_context* ast_dump_context) const
3846
{
3847
  ast_dump_context->dump_type(this->type_);
3848
  ast_dump_context->ostream() << "(";
3849
  ast_dump_context->dump_expression(this->expr_);
3850
  ast_dump_context->ostream() << ") ";
3851
}
3852
 
3853
// Make a type cast expression.
3854
 
3855
Expression*
3856
Expression::make_cast(Type* type, Expression* val, Location location)
3857
{
3858
  if (type->is_error_type() || val->is_error_expression())
3859
    return Expression::make_error(location);
3860
  return new Type_conversion_expression(type, val, location);
3861
}
3862
 
3863
// An unsafe type conversion, used to pass values to builtin functions.
3864
 
3865
class Unsafe_type_conversion_expression : public Expression
3866
{
3867
 public:
3868
  Unsafe_type_conversion_expression(Type* type, Expression* expr,
3869
                                    Location location)
3870
    : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3871
      type_(type), expr_(expr)
3872
  { }
3873
 
3874
 protected:
3875
  int
3876
  do_traverse(Traverse* traverse);
3877
 
3878
  Type*
3879
  do_type()
3880
  { return this->type_; }
3881
 
3882
  void
3883
  do_determine_type(const Type_context*)
3884
  { this->expr_->determine_type_no_context(); }
3885
 
3886
  Expression*
3887
  do_copy()
3888
  {
3889
    return new Unsafe_type_conversion_expression(this->type_,
3890
                                                 this->expr_->copy(),
3891
                                                 this->location());
3892
  }
3893
 
3894
  tree
3895
  do_get_tree(Translate_context*);
3896
 
3897
  void
3898
  do_dump_expression(Ast_dump_context*) const;
3899
 
3900
 private:
3901
  // The type to convert to.
3902
  Type* type_;
3903
  // The expression to convert.
3904
  Expression* expr_;
3905
};
3906
 
3907
// Traversal.
3908
 
3909
int
3910
Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3911
{
3912
  if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3913
      || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3914
    return TRAVERSE_EXIT;
3915
  return TRAVERSE_CONTINUE;
3916
}
3917
 
3918
// Convert to backend representation.
3919
 
3920
tree
3921
Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3922
{
3923
  // We are only called for a limited number of cases.
3924
 
3925
  Type* t = this->type_;
3926
  Type* et = this->expr_->type();
3927
 
3928
  tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3929
  tree expr_tree = this->expr_->get_tree(context);
3930
  if (type_tree == error_mark_node || expr_tree == error_mark_node)
3931
    return error_mark_node;
3932
 
3933
  Location loc = this->location();
3934
 
3935
  bool use_view_convert = false;
3936
  if (t->is_slice_type())
3937
    {
3938
      go_assert(et->is_slice_type());
3939
      use_view_convert = true;
3940
    }
3941
  else if (t->map_type() != NULL)
3942
    go_assert(et->map_type() != NULL);
3943
  else if (t->channel_type() != NULL)
3944
    go_assert(et->channel_type() != NULL);
3945
  else if (t->points_to() != NULL && t->points_to()->channel_type() != NULL)
3946
    go_assert((et->points_to() != NULL
3947
                && et->points_to()->channel_type() != NULL)
3948
               || et->is_nil_type());
3949
  else if (t->points_to() != NULL)
3950
    go_assert(et->points_to() != NULL || et->is_nil_type());
3951
  else if (et->is_unsafe_pointer_type())
3952
    go_assert(t->points_to() != NULL);
3953
  else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3954
    {
3955
      go_assert(et->interface_type() != NULL
3956
                 && !et->interface_type()->is_empty());
3957
      use_view_convert = true;
3958
    }
3959
  else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3960
    {
3961
      go_assert(et->interface_type() != NULL
3962
                 && et->interface_type()->is_empty());
3963
      use_view_convert = true;
3964
    }
3965
  else if (t->integer_type() != NULL)
3966
    {
3967
      go_assert(et->is_boolean_type()
3968
                 || et->integer_type() != NULL
3969
                 || et->function_type() != NULL
3970
                 || et->points_to() != NULL
3971
                 || et->map_type() != NULL
3972
                 || et->channel_type() != NULL);
3973
      return convert_to_integer(type_tree, expr_tree);
3974
    }
3975
  else
3976
    go_unreachable();
3977
 
3978
  if (use_view_convert)
3979
    return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3980
                           expr_tree);
3981
  else
3982
    return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3983
}
3984
 
3985
// Dump ast representation for an unsafe type conversion expression.
3986
 
3987
void
3988
Unsafe_type_conversion_expression::do_dump_expression(
3989
    Ast_dump_context* ast_dump_context) const
3990
{
3991
  ast_dump_context->dump_type(this->type_);
3992
  ast_dump_context->ostream() << "(";
3993
  ast_dump_context->dump_expression(this->expr_);
3994
  ast_dump_context->ostream() << ") ";
3995
}
3996
 
3997
// Make an unsafe type conversion expression.
3998
 
3999
Expression*
4000
Expression::make_unsafe_cast(Type* type, Expression* expr,
4001
                             Location location)
4002
{
4003
  return new Unsafe_type_conversion_expression(type, expr, location);
4004
}
4005
 
4006
// Unary expressions.
4007
 
4008
class Unary_expression : public Expression
4009
{
4010
 public:
4011
  Unary_expression(Operator op, Expression* expr, Location location)
4012
    : Expression(EXPRESSION_UNARY, location),
4013
      op_(op), escapes_(true), create_temp_(false), expr_(expr)
4014
  { }
4015
 
4016
  // Return the operator.
4017
  Operator
4018
  op() const
4019
  { return this->op_; }
4020
 
4021
  // Return the operand.
4022
  Expression*
4023
  operand() const
4024
  { return this->expr_; }
4025
 
4026
  // Record that an address expression does not escape.
4027
  void
4028
  set_does_not_escape()
4029
  {
4030
    go_assert(this->op_ == OPERATOR_AND);
4031
    this->escapes_ = false;
4032
  }
4033
 
4034
  // Record that this is an address expression which should create a
4035
  // temporary variable if necessary.  This is used for method calls.
4036
  void
4037
  set_create_temp()
4038
  {
4039
    go_assert(this->op_ == OPERATOR_AND);
4040
    this->create_temp_ = true;
4041
  }
4042
 
4043
  // Apply unary opcode OP to UVAL, setting VAL.  Return true if this
4044
  // could be done, false if not.
4045
  static bool
4046
  eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val,
4047
               Location);
4048
 
4049
  // Apply unary opcode OP to UVAL, setting VAL.  Return true if this
4050
  // could be done, false if not.
4051
  static bool
4052
  eval_float(Operator op, mpfr_t uval, mpfr_t val);
4053
 
4054
  // Apply unary opcode OP to UREAL/UIMAG, setting REAL/IMAG.  Return
4055
  // true if this could be done, false if not.
4056
  static bool
4057
  eval_complex(Operator op, mpfr_t ureal, mpfr_t uimag, mpfr_t real,
4058
               mpfr_t imag);
4059
 
4060
  static Expression*
4061
  do_import(Import*);
4062
 
4063
 protected:
4064
  int
4065
  do_traverse(Traverse* traverse)
4066
  { return Expression::traverse(&this->expr_, traverse); }
4067
 
4068
  Expression*
4069
  do_lower(Gogo*, Named_object*, Statement_inserter*, int);
4070
 
4071
  bool
4072
  do_is_constant() const;
4073
 
4074
  bool
4075
  do_integer_constant_value(bool, mpz_t, Type**) const;
4076
 
4077
  bool
4078
  do_float_constant_value(mpfr_t, Type**) const;
4079
 
4080
  bool
4081
  do_complex_constant_value(mpfr_t, mpfr_t, Type**) const;
4082
 
4083
  Type*
4084
  do_type();
4085
 
4086
  void
4087
  do_determine_type(const Type_context*);
4088
 
4089
  void
4090
  do_check_types(Gogo*);
4091
 
4092
  Expression*
4093
  do_copy()
4094
  {
4095
    return Expression::make_unary(this->op_, this->expr_->copy(),
4096
                                  this->location());
4097
  }
4098
 
4099
  bool
4100
  do_must_eval_subexpressions_in_order(int*) const
4101
  { return this->op_ == OPERATOR_MULT; }
4102
 
4103
  bool
4104
  do_is_addressable() const
4105
  { return this->op_ == OPERATOR_MULT; }
4106
 
4107
  tree
4108
  do_get_tree(Translate_context*);
4109
 
4110
  void
4111
  do_export(Export*) const;
4112
 
4113
  void
4114
  do_dump_expression(Ast_dump_context*) const;
4115
 
4116
 private:
4117
  // The unary operator to apply.
4118
  Operator op_;
4119
  // Normally true.  False if this is an address expression which does
4120
  // not escape the current function.
4121
  bool escapes_;
4122
  // True if this is an address expression which should create a
4123
  // temporary variable if necessary.
4124
  bool create_temp_;
4125
  // The operand.
4126
  Expression* expr_;
4127
};
4128
 
4129
// If we are taking the address of a composite literal, and the
4130
// contents are not constant, then we want to make a heap composite
4131
// instead.
4132
 
4133
Expression*
4134
Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
4135
{
4136
  Location loc = this->location();
4137
  Operator op = this->op_;
4138
  Expression* expr = this->expr_;
4139
 
4140
  if (op == OPERATOR_MULT && expr->is_type_expression())
4141
    return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
4142
 
4143
  // *&x simplifies to x.  *(*T)(unsafe.Pointer)(&x) does not require
4144
  // moving x to the heap.  FIXME: Is it worth doing a real escape
4145
  // analysis here?  This case is found in math/unsafe.go and is
4146
  // therefore worth special casing.
4147
  if (op == OPERATOR_MULT)
4148
    {
4149
      Expression* e = expr;
4150
      while (e->classification() == EXPRESSION_CONVERSION)
4151
        {
4152
          Type_conversion_expression* te
4153
            = static_cast<Type_conversion_expression*>(e);
4154
          e = te->expr();
4155
        }
4156
 
4157
      if (e->classification() == EXPRESSION_UNARY)
4158
        {
4159
          Unary_expression* ue = static_cast<Unary_expression*>(e);
4160
          if (ue->op_ == OPERATOR_AND)
4161
            {
4162
              if (e == expr)
4163
                {
4164
                  // *&x == x.
4165
                  return ue->expr_;
4166
                }
4167
              ue->set_does_not_escape();
4168
            }
4169
        }
4170
    }
4171
 
4172
  // Catching an invalid indirection of unsafe.Pointer here avoid
4173
  // having to deal with TYPE_VOID in other places.
4174
  if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4175
    {
4176
      error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4177
      return Expression::make_error(this->location());
4178
    }
4179
 
4180
  if (op == OPERATOR_PLUS || op == OPERATOR_MINUS
4181
      || op == OPERATOR_NOT || op == OPERATOR_XOR)
4182
    {
4183
      Expression* ret = NULL;
4184
 
4185
      mpz_t eval;
4186
      mpz_init(eval);
4187
      Type* etype;
4188
      if (expr->integer_constant_value(false, eval, &etype))
4189
        {
4190
          mpz_t val;
4191
          mpz_init(val);
4192
          if (Unary_expression::eval_integer(op, etype, eval, val, loc))
4193
            ret = Expression::make_integer(&val, etype, loc);
4194
          mpz_clear(val);
4195
        }
4196
      mpz_clear(eval);
4197
      if (ret != NULL)
4198
        return ret;
4199
 
4200
      if (op == OPERATOR_PLUS || op == OPERATOR_MINUS)
4201
        {
4202
          mpfr_t fval;
4203
          mpfr_init(fval);
4204
          Type* ftype;
4205
          if (expr->float_constant_value(fval, &ftype))
4206
            {
4207
              mpfr_t val;
4208
              mpfr_init(val);
4209
              if (Unary_expression::eval_float(op, fval, val))
4210
                ret = Expression::make_float(&val, ftype, loc);
4211
              mpfr_clear(val);
4212
            }
4213
          if (ret != NULL)
4214
            {
4215
              mpfr_clear(fval);
4216
              return ret;
4217
            }
4218
 
4219
          mpfr_t ival;
4220
          mpfr_init(ival);
4221
          if (expr->complex_constant_value(fval, ival, &ftype))
4222
            {
4223
              mpfr_t real;
4224
              mpfr_t imag;
4225
              mpfr_init(real);
4226
              mpfr_init(imag);
4227
              if (Unary_expression::eval_complex(op, fval, ival, real, imag))
4228
                ret = Expression::make_complex(&real, &imag, ftype, loc);
4229
              mpfr_clear(real);
4230
              mpfr_clear(imag);
4231
            }
4232
          mpfr_clear(ival);
4233
          mpfr_clear(fval);
4234
          if (ret != NULL)
4235
            return ret;
4236
        }
4237
    }
4238
 
4239
  return this;
4240
}
4241
 
4242
// Return whether a unary expression is a constant.
4243
 
4244
bool
4245
Unary_expression::do_is_constant() const
4246
{
4247
  if (this->op_ == OPERATOR_MULT)
4248
    {
4249
      // Indirecting through a pointer is only constant if the object
4250
      // to which the expression points is constant, but we currently
4251
      // have no way to determine that.
4252
      return false;
4253
    }
4254
  else if (this->op_ == OPERATOR_AND)
4255
    {
4256
      // Taking the address of a variable is constant if it is a
4257
      // global variable, not constant otherwise.  In other cases
4258
      // taking the address is probably not a constant.
4259
      Var_expression* ve = this->expr_->var_expression();
4260
      if (ve != NULL)
4261
        {
4262
          Named_object* no = ve->named_object();
4263
          return no->is_variable() && no->var_value()->is_global();
4264
        }
4265
      return false;
4266
    }
4267
  else
4268
    return this->expr_->is_constant();
4269
}
4270
 
4271
// Apply unary opcode OP to UVAL, setting VAL.  UTYPE is the type of
4272
// UVAL, if known; it may be NULL.  Return true if this could be done,
4273
// false if not.
4274
 
4275
bool
4276
Unary_expression::eval_integer(Operator op, Type* utype, mpz_t uval, mpz_t val,
4277
                               Location location)
4278
{
4279
  switch (op)
4280
    {
4281
    case OPERATOR_PLUS:
4282
      mpz_set(val, uval);
4283
      return true;
4284
    case OPERATOR_MINUS:
4285
      mpz_neg(val, uval);
4286
      return Integer_expression::check_constant(val, utype, location);
4287
    case OPERATOR_NOT:
4288
      mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4289
      return true;
4290
    case OPERATOR_XOR:
4291
      if (utype == NULL
4292
          || utype->integer_type() == NULL
4293
          || utype->integer_type()->is_abstract())
4294
        mpz_com(val, uval);
4295
      else
4296
        {
4297
          // The number of HOST_WIDE_INTs that it takes to represent
4298
          // UVAL.
4299
          size_t count = ((mpz_sizeinbase(uval, 2)
4300
                           + HOST_BITS_PER_WIDE_INT
4301
                           - 1)
4302
                          / HOST_BITS_PER_WIDE_INT);
4303
 
4304
          unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4305
          memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4306
 
4307
          size_t ecount;
4308
          mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4309
          go_assert(ecount <= count);
4310
 
4311
          // Trim down to the number of words required by the type.
4312
          size_t obits = utype->integer_type()->bits();
4313
          if (!utype->integer_type()->is_unsigned())
4314
            ++obits;
4315
          size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4316
                           / HOST_BITS_PER_WIDE_INT);
4317
          go_assert(ocount <= count);
4318
 
4319
          for (size_t i = 0; i < ocount; ++i)
4320
            phwi[i] = ~phwi[i];
4321
 
4322
          size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4323
          if (clearbits != 0)
4324
            phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4325
                                 >> clearbits);
4326
 
4327
          mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4328
 
4329
          delete[] phwi;
4330
        }
4331
      return Integer_expression::check_constant(val, utype, location);
4332
    case OPERATOR_AND:
4333
    case OPERATOR_MULT:
4334
      return false;
4335
    default:
4336
      go_unreachable();
4337
    }
4338
}
4339
 
4340
// Apply unary opcode OP to UVAL, setting VAL.  Return true if this
4341
// could be done, false if not.
4342
 
4343
bool
4344
Unary_expression::eval_float(Operator op, mpfr_t uval, mpfr_t val)
4345
{
4346
  switch (op)
4347
    {
4348
    case OPERATOR_PLUS:
4349
      mpfr_set(val, uval, GMP_RNDN);
4350
      return true;
4351
    case OPERATOR_MINUS:
4352
      mpfr_neg(val, uval, GMP_RNDN);
4353
      return true;
4354
    case OPERATOR_NOT:
4355
    case OPERATOR_XOR:
4356
    case OPERATOR_AND:
4357
    case OPERATOR_MULT:
4358
      return false;
4359
    default:
4360
      go_unreachable();
4361
    }
4362
}
4363
 
4364
// Apply unary opcode OP to RVAL/IVAL, setting REAL/IMAG.  Return true
4365
// if this could be done, false if not.
4366
 
4367
bool
4368
Unary_expression::eval_complex(Operator op, mpfr_t rval, mpfr_t ival,
4369
                               mpfr_t real, mpfr_t imag)
4370
{
4371
  switch (op)
4372
    {
4373
    case OPERATOR_PLUS:
4374
      mpfr_set(real, rval, GMP_RNDN);
4375
      mpfr_set(imag, ival, GMP_RNDN);
4376
      return true;
4377
    case OPERATOR_MINUS:
4378
      mpfr_neg(real, rval, GMP_RNDN);
4379
      mpfr_neg(imag, ival, GMP_RNDN);
4380
      return true;
4381
    case OPERATOR_NOT:
4382
    case OPERATOR_XOR:
4383
    case OPERATOR_AND:
4384
    case OPERATOR_MULT:
4385
      return false;
4386
    default:
4387
      go_unreachable();
4388
    }
4389
}
4390
 
4391
// Return the integral constant value of a unary expression, if it has one.
4392
 
4393
bool
4394
Unary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val,
4395
                                            Type** ptype) const
4396
{
4397
  mpz_t uval;
4398
  mpz_init(uval);
4399
  bool ret;
4400
  if (!this->expr_->integer_constant_value(iota_is_constant, uval, ptype))
4401
    ret = false;
4402
  else
4403
    ret = Unary_expression::eval_integer(this->op_, *ptype, uval, val,
4404
                                         this->location());
4405
  mpz_clear(uval);
4406
  return ret;
4407
}
4408
 
4409
// Return the floating point constant value of a unary expression, if
4410
// it has one.
4411
 
4412
bool
4413
Unary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
4414
{
4415
  mpfr_t uval;
4416
  mpfr_init(uval);
4417
  bool ret;
4418
  if (!this->expr_->float_constant_value(uval, ptype))
4419
    ret = false;
4420
  else
4421
    ret = Unary_expression::eval_float(this->op_, uval, val);
4422
  mpfr_clear(uval);
4423
  return ret;
4424
}
4425
 
4426
// Return the complex constant value of a unary expression, if it has
4427
// one.
4428
 
4429
bool
4430
Unary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
4431
                                            Type** ptype) const
4432
{
4433
  mpfr_t rval;
4434
  mpfr_t ival;
4435
  mpfr_init(rval);
4436
  mpfr_init(ival);
4437
  bool ret;
4438
  if (!this->expr_->complex_constant_value(rval, ival, ptype))
4439
    ret = false;
4440
  else
4441
    ret = Unary_expression::eval_complex(this->op_, rval, ival, real, imag);
4442
  mpfr_clear(rval);
4443
  mpfr_clear(ival);
4444
  return ret;
4445
}
4446
 
4447
// Return the type of a unary expression.
4448
 
4449
Type*
4450
Unary_expression::do_type()
4451
{
4452
  switch (this->op_)
4453
    {
4454
    case OPERATOR_PLUS:
4455
    case OPERATOR_MINUS:
4456
    case OPERATOR_NOT:
4457
    case OPERATOR_XOR:
4458
      return this->expr_->type();
4459
 
4460
    case OPERATOR_AND:
4461
      return Type::make_pointer_type(this->expr_->type());
4462
 
4463
    case OPERATOR_MULT:
4464
      {
4465
        Type* subtype = this->expr_->type();
4466
        Type* points_to = subtype->points_to();
4467
        if (points_to == NULL)
4468
          return Type::make_error_type();
4469
        return points_to;
4470
      }
4471
 
4472
    default:
4473
      go_unreachable();
4474
    }
4475
}
4476
 
4477
// Determine abstract types for a unary expression.
4478
 
4479
void
4480
Unary_expression::do_determine_type(const Type_context* context)
4481
{
4482
  switch (this->op_)
4483
    {
4484
    case OPERATOR_PLUS:
4485
    case OPERATOR_MINUS:
4486
    case OPERATOR_NOT:
4487
    case OPERATOR_XOR:
4488
      this->expr_->determine_type(context);
4489
      break;
4490
 
4491
    case OPERATOR_AND:
4492
      // Taking the address of something.
4493
      {
4494
        Type* subtype = (context->type == NULL
4495
                         ? NULL
4496
                         : context->type->points_to());
4497
        Type_context subcontext(subtype, false);
4498
        this->expr_->determine_type(&subcontext);
4499
      }
4500
      break;
4501
 
4502
    case OPERATOR_MULT:
4503
      // Indirecting through a pointer.
4504
      {
4505
        Type* subtype = (context->type == NULL
4506
                         ? NULL
4507
                         : Type::make_pointer_type(context->type));
4508
        Type_context subcontext(subtype, false);
4509
        this->expr_->determine_type(&subcontext);
4510
      }
4511
      break;
4512
 
4513
    default:
4514
      go_unreachable();
4515
    }
4516
}
4517
 
4518
// Check types for a unary expression.
4519
 
4520
void
4521
Unary_expression::do_check_types(Gogo*)
4522
{
4523
  Type* type = this->expr_->type();
4524
  if (type->is_error())
4525
    {
4526
      this->set_is_error();
4527
      return;
4528
    }
4529
 
4530
  switch (this->op_)
4531
    {
4532
    case OPERATOR_PLUS:
4533
    case OPERATOR_MINUS:
4534
      if (type->integer_type() == NULL
4535
          && type->float_type() == NULL
4536
          && type->complex_type() == NULL)
4537
        this->report_error(_("expected numeric type"));
4538
      break;
4539
 
4540
    case OPERATOR_NOT:
4541
    case OPERATOR_XOR:
4542
      if (type->integer_type() == NULL
4543
          && !type->is_boolean_type())
4544
        this->report_error(_("expected integer or boolean type"));
4545
      break;
4546
 
4547
    case OPERATOR_AND:
4548
      if (!this->expr_->is_addressable())
4549
        {
4550
          if (!this->create_temp_)
4551
            this->report_error(_("invalid operand for unary %<&%>"));
4552
        }
4553
      else
4554
        this->expr_->address_taken(this->escapes_);
4555
      break;
4556
 
4557
    case OPERATOR_MULT:
4558
      // Indirecting through a pointer.
4559
      if (type->points_to() == NULL)
4560
        this->report_error(_("expected pointer"));
4561
      break;
4562
 
4563
    default:
4564
      go_unreachable();
4565
    }
4566
}
4567
 
4568
// Get a tree for a unary expression.
4569
 
4570
tree
4571
Unary_expression::do_get_tree(Translate_context* context)
4572
{
4573
  Location loc = this->location();
4574
 
4575
  // Taking the address of a set-and-use-temporary expression requires
4576
  // setting the temporary and then taking the address.
4577
  if (this->op_ == OPERATOR_AND)
4578
    {
4579
      Set_and_use_temporary_expression* sut =
4580
        this->expr_->set_and_use_temporary_expression();
4581
      if (sut != NULL)
4582
        {
4583
          Temporary_statement* temp = sut->temporary();
4584
          Bvariable* bvar = temp->get_backend_variable(context);
4585
          tree var_tree = var_to_tree(bvar);
4586
          Expression* val = sut->expression();
4587
          tree val_tree = val->get_tree(context);
4588
          if (var_tree == error_mark_node || val_tree == error_mark_node)
4589
            return error_mark_node;
4590
          tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
4591
                                                    var_tree);
4592
          return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4593
                            TREE_TYPE(addr_tree),
4594
                            build2_loc(sut->location().gcc_location(),
4595
                                       MODIFY_EXPR, void_type_node,
4596
                                       var_tree, val_tree),
4597
                            addr_tree);
4598
        }
4599
    }
4600
 
4601
  tree expr = this->expr_->get_tree(context);
4602
  if (expr == error_mark_node)
4603
    return error_mark_node;
4604
 
4605
  switch (this->op_)
4606
    {
4607
    case OPERATOR_PLUS:
4608
      return expr;
4609
 
4610
    case OPERATOR_MINUS:
4611
      {
4612
        tree type = TREE_TYPE(expr);
4613
        tree compute_type = excess_precision_type(type);
4614
        if (compute_type != NULL_TREE)
4615
          expr = ::convert(compute_type, expr);
4616
        tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
4617
                                   (compute_type != NULL_TREE
4618
                                    ? compute_type
4619
                                    : type),
4620
                                   expr);
4621
        if (compute_type != NULL_TREE)
4622
          ret = ::convert(type, ret);
4623
        return ret;
4624
      }
4625
 
4626
    case OPERATOR_NOT:
4627
      if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
4628
        return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
4629
                               TREE_TYPE(expr), expr);
4630
      else
4631
        return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
4632
                               expr, build_int_cst(TREE_TYPE(expr), 0));
4633
 
4634
    case OPERATOR_XOR:
4635
      return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4636
                             expr);
4637
 
4638
    case OPERATOR_AND:
4639
      if (!this->create_temp_)
4640
        {
4641
          // We should not see a non-constant constructor here; cases
4642
          // where we would see one should have been moved onto the
4643
          // heap at parse time.  Taking the address of a nonconstant
4644
          // constructor will not do what the programmer expects.
4645
          go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4646
          go_assert(TREE_CODE(expr) != ADDR_EXPR);
4647
        }
4648
 
4649
      // Build a decl for a constant constructor.
4650
      if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4651
        {
4652
          tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4653
                                 create_tmp_var_name("C"), TREE_TYPE(expr));
4654
          DECL_EXTERNAL(decl) = 0;
4655
          TREE_PUBLIC(decl) = 0;
4656
          TREE_READONLY(decl) = 1;
4657
          TREE_CONSTANT(decl) = 1;
4658
          TREE_STATIC(decl) = 1;
4659
          TREE_ADDRESSABLE(decl) = 1;
4660
          DECL_ARTIFICIAL(decl) = 1;
4661
          DECL_INITIAL(decl) = expr;
4662
          rest_of_decl_compilation(decl, 1, 0);
4663
          expr = decl;
4664
        }
4665
 
4666
      if (this->create_temp_
4667
          && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4668
          && !DECL_P(expr)
4669
          && TREE_CODE(expr) != INDIRECT_REF
4670
          && TREE_CODE(expr) != COMPONENT_REF)
4671
        {
4672
          tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4673
          DECL_IGNORED_P(tmp) = 1;
4674
          DECL_INITIAL(tmp) = expr;
4675
          TREE_ADDRESSABLE(tmp) = 1;
4676
          return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4677
                            build_pointer_type(TREE_TYPE(expr)),
4678
                            build1_loc(loc.gcc_location(), DECL_EXPR,
4679
                                       void_type_node, tmp),
4680
                            build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4681
        }
4682
 
4683
      return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4684
 
4685
    case OPERATOR_MULT:
4686
      {
4687
        go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4688
 
4689
        // If we are dereferencing the pointer to a large struct, we
4690
        // need to check for nil.  We don't bother to check for small
4691
        // structs because we expect the system to crash on a nil
4692
        // pointer dereference.
4693
        HOST_WIDE_INT s = int_size_in_bytes(TREE_TYPE(TREE_TYPE(expr)));
4694
        if (s == -1 || s >= 4096)
4695
          {
4696
            if (!DECL_P(expr))
4697
              expr = save_expr(expr);
4698
            tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4699
                                           boolean_type_node,
4700
                                           expr,
4701
                                           fold_convert(TREE_TYPE(expr),
4702
                                                        null_pointer_node));
4703
            tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4704
                                             loc);
4705
            expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4706
                                   TREE_TYPE(expr), build3(COND_EXPR,
4707
                                                           void_type_node,
4708
                                                           compare, crash,
4709
                                                           NULL_TREE),
4710
                                   expr);
4711
          }
4712
 
4713
        // If the type of EXPR is a recursive pointer type, then we
4714
        // need to insert a cast before indirecting.
4715
        if (TREE_TYPE(TREE_TYPE(expr)) == ptr_type_node)
4716
          {
4717
            Type* pt = this->expr_->type()->points_to();
4718
            tree ind = type_to_tree(pt->get_backend(context->gogo()));
4719
            expr = fold_convert_loc(loc.gcc_location(),
4720
                                    build_pointer_type(ind), expr);
4721
          }
4722
 
4723
        return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4724
      }
4725
 
4726
    default:
4727
      go_unreachable();
4728
    }
4729
}
4730
 
4731
// Export a unary expression.
4732
 
4733
void
4734
Unary_expression::do_export(Export* exp) const
4735
{
4736
  switch (this->op_)
4737
    {
4738
    case OPERATOR_PLUS:
4739
      exp->write_c_string("+ ");
4740
      break;
4741
    case OPERATOR_MINUS:
4742
      exp->write_c_string("- ");
4743
      break;
4744
    case OPERATOR_NOT:
4745
      exp->write_c_string("! ");
4746
      break;
4747
    case OPERATOR_XOR:
4748
      exp->write_c_string("^ ");
4749
      break;
4750
    case OPERATOR_AND:
4751
    case OPERATOR_MULT:
4752
    default:
4753
      go_unreachable();
4754
    }
4755
  this->expr_->export_expression(exp);
4756
}
4757
 
4758
// Import a unary expression.
4759
 
4760
Expression*
4761
Unary_expression::do_import(Import* imp)
4762
{
4763
  Operator op;
4764
  switch (imp->get_char())
4765
    {
4766
    case '+':
4767
      op = OPERATOR_PLUS;
4768
      break;
4769
    case '-':
4770
      op = OPERATOR_MINUS;
4771
      break;
4772
    case '!':
4773
      op = OPERATOR_NOT;
4774
      break;
4775
    case '^':
4776
      op = OPERATOR_XOR;
4777
      break;
4778
    default:
4779
      go_unreachable();
4780
    }
4781
  imp->require_c_string(" ");
4782
  Expression* expr = Expression::import_expression(imp);
4783
  return Expression::make_unary(op, expr, imp->location());
4784
}
4785
 
4786
// Dump ast representation of an unary expression.
4787
 
4788
void
4789
Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4790
{
4791
  ast_dump_context->dump_operator(this->op_);
4792
  ast_dump_context->ostream() << "(";
4793
  ast_dump_context->dump_expression(this->expr_);
4794
  ast_dump_context->ostream() << ") ";
4795
}
4796
 
4797
// Make a unary expression.
4798
 
4799
Expression*
4800
Expression::make_unary(Operator op, Expression* expr, Location location)
4801
{
4802
  return new Unary_expression(op, expr, location);
4803
}
4804
 
4805
// If this is an indirection through a pointer, return the expression
4806
// being pointed through.  Otherwise return this.
4807
 
4808
Expression*
4809
Expression::deref()
4810
{
4811
  if (this->classification_ == EXPRESSION_UNARY)
4812
    {
4813
      Unary_expression* ue = static_cast<Unary_expression*>(this);
4814
      if (ue->op() == OPERATOR_MULT)
4815
        return ue->operand();
4816
    }
4817
  return this;
4818
}
4819
 
4820
// Class Binary_expression.
4821
 
4822
// Traversal.
4823
 
4824
int
4825
Binary_expression::do_traverse(Traverse* traverse)
4826
{
4827
  int t = Expression::traverse(&this->left_, traverse);
4828
  if (t == TRAVERSE_EXIT)
4829
    return TRAVERSE_EXIT;
4830
  return Expression::traverse(&this->right_, traverse);
4831
}
4832
 
4833
// Compare integer constants according to OP.
4834
 
4835
bool
4836
Binary_expression::compare_integer(Operator op, mpz_t left_val,
4837
                                   mpz_t right_val)
4838
{
4839
  int i = mpz_cmp(left_val, right_val);
4840
  switch (op)
4841
    {
4842
    case OPERATOR_EQEQ:
4843
      return i == 0;
4844
    case OPERATOR_NOTEQ:
4845
      return i != 0;
4846
    case OPERATOR_LT:
4847
      return i < 0;
4848
    case OPERATOR_LE:
4849
      return i <= 0;
4850
    case OPERATOR_GT:
4851
      return i > 0;
4852
    case OPERATOR_GE:
4853
      return i >= 0;
4854
    default:
4855
      go_unreachable();
4856
    }
4857
}
4858
 
4859
// Compare floating point constants according to OP.
4860
 
4861
bool
4862
Binary_expression::compare_float(Operator op, Type* type, mpfr_t left_val,
4863
                                 mpfr_t right_val)
4864
{
4865
  int i;
4866
  if (type == NULL)
4867
    i = mpfr_cmp(left_val, right_val);
4868
  else
4869
    {
4870
      mpfr_t lv;
4871
      mpfr_init_set(lv, left_val, GMP_RNDN);
4872
      mpfr_t rv;
4873
      mpfr_init_set(rv, right_val, GMP_RNDN);
4874
      Float_expression::constrain_float(lv, type);
4875
      Float_expression::constrain_float(rv, type);
4876
      i = mpfr_cmp(lv, rv);
4877
      mpfr_clear(lv);
4878
      mpfr_clear(rv);
4879
    }
4880
  switch (op)
4881
    {
4882
    case OPERATOR_EQEQ:
4883
      return i == 0;
4884
    case OPERATOR_NOTEQ:
4885
      return i != 0;
4886
    case OPERATOR_LT:
4887
      return i < 0;
4888
    case OPERATOR_LE:
4889
      return i <= 0;
4890
    case OPERATOR_GT:
4891
      return i > 0;
4892
    case OPERATOR_GE:
4893
      return i >= 0;
4894
    default:
4895
      go_unreachable();
4896
    }
4897
}
4898
 
4899
// Compare complex constants according to OP.  Complex numbers may
4900
// only be compared for equality.
4901
 
4902
bool
4903
Binary_expression::compare_complex(Operator op, Type* type,
4904
                                   mpfr_t left_real, mpfr_t left_imag,
4905
                                   mpfr_t right_real, mpfr_t right_imag)
4906
{
4907
  bool is_equal;
4908
  if (type == NULL)
4909
    is_equal = (mpfr_cmp(left_real, right_real) == 0
4910
                && mpfr_cmp(left_imag, right_imag) == 0);
4911
  else
4912
    {
4913
      mpfr_t lr;
4914
      mpfr_t li;
4915
      mpfr_init_set(lr, left_real, GMP_RNDN);
4916
      mpfr_init_set(li, left_imag, GMP_RNDN);
4917
      mpfr_t rr;
4918
      mpfr_t ri;
4919
      mpfr_init_set(rr, right_real, GMP_RNDN);
4920
      mpfr_init_set(ri, right_imag, GMP_RNDN);
4921
      Complex_expression::constrain_complex(lr, li, type);
4922
      Complex_expression::constrain_complex(rr, ri, type);
4923
      is_equal = mpfr_cmp(lr, rr) == 0 && mpfr_cmp(li, ri) == 0;
4924
      mpfr_clear(lr);
4925
      mpfr_clear(li);
4926
      mpfr_clear(rr);
4927
      mpfr_clear(ri);
4928
    }
4929
  switch (op)
4930
    {
4931
    case OPERATOR_EQEQ:
4932
      return is_equal;
4933
    case OPERATOR_NOTEQ:
4934
      return !is_equal;
4935
    default:
4936
      go_unreachable();
4937
    }
4938
}
4939
 
4940
// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL.
4941
// LEFT_TYPE is the type of LEFT_VAL, RIGHT_TYPE is the type of
4942
// RIGHT_VAL; LEFT_TYPE and/or RIGHT_TYPE may be NULL.  Return true if
4943
// this could be done, false if not.
4944
 
4945
bool
4946
Binary_expression::eval_integer(Operator op, Type* left_type, mpz_t left_val,
4947
                                Type* right_type, mpz_t right_val,
4948
                                Location location, mpz_t val)
4949
{
4950
  bool is_shift_op = false;
4951
  switch (op)
4952
    {
4953
    case OPERATOR_OROR:
4954
    case OPERATOR_ANDAND:
4955
    case OPERATOR_EQEQ:
4956
    case OPERATOR_NOTEQ:
4957
    case OPERATOR_LT:
4958
    case OPERATOR_LE:
4959
    case OPERATOR_GT:
4960
    case OPERATOR_GE:
4961
      // These return boolean values.  We should probably handle them
4962
      // anyhow in case a type conversion is used on the result.
4963
      return false;
4964
    case OPERATOR_PLUS:
4965
      mpz_add(val, left_val, right_val);
4966
      break;
4967
    case OPERATOR_MINUS:
4968
      mpz_sub(val, left_val, right_val);
4969
      break;
4970
    case OPERATOR_OR:
4971
      mpz_ior(val, left_val, right_val);
4972
      break;
4973
    case OPERATOR_XOR:
4974
      mpz_xor(val, left_val, right_val);
4975
      break;
4976
    case OPERATOR_MULT:
4977
      mpz_mul(val, left_val, right_val);
4978
      break;
4979
    case OPERATOR_DIV:
4980
      if (mpz_sgn(right_val) != 0)
4981
        mpz_tdiv_q(val, left_val, right_val);
4982
      else
4983
        {
4984
          error_at(location, "division by zero");
4985
          mpz_set_ui(val, 0);
4986
          return true;
4987
        }
4988
      break;
4989
    case OPERATOR_MOD:
4990
      if (mpz_sgn(right_val) != 0)
4991
        mpz_tdiv_r(val, left_val, right_val);
4992
      else
4993
        {
4994
          error_at(location, "division by zero");
4995
          mpz_set_ui(val, 0);
4996
          return true;
4997
        }
4998
      break;
4999
    case OPERATOR_LSHIFT:
5000
      {
5001
        unsigned long shift = mpz_get_ui(right_val);
5002
        if (mpz_cmp_ui(right_val, shift) != 0 || shift > 0x100000)
5003
          {
5004
            error_at(location, "shift count overflow");
5005
            mpz_set_ui(val, 0);
5006
            return true;
5007
          }
5008
        mpz_mul_2exp(val, left_val, shift);
5009
        is_shift_op = true;
5010
        break;
5011
      }
5012
      break;
5013
    case OPERATOR_RSHIFT:
5014
      {
5015
        unsigned long shift = mpz_get_ui(right_val);
5016
        if (mpz_cmp_ui(right_val, shift) != 0)
5017
          {
5018
            error_at(location, "shift count overflow");
5019
            mpz_set_ui(val, 0);
5020
            return true;
5021
          }
5022
        if (mpz_cmp_ui(left_val, 0) >= 0)
5023
          mpz_tdiv_q_2exp(val, left_val, shift);
5024
        else
5025
          mpz_fdiv_q_2exp(val, left_val, shift);
5026
        is_shift_op = true;
5027
        break;
5028
      }
5029
      break;
5030
    case OPERATOR_AND:
5031
      mpz_and(val, left_val, right_val);
5032
      break;
5033
    case OPERATOR_BITCLEAR:
5034
      {
5035
        mpz_t tval;
5036
        mpz_init(tval);
5037
        mpz_com(tval, right_val);
5038
        mpz_and(val, left_val, tval);
5039
        mpz_clear(tval);
5040
      }
5041
      break;
5042
    default:
5043
      go_unreachable();
5044
    }
5045
 
5046
  Type* type = left_type;
5047
  if (!is_shift_op)
5048
    {
5049
      if (type == NULL)
5050
        type = right_type;
5051
      else if (type != right_type && right_type != NULL)
5052
        {
5053
          if (type->is_abstract())
5054
            type = right_type;
5055
          else if (!right_type->is_abstract())
5056
            {
5057
              // This look like a type error which should be diagnosed
5058
              // elsewhere.  Don't do anything here, to avoid an
5059
              // unhelpful chain of error messages.
5060
              return true;
5061
            }
5062
        }
5063
    }
5064
 
5065
  if (type != NULL && !type->is_abstract())
5066
    {
5067
      // We have to check the operands too, as we have implicitly
5068
      // coerced them to TYPE.
5069
      if ((type != left_type
5070
           && !Integer_expression::check_constant(left_val, type, location))
5071
          || (!is_shift_op
5072
              && type != right_type
5073
              && !Integer_expression::check_constant(right_val, type,
5074
                                                     location))
5075
          || !Integer_expression::check_constant(val, type, location))
5076
        mpz_set_ui(val, 0);
5077
    }
5078
 
5079
  return true;
5080
}
5081
 
5082
// Apply binary opcode OP to LEFT_VAL and RIGHT_VAL, setting VAL.
5083
// Return true if this could be done, false if not.
5084
 
5085
bool
5086
Binary_expression::eval_float(Operator op, Type* left_type, mpfr_t left_val,
5087
                              Type* right_type, mpfr_t right_val,
5088
                              mpfr_t val, Location location)
5089
{
5090
  switch (op)
5091
    {
5092
    case OPERATOR_OROR:
5093
    case OPERATOR_ANDAND:
5094
    case OPERATOR_EQEQ:
5095
    case OPERATOR_NOTEQ:
5096
    case OPERATOR_LT:
5097
    case OPERATOR_LE:
5098
    case OPERATOR_GT:
5099
    case OPERATOR_GE:
5100
      // These return boolean values.  We should probably handle them
5101
      // anyhow in case a type conversion is used on the result.
5102
      return false;
5103
    case OPERATOR_PLUS:
5104
      mpfr_add(val, left_val, right_val, GMP_RNDN);
5105
      break;
5106
    case OPERATOR_MINUS:
5107
      mpfr_sub(val, left_val, right_val, GMP_RNDN);
5108
      break;
5109
    case OPERATOR_OR:
5110
    case OPERATOR_XOR:
5111
    case OPERATOR_AND:
5112
    case OPERATOR_BITCLEAR:
5113
      return false;
5114
    case OPERATOR_MULT:
5115
      mpfr_mul(val, left_val, right_val, GMP_RNDN);
5116
      break;
5117
    case OPERATOR_DIV:
5118
      if (mpfr_zero_p(right_val))
5119
        error_at(location, "division by zero");
5120
      mpfr_div(val, left_val, right_val, GMP_RNDN);
5121
      break;
5122
    case OPERATOR_MOD:
5123
      return false;
5124
    case OPERATOR_LSHIFT:
5125
    case OPERATOR_RSHIFT:
5126
      return false;
5127
    default:
5128
      go_unreachable();
5129
    }
5130
 
5131
  Type* type = left_type;
5132
  if (type == NULL)
5133
    type = right_type;
5134
  else if (type != right_type && right_type != NULL)
5135
    {
5136
      if (type->is_abstract())
5137
        type = right_type;
5138
      else if (!right_type->is_abstract())
5139
        {
5140
          // This looks like a type error which should be diagnosed
5141
          // elsewhere.  Don't do anything here, to avoid an unhelpful
5142
          // chain of error messages.
5143
          return true;
5144
        }
5145
    }
5146
 
5147
  if (type != NULL && !type->is_abstract())
5148
    {
5149
      if ((type != left_type
5150
           && !Float_expression::check_constant(left_val, type, location))
5151
          || (type != right_type
5152
              && !Float_expression::check_constant(right_val, type,
5153
                                                   location))
5154
          || !Float_expression::check_constant(val, type, location))
5155
        mpfr_set_ui(val, 0, GMP_RNDN);
5156
    }
5157
 
5158
  return true;
5159
}
5160
 
5161
// Apply binary opcode OP to LEFT_REAL/LEFT_IMAG and
5162
// RIGHT_REAL/RIGHT_IMAG, setting REAL/IMAG.  Return true if this
5163
// could be done, false if not.
5164
 
5165
bool
5166
Binary_expression::eval_complex(Operator op, Type* left_type,
5167
                                mpfr_t left_real, mpfr_t left_imag,
5168
                                Type *right_type,
5169
                                mpfr_t right_real, mpfr_t right_imag,
5170
                                mpfr_t real, mpfr_t imag,
5171
                                Location location)
5172
{
5173
  switch (op)
5174
    {
5175
    case OPERATOR_OROR:
5176
    case OPERATOR_ANDAND:
5177
    case OPERATOR_EQEQ:
5178
    case OPERATOR_NOTEQ:
5179
    case OPERATOR_LT:
5180
    case OPERATOR_LE:
5181
    case OPERATOR_GT:
5182
    case OPERATOR_GE:
5183
      // These return boolean values and must be handled differently.
5184
      return false;
5185
    case OPERATOR_PLUS:
5186
      mpfr_add(real, left_real, right_real, GMP_RNDN);
5187
      mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
5188
      break;
5189
    case OPERATOR_MINUS:
5190
      mpfr_sub(real, left_real, right_real, GMP_RNDN);
5191
      mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
5192
      break;
5193
    case OPERATOR_OR:
5194
    case OPERATOR_XOR:
5195
    case OPERATOR_AND:
5196
    case OPERATOR_BITCLEAR:
5197
      return false;
5198
    case OPERATOR_MULT:
5199
      {
5200
        // You might think that multiplying two complex numbers would
5201
        // be simple, and you would be right, until you start to think
5202
        // about getting the right answer for infinity.  If one
5203
        // operand here is infinity and the other is anything other
5204
        // than zero or NaN, then we are going to wind up subtracting
5205
        // two infinity values.  That will give us a NaN, but the
5206
        // correct answer is infinity.
5207
 
5208
        mpfr_t lrrr;
5209
        mpfr_init(lrrr);
5210
        mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
5211
 
5212
        mpfr_t lrri;
5213
        mpfr_init(lrri);
5214
        mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
5215
 
5216
        mpfr_t lirr;
5217
        mpfr_init(lirr);
5218
        mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
5219
 
5220
        mpfr_t liri;
5221
        mpfr_init(liri);
5222
        mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
5223
 
5224
        mpfr_sub(real, lrrr, liri, GMP_RNDN);
5225
        mpfr_add(imag, lrri, lirr, GMP_RNDN);
5226
 
5227
        // If we get NaN on both sides, check whether it should really
5228
        // be infinity.  The rule is that if either side of the
5229
        // complex number is infinity, then the whole value is
5230
        // infinity, even if the other side is NaN.  So the only case
5231
        // we have to fix is the one in which both sides are NaN.
5232
        if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5233
            && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5234
            && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5235
          {
5236
            bool is_infinity = false;
5237
 
5238
            mpfr_t lr;
5239
            mpfr_t li;
5240
            mpfr_init_set(lr, left_real, GMP_RNDN);
5241
            mpfr_init_set(li, left_imag, GMP_RNDN);
5242
 
5243
            mpfr_t rr;
5244
            mpfr_t ri;
5245
            mpfr_init_set(rr, right_real, GMP_RNDN);
5246
            mpfr_init_set(ri, right_imag, GMP_RNDN);
5247
 
5248
            // If the left side is infinity, then the result is
5249
            // infinity.
5250
            if (mpfr_inf_p(lr) || mpfr_inf_p(li))
5251
              {
5252
                mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
5253
                mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5254
                mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
5255
                mpfr_copysign(li, li, left_imag, GMP_RNDN);
5256
                if (mpfr_nan_p(rr))
5257
                  {
5258
                    mpfr_set_ui(rr, 0, GMP_RNDN);
5259
                    mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5260
                  }
5261
                if (mpfr_nan_p(ri))
5262
                  {
5263
                    mpfr_set_ui(ri, 0, GMP_RNDN);
5264
                    mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5265
                  }
5266
                is_infinity = true;
5267
              }
5268
 
5269
            // If the right side is infinity, then the result is
5270
            // infinity.
5271
            if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
5272
              {
5273
                mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5274
                mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5275
                mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5276
                mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5277
                if (mpfr_nan_p(lr))
5278
                  {
5279
                    mpfr_set_ui(lr, 0, GMP_RNDN);
5280
                    mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5281
                  }
5282
                if (mpfr_nan_p(li))
5283
                  {
5284
                    mpfr_set_ui(li, 0, GMP_RNDN);
5285
                    mpfr_copysign(li, li, left_imag, GMP_RNDN);
5286
                  }
5287
                is_infinity = true;
5288
              }
5289
 
5290
            // If we got an overflow in the intermediate computations,
5291
            // then the result is infinity.
5292
            if (!is_infinity
5293
                && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
5294
                    || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
5295
              {
5296
                if (mpfr_nan_p(lr))
5297
                  {
5298
                    mpfr_set_ui(lr, 0, GMP_RNDN);
5299
                    mpfr_copysign(lr, lr, left_real, GMP_RNDN);
5300
                  }
5301
                if (mpfr_nan_p(li))
5302
                  {
5303
                    mpfr_set_ui(li, 0, GMP_RNDN);
5304
                    mpfr_copysign(li, li, left_imag, GMP_RNDN);
5305
                  }
5306
                if (mpfr_nan_p(rr))
5307
                  {
5308
                    mpfr_set_ui(rr, 0, GMP_RNDN);
5309
                    mpfr_copysign(rr, rr, right_real, GMP_RNDN);
5310
                  }
5311
                if (mpfr_nan_p(ri))
5312
                  {
5313
                    mpfr_set_ui(ri, 0, GMP_RNDN);
5314
                    mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5315
                  }
5316
                is_infinity = true;
5317
              }
5318
 
5319
            if (is_infinity)
5320
              {
5321
                mpfr_mul(lrrr, lr, rr, GMP_RNDN);
5322
                mpfr_mul(lrri, lr, ri, GMP_RNDN);
5323
                mpfr_mul(lirr, li, rr, GMP_RNDN);
5324
                mpfr_mul(liri, li, ri, GMP_RNDN);
5325
                mpfr_sub(real, lrrr, liri, GMP_RNDN);
5326
                mpfr_add(imag, lrri, lirr, GMP_RNDN);
5327
                mpfr_set_inf(real, mpfr_sgn(real));
5328
                mpfr_set_inf(imag, mpfr_sgn(imag));
5329
              }
5330
 
5331
            mpfr_clear(lr);
5332
            mpfr_clear(li);
5333
            mpfr_clear(rr);
5334
            mpfr_clear(ri);
5335
          }
5336
 
5337
        mpfr_clear(lrrr);
5338
        mpfr_clear(lrri);
5339
        mpfr_clear(lirr);
5340
        mpfr_clear(liri);
5341
      }
5342
      break;
5343
    case OPERATOR_DIV:
5344
      {
5345
        // For complex division we want to avoid having an
5346
        // intermediate overflow turn the whole result in a NaN.  We
5347
        // scale the values to try to avoid this.
5348
 
5349
        if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
5350
          error_at(location, "division by zero");
5351
 
5352
        mpfr_t rra;
5353
        mpfr_t ria;
5354
        mpfr_init(rra);
5355
        mpfr_init(ria);
5356
        mpfr_abs(rra, right_real, GMP_RNDN);
5357
        mpfr_abs(ria, right_imag, GMP_RNDN);
5358
        mpfr_t t;
5359
        mpfr_init(t);
5360
        mpfr_max(t, rra, ria, GMP_RNDN);
5361
 
5362
        mpfr_t rr;
5363
        mpfr_t ri;
5364
        mpfr_init_set(rr, right_real, GMP_RNDN);
5365
        mpfr_init_set(ri, right_imag, GMP_RNDN);
5366
        long ilogbw = 0;
5367
        if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5368
          {
5369
            ilogbw = mpfr_get_exp(t);
5370
            mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5371
            mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5372
          }
5373
 
5374
        mpfr_t denom;
5375
        mpfr_init(denom);
5376
        mpfr_mul(denom, rr, rr, GMP_RNDN);
5377
        mpfr_mul(t, ri, ri, GMP_RNDN);
5378
        mpfr_add(denom, denom, t, GMP_RNDN);
5379
 
5380
        mpfr_mul(real, left_real, rr, GMP_RNDN);
5381
        mpfr_mul(t, left_imag, ri, GMP_RNDN);
5382
        mpfr_add(real, real, t, GMP_RNDN);
5383
        mpfr_div(real, real, denom, GMP_RNDN);
5384
        mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5385
 
5386
        mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5387
        mpfr_mul(t, left_real, ri, GMP_RNDN);
5388
        mpfr_sub(imag, imag, t, GMP_RNDN);
5389
        mpfr_div(imag, imag, denom, GMP_RNDN);
5390
        mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5391
 
5392
        // If we wind up with NaN on both sides, check whether we
5393
        // should really have infinity.  The rule is that if either
5394
        // side of the complex number is infinity, then the whole
5395
        // value is infinity, even if the other side is NaN.  So the
5396
        // only case we have to fix is the one in which both sides are
5397
        // NaN.
5398
        if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5399
            && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5400
            && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5401
          {
5402
            if (mpfr_zero_p(denom))
5403
              {
5404
                mpfr_set_inf(real, mpfr_sgn(rr));
5405
                mpfr_mul(real, real, left_real, GMP_RNDN);
5406
                mpfr_set_inf(imag, mpfr_sgn(rr));
5407
                mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5408
              }
5409
            else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5410
                     && mpfr_number_p(rr) && mpfr_number_p(ri))
5411
              {
5412
                mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5413
                mpfr_copysign(t, t, left_real, GMP_RNDN);
5414
 
5415
                mpfr_t t2;
5416
                mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5417
                mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5418
 
5419
                mpfr_t t3;
5420
                mpfr_init(t3);
5421
                mpfr_mul(t3, t, rr, GMP_RNDN);
5422
 
5423
                mpfr_t t4;
5424
                mpfr_init(t4);
5425
                mpfr_mul(t4, t2, ri, GMP_RNDN);
5426
 
5427
                mpfr_add(t3, t3, t4, GMP_RNDN);
5428
                mpfr_set_inf(real, mpfr_sgn(t3));
5429
 
5430
                mpfr_mul(t3, t2, rr, GMP_RNDN);
5431
                mpfr_mul(t4, t, ri, GMP_RNDN);
5432
                mpfr_sub(t3, t3, t4, GMP_RNDN);
5433
                mpfr_set_inf(imag, mpfr_sgn(t3));
5434
 
5435
                mpfr_clear(t2);
5436
                mpfr_clear(t3);
5437
                mpfr_clear(t4);
5438
              }
5439
            else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5440
                     && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5441
              {
5442
                mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5443
                mpfr_copysign(t, t, rr, GMP_RNDN);
5444
 
5445
                mpfr_t t2;
5446
                mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5447
                mpfr_copysign(t2, t2, ri, GMP_RNDN);
5448
 
5449
                mpfr_t t3;
5450
                mpfr_init(t3);
5451
                mpfr_mul(t3, left_real, t, GMP_RNDN);
5452
 
5453
                mpfr_t t4;
5454
                mpfr_init(t4);
5455
                mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5456
 
5457
                mpfr_add(t3, t3, t4, GMP_RNDN);
5458
                mpfr_set_ui(real, 0, GMP_RNDN);
5459
                mpfr_mul(real, real, t3, GMP_RNDN);
5460
 
5461
                mpfr_mul(t3, left_imag, t, GMP_RNDN);
5462
                mpfr_mul(t4, left_real, t2, GMP_RNDN);
5463
                mpfr_sub(t3, t3, t4, GMP_RNDN);
5464
                mpfr_set_ui(imag, 0, GMP_RNDN);
5465
                mpfr_mul(imag, imag, t3, GMP_RNDN);
5466
 
5467
                mpfr_clear(t2);
5468
                mpfr_clear(t3);
5469
                mpfr_clear(t4);
5470
              }
5471
          }
5472
 
5473
        mpfr_clear(denom);
5474
        mpfr_clear(rr);
5475
        mpfr_clear(ri);
5476
        mpfr_clear(t);
5477
        mpfr_clear(rra);
5478
        mpfr_clear(ria);
5479
      }
5480
      break;
5481
    case OPERATOR_MOD:
5482
      return false;
5483
    case OPERATOR_LSHIFT:
5484
    case OPERATOR_RSHIFT:
5485
      return false;
5486
    default:
5487
      go_unreachable();
5488
    }
5489
 
5490
  Type* type = left_type;
5491
  if (type == NULL)
5492
    type = right_type;
5493
  else if (type != right_type && right_type != NULL)
5494
    {
5495
      if (type->is_abstract())
5496
        type = right_type;
5497
      else if (!right_type->is_abstract())
5498
        {
5499
          // This looks like a type error which should be diagnosed
5500
          // elsewhere.  Don't do anything here, to avoid an unhelpful
5501
          // chain of error messages.
5502
          return true;
5503
        }
5504
    }
5505
 
5506
  if (type != NULL && !type->is_abstract())
5507
    {
5508
      if ((type != left_type
5509
           && !Complex_expression::check_constant(left_real, left_imag,
5510
                                                  type, location))
5511
          || (type != right_type
5512
              && !Complex_expression::check_constant(right_real, right_imag,
5513
                                                     type, location))
5514
          || !Complex_expression::check_constant(real, imag, type,
5515
                                                 location))
5516
        {
5517
          mpfr_set_ui(real, 0, GMP_RNDN);
5518
          mpfr_set_ui(imag, 0, GMP_RNDN);
5519
        }
5520
    }
5521
 
5522
  return true;
5523
}
5524
 
5525
// Lower a binary expression.  We have to evaluate constant
5526
// expressions now, in order to implement Go's unlimited precision
5527
// constants.
5528
 
5529
Expression*
5530
Binary_expression::do_lower(Gogo* gogo, Named_object*,
5531
                            Statement_inserter* inserter, int)
5532
{
5533
  Location location = this->location();
5534
  Operator op = this->op_;
5535
  Expression* left = this->left_;
5536
  Expression* right = this->right_;
5537
 
5538
  const bool is_comparison = (op == OPERATOR_EQEQ
5539
                              || op == OPERATOR_NOTEQ
5540
                              || op == OPERATOR_LT
5541
                              || op == OPERATOR_LE
5542
                              || op == OPERATOR_GT
5543
                              || op == OPERATOR_GE);
5544
 
5545
  // Integer constant expressions.
5546
  {
5547
    mpz_t left_val;
5548
    mpz_init(left_val);
5549
    Type* left_type;
5550
    mpz_t right_val;
5551
    mpz_init(right_val);
5552
    Type* right_type;
5553
    if (left->integer_constant_value(false, left_val, &left_type)
5554
        && right->integer_constant_value(false, right_val, &right_type))
5555
      {
5556
        Expression* ret = NULL;
5557
        if (left_type != right_type
5558
            && left_type != NULL
5559
            && !left_type->is_abstract()
5560
            && right_type != NULL
5561
            && !right_type->is_abstract()
5562
            && left_type->base() != right_type->base()
5563
            && op != OPERATOR_LSHIFT
5564
            && op != OPERATOR_RSHIFT)
5565
          {
5566
            // May be a type error--let it be diagnosed later.
5567
            return this;
5568
          }
5569
        else if (is_comparison)
5570
          {
5571
            bool b = Binary_expression::compare_integer(op, left_val,
5572
                                                        right_val);
5573
            ret = Expression::make_cast(Type::lookup_bool_type(),
5574
                                        Expression::make_boolean(b, location),
5575
                                        location);
5576
          }
5577
        else
5578
          {
5579
            mpz_t val;
5580
            mpz_init(val);
5581
 
5582
            if (Binary_expression::eval_integer(op, left_type, left_val,
5583
                                                right_type, right_val,
5584
                                                location, val))
5585
              {
5586
                go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND);
5587
                Type* type;
5588
                if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5589
                  type = left_type;
5590
                else if (left_type == NULL)
5591
                  type = right_type;
5592
                else if (right_type == NULL)
5593
                  type = left_type;
5594
                else if (!left_type->is_abstract()
5595
                         && left_type->named_type() != NULL)
5596
                  type = left_type;
5597
                else if (!right_type->is_abstract()
5598
                         && right_type->named_type() != NULL)
5599
                  type = right_type;
5600
                else if (!left_type->is_abstract())
5601
                  type = left_type;
5602
                else if (!right_type->is_abstract())
5603
                  type = right_type;
5604
                else if (left_type->float_type() != NULL)
5605
                  type = left_type;
5606
                else if (right_type->float_type() != NULL)
5607
                  type = right_type;
5608
                else if (left_type->complex_type() != NULL)
5609
                  type = left_type;
5610
                else if (right_type->complex_type() != NULL)
5611
                  type = right_type;
5612
                else
5613
                  type = left_type;
5614
 
5615
                bool is_character = false;
5616
                if (type == NULL)
5617
                  {
5618
                    Type* t = this->left_->type();
5619
                    if (t->integer_type() != NULL
5620
                        && t->integer_type()->is_rune())
5621
                      is_character = true;
5622
                    else if (op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT)
5623
                      {
5624
                        t = this->right_->type();
5625
                        if (t->integer_type() != NULL
5626
                            && t->integer_type()->is_rune())
5627
                          is_character = true;
5628
                      }
5629
                  }
5630
 
5631
                if (is_character)
5632
                  ret = Expression::make_character(&val, type, location);
5633
                else
5634
                  ret = Expression::make_integer(&val, type, location);
5635
              }
5636
 
5637
            mpz_clear(val);
5638
          }
5639
 
5640
        if (ret != NULL)
5641
          {
5642
            mpz_clear(right_val);
5643
            mpz_clear(left_val);
5644
            return ret;
5645
          }
5646
      }
5647
    mpz_clear(right_val);
5648
    mpz_clear(left_val);
5649
  }
5650
 
5651
  // Floating point constant expressions.
5652
  {
5653
    mpfr_t left_val;
5654
    mpfr_init(left_val);
5655
    Type* left_type;
5656
    mpfr_t right_val;
5657
    mpfr_init(right_val);
5658
    Type* right_type;
5659
    if (left->float_constant_value(left_val, &left_type)
5660
        && right->float_constant_value(right_val, &right_type))
5661
      {
5662
        Expression* ret = NULL;
5663
        if (left_type != right_type
5664
            && left_type != NULL
5665
            && right_type != NULL
5666
            && left_type->base() != right_type->base()
5667
            && op != OPERATOR_LSHIFT
5668
            && op != OPERATOR_RSHIFT)
5669
          {
5670
            // May be a type error--let it be diagnosed later.
5671
            return this;
5672
          }
5673
        else if (is_comparison)
5674
          {
5675
            bool b = Binary_expression::compare_float(op,
5676
                                                      (left_type != NULL
5677
                                                       ? left_type
5678
                                                       : right_type),
5679
                                                      left_val, right_val);
5680
            ret = Expression::make_boolean(b, location);
5681
          }
5682
        else
5683
          {
5684
            mpfr_t val;
5685
            mpfr_init(val);
5686
 
5687
            if (Binary_expression::eval_float(op, left_type, left_val,
5688
                                              right_type, right_val, val,
5689
                                              location))
5690
              {
5691
                go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND
5692
                           && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT);
5693
                Type* type;
5694
                if (left_type == NULL)
5695
                  type = right_type;
5696
                else if (right_type == NULL)
5697
                  type = left_type;
5698
                else if (!left_type->is_abstract()
5699
                         && left_type->named_type() != NULL)
5700
                  type = left_type;
5701
                else if (!right_type->is_abstract()
5702
                         && right_type->named_type() != NULL)
5703
                  type = right_type;
5704
                else if (!left_type->is_abstract())
5705
                  type = left_type;
5706
                else if (!right_type->is_abstract())
5707
                  type = right_type;
5708
                else if (left_type->float_type() != NULL)
5709
                  type = left_type;
5710
                else if (right_type->float_type() != NULL)
5711
                  type = right_type;
5712
                else
5713
                  type = left_type;
5714
                ret = Expression::make_float(&val, type, location);
5715
              }
5716
 
5717
            mpfr_clear(val);
5718
          }
5719
 
5720
        if (ret != NULL)
5721
          {
5722
            mpfr_clear(right_val);
5723
            mpfr_clear(left_val);
5724
            return ret;
5725
          }
5726
      }
5727
    mpfr_clear(right_val);
5728
    mpfr_clear(left_val);
5729
  }
5730
 
5731
  // Complex constant expressions.
5732
  {
5733
    mpfr_t left_real;
5734
    mpfr_t left_imag;
5735
    mpfr_init(left_real);
5736
    mpfr_init(left_imag);
5737
    Type* left_type;
5738
 
5739
    mpfr_t right_real;
5740
    mpfr_t right_imag;
5741
    mpfr_init(right_real);
5742
    mpfr_init(right_imag);
5743
    Type* right_type;
5744
 
5745
    if (left->complex_constant_value(left_real, left_imag, &left_type)
5746
        && right->complex_constant_value(right_real, right_imag, &right_type))
5747
      {
5748
        Expression* ret = NULL;
5749
        if (left_type != right_type
5750
            && left_type != NULL
5751
            && right_type != NULL
5752
            && left_type->base() != right_type->base())
5753
          {
5754
            // May be a type error--let it be diagnosed later.
5755
            return this;
5756
          }
5757
        else if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5758
          {
5759
            bool b = Binary_expression::compare_complex(op,
5760
                                                        (left_type != NULL
5761
                                                         ? left_type
5762
                                                         : right_type),
5763
                                                        left_real,
5764
                                                        left_imag,
5765
                                                        right_real,
5766
                                                        right_imag);
5767
            ret = Expression::make_boolean(b, location);
5768
          }
5769
        else
5770
          {
5771
            mpfr_t real;
5772
            mpfr_t imag;
5773
            mpfr_init(real);
5774
            mpfr_init(imag);
5775
 
5776
            if (Binary_expression::eval_complex(op, left_type,
5777
                                                left_real, left_imag,
5778
                                                right_type,
5779
                                                right_real, right_imag,
5780
                                                real, imag,
5781
                                                location))
5782
              {
5783
                go_assert(op != OPERATOR_OROR && op != OPERATOR_ANDAND
5784
                           && op != OPERATOR_LSHIFT && op != OPERATOR_RSHIFT);
5785
                Type* type;
5786
                if (left_type == NULL)
5787
                  type = right_type;
5788
                else if (right_type == NULL)
5789
                  type = left_type;
5790
                else if (!left_type->is_abstract()
5791
                         && left_type->named_type() != NULL)
5792
                  type = left_type;
5793
                else if (!right_type->is_abstract()
5794
                         && right_type->named_type() != NULL)
5795
                  type = right_type;
5796
                else if (!left_type->is_abstract())
5797
                  type = left_type;
5798
                else if (!right_type->is_abstract())
5799
                  type = right_type;
5800
                else if (left_type->complex_type() != NULL)
5801
                  type = left_type;
5802
                else if (right_type->complex_type() != NULL)
5803
                  type = right_type;
5804
                else
5805
                  type = left_type;
5806
                ret = Expression::make_complex(&real, &imag, type,
5807
                                               location);
5808
              }
5809
            mpfr_clear(real);
5810
            mpfr_clear(imag);
5811
          }
5812
 
5813
        if (ret != NULL)
5814
          {
5815
            mpfr_clear(left_real);
5816
            mpfr_clear(left_imag);
5817
            mpfr_clear(right_real);
5818
            mpfr_clear(right_imag);
5819
            return ret;
5820
          }
5821
      }
5822
 
5823
    mpfr_clear(left_real);
5824
    mpfr_clear(left_imag);
5825
    mpfr_clear(right_real);
5826
    mpfr_clear(right_imag);
5827
  }
5828
 
5829
  // String constant expressions.
5830
  if (left->type()->is_string_type() && right->type()->is_string_type())
5831
    {
5832
      std::string left_string;
5833
      std::string right_string;
5834
      if (left->string_constant_value(&left_string)
5835
          && right->string_constant_value(&right_string))
5836
        {
5837
          if (op == OPERATOR_PLUS)
5838
            return Expression::make_string(left_string + right_string,
5839
                                           location);
5840
          else if (is_comparison)
5841
            {
5842
              int cmp = left_string.compare(right_string);
5843
              bool r;
5844
              switch (op)
5845
                {
5846
                case OPERATOR_EQEQ:
5847
                  r = cmp == 0;
5848
                  break;
5849
                case OPERATOR_NOTEQ:
5850
                  r = cmp != 0;
5851
                  break;
5852
                case OPERATOR_LT:
5853
                  r = cmp < 0;
5854
                  break;
5855
                case OPERATOR_LE:
5856
                  r = cmp <= 0;
5857
                  break;
5858
                case OPERATOR_GT:
5859
                  r = cmp > 0;
5860
                  break;
5861
                case OPERATOR_GE:
5862
                  r = cmp >= 0;
5863
                  break;
5864
                default:
5865
                  go_unreachable();
5866
                }
5867
              return Expression::make_boolean(r, location);
5868
            }
5869
        }
5870
    }
5871
 
5872
  // Special case for shift of a floating point constant.
5873
  if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
5874
    {
5875
      mpfr_t left_val;
5876
      mpfr_init(left_val);
5877
      Type* left_type;
5878
      mpz_t right_val;
5879
      mpz_init(right_val);
5880
      Type* right_type;
5881
      if (left->float_constant_value(left_val, &left_type)
5882
          && right->integer_constant_value(false, right_val, &right_type)
5883
          && mpfr_integer_p(left_val)
5884
          && (left_type == NULL
5885
              || left_type->is_abstract()
5886
              || left_type->integer_type() != NULL))
5887
        {
5888
          mpz_t left_int;
5889
          mpz_init(left_int);
5890
          mpfr_get_z(left_int, left_val, GMP_RNDN);
5891
 
5892
          mpz_t val;
5893
          mpz_init(val);
5894
 
5895
          Expression* ret = NULL;
5896
          if (Binary_expression::eval_integer(op, left_type, left_int,
5897
                                              right_type, right_val,
5898
                                              location, val))
5899
            ret = Expression::make_integer(&val, left_type, location);
5900
 
5901
          mpz_clear(left_int);
5902
          mpz_clear(val);
5903
 
5904
          if (ret != NULL)
5905
            {
5906
              mpfr_clear(left_val);
5907
              mpz_clear(right_val);
5908
              return ret;
5909
            }
5910
        }
5911
 
5912
      mpfr_clear(left_val);
5913
      mpz_clear(right_val);
5914
    }
5915
 
5916
  // Lower struct and array comparisons.
5917
  if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5918
    {
5919
      if (left->type()->struct_type() != NULL)
5920
        return this->lower_struct_comparison(gogo, inserter);
5921
      else if (left->type()->array_type() != NULL
5922
               && !left->type()->is_slice_type())
5923
        return this->lower_array_comparison(gogo, inserter);
5924
    }
5925
 
5926
  return this;
5927
}
5928
 
5929
// Lower a struct comparison.
5930
 
5931
Expression*
5932
Binary_expression::lower_struct_comparison(Gogo* gogo,
5933
                                           Statement_inserter* inserter)
5934
{
5935
  Struct_type* st = this->left_->type()->struct_type();
5936
  Struct_type* st2 = this->right_->type()->struct_type();
5937
  if (st2 == NULL)
5938
    return this;
5939
  if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5940
    return this;
5941
  if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5942
                                           this->right_->type(), NULL))
5943
    return this;
5944
 
5945
  // See if we can compare using memcmp.  As a heuristic, we use
5946
  // memcmp rather than field references and comparisons if there are
5947
  // more than two fields.
5948
  if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5949
    return this->lower_compare_to_memcmp(gogo, inserter);
5950
 
5951
  Location loc = this->location();
5952
 
5953
  Expression* left = this->left_;
5954
  Temporary_statement* left_temp = NULL;
5955
  if (left->var_expression() == NULL
5956
      && left->temporary_reference_expression() == NULL)
5957
    {
5958
      left_temp = Statement::make_temporary(left->type(), NULL, loc);
5959
      inserter->insert(left_temp);
5960
      left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5961
    }
5962
 
5963
  Expression* right = this->right_;
5964
  Temporary_statement* right_temp = NULL;
5965
  if (right->var_expression() == NULL
5966
      && right->temporary_reference_expression() == NULL)
5967
    {
5968
      right_temp = Statement::make_temporary(right->type(), NULL, loc);
5969
      inserter->insert(right_temp);
5970
      right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5971
    }
5972
 
5973
  Expression* ret = Expression::make_boolean(true, loc);
5974
  const Struct_field_list* fields = st->fields();
5975
  unsigned int field_index = 0;
5976
  for (Struct_field_list::const_iterator pf = fields->begin();
5977
       pf != fields->end();
5978
       ++pf, ++field_index)
5979
    {
5980
      if (field_index > 0)
5981
        {
5982
          if (left_temp == NULL)
5983
            left = left->copy();
5984
          else
5985
            left = Expression::make_temporary_reference(left_temp, loc);
5986
          if (right_temp == NULL)
5987
            right = right->copy();
5988
          else
5989
            right = Expression::make_temporary_reference(right_temp, loc);
5990
        }
5991
      Expression* f1 = Expression::make_field_reference(left, field_index,
5992
                                                        loc);
5993
      Expression* f2 = Expression::make_field_reference(right, field_index,
5994
                                                        loc);
5995
      Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5996
      ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5997
    }
5998
 
5999
  if (this->op_ == OPERATOR_NOTEQ)
6000
    ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6001
 
6002
  return ret;
6003
}
6004
 
6005
// Lower an array comparison.
6006
 
6007
Expression*
6008
Binary_expression::lower_array_comparison(Gogo* gogo,
6009
                                          Statement_inserter* inserter)
6010
{
6011
  Array_type* at = this->left_->type()->array_type();
6012
  Array_type* at2 = this->right_->type()->array_type();
6013
  if (at2 == NULL)
6014
    return this;
6015
  if (at != at2 && !Type::are_identical(at, at2, false, NULL))
6016
    return this;
6017
  if (!Type::are_compatible_for_comparison(true, this->left_->type(),
6018
                                           this->right_->type(), NULL))
6019
    return this;
6020
 
6021
  // Call memcmp directly if possible.  This may let the middle-end
6022
  // optimize the call.
6023
  if (at->compare_is_identity(gogo))
6024
    return this->lower_compare_to_memcmp(gogo, inserter);
6025
 
6026
  // Call the array comparison function.
6027
  Named_object* hash_fn;
6028
  Named_object* equal_fn;
6029
  at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
6030
                     &hash_fn, &equal_fn);
6031
 
6032
  Location loc = this->location();
6033
 
6034
  Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
6035
 
6036
  Expression_list* args = new Expression_list();
6037
  args->push_back(this->operand_address(inserter, this->left_));
6038
  args->push_back(this->operand_address(inserter, this->right_));
6039
  args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
6040
 
6041
  Expression* ret = Expression::make_call(func, args, false, loc);
6042
 
6043
  if (this->op_ == OPERATOR_NOTEQ)
6044
    ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
6045
 
6046
  return ret;
6047
}
6048
 
6049
// Lower a struct or array comparison to a call to memcmp.
6050
 
6051
Expression*
6052
Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
6053
{
6054
  Location loc = this->location();
6055
 
6056
  Expression* a1 = this->operand_address(inserter, this->left_);
6057
  Expression* a2 = this->operand_address(inserter, this->right_);
6058
  Expression* len = Expression::make_type_info(this->left_->type(),
6059
                                               TYPE_INFO_SIZE);
6060
 
6061
  Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
6062
 
6063
  mpz_t zval;
6064
  mpz_init_set_ui(zval, 0);
6065
  Expression* zero = Expression::make_integer(&zval, NULL, loc);
6066
  mpz_clear(zval);
6067
 
6068
  return Expression::make_binary(this->op_, call, zero, loc);
6069
}
6070
 
6071
// Return the address of EXPR, cast to unsafe.Pointer.
6072
 
6073
Expression*
6074
Binary_expression::operand_address(Statement_inserter* inserter,
6075
                                   Expression* expr)
6076
{
6077
  Location loc = this->location();
6078
 
6079
  if (!expr->is_addressable())
6080
    {
6081
      Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
6082
                                                            loc);
6083
      inserter->insert(temp);
6084
      expr = Expression::make_set_and_use_temporary(temp, expr, loc);
6085
    }
6086
  expr = Expression::make_unary(OPERATOR_AND, expr, loc);
6087
  static_cast<Unary_expression*>(expr)->set_does_not_escape();
6088
  Type* void_type = Type::make_void_type();
6089
  Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
6090
  return Expression::make_cast(unsafe_pointer_type, expr, loc);
6091
}
6092
 
6093
// Return the integer constant value, if it has one.
6094
 
6095
bool
6096
Binary_expression::do_integer_constant_value(bool iota_is_constant, mpz_t val,
6097
                                             Type** ptype) const
6098
{
6099
  mpz_t left_val;
6100
  mpz_init(left_val);
6101
  Type* left_type;
6102
  if (!this->left_->integer_constant_value(iota_is_constant, left_val,
6103
                                           &left_type))
6104
    {
6105
      mpz_clear(left_val);
6106
      return false;
6107
    }
6108
 
6109
  mpz_t right_val;
6110
  mpz_init(right_val);
6111
  Type* right_type;
6112
  if (!this->right_->integer_constant_value(iota_is_constant, right_val,
6113
                                            &right_type))
6114
    {
6115
      mpz_clear(right_val);
6116
      mpz_clear(left_val);
6117
      return false;
6118
    }
6119
 
6120
  bool ret;
6121
  if (left_type != right_type
6122
      && left_type != NULL
6123
      && right_type != NULL
6124
      && left_type->base() != right_type->base()
6125
      && this->op_ != OPERATOR_RSHIFT
6126
      && this->op_ != OPERATOR_LSHIFT)
6127
    ret = false;
6128
  else
6129
    ret = Binary_expression::eval_integer(this->op_, left_type, left_val,
6130
                                          right_type, right_val,
6131
                                          this->location(), val);
6132
 
6133
  mpz_clear(right_val);
6134
  mpz_clear(left_val);
6135
 
6136
  if (ret)
6137
    *ptype = left_type;
6138
 
6139
  return ret;
6140
}
6141
 
6142
// Return the floating point constant value, if it has one.
6143
 
6144
bool
6145
Binary_expression::do_float_constant_value(mpfr_t val, Type** ptype) const
6146
{
6147
  mpfr_t left_val;
6148
  mpfr_init(left_val);
6149
  Type* left_type;
6150
  if (!this->left_->float_constant_value(left_val, &left_type))
6151
    {
6152
      mpfr_clear(left_val);
6153
      return false;
6154
    }
6155
 
6156
  mpfr_t right_val;
6157
  mpfr_init(right_val);
6158
  Type* right_type;
6159
  if (!this->right_->float_constant_value(right_val, &right_type))
6160
    {
6161
      mpfr_clear(right_val);
6162
      mpfr_clear(left_val);
6163
      return false;
6164
    }
6165
 
6166
  bool ret;
6167
  if (left_type != right_type
6168
      && left_type != NULL
6169
      && right_type != NULL
6170
      && left_type->base() != right_type->base())
6171
    ret = false;
6172
  else
6173
    ret = Binary_expression::eval_float(this->op_, left_type, left_val,
6174
                                        right_type, right_val,
6175
                                        val, this->location());
6176
 
6177
  mpfr_clear(left_val);
6178
  mpfr_clear(right_val);
6179
 
6180
  if (ret)
6181
    *ptype = left_type;
6182
 
6183
  return ret;
6184
}
6185
 
6186
// Return the complex constant value, if it has one.
6187
 
6188
bool
6189
Binary_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
6190
                                             Type** ptype) const
6191
{
6192
  mpfr_t left_real;
6193
  mpfr_t left_imag;
6194
  mpfr_init(left_real);
6195
  mpfr_init(left_imag);
6196
  Type* left_type;
6197
  if (!this->left_->complex_constant_value(left_real, left_imag, &left_type))
6198
    {
6199
      mpfr_clear(left_real);
6200
      mpfr_clear(left_imag);
6201
      return false;
6202
    }
6203
 
6204
  mpfr_t right_real;
6205
  mpfr_t right_imag;
6206
  mpfr_init(right_real);
6207
  mpfr_init(right_imag);
6208
  Type* right_type;
6209
  if (!this->right_->complex_constant_value(right_real, right_imag,
6210
                                            &right_type))
6211
    {
6212
      mpfr_clear(left_real);
6213
      mpfr_clear(left_imag);
6214
      mpfr_clear(right_real);
6215
      mpfr_clear(right_imag);
6216
      return false;
6217
    }
6218
 
6219
  bool ret;
6220
  if (left_type != right_type
6221
      && left_type != NULL
6222
      && right_type != NULL
6223
      && left_type->base() != right_type->base())
6224
    ret = false;
6225
  else
6226
    ret = Binary_expression::eval_complex(this->op_, left_type,
6227
                                          left_real, left_imag,
6228
                                          right_type,
6229
                                          right_real, right_imag,
6230
                                          real, imag,
6231
                                          this->location());
6232
  mpfr_clear(left_real);
6233
  mpfr_clear(left_imag);
6234
  mpfr_clear(right_real);
6235
  mpfr_clear(right_imag);
6236
 
6237
  if (ret)
6238
    *ptype = left_type;
6239
 
6240
  return ret;
6241
}
6242
 
6243
// Note that the value is being discarded.
6244
 
6245
void
6246
Binary_expression::do_discarding_value()
6247
{
6248
  if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
6249
    this->right_->discarding_value();
6250
  else
6251
    this->unused_value_error();
6252
}
6253
 
6254
// Get type.
6255
 
6256
Type*
6257
Binary_expression::do_type()
6258
{
6259
  if (this->classification() == EXPRESSION_ERROR)
6260
    return Type::make_error_type();
6261
 
6262
  switch (this->op_)
6263
    {
6264
    case OPERATOR_OROR:
6265
    case OPERATOR_ANDAND:
6266
    case OPERATOR_EQEQ:
6267
    case OPERATOR_NOTEQ:
6268
    case OPERATOR_LT:
6269
    case OPERATOR_LE:
6270
    case OPERATOR_GT:
6271
    case OPERATOR_GE:
6272
      return Type::lookup_bool_type();
6273
 
6274
    case OPERATOR_PLUS:
6275
    case OPERATOR_MINUS:
6276
    case OPERATOR_OR:
6277
    case OPERATOR_XOR:
6278
    case OPERATOR_MULT:
6279
    case OPERATOR_DIV:
6280
    case OPERATOR_MOD:
6281
    case OPERATOR_AND:
6282
    case OPERATOR_BITCLEAR:
6283
      {
6284
        Type* left_type = this->left_->type();
6285
        Type* right_type = this->right_->type();
6286
        if (left_type->is_error())
6287
          return left_type;
6288
        else if (right_type->is_error())
6289
          return right_type;
6290
        else if (!Type::are_compatible_for_binop(left_type, right_type))
6291
          {
6292
            this->report_error(_("incompatible types in binary expression"));
6293
            return Type::make_error_type();
6294
          }
6295
        else if (!left_type->is_abstract() && left_type->named_type() != NULL)
6296
          return left_type;
6297
        else if (!right_type->is_abstract() && right_type->named_type() != NULL)
6298
          return right_type;
6299
        else if (!left_type->is_abstract())
6300
          return left_type;
6301
        else if (!right_type->is_abstract())
6302
          return right_type;
6303
        else if (left_type->complex_type() != NULL)
6304
          return left_type;
6305
        else if (right_type->complex_type() != NULL)
6306
          return right_type;
6307
        else if (left_type->float_type() != NULL)
6308
          return left_type;
6309
        else if (right_type->float_type() != NULL)
6310
          return right_type;
6311
        else if (left_type->integer_type() != NULL
6312
                 && left_type->integer_type()->is_rune())
6313
          return left_type;
6314
        else if (right_type->integer_type() != NULL
6315
                 && right_type->integer_type()->is_rune())
6316
          return right_type;
6317
        else
6318
          return left_type;
6319
      }
6320
 
6321
    case OPERATOR_LSHIFT:
6322
    case OPERATOR_RSHIFT:
6323
      return this->left_->type();
6324
 
6325
    default:
6326
      go_unreachable();
6327
    }
6328
}
6329
 
6330
// Set type for a binary expression.
6331
 
6332
void
6333
Binary_expression::do_determine_type(const Type_context* context)
6334
{
6335
  Type* tleft = this->left_->type();
6336
  Type* tright = this->right_->type();
6337
 
6338
  // Both sides should have the same type, except for the shift
6339
  // operations.  For a comparison, we should ignore the incoming
6340
  // type.
6341
 
6342
  bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
6343
                      || this->op_ == OPERATOR_RSHIFT);
6344
 
6345
  bool is_comparison = (this->op_ == OPERATOR_EQEQ
6346
                        || this->op_ == OPERATOR_NOTEQ
6347
                        || this->op_ == OPERATOR_LT
6348
                        || this->op_ == OPERATOR_LE
6349
                        || this->op_ == OPERATOR_GT
6350
                        || this->op_ == OPERATOR_GE);
6351
 
6352
  Type_context subcontext(*context);
6353
 
6354
  if (is_comparison)
6355
    {
6356
      // In a comparison, the context does not determine the types of
6357
      // the operands.
6358
      subcontext.type = NULL;
6359
    }
6360
 
6361
  // Set the context for the left hand operand.
6362
  if (is_shift_op)
6363
    {
6364
      // The right hand operand of a shift plays no role in
6365
      // determining the type of the left hand operand.
6366
    }
6367
  else if (!tleft->is_abstract())
6368
    subcontext.type = tleft;
6369
  else if (!tright->is_abstract())
6370
    subcontext.type = tright;
6371
  else if (subcontext.type == NULL)
6372
    {
6373
      if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
6374
          || (tleft->float_type() != NULL && tright->float_type() != NULL)
6375
          || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
6376
        {
6377
          // Both sides have an abstract integer, abstract float, or
6378
          // abstract complex type.  Just let CONTEXT determine
6379
          // whether they may remain abstract or not.
6380
        }
6381
      else if (tleft->complex_type() != NULL)
6382
        subcontext.type = tleft;
6383
      else if (tright->complex_type() != NULL)
6384
        subcontext.type = tright;
6385
      else if (tleft->float_type() != NULL)
6386
        subcontext.type = tleft;
6387
      else if (tright->float_type() != NULL)
6388
        subcontext.type = tright;
6389
      else
6390
        subcontext.type = tleft;
6391
 
6392
      if (subcontext.type != NULL && !context->may_be_abstract)
6393
        subcontext.type = subcontext.type->make_non_abstract_type();
6394
    }
6395
 
6396
  this->left_->determine_type(&subcontext);
6397
 
6398
  if (is_shift_op)
6399
    {
6400
      // We may have inherited an unusable type for the shift operand.
6401
      // Give a useful error if that happened.
6402
      if (tleft->is_abstract()
6403
          && subcontext.type != NULL
6404
          && (this->left_->type()->integer_type() == NULL
6405
              || (subcontext.type->integer_type() == NULL
6406
                  && subcontext.type->float_type() == NULL
6407
                  && subcontext.type->complex_type() == NULL)))
6408
        this->report_error(("invalid context-determined non-integer type "
6409
                            "for shift operand"));
6410
 
6411
      // The context for the right hand operand is the same as for the
6412
      // left hand operand, except for a shift operator.
6413
      subcontext.type = Type::lookup_integer_type("uint");
6414
      subcontext.may_be_abstract = false;
6415
    }
6416
 
6417
  this->right_->determine_type(&subcontext);
6418
}
6419
 
6420
// Report an error if the binary operator OP does not support TYPE.
6421
// OTYPE is the type of the other operand.  Return whether the
6422
// operation is OK.  This should not be used for shift.
6423
 
6424
bool
6425
Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6426
                                       Location location)
6427
{
6428
  switch (op)
6429
    {
6430
    case OPERATOR_OROR:
6431
    case OPERATOR_ANDAND:
6432
      if (!type->is_boolean_type())
6433
        {
6434
          error_at(location, "expected boolean type");
6435
          return false;
6436
        }
6437
      break;
6438
 
6439
    case OPERATOR_EQEQ:
6440
    case OPERATOR_NOTEQ:
6441
      {
6442
        std::string reason;
6443
        if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6444
          {
6445
            error_at(location, "%s", reason.c_str());
6446
            return false;
6447
          }
6448
      }
6449
      break;
6450
 
6451
    case OPERATOR_LT:
6452
    case OPERATOR_LE:
6453
    case OPERATOR_GT:
6454
    case OPERATOR_GE:
6455
      {
6456
        std::string reason;
6457
        if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6458
          {
6459
            error_at(location, "%s", reason.c_str());
6460
            return false;
6461
          }
6462
      }
6463
      break;
6464
 
6465
    case OPERATOR_PLUS:
6466
    case OPERATOR_PLUSEQ:
6467
      if (type->integer_type() == NULL
6468
          && type->float_type() == NULL
6469
          && type->complex_type() == NULL
6470
          && !type->is_string_type())
6471
        {
6472
          error_at(location,
6473
                   "expected integer, floating, complex, or string type");
6474
          return false;
6475
        }
6476
      break;
6477
 
6478
    case OPERATOR_MINUS:
6479
    case OPERATOR_MINUSEQ:
6480
    case OPERATOR_MULT:
6481
    case OPERATOR_MULTEQ:
6482
    case OPERATOR_DIV:
6483
    case OPERATOR_DIVEQ:
6484
      if (type->integer_type() == NULL
6485
          && type->float_type() == NULL
6486
          && type->complex_type() == NULL)
6487
        {
6488
          error_at(location, "expected integer, floating, or complex type");
6489
          return false;
6490
        }
6491
      break;
6492
 
6493
    case OPERATOR_MOD:
6494
    case OPERATOR_MODEQ:
6495
    case OPERATOR_OR:
6496
    case OPERATOR_OREQ:
6497
    case OPERATOR_AND:
6498
    case OPERATOR_ANDEQ:
6499
    case OPERATOR_XOR:
6500
    case OPERATOR_XOREQ:
6501
    case OPERATOR_BITCLEAR:
6502
    case OPERATOR_BITCLEAREQ:
6503
      if (type->integer_type() == NULL)
6504
        {
6505
          error_at(location, "expected integer type");
6506
          return false;
6507
        }
6508
      break;
6509
 
6510
    default:
6511
      go_unreachable();
6512
    }
6513
 
6514
  return true;
6515
}
6516
 
6517
// Check types.
6518
 
6519
void
6520
Binary_expression::do_check_types(Gogo*)
6521
{
6522
  if (this->classification() == EXPRESSION_ERROR)
6523
    return;
6524
 
6525
  Type* left_type = this->left_->type();
6526
  Type* right_type = this->right_->type();
6527
  if (left_type->is_error() || right_type->is_error())
6528
    {
6529
      this->set_is_error();
6530
      return;
6531
    }
6532
 
6533
  if (this->op_ == OPERATOR_EQEQ
6534
      || this->op_ == OPERATOR_NOTEQ
6535
      || this->op_ == OPERATOR_LT
6536
      || this->op_ == OPERATOR_LE
6537
      || this->op_ == OPERATOR_GT
6538
      || this->op_ == OPERATOR_GE)
6539
    {
6540
      if (!Type::are_assignable(left_type, right_type, NULL)
6541
          && !Type::are_assignable(right_type, left_type, NULL))
6542
        {
6543
          this->report_error(_("incompatible types in binary expression"));
6544
          return;
6545
        }
6546
      if (!Binary_expression::check_operator_type(this->op_, left_type,
6547
                                                  right_type,
6548
                                                  this->location())
6549
          || !Binary_expression::check_operator_type(this->op_, right_type,
6550
                                                     left_type,
6551
                                                     this->location()))
6552
        {
6553
          this->set_is_error();
6554
          return;
6555
        }
6556
    }
6557
  else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6558
    {
6559
      if (!Type::are_compatible_for_binop(left_type, right_type))
6560
        {
6561
          this->report_error(_("incompatible types in binary expression"));
6562
          return;
6563
        }
6564
      if (!Binary_expression::check_operator_type(this->op_, left_type,
6565
                                                  right_type,
6566
                                                  this->location()))
6567
        {
6568
          this->set_is_error();
6569
          return;
6570
        }
6571
    }
6572
  else
6573
    {
6574
      if (left_type->integer_type() == NULL)
6575
        this->report_error(_("shift of non-integer operand"));
6576
 
6577
      if (!right_type->is_abstract()
6578
          && (right_type->integer_type() == NULL
6579
              || !right_type->integer_type()->is_unsigned()))
6580
        this->report_error(_("shift count not unsigned integer"));
6581
      else
6582
        {
6583
          mpz_t val;
6584
          mpz_init(val);
6585
          Type* type;
6586
          if (this->right_->integer_constant_value(true, val, &type))
6587
            {
6588
              if (mpz_sgn(val) < 0)
6589
                {
6590
                  this->report_error(_("negative shift count"));
6591
                  mpz_set_ui(val, 0);
6592
                  Location rloc = this->right_->location();
6593
                  this->right_ = Expression::make_integer(&val, right_type,
6594
                                                          rloc);
6595
                }
6596
            }
6597
          mpz_clear(val);
6598
        }
6599
    }
6600
}
6601
 
6602
// Get a tree for a binary expression.
6603
 
6604
tree
6605
Binary_expression::do_get_tree(Translate_context* context)
6606
{
6607
  tree left = this->left_->get_tree(context);
6608
  tree right = this->right_->get_tree(context);
6609
 
6610
  if (left == error_mark_node || right == error_mark_node)
6611
    return error_mark_node;
6612
 
6613
  enum tree_code code;
6614
  bool use_left_type = true;
6615
  bool is_shift_op = false;
6616
  switch (this->op_)
6617
    {
6618
    case OPERATOR_EQEQ:
6619
    case OPERATOR_NOTEQ:
6620
    case OPERATOR_LT:
6621
    case OPERATOR_LE:
6622
    case OPERATOR_GT:
6623
    case OPERATOR_GE:
6624
      return Expression::comparison_tree(context, this->op_,
6625
                                         this->left_->type(), left,
6626
                                         this->right_->type(), right,
6627
                                         this->location());
6628
 
6629
    case OPERATOR_OROR:
6630
      code = TRUTH_ORIF_EXPR;
6631
      use_left_type = false;
6632
      break;
6633
    case OPERATOR_ANDAND:
6634
      code = TRUTH_ANDIF_EXPR;
6635
      use_left_type = false;
6636
      break;
6637
    case OPERATOR_PLUS:
6638
      code = PLUS_EXPR;
6639
      break;
6640
    case OPERATOR_MINUS:
6641
      code = MINUS_EXPR;
6642
      break;
6643
    case OPERATOR_OR:
6644
      code = BIT_IOR_EXPR;
6645
      break;
6646
    case OPERATOR_XOR:
6647
      code = BIT_XOR_EXPR;
6648
      break;
6649
    case OPERATOR_MULT:
6650
      code = MULT_EXPR;
6651
      break;
6652
    case OPERATOR_DIV:
6653
      {
6654
        Type *t = this->left_->type();
6655
        if (t->float_type() != NULL || t->complex_type() != NULL)
6656
          code = RDIV_EXPR;
6657
        else
6658
          code = TRUNC_DIV_EXPR;
6659
      }
6660
      break;
6661
    case OPERATOR_MOD:
6662
      code = TRUNC_MOD_EXPR;
6663
      break;
6664
    case OPERATOR_LSHIFT:
6665
      code = LSHIFT_EXPR;
6666
      is_shift_op = true;
6667
      break;
6668
    case OPERATOR_RSHIFT:
6669
      code = RSHIFT_EXPR;
6670
      is_shift_op = true;
6671
      break;
6672
    case OPERATOR_AND:
6673
      code = BIT_AND_EXPR;
6674
      break;
6675
    case OPERATOR_BITCLEAR:
6676
      right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
6677
      code = BIT_AND_EXPR;
6678
      break;
6679
    default:
6680
      go_unreachable();
6681
    }
6682
 
6683
  tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
6684
 
6685
  if (this->left_->type()->is_string_type())
6686
    {
6687
      go_assert(this->op_ == OPERATOR_PLUS);
6688
      Type* st = Type::make_string_type();
6689
      tree string_type = type_to_tree(st->get_backend(context->gogo()));
6690
      static tree string_plus_decl;
6691
      return Gogo::call_builtin(&string_plus_decl,
6692
                                this->location(),
6693
                                "__go_string_plus",
6694
                                2,
6695
                                string_type,
6696
                                string_type,
6697
                                left,
6698
                                string_type,
6699
                                right);
6700
    }
6701
 
6702
  tree compute_type = excess_precision_type(type);
6703
  if (compute_type != NULL_TREE)
6704
    {
6705
      left = ::convert(compute_type, left);
6706
      right = ::convert(compute_type, right);
6707
    }
6708
 
6709
  tree eval_saved = NULL_TREE;
6710
  if (is_shift_op)
6711
    {
6712
      // Make sure the values are evaluated.
6713
      if (!DECL_P(left) && TREE_SIDE_EFFECTS(left))
6714
        {
6715
          left = save_expr(left);
6716
          eval_saved = left;
6717
        }
6718
      if (!DECL_P(right) && TREE_SIDE_EFFECTS(right))
6719
        {
6720
          right = save_expr(right);
6721
          if (eval_saved == NULL_TREE)
6722
            eval_saved = right;
6723
          else
6724
            eval_saved = fold_build2_loc(this->location().gcc_location(),
6725
                                         COMPOUND_EXPR,
6726
                                         void_type_node, eval_saved, right);
6727
        }
6728
    }
6729
 
6730
  tree ret = fold_build2_loc(this->location().gcc_location(),
6731
                             code,
6732
                             compute_type != NULL_TREE ? compute_type : type,
6733
                             left, right);
6734
 
6735
  if (compute_type != NULL_TREE)
6736
    ret = ::convert(type, ret);
6737
 
6738
  // In Go, a shift larger than the size of the type is well-defined.
6739
  // This is not true in GENERIC, so we need to insert a conditional.
6740
  if (is_shift_op)
6741
    {
6742
      go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
6743
      go_assert(this->left_->type()->integer_type() != NULL);
6744
      int bits = TYPE_PRECISION(TREE_TYPE(left));
6745
 
6746
      tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
6747
                                 build_int_cst_type(TREE_TYPE(right), bits));
6748
 
6749
      tree overflow_result = fold_convert_loc(this->location().gcc_location(),
6750
                                              TREE_TYPE(left),
6751
                                              integer_zero_node);
6752
      if (this->op_ == OPERATOR_RSHIFT
6753
          && !this->left_->type()->integer_type()->is_unsigned())
6754
        {
6755
          tree neg =
6756
            fold_build2_loc(this->location().gcc_location(), LT_EXPR,
6757
                            boolean_type_node, left,
6758
                            fold_convert_loc(this->location().gcc_location(),
6759
                                             TREE_TYPE(left),
6760
                                             integer_zero_node));
6761
          tree neg_one =
6762
            fold_build2_loc(this->location().gcc_location(),
6763
                            MINUS_EXPR, TREE_TYPE(left),
6764
                            fold_convert_loc(this->location().gcc_location(),
6765
                                             TREE_TYPE(left),
6766
                                             integer_zero_node),
6767
                            fold_convert_loc(this->location().gcc_location(),
6768
                                             TREE_TYPE(left),
6769
                                             integer_one_node));
6770
          overflow_result =
6771
            fold_build3_loc(this->location().gcc_location(), COND_EXPR,
6772
                            TREE_TYPE(left), neg, neg_one,
6773
                            overflow_result);
6774
        }
6775
 
6776
      ret = fold_build3_loc(this->location().gcc_location(), COND_EXPR,
6777
                            TREE_TYPE(left), compare, ret, overflow_result);
6778
 
6779
      if (eval_saved != NULL_TREE)
6780
        ret = fold_build2_loc(this->location().gcc_location(), COMPOUND_EXPR,
6781
                              TREE_TYPE(ret), eval_saved, ret);
6782
    }
6783
 
6784
  return ret;
6785
}
6786
 
6787
// Export a binary expression.
6788
 
6789
void
6790
Binary_expression::do_export(Export* exp) const
6791
{
6792
  exp->write_c_string("(");
6793
  this->left_->export_expression(exp);
6794
  switch (this->op_)
6795
    {
6796
    case OPERATOR_OROR:
6797
      exp->write_c_string(" || ");
6798
      break;
6799
    case OPERATOR_ANDAND:
6800
      exp->write_c_string(" && ");
6801
      break;
6802
    case OPERATOR_EQEQ:
6803
      exp->write_c_string(" == ");
6804
      break;
6805
    case OPERATOR_NOTEQ:
6806
      exp->write_c_string(" != ");
6807
      break;
6808
    case OPERATOR_LT:
6809
      exp->write_c_string(" < ");
6810
      break;
6811
    case OPERATOR_LE:
6812
      exp->write_c_string(" <= ");
6813
      break;
6814
    case OPERATOR_GT:
6815
      exp->write_c_string(" > ");
6816
      break;
6817
    case OPERATOR_GE:
6818
      exp->write_c_string(" >= ");
6819
      break;
6820
    case OPERATOR_PLUS:
6821
      exp->write_c_string(" + ");
6822
      break;
6823
    case OPERATOR_MINUS:
6824
      exp->write_c_string(" - ");
6825
      break;
6826
    case OPERATOR_OR:
6827
      exp->write_c_string(" | ");
6828
      break;
6829
    case OPERATOR_XOR:
6830
      exp->write_c_string(" ^ ");
6831
      break;
6832
    case OPERATOR_MULT:
6833
      exp->write_c_string(" * ");
6834
      break;
6835
    case OPERATOR_DIV:
6836
      exp->write_c_string(" / ");
6837
      break;
6838
    case OPERATOR_MOD:
6839
      exp->write_c_string(" % ");
6840
      break;
6841
    case OPERATOR_LSHIFT:
6842
      exp->write_c_string(" << ");
6843
      break;
6844
    case OPERATOR_RSHIFT:
6845
      exp->write_c_string(" >> ");
6846
      break;
6847
    case OPERATOR_AND:
6848
      exp->write_c_string(" & ");
6849
      break;
6850
    case OPERATOR_BITCLEAR:
6851
      exp->write_c_string(" &^ ");
6852
      break;
6853
    default:
6854
      go_unreachable();
6855
    }
6856
  this->right_->export_expression(exp);
6857
  exp->write_c_string(")");
6858
}
6859
 
6860
// Import a binary expression.
6861
 
6862
Expression*
6863
Binary_expression::do_import(Import* imp)
6864
{
6865
  imp->require_c_string("(");
6866
 
6867
  Expression* left = Expression::import_expression(imp);
6868
 
6869
  Operator op;
6870
  if (imp->match_c_string(" || "))
6871
    {
6872
      op = OPERATOR_OROR;
6873
      imp->advance(4);
6874
    }
6875
  else if (imp->match_c_string(" && "))
6876
    {
6877
      op = OPERATOR_ANDAND;
6878
      imp->advance(4);
6879
    }
6880
  else if (imp->match_c_string(" == "))
6881
    {
6882
      op = OPERATOR_EQEQ;
6883
      imp->advance(4);
6884
    }
6885
  else if (imp->match_c_string(" != "))
6886
    {
6887
      op = OPERATOR_NOTEQ;
6888
      imp->advance(4);
6889
    }
6890
  else if (imp->match_c_string(" < "))
6891
    {
6892
      op = OPERATOR_LT;
6893
      imp->advance(3);
6894
    }
6895
  else if (imp->match_c_string(" <= "))
6896
    {
6897
      op = OPERATOR_LE;
6898
      imp->advance(4);
6899
    }
6900
  else if (imp->match_c_string(" > "))
6901
    {
6902
      op = OPERATOR_GT;
6903
      imp->advance(3);
6904
    }
6905
  else if (imp->match_c_string(" >= "))
6906
    {
6907
      op = OPERATOR_GE;
6908
      imp->advance(4);
6909
    }
6910
  else if (imp->match_c_string(" + "))
6911
    {
6912
      op = OPERATOR_PLUS;
6913
      imp->advance(3);
6914
    }
6915
  else if (imp->match_c_string(" - "))
6916
    {
6917
      op = OPERATOR_MINUS;
6918
      imp->advance(3);
6919
    }
6920
  else if (imp->match_c_string(" | "))
6921
    {
6922
      op = OPERATOR_OR;
6923
      imp->advance(3);
6924
    }
6925
  else if (imp->match_c_string(" ^ "))
6926
    {
6927
      op = OPERATOR_XOR;
6928
      imp->advance(3);
6929
    }
6930
  else if (imp->match_c_string(" * "))
6931
    {
6932
      op = OPERATOR_MULT;
6933
      imp->advance(3);
6934
    }
6935
  else if (imp->match_c_string(" / "))
6936
    {
6937
      op = OPERATOR_DIV;
6938
      imp->advance(3);
6939
    }
6940
  else if (imp->match_c_string(" % "))
6941
    {
6942
      op = OPERATOR_MOD;
6943
      imp->advance(3);
6944
    }
6945
  else if (imp->match_c_string(" << "))
6946
    {
6947
      op = OPERATOR_LSHIFT;
6948
      imp->advance(4);
6949
    }
6950
  else if (imp->match_c_string(" >> "))
6951
    {
6952
      op = OPERATOR_RSHIFT;
6953
      imp->advance(4);
6954
    }
6955
  else if (imp->match_c_string(" & "))
6956
    {
6957
      op = OPERATOR_AND;
6958
      imp->advance(3);
6959
    }
6960
  else if (imp->match_c_string(" &^ "))
6961
    {
6962
      op = OPERATOR_BITCLEAR;
6963
      imp->advance(4);
6964
    }
6965
  else
6966
    {
6967
      error_at(imp->location(), "unrecognized binary operator");
6968
      return Expression::make_error(imp->location());
6969
    }
6970
 
6971
  Expression* right = Expression::import_expression(imp);
6972
 
6973
  imp->require_c_string(")");
6974
 
6975
  return Expression::make_binary(op, left, right, imp->location());
6976
}
6977
 
6978
// Dump ast representation of a binary expression.
6979
 
6980
void
6981
Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6982
{
6983
  ast_dump_context->ostream() << "(";
6984
  ast_dump_context->dump_expression(this->left_);
6985
  ast_dump_context->ostream() << " ";
6986
  ast_dump_context->dump_operator(this->op_);
6987
  ast_dump_context->ostream() << " ";
6988
  ast_dump_context->dump_expression(this->right_);
6989
  ast_dump_context->ostream() << ") ";
6990
}
6991
 
6992
// Make a binary expression.
6993
 
6994
Expression*
6995
Expression::make_binary(Operator op, Expression* left, Expression* right,
6996
                        Location location)
6997
{
6998
  return new Binary_expression(op, left, right, location);
6999
}
7000
 
7001
// Implement a comparison.
7002
 
7003
tree
7004
Expression::comparison_tree(Translate_context* context, Operator op,
7005
                            Type* left_type, tree left_tree,
7006
                            Type* right_type, tree right_tree,
7007
                            Location location)
7008
{
7009
  enum tree_code code;
7010
  switch (op)
7011
    {
7012
    case OPERATOR_EQEQ:
7013
      code = EQ_EXPR;
7014
      break;
7015
    case OPERATOR_NOTEQ:
7016
      code = NE_EXPR;
7017
      break;
7018
    case OPERATOR_LT:
7019
      code = LT_EXPR;
7020
      break;
7021
    case OPERATOR_LE:
7022
      code = LE_EXPR;
7023
      break;
7024
    case OPERATOR_GT:
7025
      code = GT_EXPR;
7026
      break;
7027
    case OPERATOR_GE:
7028
      code = GE_EXPR;
7029
      break;
7030
    default:
7031
      go_unreachable();
7032
    }
7033
 
7034
  if (left_type->is_string_type() && right_type->is_string_type())
7035
    {
7036
      Type* st = Type::make_string_type();
7037
      tree string_type = type_to_tree(st->get_backend(context->gogo()));
7038
      static tree string_compare_decl;
7039
      left_tree = Gogo::call_builtin(&string_compare_decl,
7040
                                     location,
7041
                                     "__go_strcmp",
7042
                                     2,
7043
                                     integer_type_node,
7044
                                     string_type,
7045
                                     left_tree,
7046
                                     string_type,
7047
                                     right_tree);
7048
      right_tree = build_int_cst_type(integer_type_node, 0);
7049
    }
7050
  else if ((left_type->interface_type() != NULL
7051
            && right_type->interface_type() == NULL
7052
            && !right_type->is_nil_type())
7053
           || (left_type->interface_type() == NULL
7054
               && !left_type->is_nil_type()
7055
               && right_type->interface_type() != NULL))
7056
    {
7057
      // Comparing an interface value to a non-interface value.
7058
      if (left_type->interface_type() == NULL)
7059
        {
7060
          std::swap(left_type, right_type);
7061
          std::swap(left_tree, right_tree);
7062
        }
7063
 
7064
      // The right operand is not an interface.  We need to take its
7065
      // address if it is not a pointer.
7066
      tree make_tmp;
7067
      tree arg;
7068
      if (right_type->points_to() != NULL)
7069
        {
7070
          make_tmp = NULL_TREE;
7071
          arg = right_tree;
7072
        }
7073
      else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree))
7074
        {
7075
          make_tmp = NULL_TREE;
7076
          arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
7077
          if (DECL_P(right_tree))
7078
            TREE_ADDRESSABLE(right_tree) = 1;
7079
        }
7080
      else
7081
        {
7082
          tree tmp = create_tmp_var(TREE_TYPE(right_tree),
7083
                                    get_name(right_tree));
7084
          DECL_IGNORED_P(tmp) = 0;
7085
          DECL_INITIAL(tmp) = right_tree;
7086
          TREE_ADDRESSABLE(tmp) = 1;
7087
          make_tmp = build1(DECL_EXPR, void_type_node, tmp);
7088
          SET_EXPR_LOCATION(make_tmp, location.gcc_location());
7089
          arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
7090
        }
7091
      arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
7092
 
7093
      tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
7094
                                                            location);
7095
 
7096
      if (left_type->interface_type()->is_empty())
7097
        {
7098
          static tree empty_interface_value_compare_decl;
7099
          left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
7100
                                         location,
7101
                                         "__go_empty_interface_value_compare",
7102
                                         3,
7103
                                         integer_type_node,
7104
                                         TREE_TYPE(left_tree),
7105
                                         left_tree,
7106
                                         TREE_TYPE(descriptor),
7107
                                         descriptor,
7108
                                         ptr_type_node,
7109
                                         arg);
7110
          if (left_tree == error_mark_node)
7111
            return error_mark_node;
7112
          // This can panic if the type is not comparable.
7113
          TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
7114
        }
7115
      else
7116
        {
7117
          static tree interface_value_compare_decl;
7118
          left_tree = Gogo::call_builtin(&interface_value_compare_decl,
7119
                                         location,
7120
                                         "__go_interface_value_compare",
7121
                                         3,
7122
                                         integer_type_node,
7123
                                         TREE_TYPE(left_tree),
7124
                                         left_tree,
7125
                                         TREE_TYPE(descriptor),
7126
                                         descriptor,
7127
                                         ptr_type_node,
7128
                                         arg);
7129
          if (left_tree == error_mark_node)
7130
            return error_mark_node;
7131
          // This can panic if the type is not comparable.
7132
          TREE_NOTHROW(interface_value_compare_decl) = 0;
7133
        }
7134
      right_tree = build_int_cst_type(integer_type_node, 0);
7135
 
7136
      if (make_tmp != NULL_TREE)
7137
        left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
7138
                           left_tree);
7139
    }
7140
  else if (left_type->interface_type() != NULL
7141
           && right_type->interface_type() != NULL)
7142
    {
7143
      if (left_type->interface_type()->is_empty()
7144
          && right_type->interface_type()->is_empty())
7145
        {
7146
          static tree empty_interface_compare_decl;
7147
          left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
7148
                                         location,
7149
                                         "__go_empty_interface_compare",
7150
                                         2,
7151
                                         integer_type_node,
7152
                                         TREE_TYPE(left_tree),
7153
                                         left_tree,
7154
                                         TREE_TYPE(right_tree),
7155
                                         right_tree);
7156
          if (left_tree == error_mark_node)
7157
            return error_mark_node;
7158
          // This can panic if the type is uncomparable.
7159
          TREE_NOTHROW(empty_interface_compare_decl) = 0;
7160
        }
7161
      else if (!left_type->interface_type()->is_empty()
7162
               && !right_type->interface_type()->is_empty())
7163
        {
7164
          static tree interface_compare_decl;
7165
          left_tree = Gogo::call_builtin(&interface_compare_decl,
7166
                                         location,
7167
                                         "__go_interface_compare",
7168
                                         2,
7169
                                         integer_type_node,
7170
                                         TREE_TYPE(left_tree),
7171
                                         left_tree,
7172
                                         TREE_TYPE(right_tree),
7173
                                         right_tree);
7174
          if (left_tree == error_mark_node)
7175
            return error_mark_node;
7176
          // This can panic if the type is uncomparable.
7177
          TREE_NOTHROW(interface_compare_decl) = 0;
7178
        }
7179
      else
7180
        {
7181
          if (left_type->interface_type()->is_empty())
7182
            {
7183
              go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
7184
              std::swap(left_type, right_type);
7185
              std::swap(left_tree, right_tree);
7186
            }
7187
          go_assert(!left_type->interface_type()->is_empty());
7188
          go_assert(right_type->interface_type()->is_empty());
7189
          static tree interface_empty_compare_decl;
7190
          left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
7191
                                         location,
7192
                                         "__go_interface_empty_compare",
7193
                                         2,
7194
                                         integer_type_node,
7195
                                         TREE_TYPE(left_tree),
7196
                                         left_tree,
7197
                                         TREE_TYPE(right_tree),
7198
                                         right_tree);
7199
          if (left_tree == error_mark_node)
7200
            return error_mark_node;
7201
          // This can panic if the type is uncomparable.
7202
          TREE_NOTHROW(interface_empty_compare_decl) = 0;
7203
        }
7204
 
7205
      right_tree = build_int_cst_type(integer_type_node, 0);
7206
    }
7207
 
7208
  if (left_type->is_nil_type()
7209
      && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
7210
    {
7211
      std::swap(left_type, right_type);
7212
      std::swap(left_tree, right_tree);
7213
    }
7214
 
7215
  if (right_type->is_nil_type())
7216
    {
7217
      if (left_type->array_type() != NULL
7218
          && left_type->array_type()->length() == NULL)
7219
        {
7220
          Array_type* at = left_type->array_type();
7221
          left_tree = at->value_pointer_tree(context->gogo(), left_tree);
7222
          right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
7223
        }
7224
      else if (left_type->interface_type() != NULL)
7225
        {
7226
          // An interface is nil if the first field is nil.
7227
          tree left_type_tree = TREE_TYPE(left_tree);
7228
          go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
7229
          tree field = TYPE_FIELDS(left_type_tree);
7230
          left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
7231
                             field, NULL_TREE);
7232
          right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
7233
        }
7234
      else
7235
        {
7236
          go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
7237
          right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
7238
        }
7239
    }
7240
 
7241
  if (left_tree == error_mark_node || right_tree == error_mark_node)
7242
    return error_mark_node;
7243
 
7244
  tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
7245
  if (CAN_HAVE_LOCATION_P(ret))
7246
    SET_EXPR_LOCATION(ret, location.gcc_location());
7247
  return ret;
7248
}
7249
 
7250
// Class Bound_method_expression.
7251
 
7252
// Traversal.
7253
 
7254
int
7255
Bound_method_expression::do_traverse(Traverse* traverse)
7256
{
7257
  return Expression::traverse(&this->expr_, traverse);
7258
}
7259
 
7260
// Return the type of a bound method expression.  The type of this
7261
// object is really the type of the method with no receiver.  We
7262
// should be able to get away with just returning the type of the
7263
// method.
7264
 
7265
Type*
7266
Bound_method_expression::do_type()
7267
{
7268
  if (this->method_->is_function())
7269
    return this->method_->func_value()->type();
7270
  else if (this->method_->is_function_declaration())
7271
    return this->method_->func_declaration_value()->type();
7272
  else
7273
    return Type::make_error_type();
7274
}
7275
 
7276
// Determine the types of a method expression.
7277
 
7278
void
7279
Bound_method_expression::do_determine_type(const Type_context*)
7280
{
7281
  Function_type* fntype = this->type()->function_type();
7282
  if (fntype == NULL || !fntype->is_method())
7283
    this->expr_->determine_type_no_context();
7284
  else
7285
    {
7286
      Type_context subcontext(fntype->receiver()->type(), false);
7287
      this->expr_->determine_type(&subcontext);
7288
    }
7289
}
7290
 
7291
// Check the types of a method expression.
7292
 
7293
void
7294
Bound_method_expression::do_check_types(Gogo*)
7295
{
7296
  if (!this->method_->is_function()
7297
      && !this->method_->is_function_declaration())
7298
    this->report_error(_("object is not a method"));
7299
  else
7300
    {
7301
      Type* rtype = this->type()->function_type()->receiver()->type()->deref();
7302
      Type* etype = (this->expr_type_ != NULL
7303
                     ? this->expr_type_
7304
                     : this->expr_->type());
7305
      etype = etype->deref();
7306
      if (!Type::are_identical(rtype, etype, true, NULL))
7307
        this->report_error(_("method type does not match object type"));
7308
    }
7309
}
7310
 
7311
// Get the tree for a method expression.  There is no standard tree
7312
// representation for this.  The only places it may currently be used
7313
// are in a Call_expression or a Go_statement, which will take it
7314
// apart directly.  So this has nothing to do at present.
7315
 
7316
tree
7317
Bound_method_expression::do_get_tree(Translate_context*)
7318
{
7319
  error_at(this->location(), "reference to method other than calling it");
7320
  return error_mark_node;
7321
}
7322
 
7323
// Dump ast representation of a bound method expression.
7324
 
7325
void
7326
Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7327
    const
7328
{
7329
  if (this->expr_type_ != NULL)
7330
    ast_dump_context->ostream() << "(";
7331
  ast_dump_context->dump_expression(this->expr_);
7332
  if (this->expr_type_ != NULL)
7333
    {
7334
      ast_dump_context->ostream() << ":";
7335
      ast_dump_context->dump_type(this->expr_type_);
7336
      ast_dump_context->ostream() << ")";
7337
    }
7338
 
7339
  ast_dump_context->ostream() << "." << this->method_->name();
7340
}
7341
 
7342
// Make a method expression.
7343
 
7344
Bound_method_expression*
7345
Expression::make_bound_method(Expression* expr, Named_object* method,
7346
                              Location location)
7347
{
7348
  return new Bound_method_expression(expr, method, location);
7349
}
7350
 
7351
// Class Builtin_call_expression.  This is used for a call to a
7352
// builtin function.
7353
 
7354
class Builtin_call_expression : public Call_expression
7355
{
7356
 public:
7357
  Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
7358
                          bool is_varargs, Location location);
7359
 
7360
 protected:
7361
  // This overrides Call_expression::do_lower.
7362
  Expression*
7363
  do_lower(Gogo*, Named_object*, Statement_inserter*, int);
7364
 
7365
  bool
7366
  do_is_constant() const;
7367
 
7368
  bool
7369
  do_integer_constant_value(bool, mpz_t, Type**) const;
7370
 
7371
  bool
7372
  do_float_constant_value(mpfr_t, Type**) const;
7373
 
7374
  bool
7375
  do_complex_constant_value(mpfr_t, mpfr_t, Type**) const;
7376
 
7377
  void
7378
  do_discarding_value();
7379
 
7380
  Type*
7381
  do_type();
7382
 
7383
  void
7384
  do_determine_type(const Type_context*);
7385
 
7386
  void
7387
  do_check_types(Gogo*);
7388
 
7389
  Expression*
7390
  do_copy()
7391
  {
7392
    return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
7393
                                       this->args()->copy(),
7394
                                       this->is_varargs(),
7395
                                       this->location());
7396
  }
7397
 
7398
  tree
7399
  do_get_tree(Translate_context*);
7400
 
7401
  void
7402
  do_export(Export*) const;
7403
 
7404
  virtual bool
7405
  do_is_recover_call() const;
7406
 
7407
  virtual void
7408
  do_set_recover_arg(Expression*);
7409
 
7410
 private:
7411
  // The builtin functions.
7412
  enum Builtin_function_code
7413
    {
7414
      BUILTIN_INVALID,
7415
 
7416
      // Predeclared builtin functions.
7417
      BUILTIN_APPEND,
7418
      BUILTIN_CAP,
7419
      BUILTIN_CLOSE,
7420
      BUILTIN_COMPLEX,
7421
      BUILTIN_COPY,
7422
      BUILTIN_DELETE,
7423
      BUILTIN_IMAG,
7424
      BUILTIN_LEN,
7425
      BUILTIN_MAKE,
7426
      BUILTIN_NEW,
7427
      BUILTIN_PANIC,
7428
      BUILTIN_PRINT,
7429
      BUILTIN_PRINTLN,
7430
      BUILTIN_REAL,
7431
      BUILTIN_RECOVER,
7432
 
7433
      // Builtin functions from the unsafe package.
7434
      BUILTIN_ALIGNOF,
7435
      BUILTIN_OFFSETOF,
7436
      BUILTIN_SIZEOF
7437
    };
7438
 
7439
  Expression*
7440
  one_arg() const;
7441
 
7442
  bool
7443
  check_one_arg();
7444
 
7445
  static Type*
7446
  real_imag_type(Type*);
7447
 
7448
  static Type*
7449
  complex_type(Type*);
7450
 
7451
  Expression*
7452
  lower_make();
7453
 
7454
  bool
7455
  check_int_value(Expression*);
7456
 
7457
  // A pointer back to the general IR structure.  This avoids a global
7458
  // variable, or passing it around everywhere.
7459
  Gogo* gogo_;
7460
  // The builtin function being called.
7461
  Builtin_function_code code_;
7462
  // Used to stop endless loops when the length of an array uses len
7463
  // or cap of the array itself.
7464
  mutable bool seen_;
7465
};
7466
 
7467
Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7468
                                                 Expression* fn,
7469
                                                 Expression_list* args,
7470
                                                 bool is_varargs,
7471
                                                 Location location)
7472
  : Call_expression(fn, args, is_varargs, location),
7473
    gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
7474
{
7475
  Func_expression* fnexp = this->fn()->func_expression();
7476
  go_assert(fnexp != NULL);
7477
  const std::string& name(fnexp->named_object()->name());
7478
  if (name == "append")
7479
    this->code_ = BUILTIN_APPEND;
7480
  else if (name == "cap")
7481
    this->code_ = BUILTIN_CAP;
7482
  else if (name == "close")
7483
    this->code_ = BUILTIN_CLOSE;
7484
  else if (name == "complex")
7485
    this->code_ = BUILTIN_COMPLEX;
7486
  else if (name == "copy")
7487
    this->code_ = BUILTIN_COPY;
7488
  else if (name == "delete")
7489
    this->code_ = BUILTIN_DELETE;
7490
  else if (name == "imag")
7491
    this->code_ = BUILTIN_IMAG;
7492
  else if (name == "len")
7493
    this->code_ = BUILTIN_LEN;
7494
  else if (name == "make")
7495
    this->code_ = BUILTIN_MAKE;
7496
  else if (name == "new")
7497
    this->code_ = BUILTIN_NEW;
7498
  else if (name == "panic")
7499
    this->code_ = BUILTIN_PANIC;
7500
  else if (name == "print")
7501
    this->code_ = BUILTIN_PRINT;
7502
  else if (name == "println")
7503
    this->code_ = BUILTIN_PRINTLN;
7504
  else if (name == "real")
7505
    this->code_ = BUILTIN_REAL;
7506
  else if (name == "recover")
7507
    this->code_ = BUILTIN_RECOVER;
7508
  else if (name == "Alignof")
7509
    this->code_ = BUILTIN_ALIGNOF;
7510
  else if (name == "Offsetof")
7511
    this->code_ = BUILTIN_OFFSETOF;
7512
  else if (name == "Sizeof")
7513
    this->code_ = BUILTIN_SIZEOF;
7514
  else
7515
    go_unreachable();
7516
}
7517
 
7518
// Return whether this is a call to recover.  This is a virtual
7519
// function called from the parent class.
7520
 
7521
bool
7522
Builtin_call_expression::do_is_recover_call() const
7523
{
7524
  if (this->classification() == EXPRESSION_ERROR)
7525
    return false;
7526
  return this->code_ == BUILTIN_RECOVER;
7527
}
7528
 
7529
// Set the argument for a call to recover.
7530
 
7531
void
7532
Builtin_call_expression::do_set_recover_arg(Expression* arg)
7533
{
7534
  const Expression_list* args = this->args();
7535
  go_assert(args == NULL || args->empty());
7536
  Expression_list* new_args = new Expression_list();
7537
  new_args->push_back(arg);
7538
  this->set_args(new_args);
7539
}
7540
 
7541
// A traversal class which looks for a call expression.
7542
 
7543
class Find_call_expression : public Traverse
7544
{
7545
 public:
7546
  Find_call_expression()
7547
    : Traverse(traverse_expressions),
7548
      found_(false)
7549
  { }
7550
 
7551
  int
7552
  expression(Expression**);
7553
 
7554
  bool
7555
  found()
7556
  { return this->found_; }
7557
 
7558
 private:
7559
  bool found_;
7560
};
7561
 
7562
int
7563
Find_call_expression::expression(Expression** pexpr)
7564
{
7565
  if ((*pexpr)->call_expression() != NULL)
7566
    {
7567
      this->found_ = true;
7568
      return TRAVERSE_EXIT;
7569
    }
7570
  return TRAVERSE_CONTINUE;
7571
}
7572
 
7573
// Lower a builtin call expression.  This turns new and make into
7574
// specific expressions.  We also convert to a constant if we can.
7575
 
7576
Expression*
7577
Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7578
                                  Statement_inserter* inserter, int)
7579
{
7580
  if (this->classification() == EXPRESSION_ERROR)
7581
    return this;
7582
 
7583
  Location loc = this->location();
7584
 
7585
  if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7586
    {
7587
      this->report_error(_("invalid use of %<...%> with builtin function"));
7588
      return Expression::make_error(loc);
7589
    }
7590
 
7591
  if (this->is_constant())
7592
    {
7593
      // We can only lower len and cap if there are no function calls
7594
      // in the arguments.  Otherwise we have to make the call.
7595
      if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
7596
        {
7597
          Expression* arg = this->one_arg();
7598
          if (!arg->is_constant())
7599
            {
7600
              Find_call_expression find_call;
7601
              Expression::traverse(&arg, &find_call);
7602
              if (find_call.found())
7603
                return this;
7604
            }
7605
        }
7606
 
7607
      mpz_t ival;
7608
      mpz_init(ival);
7609
      Type* type;
7610
      if (this->integer_constant_value(true, ival, &type))
7611
        {
7612
          Expression* ret = Expression::make_integer(&ival, type, loc);
7613
          mpz_clear(ival);
7614
          return ret;
7615
        }
7616
      mpz_clear(ival);
7617
 
7618
      mpfr_t rval;
7619
      mpfr_init(rval);
7620
      if (this->float_constant_value(rval, &type))
7621
        {
7622
          Expression* ret = Expression::make_float(&rval, type, loc);
7623
          mpfr_clear(rval);
7624
          return ret;
7625
        }
7626
 
7627
      mpfr_t imag;
7628
      mpfr_init(imag);
7629
      if (this->complex_constant_value(rval, imag, &type))
7630
        {
7631
          Expression* ret = Expression::make_complex(&rval, &imag, type, loc);
7632
          mpfr_clear(rval);
7633
          mpfr_clear(imag);
7634
          return ret;
7635
        }
7636
      mpfr_clear(rval);
7637
      mpfr_clear(imag);
7638
    }
7639
 
7640
  switch (this->code_)
7641
    {
7642
    default:
7643
      break;
7644
 
7645
    case BUILTIN_NEW:
7646
      {
7647
        const Expression_list* args = this->args();
7648
        if (args == NULL || args->size() < 1)
7649
          this->report_error(_("not enough arguments"));
7650
        else if (args->size() > 1)
7651
          this->report_error(_("too many arguments"));
7652
        else
7653
          {
7654
            Expression* arg = args->front();
7655
            if (!arg->is_type_expression())
7656
              {
7657
                error_at(arg->location(), "expected type");
7658
                this->set_is_error();
7659
              }
7660
            else
7661
              return Expression::make_allocation(arg->type(), loc);
7662
          }
7663
      }
7664
      break;
7665
 
7666
    case BUILTIN_MAKE:
7667
      return this->lower_make();
7668
 
7669
    case BUILTIN_RECOVER:
7670
      if (function != NULL)
7671
        function->func_value()->set_calls_recover();
7672
      else
7673
        {
7674
          // Calling recover outside of a function always returns the
7675
          // nil empty interface.
7676
          Type* eface = Type::make_empty_interface_type(loc);
7677
          return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7678
        }
7679
      break;
7680
 
7681
    case BUILTIN_APPEND:
7682
      {
7683
        // Lower the varargs.
7684
        const Expression_list* args = this->args();
7685
        if (args == NULL || args->empty())
7686
          return this;
7687
        Type* slice_type = args->front()->type();
7688
        if (!slice_type->is_slice_type())
7689
          {
7690
            error_at(args->front()->location(), "argument 1 must be a slice");
7691
            this->set_is_error();
7692
            return this;
7693
          }
7694
        Type* element_type = slice_type->array_type()->element_type();
7695
        this->lower_varargs(gogo, function, inserter,
7696
                            Type::make_array_type(element_type, NULL),
7697
                            2);
7698
      }
7699
      break;
7700
 
7701
    case BUILTIN_DELETE:
7702
      {
7703
        // Lower to a runtime function call.
7704
        const Expression_list* args = this->args();
7705
        if (args == NULL || args->size() < 2)
7706
          this->report_error(_("not enough arguments"));
7707
        else if (args->size() > 2)
7708
          this->report_error(_("too many arguments"));
7709
        else if (args->front()->type()->map_type() == NULL)
7710
          this->report_error(_("argument 1 must be a map"));
7711
        else
7712
          {
7713
            // Since this function returns no value it must appear in
7714
            // a statement by itself, so we don't have to worry about
7715
            // order of evaluation of values around it.  Evaluate the
7716
            // map first to get order of evaluation right.
7717
            Map_type* mt = args->front()->type()->map_type();
7718
            Temporary_statement* map_temp =
7719
              Statement::make_temporary(mt, args->front(), loc);
7720
            inserter->insert(map_temp);
7721
 
7722
            Temporary_statement* key_temp =
7723
              Statement::make_temporary(mt->key_type(), args->back(), loc);
7724
            inserter->insert(key_temp);
7725
 
7726
            Expression* e1 = Expression::make_temporary_reference(map_temp,
7727
                                                                  loc);
7728
            Expression* e2 = Expression::make_temporary_reference(key_temp,
7729
                                                                  loc);
7730
            e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7731
            return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7732
                                      2, e1, e2);
7733
          }
7734
      }
7735
      break;
7736
    }
7737
 
7738
  return this;
7739
}
7740
 
7741
// Lower a make expression.
7742
 
7743
Expression*
7744
Builtin_call_expression::lower_make()
7745
{
7746
  Location loc = this->location();
7747
 
7748
  const Expression_list* args = this->args();
7749
  if (args == NULL || args->size() < 1)
7750
    {
7751
      this->report_error(_("not enough arguments"));
7752
      return Expression::make_error(this->location());
7753
    }
7754
 
7755
  Expression_list::const_iterator parg = args->begin();
7756
 
7757
  Expression* first_arg = *parg;
7758
  if (!first_arg->is_type_expression())
7759
    {
7760
      error_at(first_arg->location(), "expected type");
7761
      this->set_is_error();
7762
      return Expression::make_error(this->location());
7763
    }
7764
  Type* type = first_arg->type();
7765
 
7766
  bool is_slice = false;
7767
  bool is_map = false;
7768
  bool is_chan = false;
7769
  if (type->is_slice_type())
7770
    is_slice = true;
7771
  else if (type->map_type() != NULL)
7772
    is_map = true;
7773
  else if (type->channel_type() != NULL)
7774
    is_chan = true;
7775
  else
7776
    {
7777
      this->report_error(_("invalid type for make function"));
7778
      return Expression::make_error(this->location());
7779
    }
7780
 
7781
  bool have_big_args = false;
7782
  Type* uintptr_type = Type::lookup_integer_type("uintptr");
7783
  int uintptr_bits = uintptr_type->integer_type()->bits();
7784
 
7785
  ++parg;
7786
  Expression* len_arg;
7787
  if (parg == args->end())
7788
    {
7789
      if (is_slice)
7790
        {
7791
          this->report_error(_("length required when allocating a slice"));
7792
          return Expression::make_error(this->location());
7793
        }
7794
 
7795
      mpz_t zval;
7796
      mpz_init_set_ui(zval, 0);
7797
      len_arg = Expression::make_integer(&zval, NULL, loc);
7798
      mpz_clear(zval);
7799
    }
7800
  else
7801
    {
7802
      len_arg = *parg;
7803
      if (!this->check_int_value(len_arg))
7804
        {
7805
          this->report_error(_("bad size for make"));
7806
          return Expression::make_error(this->location());
7807
        }
7808
      if (len_arg->type()->integer_type() != NULL
7809
          && len_arg->type()->integer_type()->bits() > uintptr_bits)
7810
        have_big_args = true;
7811
      ++parg;
7812
    }
7813
 
7814
  Expression* cap_arg = NULL;
7815
  if (is_slice && parg != args->end())
7816
    {
7817
      cap_arg = *parg;
7818
      if (!this->check_int_value(cap_arg))
7819
        {
7820
          this->report_error(_("bad capacity when making slice"));
7821
          return Expression::make_error(this->location());
7822
        }
7823
      if (cap_arg->type()->integer_type() != NULL
7824
          && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7825
        have_big_args = true;
7826
      ++parg;
7827
    }
7828
 
7829
  if (parg != args->end())
7830
    {
7831
      this->report_error(_("too many arguments to make"));
7832
      return Expression::make_error(this->location());
7833
    }
7834
 
7835
  Location type_loc = first_arg->location();
7836
  Expression* type_arg;
7837
  if (is_slice || is_chan)
7838
    type_arg = Expression::make_type_descriptor(type, type_loc);
7839
  else if (is_map)
7840
    type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7841
  else
7842
    go_unreachable();
7843
 
7844
  Expression* call;
7845
  if (is_slice)
7846
    {
7847
      if (cap_arg == NULL)
7848
        call = Runtime::make_call((have_big_args
7849
                                   ? Runtime::MAKESLICE1BIG
7850
                                   : Runtime::MAKESLICE1),
7851
                                  loc, 2, type_arg, len_arg);
7852
      else
7853
        call = Runtime::make_call((have_big_args
7854
                                   ? Runtime::MAKESLICE2BIG
7855
                                   : Runtime::MAKESLICE2),
7856
                                  loc, 3, type_arg, len_arg, cap_arg);
7857
    }
7858
  else if (is_map)
7859
    call = Runtime::make_call((have_big_args
7860
                               ? Runtime::MAKEMAPBIG
7861
                               : Runtime::MAKEMAP),
7862
                              loc, 2, type_arg, len_arg);
7863
  else if (is_chan)
7864
    call = Runtime::make_call((have_big_args
7865
                               ? Runtime::MAKECHANBIG
7866
                               : Runtime::MAKECHAN),
7867
                              loc, 2, type_arg, len_arg);
7868
  else
7869
    go_unreachable();
7870
 
7871
  return Expression::make_unsafe_cast(type, call, loc);
7872
}
7873
 
7874
// Return whether an expression has an integer value.  Report an error
7875
// if not.  This is used when handling calls to the predeclared make
7876
// function.
7877
 
7878
bool
7879
Builtin_call_expression::check_int_value(Expression* e)
7880
{
7881
  if (e->type()->integer_type() != NULL)
7882
    return true;
7883
 
7884
  // Check for a floating point constant with integer value.
7885
  mpfr_t fval;
7886
  mpfr_init(fval);
7887
 
7888
  Type* dummy;
7889
  if (e->float_constant_value(fval, &dummy) && mpfr_integer_p(fval))
7890
    {
7891
      mpz_t ival;
7892
      mpz_init(ival);
7893
 
7894
      bool ok = false;
7895
 
7896
      mpfr_clear_overflow();
7897
      mpfr_clear_erangeflag();
7898
      mpfr_get_z(ival, fval, GMP_RNDN);
7899
      if (!mpfr_overflow_p()
7900
          && !mpfr_erangeflag_p()
7901
          && mpz_sgn(ival) >= 0)
7902
        {
7903
          Named_type* ntype = Type::lookup_integer_type("int");
7904
          Integer_type* inttype = ntype->integer_type();
7905
          mpz_t max;
7906
          mpz_init_set_ui(max, 1);
7907
          mpz_mul_2exp(max, max, inttype->bits() - 1);
7908
          ok = mpz_cmp(ival, max) < 0;
7909
          mpz_clear(max);
7910
        }
7911
      mpz_clear(ival);
7912
 
7913
      if (ok)
7914
        {
7915
          mpfr_clear(fval);
7916
          return true;
7917
        }
7918
    }
7919
 
7920
  mpfr_clear(fval);
7921
 
7922
  return false;
7923
}
7924
 
7925
// Return the type of the real or imag functions, given the type of
7926
// the argument.  We need to map complex to float, complex64 to
7927
// float32, and complex128 to float64, so it has to be done by name.
7928
// This returns NULL if it can't figure out the type.
7929
 
7930
Type*
7931
Builtin_call_expression::real_imag_type(Type* arg_type)
7932
{
7933
  if (arg_type == NULL || arg_type->is_abstract())
7934
    return NULL;
7935
  Named_type* nt = arg_type->named_type();
7936
  if (nt == NULL)
7937
    return NULL;
7938
  while (nt->real_type()->named_type() != NULL)
7939
    nt = nt->real_type()->named_type();
7940
  if (nt->name() == "complex64")
7941
    return Type::lookup_float_type("float32");
7942
  else if (nt->name() == "complex128")
7943
    return Type::lookup_float_type("float64");
7944
  else
7945
    return NULL;
7946
}
7947
 
7948
// Return the type of the complex function, given the type of one of the
7949
// argments.  Like real_imag_type, we have to map by name.
7950
 
7951
Type*
7952
Builtin_call_expression::complex_type(Type* arg_type)
7953
{
7954
  if (arg_type == NULL || arg_type->is_abstract())
7955
    return NULL;
7956
  Named_type* nt = arg_type->named_type();
7957
  if (nt == NULL)
7958
    return NULL;
7959
  while (nt->real_type()->named_type() != NULL)
7960
    nt = nt->real_type()->named_type();
7961
  if (nt->name() == "float32")
7962
    return Type::lookup_complex_type("complex64");
7963
  else if (nt->name() == "float64")
7964
    return Type::lookup_complex_type("complex128");
7965
  else
7966
    return NULL;
7967
}
7968
 
7969
// Return a single argument, or NULL if there isn't one.
7970
 
7971
Expression*
7972
Builtin_call_expression::one_arg() const
7973
{
7974
  const Expression_list* args = this->args();
7975
  if (args->size() != 1)
7976
    return NULL;
7977
  return args->front();
7978
}
7979
 
7980
// Return whether this is constant: len of a string, or len or cap of
7981
// a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
7982
 
7983
bool
7984
Builtin_call_expression::do_is_constant() const
7985
{
7986
  switch (this->code_)
7987
    {
7988
    case BUILTIN_LEN:
7989
    case BUILTIN_CAP:
7990
      {
7991
        if (this->seen_)
7992
          return false;
7993
 
7994
        Expression* arg = this->one_arg();
7995
        if (arg == NULL)
7996
          return false;
7997
        Type* arg_type = arg->type();
7998
 
7999
        if (arg_type->points_to() != NULL
8000
            && arg_type->points_to()->array_type() != NULL
8001
            && !arg_type->points_to()->is_slice_type())
8002
          arg_type = arg_type->points_to();
8003
 
8004
        if (arg_type->array_type() != NULL
8005
            && arg_type->array_type()->length() != NULL)
8006
          return true;
8007
 
8008
        if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8009
          {
8010
            this->seen_ = true;
8011
            bool ret = arg->is_constant();
8012
            this->seen_ = false;
8013
            return ret;
8014
          }
8015
      }
8016
      break;
8017
 
8018
    case BUILTIN_SIZEOF:
8019
    case BUILTIN_ALIGNOF:
8020
      return this->one_arg() != NULL;
8021
 
8022
    case BUILTIN_OFFSETOF:
8023
      {
8024
        Expression* arg = this->one_arg();
8025
        if (arg == NULL)
8026
          return false;
8027
        return arg->field_reference_expression() != NULL;
8028
      }
8029
 
8030
    case BUILTIN_COMPLEX:
8031
      {
8032
        const Expression_list* args = this->args();
8033
        if (args != NULL && args->size() == 2)
8034
          return args->front()->is_constant() && args->back()->is_constant();
8035
      }
8036
      break;
8037
 
8038
    case BUILTIN_REAL:
8039
    case BUILTIN_IMAG:
8040
      {
8041
        Expression* arg = this->one_arg();
8042
        return arg != NULL && arg->is_constant();
8043
      }
8044
 
8045
    default:
8046
      break;
8047
    }
8048
 
8049
  return false;
8050
}
8051
 
8052
// Return an integer constant value if possible.
8053
 
8054
bool
8055
Builtin_call_expression::do_integer_constant_value(bool iota_is_constant,
8056
                                                   mpz_t val,
8057
                                                   Type** ptype) const
8058
{
8059
  if (this->code_ == BUILTIN_LEN
8060
      || this->code_ == BUILTIN_CAP)
8061
    {
8062
      Expression* arg = this->one_arg();
8063
      if (arg == NULL)
8064
        return false;
8065
      Type* arg_type = arg->type();
8066
 
8067
      if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8068
        {
8069
          std::string sval;
8070
          if (arg->string_constant_value(&sval))
8071
            {
8072
              mpz_set_ui(val, sval.length());
8073
              *ptype = Type::lookup_integer_type("int");
8074
              return true;
8075
            }
8076
        }
8077
 
8078
      if (arg_type->points_to() != NULL
8079
          && arg_type->points_to()->array_type() != NULL
8080
          && !arg_type->points_to()->is_slice_type())
8081
        arg_type = arg_type->points_to();
8082
 
8083
      if (arg_type->array_type() != NULL
8084
          && arg_type->array_type()->length() != NULL)
8085
        {
8086
          if (this->seen_)
8087
            return false;
8088
          Expression* e = arg_type->array_type()->length();
8089
          this->seen_ = true;
8090
          bool r = e->integer_constant_value(iota_is_constant, val, ptype);
8091
          this->seen_ = false;
8092
          if (r)
8093
            {
8094
              *ptype = Type::lookup_integer_type("int");
8095
              return true;
8096
            }
8097
        }
8098
    }
8099
  else if (this->code_ == BUILTIN_SIZEOF
8100
           || this->code_ == BUILTIN_ALIGNOF)
8101
    {
8102
      Expression* arg = this->one_arg();
8103
      if (arg == NULL)
8104
        return false;
8105
      Type* arg_type = arg->type();
8106
      if (arg_type->is_error())
8107
        return false;
8108
      if (arg_type->is_abstract())
8109
        return false;
8110
      if (arg_type->named_type() != NULL)
8111
        arg_type->named_type()->convert(this->gogo_);
8112
 
8113
      unsigned int ret;
8114
      if (this->code_ == BUILTIN_SIZEOF)
8115
        {
8116
          if (!arg_type->backend_type_size(this->gogo_, &ret))
8117
            return false;
8118
        }
8119
      else if (this->code_ == BUILTIN_ALIGNOF)
8120
        {
8121
          if (arg->field_reference_expression() == NULL)
8122
            {
8123
              if (!arg_type->backend_type_align(this->gogo_, &ret))
8124
                return false;
8125
            }
8126
          else
8127
            {
8128
              // Calling unsafe.Alignof(s.f) returns the alignment of
8129
              // the type of f when it is used as a field in a struct.
8130
              if (!arg_type->backend_type_field_align(this->gogo_, &ret))
8131
                return false;
8132
            }
8133
        }
8134
      else
8135
        go_unreachable();
8136
 
8137
      mpz_set_ui(val, ret);
8138
      *ptype = NULL;
8139
      return true;
8140
    }
8141
  else if (this->code_ == BUILTIN_OFFSETOF)
8142
    {
8143
      Expression* arg = this->one_arg();
8144
      if (arg == NULL)
8145
        return false;
8146
      Field_reference_expression* farg = arg->field_reference_expression();
8147
      if (farg == NULL)
8148
        return false;
8149
      Expression* struct_expr = farg->expr();
8150
      Type* st = struct_expr->type();
8151
      if (st->struct_type() == NULL)
8152
        return false;
8153
      if (st->named_type() != NULL)
8154
        st->named_type()->convert(this->gogo_);
8155
      unsigned int offset;
8156
      if (!st->struct_type()->backend_field_offset(this->gogo_,
8157
                                                   farg->field_index(),
8158
                                                   &offset))
8159
        return false;
8160
      mpz_set_ui(val, offset);
8161
      return true;
8162
    }
8163
  return false;
8164
}
8165
 
8166
// Return a floating point constant value if possible.
8167
 
8168
bool
8169
Builtin_call_expression::do_float_constant_value(mpfr_t val,
8170
                                                 Type** ptype) const
8171
{
8172
  if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8173
    {
8174
      Expression* arg = this->one_arg();
8175
      if (arg == NULL)
8176
        return false;
8177
 
8178
      mpfr_t real;
8179
      mpfr_t imag;
8180
      mpfr_init(real);
8181
      mpfr_init(imag);
8182
 
8183
      bool ret = false;
8184
      Type* type;
8185
      if (arg->complex_constant_value(real, imag, &type))
8186
        {
8187
          if (this->code_ == BUILTIN_REAL)
8188
            mpfr_set(val, real, GMP_RNDN);
8189
          else
8190
            mpfr_set(val, imag, GMP_RNDN);
8191
          *ptype = Builtin_call_expression::real_imag_type(type);
8192
          ret = true;
8193
        }
8194
 
8195
      mpfr_clear(real);
8196
      mpfr_clear(imag);
8197
      return ret;
8198
    }
8199
 
8200
  return false;
8201
}
8202
 
8203
// Return a complex constant value if possible.
8204
 
8205
bool
8206
Builtin_call_expression::do_complex_constant_value(mpfr_t real, mpfr_t imag,
8207
                                                   Type** ptype) const
8208
{
8209
  if (this->code_ == BUILTIN_COMPLEX)
8210
    {
8211
      const Expression_list* args = this->args();
8212
      if (args == NULL || args->size() != 2)
8213
        return false;
8214
 
8215
      mpfr_t r;
8216
      mpfr_init(r);
8217
      Type* rtype;
8218
      if (!args->front()->float_constant_value(r, &rtype))
8219
        {
8220
          mpfr_clear(r);
8221
          return false;
8222
        }
8223
 
8224
      mpfr_t i;
8225
      mpfr_init(i);
8226
 
8227
      bool ret = false;
8228
      Type* itype;
8229
      if (args->back()->float_constant_value(i, &itype)
8230
          && Type::are_identical(rtype, itype, false, NULL))
8231
        {
8232
          mpfr_set(real, r, GMP_RNDN);
8233
          mpfr_set(imag, i, GMP_RNDN);
8234
          *ptype = Builtin_call_expression::complex_type(rtype);
8235
          ret = true;
8236
        }
8237
 
8238
      mpfr_clear(r);
8239
      mpfr_clear(i);
8240
 
8241
      return ret;
8242
    }
8243
 
8244
  return false;
8245
}
8246
 
8247
// Give an error if we are discarding the value of an expression which
8248
// should not normally be discarded.  We don't give an error for
8249
// discarding the value of an ordinary function call, but we do for
8250
// builtin functions, purely for consistency with the gc compiler.
8251
 
8252
void
8253
Builtin_call_expression::do_discarding_value()
8254
{
8255
  switch (this->code_)
8256
    {
8257
    case BUILTIN_INVALID:
8258
    default:
8259
      go_unreachable();
8260
 
8261
    case BUILTIN_APPEND:
8262
    case BUILTIN_CAP:
8263
    case BUILTIN_COMPLEX:
8264
    case BUILTIN_IMAG:
8265
    case BUILTIN_LEN:
8266
    case BUILTIN_MAKE:
8267
    case BUILTIN_NEW:
8268
    case BUILTIN_REAL:
8269
    case BUILTIN_ALIGNOF:
8270
    case BUILTIN_OFFSETOF:
8271
    case BUILTIN_SIZEOF:
8272
      this->unused_value_error();
8273
      break;
8274
 
8275
    case BUILTIN_CLOSE:
8276
    case BUILTIN_COPY:
8277
    case BUILTIN_DELETE:
8278
    case BUILTIN_PANIC:
8279
    case BUILTIN_PRINT:
8280
    case BUILTIN_PRINTLN:
8281
    case BUILTIN_RECOVER:
8282
      break;
8283
    }
8284
}
8285
 
8286
// Return the type.
8287
 
8288
Type*
8289
Builtin_call_expression::do_type()
8290
{
8291
  switch (this->code_)
8292
    {
8293
    case BUILTIN_INVALID:
8294
    default:
8295
      go_unreachable();
8296
 
8297
    case BUILTIN_NEW:
8298
    case BUILTIN_MAKE:
8299
      {
8300
        const Expression_list* args = this->args();
8301
        if (args == NULL || args->empty())
8302
          return Type::make_error_type();
8303
        return Type::make_pointer_type(args->front()->type());
8304
      }
8305
 
8306
    case BUILTIN_CAP:
8307
    case BUILTIN_COPY:
8308
    case BUILTIN_LEN:
8309
    case BUILTIN_ALIGNOF:
8310
    case BUILTIN_OFFSETOF:
8311
    case BUILTIN_SIZEOF:
8312
      return Type::lookup_integer_type("int");
8313
 
8314
    case BUILTIN_CLOSE:
8315
    case BUILTIN_DELETE:
8316
    case BUILTIN_PANIC:
8317
    case BUILTIN_PRINT:
8318
    case BUILTIN_PRINTLN:
8319
      return Type::make_void_type();
8320
 
8321
    case BUILTIN_RECOVER:
8322
      return Type::make_empty_interface_type(Linemap::predeclared_location());
8323
 
8324
    case BUILTIN_APPEND:
8325
      {
8326
        const Expression_list* args = this->args();
8327
        if (args == NULL || args->empty())
8328
          return Type::make_error_type();
8329
        return args->front()->type();
8330
      }
8331
 
8332
    case BUILTIN_REAL:
8333
    case BUILTIN_IMAG:
8334
      {
8335
        Expression* arg = this->one_arg();
8336
        if (arg == NULL)
8337
          return Type::make_error_type();
8338
        Type* t = arg->type();
8339
        if (t->is_abstract())
8340
          t = t->make_non_abstract_type();
8341
        t = Builtin_call_expression::real_imag_type(t);
8342
        if (t == NULL)
8343
          t = Type::make_error_type();
8344
        return t;
8345
      }
8346
 
8347
    case BUILTIN_COMPLEX:
8348
      {
8349
        const Expression_list* args = this->args();
8350
        if (args == NULL || args->size() != 2)
8351
          return Type::make_error_type();
8352
        Type* t = args->front()->type();
8353
        if (t->is_abstract())
8354
          {
8355
            t = args->back()->type();
8356
            if (t->is_abstract())
8357
              t = t->make_non_abstract_type();
8358
          }
8359
        t = Builtin_call_expression::complex_type(t);
8360
        if (t == NULL)
8361
          t = Type::make_error_type();
8362
        return t;
8363
      }
8364
    }
8365
}
8366
 
8367
// Determine the type.
8368
 
8369
void
8370
Builtin_call_expression::do_determine_type(const Type_context* context)
8371
{
8372
  if (!this->determining_types())
8373
    return;
8374
 
8375
  this->fn()->determine_type_no_context();
8376
 
8377
  const Expression_list* args = this->args();
8378
 
8379
  bool is_print;
8380
  Type* arg_type = NULL;
8381
  switch (this->code_)
8382
    {
8383
    case BUILTIN_PRINT:
8384
    case BUILTIN_PRINTLN:
8385
      // Do not force a large integer constant to "int".
8386
      is_print = true;
8387
      break;
8388
 
8389
    case BUILTIN_REAL:
8390
    case BUILTIN_IMAG:
8391
      arg_type = Builtin_call_expression::complex_type(context->type);
8392
      is_print = false;
8393
      break;
8394
 
8395
    case BUILTIN_COMPLEX:
8396
      {
8397
        // For the complex function the type of one operand can
8398
        // determine the type of the other, as in a binary expression.
8399
        arg_type = Builtin_call_expression::real_imag_type(context->type);
8400
        if (args != NULL && args->size() == 2)
8401
          {
8402
            Type* t1 = args->front()->type();
8403
            Type* t2 = args->front()->type();
8404
            if (!t1->is_abstract())
8405
              arg_type = t1;
8406
            else if (!t2->is_abstract())
8407
              arg_type = t2;
8408
          }
8409
        is_print = false;
8410
      }
8411
      break;
8412
 
8413
    default:
8414
      is_print = false;
8415
      break;
8416
    }
8417
 
8418
  if (args != NULL)
8419
    {
8420
      for (Expression_list::const_iterator pa = args->begin();
8421
           pa != args->end();
8422
           ++pa)
8423
        {
8424
          Type_context subcontext;
8425
          subcontext.type = arg_type;
8426
 
8427
          if (is_print)
8428
            {
8429
              // We want to print large constants, we so can't just
8430
              // use the appropriate nonabstract type.  Use uint64 for
8431
              // an integer if we know it is nonnegative, otherwise
8432
              // use int64 for a integer, otherwise use float64 for a
8433
              // float or complex128 for a complex.
8434
              Type* want_type = NULL;
8435
              Type* atype = (*pa)->type();
8436
              if (atype->is_abstract())
8437
                {
8438
                  if (atype->integer_type() != NULL)
8439
                    {
8440
                      mpz_t val;
8441
                      mpz_init(val);
8442
                      Type* dummy;
8443
                      if (this->integer_constant_value(true, val, &dummy)
8444
                          && mpz_sgn(val) >= 0)
8445
                        want_type = Type::lookup_integer_type("uint64");
8446
                      else
8447
                        want_type = Type::lookup_integer_type("int64");
8448
                      mpz_clear(val);
8449
                    }
8450
                  else if (atype->float_type() != NULL)
8451
                    want_type = Type::lookup_float_type("float64");
8452
                  else if (atype->complex_type() != NULL)
8453
                    want_type = Type::lookup_complex_type("complex128");
8454
                  else if (atype->is_abstract_string_type())
8455
                    want_type = Type::lookup_string_type();
8456
                  else if (atype->is_abstract_boolean_type())
8457
                    want_type = Type::lookup_bool_type();
8458
                  else
8459
                    go_unreachable();
8460
                  subcontext.type = want_type;
8461
                }
8462
            }
8463
 
8464
          (*pa)->determine_type(&subcontext);
8465
        }
8466
    }
8467
}
8468
 
8469
// If there is exactly one argument, return true.  Otherwise give an
8470
// error message and return false.
8471
 
8472
bool
8473
Builtin_call_expression::check_one_arg()
8474
{
8475
  const Expression_list* args = this->args();
8476
  if (args == NULL || args->size() < 1)
8477
    {
8478
      this->report_error(_("not enough arguments"));
8479
      return false;
8480
    }
8481
  else if (args->size() > 1)
8482
    {
8483
      this->report_error(_("too many arguments"));
8484
      return false;
8485
    }
8486
  if (args->front()->is_error_expression()
8487
      || args->front()->type()->is_error())
8488
    {
8489
      this->set_is_error();
8490
      return false;
8491
    }
8492
  return true;
8493
}
8494
 
8495
// Check argument types for a builtin function.
8496
 
8497
void
8498
Builtin_call_expression::do_check_types(Gogo*)
8499
{
8500
  switch (this->code_)
8501
    {
8502
    case BUILTIN_INVALID:
8503
    case BUILTIN_NEW:
8504
    case BUILTIN_MAKE:
8505
      return;
8506
 
8507
    case BUILTIN_LEN:
8508
    case BUILTIN_CAP:
8509
      {
8510
        // The single argument may be either a string or an array or a
8511
        // map or a channel, or a pointer to a closed array.
8512
        if (this->check_one_arg())
8513
          {
8514
            Type* arg_type = this->one_arg()->type();
8515
            if (arg_type->points_to() != NULL
8516
                && arg_type->points_to()->array_type() != NULL
8517
                && !arg_type->points_to()->is_slice_type())
8518
              arg_type = arg_type->points_to();
8519
            if (this->code_ == BUILTIN_CAP)
8520
              {
8521
                if (!arg_type->is_error()
8522
                    && arg_type->array_type() == NULL
8523
                    && arg_type->channel_type() == NULL)
8524
                  this->report_error(_("argument must be array or slice "
8525
                                       "or channel"));
8526
              }
8527
            else
8528
              {
8529
                if (!arg_type->is_error()
8530
                    && !arg_type->is_string_type()
8531
                    && arg_type->array_type() == NULL
8532
                    && arg_type->map_type() == NULL
8533
                    && arg_type->channel_type() == NULL)
8534
                  this->report_error(_("argument must be string or "
8535
                                       "array or slice or map or channel"));
8536
              }
8537
          }
8538
      }
8539
      break;
8540
 
8541
    case BUILTIN_PRINT:
8542
    case BUILTIN_PRINTLN:
8543
      {
8544
        const Expression_list* args = this->args();
8545
        if (args == NULL)
8546
          {
8547
            if (this->code_ == BUILTIN_PRINT)
8548
              warning_at(this->location(), 0,
8549
                         "no arguments for builtin function %<%s%>",
8550
                         (this->code_ == BUILTIN_PRINT
8551
                          ? "print"
8552
                          : "println"));
8553
          }
8554
        else
8555
          {
8556
            for (Expression_list::const_iterator p = args->begin();
8557
                 p != args->end();
8558
                 ++p)
8559
              {
8560
                Type* type = (*p)->type();
8561
                if (type->is_error()
8562
                    || type->is_string_type()
8563
                    || type->integer_type() != NULL
8564
                    || type->float_type() != NULL
8565
                    || type->complex_type() != NULL
8566
                    || type->is_boolean_type()
8567
                    || type->points_to() != NULL
8568
                    || type->interface_type() != NULL
8569
                    || type->channel_type() != NULL
8570
                    || type->map_type() != NULL
8571
                    || type->function_type() != NULL
8572
                    || type->is_slice_type())
8573
                  ;
8574
                else if ((*p)->is_type_expression())
8575
                  {
8576
                    // If this is a type expression it's going to give
8577
                    // an error anyhow, so we don't need one here.
8578
                  }
8579
                else
8580
                  this->report_error(_("unsupported argument type to "
8581
                                       "builtin function"));
8582
              }
8583
          }
8584
      }
8585
      break;
8586
 
8587
    case BUILTIN_CLOSE:
8588
      if (this->check_one_arg())
8589
        {
8590
          if (this->one_arg()->type()->channel_type() == NULL)
8591
            this->report_error(_("argument must be channel"));
8592
          else if (!this->one_arg()->type()->channel_type()->may_send())
8593
            this->report_error(_("cannot close receive-only channel"));
8594
        }
8595
      break;
8596
 
8597
    case BUILTIN_PANIC:
8598
    case BUILTIN_SIZEOF:
8599
    case BUILTIN_ALIGNOF:
8600
      this->check_one_arg();
8601
      break;
8602
 
8603
    case BUILTIN_RECOVER:
8604
      if (this->args() != NULL && !this->args()->empty())
8605
        this->report_error(_("too many arguments"));
8606
      break;
8607
 
8608
    case BUILTIN_OFFSETOF:
8609
      if (this->check_one_arg())
8610
        {
8611
          Expression* arg = this->one_arg();
8612
          if (arg->field_reference_expression() == NULL)
8613
            this->report_error(_("argument must be a field reference"));
8614
        }
8615
      break;
8616
 
8617
    case BUILTIN_COPY:
8618
      {
8619
        const Expression_list* args = this->args();
8620
        if (args == NULL || args->size() < 2)
8621
          {
8622
            this->report_error(_("not enough arguments"));
8623
            break;
8624
          }
8625
        else if (args->size() > 2)
8626
          {
8627
            this->report_error(_("too many arguments"));
8628
            break;
8629
          }
8630
        Type* arg1_type = args->front()->type();
8631
        Type* arg2_type = args->back()->type();
8632
        if (arg1_type->is_error() || arg2_type->is_error())
8633
          break;
8634
 
8635
        Type* e1;
8636
        if (arg1_type->is_slice_type())
8637
          e1 = arg1_type->array_type()->element_type();
8638
        else
8639
          {
8640
            this->report_error(_("left argument must be a slice"));
8641
            break;
8642
          }
8643
 
8644
        if (arg2_type->is_slice_type())
8645
          {
8646
            Type* e2 = arg2_type->array_type()->element_type();
8647
            if (!Type::are_identical(e1, e2, true, NULL))
8648
              this->report_error(_("element types must be the same"));
8649
          }
8650
        else if (arg2_type->is_string_type())
8651
          {
8652
            if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8653
              this->report_error(_("first argument must be []byte"));
8654
          }
8655
        else
8656
            this->report_error(_("second argument must be slice or string"));
8657
      }
8658
      break;
8659
 
8660
    case BUILTIN_APPEND:
8661
      {
8662
        const Expression_list* args = this->args();
8663
        if (args == NULL || args->size() < 2)
8664
          {
8665
            this->report_error(_("not enough arguments"));
8666
            break;
8667
          }
8668
        if (args->size() > 2)
8669
          {
8670
            this->report_error(_("too many arguments"));
8671
            break;
8672
          }
8673
 
8674
        // The language permits appending a string to a []byte, as a
8675
        // special case.
8676
        if (args->back()->type()->is_string_type())
8677
          {
8678
            const Array_type* at = args->front()->type()->array_type();
8679
            const Type* e = at->element_type()->forwarded();
8680
            if (e->integer_type() != NULL && e->integer_type()->is_byte())
8681
              break;
8682
          }
8683
 
8684
        // The language says that the second argument must be
8685
        // assignable to a slice of the element type of the first
8686
        // argument.  We already know the first argument is a slice
8687
        // type.
8688
        Array_type* at = args->front()->type()->array_type();
8689
        Type* arg2_type = Type::make_array_type(at->element_type(), NULL);
8690
        std::string reason;
8691
        if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8692
          {
8693
            if (reason.empty())
8694
              this->report_error(_("argument 2 has invalid type"));
8695
            else
8696
              {
8697
                error_at(this->location(), "argument 2 has invalid type (%s)",
8698
                         reason.c_str());
8699
                this->set_is_error();
8700
              }
8701
          }
8702
        break;
8703
      }
8704
 
8705
    case BUILTIN_REAL:
8706
    case BUILTIN_IMAG:
8707
      if (this->check_one_arg())
8708
        {
8709
          if (this->one_arg()->type()->complex_type() == NULL)
8710
            this->report_error(_("argument must have complex type"));
8711
        }
8712
      break;
8713
 
8714
    case BUILTIN_COMPLEX:
8715
      {
8716
        const Expression_list* args = this->args();
8717
        if (args == NULL || args->size() < 2)
8718
          this->report_error(_("not enough arguments"));
8719
        else if (args->size() > 2)
8720
          this->report_error(_("too many arguments"));
8721
        else if (args->front()->is_error_expression()
8722
                 || args->front()->type()->is_error()
8723
                 || args->back()->is_error_expression()
8724
                 || args->back()->type()->is_error())
8725
          this->set_is_error();
8726
        else if (!Type::are_identical(args->front()->type(),
8727
                                      args->back()->type(), true, NULL))
8728
          this->report_error(_("complex arguments must have identical types"));
8729
        else if (args->front()->type()->float_type() == NULL)
8730
          this->report_error(_("complex arguments must have "
8731
                               "floating-point type"));
8732
      }
8733
      break;
8734
 
8735
    default:
8736
      go_unreachable();
8737
    }
8738
}
8739
 
8740
// Return the tree for a builtin function.
8741
 
8742
tree
8743
Builtin_call_expression::do_get_tree(Translate_context* context)
8744
{
8745
  Gogo* gogo = context->gogo();
8746
  Location location = this->location();
8747
  switch (this->code_)
8748
    {
8749
    case BUILTIN_INVALID:
8750
    case BUILTIN_NEW:
8751
    case BUILTIN_MAKE:
8752
      go_unreachable();
8753
 
8754
    case BUILTIN_LEN:
8755
    case BUILTIN_CAP:
8756
      {
8757
        const Expression_list* args = this->args();
8758
        go_assert(args != NULL && args->size() == 1);
8759
        Expression* arg = *args->begin();
8760
        Type* arg_type = arg->type();
8761
 
8762
        if (this->seen_)
8763
          {
8764
            go_assert(saw_errors());
8765
            return error_mark_node;
8766
          }
8767
        this->seen_ = true;
8768
 
8769
        tree arg_tree = arg->get_tree(context);
8770
 
8771
        this->seen_ = false;
8772
 
8773
        if (arg_tree == error_mark_node)
8774
          return error_mark_node;
8775
 
8776
        if (arg_type->points_to() != NULL)
8777
          {
8778
            arg_type = arg_type->points_to();
8779
            go_assert(arg_type->array_type() != NULL
8780
                       && !arg_type->is_slice_type());
8781
            go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
8782
            arg_tree = build_fold_indirect_ref(arg_tree);
8783
          }
8784
 
8785
        tree val_tree;
8786
        if (this->code_ == BUILTIN_LEN)
8787
          {
8788
            if (arg_type->is_string_type())
8789
              val_tree = String_type::length_tree(gogo, arg_tree);
8790
            else if (arg_type->array_type() != NULL)
8791
              {
8792
                if (this->seen_)
8793
                  {
8794
                    go_assert(saw_errors());
8795
                    return error_mark_node;
8796
                  }
8797
                this->seen_ = true;
8798
                val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
8799
                this->seen_ = false;
8800
              }
8801
            else if (arg_type->map_type() != NULL)
8802
              {
8803
                tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8804
                static tree map_len_fndecl;
8805
                val_tree = Gogo::call_builtin(&map_len_fndecl,
8806
                                              location,
8807
                                              "__go_map_len",
8808
                                              1,
8809
                                              integer_type_node,
8810
                                              arg_type_tree,
8811
                                              arg_tree);
8812
              }
8813
            else if (arg_type->channel_type() != NULL)
8814
              {
8815
                tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8816
                static tree chan_len_fndecl;
8817
                val_tree = Gogo::call_builtin(&chan_len_fndecl,
8818
                                              location,
8819
                                              "__go_chan_len",
8820
                                              1,
8821
                                              integer_type_node,
8822
                                              arg_type_tree,
8823
                                              arg_tree);
8824
              }
8825
            else
8826
              go_unreachable();
8827
          }
8828
        else
8829
          {
8830
            if (arg_type->array_type() != NULL)
8831
              {
8832
                if (this->seen_)
8833
                  {
8834
                    go_assert(saw_errors());
8835
                    return error_mark_node;
8836
                  }
8837
                this->seen_ = true;
8838
                val_tree = arg_type->array_type()->capacity_tree(gogo,
8839
                                                                 arg_tree);
8840
                this->seen_ = false;
8841
              }
8842
            else if (arg_type->channel_type() != NULL)
8843
              {
8844
                tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
8845
                static tree chan_cap_fndecl;
8846
                val_tree = Gogo::call_builtin(&chan_cap_fndecl,
8847
                                              location,
8848
                                              "__go_chan_cap",
8849
                                              1,
8850
                                              integer_type_node,
8851
                                              arg_type_tree,
8852
                                              arg_tree);
8853
              }
8854
            else
8855
              go_unreachable();
8856
          }
8857
 
8858
        if (val_tree == error_mark_node)
8859
          return error_mark_node;
8860
 
8861
        Type* int_type = Type::lookup_integer_type("int");
8862
        tree type_tree = type_to_tree(int_type->get_backend(gogo));
8863
        if (type_tree == TREE_TYPE(val_tree))
8864
          return val_tree;
8865
        else
8866
          return fold(convert_to_integer(type_tree, val_tree));
8867
      }
8868
 
8869
    case BUILTIN_PRINT:
8870
    case BUILTIN_PRINTLN:
8871
      {
8872
        const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8873
        tree stmt_list = NULL_TREE;
8874
 
8875
        const Expression_list* call_args = this->args();
8876
        if (call_args != NULL)
8877
          {
8878
            for (Expression_list::const_iterator p = call_args->begin();
8879
                 p != call_args->end();
8880
                 ++p)
8881
              {
8882
                if (is_ln && p != call_args->begin())
8883
                  {
8884
                    static tree print_space_fndecl;
8885
                    tree call = Gogo::call_builtin(&print_space_fndecl,
8886
                                                   location,
8887
                                                   "__go_print_space",
8888
                                                   0,
8889
                                                   void_type_node);
8890
                    if (call == error_mark_node)
8891
                      return error_mark_node;
8892
                    append_to_statement_list(call, &stmt_list);
8893
                  }
8894
 
8895
                Type* type = (*p)->type();
8896
 
8897
                tree arg = (*p)->get_tree(context);
8898
                if (arg == error_mark_node)
8899
                  return error_mark_node;
8900
 
8901
                tree* pfndecl;
8902
                const char* fnname;
8903
                if (type->is_string_type())
8904
                  {
8905
                    static tree print_string_fndecl;
8906
                    pfndecl = &print_string_fndecl;
8907
                    fnname = "__go_print_string";
8908
                  }
8909
                else if (type->integer_type() != NULL
8910
                         && type->integer_type()->is_unsigned())
8911
                  {
8912
                    static tree print_uint64_fndecl;
8913
                    pfndecl = &print_uint64_fndecl;
8914
                    fnname = "__go_print_uint64";
8915
                    Type* itype = Type::lookup_integer_type("uint64");
8916
                    Btype* bitype = itype->get_backend(gogo);
8917
                    arg = fold_convert_loc(location.gcc_location(),
8918
                                           type_to_tree(bitype), arg);
8919
                  }
8920
                else if (type->integer_type() != NULL)
8921
                  {
8922
                    static tree print_int64_fndecl;
8923
                    pfndecl = &print_int64_fndecl;
8924
                    fnname = "__go_print_int64";
8925
                    Type* itype = Type::lookup_integer_type("int64");
8926
                    Btype* bitype = itype->get_backend(gogo);
8927
                    arg = fold_convert_loc(location.gcc_location(),
8928
                                           type_to_tree(bitype), arg);
8929
                  }
8930
                else if (type->float_type() != NULL)
8931
                  {
8932
                    static tree print_double_fndecl;
8933
                    pfndecl = &print_double_fndecl;
8934
                    fnname = "__go_print_double";
8935
                    arg = fold_convert_loc(location.gcc_location(),
8936
                                           double_type_node, arg);
8937
                  }
8938
                else if (type->complex_type() != NULL)
8939
                  {
8940
                    static tree print_complex_fndecl;
8941
                    pfndecl = &print_complex_fndecl;
8942
                    fnname = "__go_print_complex";
8943
                    arg = fold_convert_loc(location.gcc_location(),
8944
                                           complex_double_type_node, arg);
8945
                  }
8946
                else if (type->is_boolean_type())
8947
                  {
8948
                    static tree print_bool_fndecl;
8949
                    pfndecl = &print_bool_fndecl;
8950
                    fnname = "__go_print_bool";
8951
                  }
8952
                else if (type->points_to() != NULL
8953
                         || type->channel_type() != NULL
8954
                         || type->map_type() != NULL
8955
                         || type->function_type() != NULL)
8956
                  {
8957
                    static tree print_pointer_fndecl;
8958
                    pfndecl = &print_pointer_fndecl;
8959
                    fnname = "__go_print_pointer";
8960
                    arg = fold_convert_loc(location.gcc_location(),
8961
                                           ptr_type_node, arg);
8962
                  }
8963
                else if (type->interface_type() != NULL)
8964
                  {
8965
                    if (type->interface_type()->is_empty())
8966
                      {
8967
                        static tree print_empty_interface_fndecl;
8968
                        pfndecl = &print_empty_interface_fndecl;
8969
                        fnname = "__go_print_empty_interface";
8970
                      }
8971
                    else
8972
                      {
8973
                        static tree print_interface_fndecl;
8974
                        pfndecl = &print_interface_fndecl;
8975
                        fnname = "__go_print_interface";
8976
                      }
8977
                  }
8978
                else if (type->is_slice_type())
8979
                  {
8980
                    static tree print_slice_fndecl;
8981
                    pfndecl = &print_slice_fndecl;
8982
                    fnname = "__go_print_slice";
8983
                  }
8984
                else
8985
                  go_unreachable();
8986
 
8987
                tree call = Gogo::call_builtin(pfndecl,
8988
                                               location,
8989
                                               fnname,
8990
                                               1,
8991
                                               void_type_node,
8992
                                               TREE_TYPE(arg),
8993
                                               arg);
8994
                if (call == error_mark_node)
8995
                  return error_mark_node;
8996
                append_to_statement_list(call, &stmt_list);
8997
              }
8998
          }
8999
 
9000
        if (is_ln)
9001
          {
9002
            static tree print_nl_fndecl;
9003
            tree call = Gogo::call_builtin(&print_nl_fndecl,
9004
                                           location,
9005
                                           "__go_print_nl",
9006
                                           0,
9007
                                           void_type_node);
9008
            if (call == error_mark_node)
9009
              return error_mark_node;
9010
            append_to_statement_list(call, &stmt_list);
9011
          }
9012
 
9013
        return stmt_list;
9014
      }
9015
 
9016
    case BUILTIN_PANIC:
9017
      {
9018
        const Expression_list* args = this->args();
9019
        go_assert(args != NULL && args->size() == 1);
9020
        Expression* arg = args->front();
9021
        tree arg_tree = arg->get_tree(context);
9022
        if (arg_tree == error_mark_node)
9023
          return error_mark_node;
9024
        Type *empty =
9025
          Type::make_empty_interface_type(Linemap::predeclared_location());
9026
        arg_tree = Expression::convert_for_assignment(context, empty,
9027
                                                      arg->type(),
9028
                                                      arg_tree, location);
9029
        static tree panic_fndecl;
9030
        tree call = Gogo::call_builtin(&panic_fndecl,
9031
                                       location,
9032
                                       "__go_panic",
9033
                                       1,
9034
                                       void_type_node,
9035
                                       TREE_TYPE(arg_tree),
9036
                                       arg_tree);
9037
        if (call == error_mark_node)
9038
          return error_mark_node;
9039
        // This function will throw an exception.
9040
        TREE_NOTHROW(panic_fndecl) = 0;
9041
        // This function will not return.
9042
        TREE_THIS_VOLATILE(panic_fndecl) = 1;
9043
        return call;
9044
      }
9045
 
9046
    case BUILTIN_RECOVER:
9047
      {
9048
        // The argument is set when building recover thunks.  It's a
9049
        // boolean value which is true if we can recover a value now.
9050
        const Expression_list* args = this->args();
9051
        go_assert(args != NULL && args->size() == 1);
9052
        Expression* arg = args->front();
9053
        tree arg_tree = arg->get_tree(context);
9054
        if (arg_tree == error_mark_node)
9055
          return error_mark_node;
9056
 
9057
        Type *empty =
9058
          Type::make_empty_interface_type(Linemap::predeclared_location());
9059
        tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
9060
 
9061
        Type* nil_type = Type::make_nil_type();
9062
        Expression* nil = Expression::make_nil(location);
9063
        tree nil_tree = nil->get_tree(context);
9064
        tree empty_nil_tree = Expression::convert_for_assignment(context,
9065
                                                                 empty,
9066
                                                                 nil_type,
9067
                                                                 nil_tree,
9068
                                                                 location);
9069
 
9070
        // We need to handle a deferred call to recover specially,
9071
        // because it changes whether it can recover a panic or not.
9072
        // See test7 in test/recover1.go.
9073
        tree call;
9074
        if (this->is_deferred())
9075
          {
9076
            static tree deferred_recover_fndecl;
9077
            call = Gogo::call_builtin(&deferred_recover_fndecl,
9078
                                      location,
9079
                                      "__go_deferred_recover",
9080
                                      0,
9081
                                      empty_tree);
9082
          }
9083
        else
9084
          {
9085
            static tree recover_fndecl;
9086
            call = Gogo::call_builtin(&recover_fndecl,
9087
                                      location,
9088
                                      "__go_recover",
9089
                                      0,
9090
                                      empty_tree);
9091
          }
9092
        if (call == error_mark_node)
9093
          return error_mark_node;
9094
        return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
9095
                               arg_tree, call, empty_nil_tree);
9096
      }
9097
 
9098
    case BUILTIN_CLOSE:
9099
      {
9100
        const Expression_list* args = this->args();
9101
        go_assert(args != NULL && args->size() == 1);
9102
        Expression* arg = args->front();
9103
        tree arg_tree = arg->get_tree(context);
9104
        if (arg_tree == error_mark_node)
9105
          return error_mark_node;
9106
        static tree close_fndecl;
9107
        return Gogo::call_builtin(&close_fndecl,
9108
                                  location,
9109
                                  "__go_builtin_close",
9110
                                  1,
9111
                                  void_type_node,
9112
                                  TREE_TYPE(arg_tree),
9113
                                  arg_tree);
9114
      }
9115
 
9116
    case BUILTIN_SIZEOF:
9117
    case BUILTIN_OFFSETOF:
9118
    case BUILTIN_ALIGNOF:
9119
      {
9120
        mpz_t val;
9121
        mpz_init(val);
9122
        Type* dummy;
9123
        bool b = this->integer_constant_value(true, val, &dummy);
9124
        if (!b)
9125
          {
9126
            go_assert(saw_errors());
9127
            return error_mark_node;
9128
          }
9129
        Type* int_type = Type::lookup_integer_type("int");
9130
        tree type = type_to_tree(int_type->get_backend(gogo));
9131
        tree ret = Expression::integer_constant_tree(val, type);
9132
        mpz_clear(val);
9133
        return ret;
9134
      }
9135
 
9136
    case BUILTIN_COPY:
9137
      {
9138
        const Expression_list* args = this->args();
9139
        go_assert(args != NULL && args->size() == 2);
9140
        Expression* arg1 = args->front();
9141
        Expression* arg2 = args->back();
9142
 
9143
        tree arg1_tree = arg1->get_tree(context);
9144
        tree arg2_tree = arg2->get_tree(context);
9145
        if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
9146
          return error_mark_node;
9147
 
9148
        Type* arg1_type = arg1->type();
9149
        Array_type* at = arg1_type->array_type();
9150
        arg1_tree = save_expr(arg1_tree);
9151
        tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
9152
        tree arg1_len = at->length_tree(gogo, arg1_tree);
9153
        if (arg1_val == error_mark_node || arg1_len == error_mark_node)
9154
          return error_mark_node;
9155
 
9156
        Type* arg2_type = arg2->type();
9157
        tree arg2_val;
9158
        tree arg2_len;
9159
        if (arg2_type->is_slice_type())
9160
          {
9161
            at = arg2_type->array_type();
9162
            arg2_tree = save_expr(arg2_tree);
9163
            arg2_val = at->value_pointer_tree(gogo, arg2_tree);
9164
            arg2_len = at->length_tree(gogo, arg2_tree);
9165
          }
9166
        else
9167
          {
9168
            arg2_tree = save_expr(arg2_tree);
9169
            arg2_val = String_type::bytes_tree(gogo, arg2_tree);
9170
            arg2_len = String_type::length_tree(gogo, arg2_tree);
9171
          }
9172
        if (arg2_val == error_mark_node || arg2_len == error_mark_node)
9173
          return error_mark_node;
9174
 
9175
        arg1_len = save_expr(arg1_len);
9176
        arg2_len = save_expr(arg2_len);
9177
        tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
9178
                                   TREE_TYPE(arg1_len),
9179
                                   fold_build2_loc(location.gcc_location(),
9180
                                                   LT_EXPR, boolean_type_node,
9181
                                                   arg1_len, arg2_len),
9182
                                   arg1_len, arg2_len);
9183
        len = save_expr(len);
9184
 
9185
        Type* element_type = at->element_type();
9186
        Btype* element_btype = element_type->get_backend(gogo);
9187
        tree element_type_tree = type_to_tree(element_btype);
9188
        if (element_type_tree == error_mark_node)
9189
          return error_mark_node;
9190
        tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9191
        tree bytecount = fold_convert_loc(location.gcc_location(),
9192
                                          TREE_TYPE(element_size), len);
9193
        bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
9194
                                    TREE_TYPE(element_size),
9195
                                    bytecount, element_size);
9196
        bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
9197
                                     bytecount);
9198
 
9199
        arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
9200
                                    arg1_val);
9201
        arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
9202
                                    arg2_val);
9203
 
9204
        static tree copy_fndecl;
9205
        tree call = Gogo::call_builtin(&copy_fndecl,
9206
                                       location,
9207
                                       "__go_copy",
9208
                                       3,
9209
                                       void_type_node,
9210
                                       ptr_type_node,
9211
                                       arg1_val,
9212
                                       ptr_type_node,
9213
                                       arg2_val,
9214
                                       size_type_node,
9215
                                       bytecount);
9216
        if (call == error_mark_node)
9217
          return error_mark_node;
9218
 
9219
        return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
9220
                               TREE_TYPE(len), call, len);
9221
      }
9222
 
9223
    case BUILTIN_APPEND:
9224
      {
9225
        const Expression_list* args = this->args();
9226
        go_assert(args != NULL && args->size() == 2);
9227
        Expression* arg1 = args->front();
9228
        Expression* arg2 = args->back();
9229
 
9230
        tree arg1_tree = arg1->get_tree(context);
9231
        tree arg2_tree = arg2->get_tree(context);
9232
        if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
9233
          return error_mark_node;
9234
 
9235
        Array_type* at = arg1->type()->array_type();
9236
        Type* element_type = at->element_type()->forwarded();
9237
 
9238
        tree arg2_val;
9239
        tree arg2_len;
9240
        tree element_size;
9241
        if (arg2->type()->is_string_type()
9242
            && element_type->integer_type() != NULL
9243
            && element_type->integer_type()->is_byte())
9244
          {
9245
            arg2_tree = save_expr(arg2_tree);
9246
            arg2_val = String_type::bytes_tree(gogo, arg2_tree);
9247
            arg2_len = String_type::length_tree(gogo, arg2_tree);
9248
            element_size = size_int(1);
9249
          }
9250
        else
9251
          {
9252
            arg2_tree = Expression::convert_for_assignment(context, at,
9253
                                                           arg2->type(),
9254
                                                           arg2_tree,
9255
                                                           location);
9256
            if (arg2_tree == error_mark_node)
9257
              return error_mark_node;
9258
 
9259
            arg2_tree = save_expr(arg2_tree);
9260
 
9261
             arg2_val = at->value_pointer_tree(gogo, arg2_tree);
9262
             arg2_len = at->length_tree(gogo, arg2_tree);
9263
 
9264
             Btype* element_btype = element_type->get_backend(gogo);
9265
             tree element_type_tree = type_to_tree(element_btype);
9266
             if (element_type_tree == error_mark_node)
9267
               return error_mark_node;
9268
             element_size = TYPE_SIZE_UNIT(element_type_tree);
9269
          }
9270
 
9271
        arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
9272
                                    arg2_val);
9273
        arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
9274
                                    arg2_len);
9275
        element_size = fold_convert_loc(location.gcc_location(), size_type_node,
9276
                                        element_size);
9277
 
9278
        if (arg2_val == error_mark_node
9279
            || arg2_len == error_mark_node
9280
            || element_size == error_mark_node)
9281
          return error_mark_node;
9282
 
9283
        // We rebuild the decl each time since the slice types may
9284
        // change.
9285
        tree append_fndecl = NULL_TREE;
9286
        return Gogo::call_builtin(&append_fndecl,
9287
                                  location,
9288
                                  "__go_append",
9289
                                  4,
9290
                                  TREE_TYPE(arg1_tree),
9291
                                  TREE_TYPE(arg1_tree),
9292
                                  arg1_tree,
9293
                                  ptr_type_node,
9294
                                  arg2_val,
9295
                                  size_type_node,
9296
                                  arg2_len,
9297
                                  size_type_node,
9298
                                  element_size);
9299
      }
9300
 
9301
    case BUILTIN_REAL:
9302
    case BUILTIN_IMAG:
9303
      {
9304
        const Expression_list* args = this->args();
9305
        go_assert(args != NULL && args->size() == 1);
9306
        Expression* arg = args->front();
9307
        tree arg_tree = arg->get_tree(context);
9308
        if (arg_tree == error_mark_node)
9309
          return error_mark_node;
9310
        go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
9311
        if (this->code_ == BUILTIN_REAL)
9312
          return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
9313
                                 TREE_TYPE(TREE_TYPE(arg_tree)),
9314
                                 arg_tree);
9315
        else
9316
          return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
9317
                                 TREE_TYPE(TREE_TYPE(arg_tree)),
9318
                                 arg_tree);
9319
      }
9320
 
9321
    case BUILTIN_COMPLEX:
9322
      {
9323
        const Expression_list* args = this->args();
9324
        go_assert(args != NULL && args->size() == 2);
9325
        tree r = args->front()->get_tree(context);
9326
        tree i = args->back()->get_tree(context);
9327
        if (r == error_mark_node || i == error_mark_node)
9328
          return error_mark_node;
9329
        go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
9330
                   == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
9331
        go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
9332
        return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
9333
                               build_complex_type(TREE_TYPE(r)),
9334
                               r, i);
9335
      }
9336
 
9337
    default:
9338
      go_unreachable();
9339
    }
9340
}
9341
 
9342
// We have to support exporting a builtin call expression, because
9343
// code can set a constant to the result of a builtin expression.
9344
 
9345
void
9346
Builtin_call_expression::do_export(Export* exp) const
9347
{
9348
  bool ok = false;
9349
 
9350
  mpz_t val;
9351
  mpz_init(val);
9352
  Type* dummy;
9353
  if (this->integer_constant_value(true, val, &dummy))
9354
    {
9355
      Integer_expression::export_integer(exp, val);
9356
      ok = true;
9357
    }
9358
  mpz_clear(val);
9359
 
9360
  if (!ok)
9361
    {
9362
      mpfr_t fval;
9363
      mpfr_init(fval);
9364
      if (this->float_constant_value(fval, &dummy))
9365
        {
9366
          Float_expression::export_float(exp, fval);
9367
          ok = true;
9368
        }
9369
      mpfr_clear(fval);
9370
    }
9371
 
9372
  if (!ok)
9373
    {
9374
      mpfr_t real;
9375
      mpfr_t imag;
9376
      mpfr_init(real);
9377
      mpfr_init(imag);
9378
      if (this->complex_constant_value(real, imag, &dummy))
9379
        {
9380
          Complex_expression::export_complex(exp, real, imag);
9381
          ok = true;
9382
        }
9383
      mpfr_clear(real);
9384
      mpfr_clear(imag);
9385
    }
9386
 
9387
  if (!ok)
9388
    {
9389
      error_at(this->location(), "value is not constant");
9390
      return;
9391
    }
9392
 
9393
  // A trailing space lets us reliably identify the end of the number.
9394
  exp->write_c_string(" ");
9395
}
9396
 
9397
// Class Call_expression.
9398
 
9399
// Traversal.
9400
 
9401
int
9402
Call_expression::do_traverse(Traverse* traverse)
9403
{
9404
  if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9405
    return TRAVERSE_EXIT;
9406
  if (this->args_ != NULL)
9407
    {
9408
      if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9409
        return TRAVERSE_EXIT;
9410
    }
9411
  return TRAVERSE_CONTINUE;
9412
}
9413
 
9414
// Lower a call statement.
9415
 
9416
Expression*
9417
Call_expression::do_lower(Gogo* gogo, Named_object* function,
9418
                          Statement_inserter* inserter, int)
9419
{
9420
  Location loc = this->location();
9421
 
9422
  // A type cast can look like a function call.
9423
  if (this->fn_->is_type_expression()
9424
      && this->args_ != NULL
9425
      && this->args_->size() == 1)
9426
    return Expression::make_cast(this->fn_->type(), this->args_->front(),
9427
                                 loc);
9428
 
9429
  // Recognize a call to a builtin function.
9430
  Func_expression* fne = this->fn_->func_expression();
9431
  if (fne != NULL
9432
      && fne->named_object()->is_function_declaration()
9433
      && fne->named_object()->func_declaration_value()->type()->is_builtin())
9434
    return new Builtin_call_expression(gogo, this->fn_, this->args_,
9435
                                       this->is_varargs_, loc);
9436
 
9437
  // Handle an argument which is a call to a function which returns
9438
  // multiple results.
9439
  if (this->args_ != NULL
9440
      && this->args_->size() == 1
9441
      && this->args_->front()->call_expression() != NULL
9442
      && this->fn_->type()->function_type() != NULL)
9443
    {
9444
      Function_type* fntype = this->fn_->type()->function_type();
9445
      size_t rc = this->args_->front()->call_expression()->result_count();
9446
      if (rc > 1
9447
          && fntype->parameters() != NULL
9448
          && (fntype->parameters()->size() == rc
9449
              || (fntype->is_varargs()
9450
                  && fntype->parameters()->size() - 1 <= rc)))
9451
        {
9452
          Call_expression* call = this->args_->front()->call_expression();
9453
          Expression_list* args = new Expression_list;
9454
          for (size_t i = 0; i < rc; ++i)
9455
            args->push_back(Expression::make_call_result(call, i));
9456
          // We can't return a new call expression here, because this
9457
          // one may be referenced by Call_result expressions.  We
9458
          // also can't delete the old arguments, because we may still
9459
          // traverse them somewhere up the call stack.  FIXME.
9460
          this->args_ = args;
9461
        }
9462
    }
9463
 
9464
  // If this call returns multiple results, create a temporary
9465
  // variable for each result.
9466
  size_t rc = this->result_count();
9467
  if (rc > 1 && this->results_ == NULL)
9468
    {
9469
      std::vector<Temporary_statement*>* temps =
9470
        new std::vector<Temporary_statement*>;
9471
      temps->reserve(rc);
9472
      const Typed_identifier_list* results =
9473
        this->fn_->type()->function_type()->results();
9474
      for (Typed_identifier_list::const_iterator p = results->begin();
9475
           p != results->end();
9476
           ++p)
9477
        {
9478
          Temporary_statement* temp = Statement::make_temporary(p->type(),
9479
                                                                NULL, loc);
9480
          inserter->insert(temp);
9481
          temps->push_back(temp);
9482
        }
9483
      this->results_ = temps;
9484
    }
9485
 
9486
  // Handle a call to a varargs function by packaging up the extra
9487
  // parameters.
9488
  if (this->fn_->type()->function_type() != NULL
9489
      && this->fn_->type()->function_type()->is_varargs())
9490
    {
9491
      Function_type* fntype = this->fn_->type()->function_type();
9492
      const Typed_identifier_list* parameters = fntype->parameters();
9493
      go_assert(parameters != NULL && !parameters->empty());
9494
      Type* varargs_type = parameters->back().type();
9495
      this->lower_varargs(gogo, function, inserter, varargs_type,
9496
                          parameters->size());
9497
    }
9498
 
9499
  // If this is call to a method, call the method directly passing the
9500
  // object as the first parameter.
9501
  Bound_method_expression* bme = this->fn_->bound_method_expression();
9502
  if (bme != NULL)
9503
    {
9504
      Named_object* method = bme->method();
9505
      Expression* first_arg = bme->first_argument();
9506
 
9507
      // We always pass a pointer when calling a method.
9508
      if (first_arg->type()->points_to() == NULL
9509
          && !first_arg->type()->is_error())
9510
        {
9511
          first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9512
          // We may need to create a temporary variable so that we can
9513
          // take the address.  We can't do that here because it will
9514
          // mess up the order of evaluation.
9515
          Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9516
          ue->set_create_temp();
9517
        }
9518
 
9519
      // If we are calling a method which was inherited from an
9520
      // embedded struct, and the method did not get a stub, then the
9521
      // first type may be wrong.
9522
      Type* fatype = bme->first_argument_type();
9523
      if (fatype != NULL)
9524
        {
9525
          if (fatype->points_to() == NULL)
9526
            fatype = Type::make_pointer_type(fatype);
9527
          first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9528
        }
9529
 
9530
      Expression_list* new_args = new Expression_list();
9531
      new_args->push_back(first_arg);
9532
      if (this->args_ != NULL)
9533
        {
9534
          for (Expression_list::const_iterator p = this->args_->begin();
9535
               p != this->args_->end();
9536
               ++p)
9537
            new_args->push_back(*p);
9538
        }
9539
 
9540
      // We have to change in place because this structure may be
9541
      // referenced by Call_result_expressions.  We can't delete the
9542
      // old arguments, because we may be traversing them up in some
9543
      // caller.  FIXME.
9544
      this->args_ = new_args;
9545
      this->fn_ = Expression::make_func_reference(method, NULL,
9546
                                                  bme->location());
9547
    }
9548
 
9549
  return this;
9550
}
9551
 
9552
// Lower a call to a varargs function.  FUNCTION is the function in
9553
// which the call occurs--it's not the function we are calling.
9554
// VARARGS_TYPE is the type of the varargs parameter, a slice type.
9555
// PARAM_COUNT is the number of parameters of the function we are
9556
// calling; the last of these parameters will be the varargs
9557
// parameter.
9558
 
9559
void
9560
Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9561
                               Statement_inserter* inserter,
9562
                               Type* varargs_type, size_t param_count)
9563
{
9564
  if (this->varargs_are_lowered_)
9565
    return;
9566
 
9567
  Location loc = this->location();
9568
 
9569
  go_assert(param_count > 0);
9570
  go_assert(varargs_type->is_slice_type());
9571
 
9572
  size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9573
  if (arg_count < param_count - 1)
9574
    {
9575
      // Not enough arguments; will be caught in check_types.
9576
      return;
9577
    }
9578
 
9579
  Expression_list* old_args = this->args_;
9580
  Expression_list* new_args = new Expression_list();
9581
  bool push_empty_arg = false;
9582
  if (old_args == NULL || old_args->empty())
9583
    {
9584
      go_assert(param_count == 1);
9585
      push_empty_arg = true;
9586
    }
9587
  else
9588
    {
9589
      Expression_list::const_iterator pa;
9590
      int i = 1;
9591
      for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9592
        {
9593
          if (static_cast<size_t>(i) == param_count)
9594
            break;
9595
          new_args->push_back(*pa);
9596
        }
9597
 
9598
      // We have reached the varargs parameter.
9599
 
9600
      bool issued_error = false;
9601
      if (pa == old_args->end())
9602
        push_empty_arg = true;
9603
      else if (pa + 1 == old_args->end() && this->is_varargs_)
9604
        new_args->push_back(*pa);
9605
      else if (this->is_varargs_)
9606
        {
9607
          this->report_error(_("too many arguments"));
9608
          return;
9609
        }
9610
      else
9611
        {
9612
          Type* element_type = varargs_type->array_type()->element_type();
9613
          Expression_list* vals = new Expression_list;
9614
          for (; pa != old_args->end(); ++pa, ++i)
9615
            {
9616
              // Check types here so that we get a better message.
9617
              Type* patype = (*pa)->type();
9618
              Location paloc = (*pa)->location();
9619
              if (!this->check_argument_type(i, element_type, patype,
9620
                                             paloc, issued_error))
9621
                continue;
9622
              vals->push_back(*pa);
9623
            }
9624
          Expression* val =
9625
            Expression::make_slice_composite_literal(varargs_type, vals, loc);
9626
          gogo->lower_expression(function, inserter, &val);
9627
          new_args->push_back(val);
9628
        }
9629
    }
9630
 
9631
  if (push_empty_arg)
9632
    new_args->push_back(Expression::make_nil(loc));
9633
 
9634
  // We can't return a new call expression here, because this one may
9635
  // be referenced by Call_result expressions.  FIXME.  We can't
9636
  // delete OLD_ARGS because we may have both a Call_expression and a
9637
  // Builtin_call_expression which refer to them.  FIXME.
9638
  this->args_ = new_args;
9639
  this->varargs_are_lowered_ = true;
9640
}
9641
 
9642
// Get the function type.  This can return NULL in error cases.
9643
 
9644
Function_type*
9645
Call_expression::get_function_type() const
9646
{
9647
  return this->fn_->type()->function_type();
9648
}
9649
 
9650
// Return the number of values which this call will return.
9651
 
9652
size_t
9653
Call_expression::result_count() const
9654
{
9655
  const Function_type* fntype = this->get_function_type();
9656
  if (fntype == NULL)
9657
    return 0;
9658
  if (fntype->results() == NULL)
9659
    return 0;
9660
  return fntype->results()->size();
9661
}
9662
 
9663
// Return the temporary which holds a result.
9664
 
9665
Temporary_statement*
9666
Call_expression::result(size_t i) const
9667
{
9668
  go_assert(this->results_ != NULL
9669
            && this->results_->size() > i);
9670
  return (*this->results_)[i];
9671
}
9672
 
9673
// Return whether this is a call to the predeclared function recover.
9674
 
9675
bool
9676
Call_expression::is_recover_call() const
9677
{
9678
  return this->do_is_recover_call();
9679
}
9680
 
9681
// Set the argument to the recover function.
9682
 
9683
void
9684
Call_expression::set_recover_arg(Expression* arg)
9685
{
9686
  this->do_set_recover_arg(arg);
9687
}
9688
 
9689
// Virtual functions also implemented by Builtin_call_expression.
9690
 
9691
bool
9692
Call_expression::do_is_recover_call() const
9693
{
9694
  return false;
9695
}
9696
 
9697
void
9698
Call_expression::do_set_recover_arg(Expression*)
9699
{
9700
  go_unreachable();
9701
}
9702
 
9703
// We have found an error with this call expression; return true if
9704
// we should report it.
9705
 
9706
bool
9707
Call_expression::issue_error()
9708
{
9709
  if (this->issued_error_)
9710
    return false;
9711
  else
9712
    {
9713
      this->issued_error_ = true;
9714
      return true;
9715
    }
9716
}
9717
 
9718
// Get the type.
9719
 
9720
Type*
9721
Call_expression::do_type()
9722
{
9723
  if (this->type_ != NULL)
9724
    return this->type_;
9725
 
9726
  Type* ret;
9727
  Function_type* fntype = this->get_function_type();
9728
  if (fntype == NULL)
9729
    return Type::make_error_type();
9730
 
9731
  const Typed_identifier_list* results = fntype->results();
9732
  if (results == NULL)
9733
    ret = Type::make_void_type();
9734
  else if (results->size() == 1)
9735
    ret = results->begin()->type();
9736
  else
9737
    ret = Type::make_call_multiple_result_type(this);
9738
 
9739
  this->type_ = ret;
9740
 
9741
  return this->type_;
9742
}
9743
 
9744
// Determine types for a call expression.  We can use the function
9745
// parameter types to set the types of the arguments.
9746
 
9747
void
9748
Call_expression::do_determine_type(const Type_context*)
9749
{
9750
  if (!this->determining_types())
9751
    return;
9752
 
9753
  this->fn_->determine_type_no_context();
9754
  Function_type* fntype = this->get_function_type();
9755
  const Typed_identifier_list* parameters = NULL;
9756
  if (fntype != NULL)
9757
    parameters = fntype->parameters();
9758
  if (this->args_ != NULL)
9759
    {
9760
      Typed_identifier_list::const_iterator pt;
9761
      if (parameters != NULL)
9762
        pt = parameters->begin();
9763
      bool first = true;
9764
      for (Expression_list::const_iterator pa = this->args_->begin();
9765
           pa != this->args_->end();
9766
           ++pa)
9767
        {
9768
          if (first)
9769
            {
9770
              first = false;
9771
              // If this is a method, the first argument is the
9772
              // receiver.
9773
              if (fntype != NULL && fntype->is_method())
9774
                {
9775
                  Type* rtype = fntype->receiver()->type();
9776
                  // The receiver is always passed as a pointer.
9777
                  if (rtype->points_to() == NULL)
9778
                    rtype = Type::make_pointer_type(rtype);
9779
                  Type_context subcontext(rtype, false);
9780
                  (*pa)->determine_type(&subcontext);
9781
                  continue;
9782
                }
9783
            }
9784
 
9785
          if (parameters != NULL && pt != parameters->end())
9786
            {
9787
              Type_context subcontext(pt->type(), false);
9788
              (*pa)->determine_type(&subcontext);
9789
              ++pt;
9790
            }
9791
          else
9792
            (*pa)->determine_type_no_context();
9793
        }
9794
    }
9795
}
9796
 
9797
// Called when determining types for a Call_expression.  Return true
9798
// if we should go ahead, false if they have already been determined.
9799
 
9800
bool
9801
Call_expression::determining_types()
9802
{
9803
  if (this->types_are_determined_)
9804
    return false;
9805
  else
9806
    {
9807
      this->types_are_determined_ = true;
9808
      return true;
9809
    }
9810
}
9811
 
9812
// Check types for parameter I.
9813
 
9814
bool
9815
Call_expression::check_argument_type(int i, const Type* parameter_type,
9816
                                     const Type* argument_type,
9817
                                     Location argument_location,
9818
                                     bool issued_error)
9819
{
9820
  std::string reason;
9821
  bool ok;
9822
  if (this->are_hidden_fields_ok_)
9823
    ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9824
                                        &reason);
9825
  else
9826
    ok = Type::are_assignable(parameter_type, argument_type, &reason);
9827
  if (!ok)
9828
    {
9829
      if (!issued_error)
9830
        {
9831
          if (reason.empty())
9832
            error_at(argument_location, "argument %d has incompatible type", i);
9833
          else
9834
            error_at(argument_location,
9835
                     "argument %d has incompatible type (%s)",
9836
                     i, reason.c_str());
9837
        }
9838
      this->set_is_error();
9839
      return false;
9840
    }
9841
  return true;
9842
}
9843
 
9844
// Check types.
9845
 
9846
void
9847
Call_expression::do_check_types(Gogo*)
9848
{
9849
  Function_type* fntype = this->get_function_type();
9850
  if (fntype == NULL)
9851
    {
9852
      if (!this->fn_->type()->is_error())
9853
        this->report_error(_("expected function"));
9854
      return;
9855
    }
9856
 
9857
  bool is_method = fntype->is_method();
9858
  if (is_method)
9859
    {
9860
      go_assert(this->args_ != NULL && !this->args_->empty());
9861
      Type* rtype = fntype->receiver()->type();
9862
      Expression* first_arg = this->args_->front();
9863
      // The language permits copying hidden fields for a method
9864
      // receiver.  We dereference the values since receivers are
9865
      // always passed as pointers.
9866
      std::string reason;
9867
      if (!Type::are_assignable_hidden_ok(rtype->deref(),
9868
                                          first_arg->type()->deref(),
9869
                                          &reason))
9870
        {
9871
          if (reason.empty())
9872
            this->report_error(_("incompatible type for receiver"));
9873
          else
9874
            {
9875
              error_at(this->location(),
9876
                       "incompatible type for receiver (%s)",
9877
                       reason.c_str());
9878
              this->set_is_error();
9879
            }
9880
        }
9881
    }
9882
 
9883
  // Note that varargs was handled by the lower_varargs() method, so
9884
  // we don't have to worry about it here.
9885
 
9886
  const Typed_identifier_list* parameters = fntype->parameters();
9887
  if (this->args_ == NULL)
9888
    {
9889
      if (parameters != NULL && !parameters->empty())
9890
        this->report_error(_("not enough arguments"));
9891
    }
9892
  else if (parameters == NULL)
9893
    {
9894
      if (!is_method || this->args_->size() > 1)
9895
        this->report_error(_("too many arguments"));
9896
    }
9897
  else
9898
    {
9899
      int i = 0;
9900
      Expression_list::const_iterator pa = this->args_->begin();
9901
      if (is_method)
9902
        ++pa;
9903
      for (Typed_identifier_list::const_iterator pt = parameters->begin();
9904
           pt != parameters->end();
9905
           ++pt, ++pa, ++i)
9906
        {
9907
          if (pa == this->args_->end())
9908
            {
9909
              this->report_error(_("not enough arguments"));
9910
              return;
9911
            }
9912
          this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9913
                                    (*pa)->location(), false);
9914
        }
9915
      if (pa != this->args_->end())
9916
        this->report_error(_("too many arguments"));
9917
    }
9918
}
9919
 
9920
// Return whether we have to use a temporary variable to ensure that
9921
// we evaluate this call expression in order.  If the call returns no
9922
// results then it will inevitably be executed last.
9923
 
9924
bool
9925
Call_expression::do_must_eval_in_order() const
9926
{
9927
  return this->result_count() > 0;
9928
}
9929
 
9930
// Get the function and the first argument to use when calling an
9931
// interface method.
9932
 
9933
tree
9934
Call_expression::interface_method_function(
9935
    Translate_context* context,
9936
    Interface_field_reference_expression* interface_method,
9937
    tree* first_arg_ptr)
9938
{
9939
  tree expr = interface_method->expr()->get_tree(context);
9940
  if (expr == error_mark_node)
9941
    return error_mark_node;
9942
  expr = save_expr(expr);
9943
  tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9944
  if (first_arg == error_mark_node)
9945
    return error_mark_node;
9946
  *first_arg_ptr = first_arg;
9947
  return interface_method->get_function_tree(context, expr);
9948
}
9949
 
9950
// Build the call expression.
9951
 
9952
tree
9953
Call_expression::do_get_tree(Translate_context* context)
9954
{
9955
  if (this->tree_ != NULL_TREE)
9956
    return this->tree_;
9957
 
9958
  Function_type* fntype = this->get_function_type();
9959
  if (fntype == NULL)
9960
    return error_mark_node;
9961
 
9962
  if (this->fn_->is_error_expression())
9963
    return error_mark_node;
9964
 
9965
  Gogo* gogo = context->gogo();
9966
  Location location = this->location();
9967
 
9968
  Func_expression* func = this->fn_->func_expression();
9969
  Interface_field_reference_expression* interface_method =
9970
    this->fn_->interface_field_reference_expression();
9971
  const bool has_closure = func != NULL && func->closure() != NULL;
9972
  const bool is_interface_method = interface_method != NULL;
9973
 
9974
  int nargs;
9975
  tree* args;
9976
  if (this->args_ == NULL || this->args_->empty())
9977
    {
9978
      nargs = is_interface_method ? 1 : 0;
9979
      args = nargs == 0 ? NULL : new tree[nargs];
9980
    }
9981
  else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9982
    {
9983
      // Passing a receiver parameter.
9984
      go_assert(!is_interface_method
9985
                && fntype->is_method()
9986
                && this->args_->size() == 1);
9987
      nargs = 1;
9988
      args = new tree[nargs];
9989
      args[0] = this->args_->front()->get_tree(context);
9990
    }
9991
  else
9992
    {
9993
      const Typed_identifier_list* params = fntype->parameters();
9994
 
9995
      nargs = this->args_->size();
9996
      int i = is_interface_method ? 1 : 0;
9997
      nargs += i;
9998
      args = new tree[nargs];
9999
 
10000
      Typed_identifier_list::const_iterator pp = params->begin();
10001
      Expression_list::const_iterator pe = this->args_->begin();
10002
      if (!is_interface_method && fntype->is_method())
10003
        {
10004
          args[i] = (*pe)->get_tree(context);
10005
          ++pe;
10006
          ++i;
10007
        }
10008
      for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10009
        {
10010
          go_assert(pp != params->end());
10011
          tree arg_val = (*pe)->get_tree(context);
10012
          args[i] = Expression::convert_for_assignment(context,
10013
                                                       pp->type(),
10014
                                                       (*pe)->type(),
10015
                                                       arg_val,
10016
                                                       location);
10017
          if (args[i] == error_mark_node)
10018
            {
10019
              delete[] args;
10020
              return error_mark_node;
10021
            }
10022
        }
10023
      go_assert(pp == params->end());
10024
      go_assert(i == nargs);
10025
    }
10026
 
10027
  tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
10028
  if (rettype == error_mark_node)
10029
    {
10030
      delete[] args;
10031
      return error_mark_node;
10032
    }
10033
 
10034
  tree fn;
10035
  if (has_closure)
10036
    fn = func->get_tree_without_closure(gogo);
10037
  else if (!is_interface_method)
10038
    fn = this->fn_->get_tree(context);
10039
  else
10040
    fn = this->interface_method_function(context, interface_method, &args[0]);
10041
 
10042
  if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
10043
    {
10044
      delete[] args;
10045
      return error_mark_node;
10046
    }
10047
 
10048
  tree fndecl = fn;
10049
  if (TREE_CODE(fndecl) == ADDR_EXPR)
10050
    fndecl = TREE_OPERAND(fndecl, 0);
10051
 
10052
  // Add a type cast in case the type of the function is a recursive
10053
  // type which refers to itself.
10054
  if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
10055
    {
10056
      tree fnt = type_to_tree(fntype->get_backend(gogo));
10057
      if (fnt == error_mark_node)
10058
        return error_mark_node;
10059
      fn = fold_convert_loc(location.gcc_location(), fnt, fn);
10060
    }
10061
 
10062
  // This is to support builtin math functions when using 80387 math.
10063
  tree excess_type = NULL_TREE;
10064
  if (optimize
10065
      && TREE_CODE(fndecl) == FUNCTION_DECL
10066
      && DECL_IS_BUILTIN(fndecl)
10067
      && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
10068
      && nargs > 0
10069
      && ((SCALAR_FLOAT_TYPE_P(rettype)
10070
           && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
10071
          || (COMPLEX_FLOAT_TYPE_P(rettype)
10072
              && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
10073
    {
10074
      excess_type = excess_precision_type(TREE_TYPE(args[0]));
10075
      if (excess_type != NULL_TREE)
10076
        {
10077
          tree excess_fndecl = mathfn_built_in(excess_type,
10078
                                               DECL_FUNCTION_CODE(fndecl));
10079
          if (excess_fndecl == NULL_TREE)
10080
            excess_type = NULL_TREE;
10081
          else
10082
            {
10083
              fn = build_fold_addr_expr_loc(location.gcc_location(),
10084
                                            excess_fndecl);
10085
              for (int i = 0; i < nargs; ++i)
10086
                {
10087
                  if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
10088
                      || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
10089
                    args[i] = ::convert(excess_type, args[i]);
10090
                }
10091
            }
10092
        }
10093
    }
10094
 
10095
  tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
10096
                              fn, nargs, args);
10097
  delete[] args;
10098
 
10099
  SET_EXPR_LOCATION(ret, location.gcc_location());
10100
 
10101
  if (has_closure)
10102
    {
10103
      tree closure_tree = func->closure()->get_tree(context);
10104
      if (closure_tree != error_mark_node)
10105
        CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
10106
    }
10107
 
10108
  // If this is a recursive function type which returns itself, as in
10109
  //   type F func() F
10110
  // we have used ptr_type_node for the return type.  Add a cast here
10111
  // to the correct type.
10112
  if (TREE_TYPE(ret) == ptr_type_node)
10113
    {
10114
      tree t = type_to_tree(this->type()->base()->get_backend(gogo));
10115
      ret = fold_convert_loc(location.gcc_location(), t, ret);
10116
    }
10117
 
10118
  if (excess_type != NULL_TREE)
10119
    {
10120
      // Calling convert here can undo our excess precision change.
10121
      // That may or may not be a bug in convert_to_real.
10122
      ret = build1(NOP_EXPR, rettype, ret);
10123
    }
10124
 
10125
  if (this->results_ != NULL)
10126
    ret = this->set_results(context, ret);
10127
 
10128
  this->tree_ = ret;
10129
 
10130
  return ret;
10131
}
10132
 
10133
// Set the result variables if this call returns multiple results.
10134
 
10135
tree
10136
Call_expression::set_results(Translate_context* context, tree call_tree)
10137
{
10138
  tree stmt_list = NULL_TREE;
10139
 
10140
  call_tree = save_expr(call_tree);
10141
 
10142
  if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
10143
    {
10144
      go_assert(saw_errors());
10145
      return call_tree;
10146
    }
10147
 
10148
  Location loc = this->location();
10149
  tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
10150
  size_t rc = this->result_count();
10151
  for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
10152
    {
10153
      go_assert(field != NULL_TREE);
10154
 
10155
      Temporary_statement* temp = this->result(i);
10156
      Temporary_reference_expression* ref =
10157
        Expression::make_temporary_reference(temp, loc);
10158
      ref->set_is_lvalue();
10159
      tree temp_tree = ref->get_tree(context);
10160
      if (temp_tree == error_mark_node)
10161
        continue;
10162
 
10163
      tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
10164
                                 TREE_TYPE(field), call_tree, field, NULL_TREE);
10165
      tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
10166
                                 void_type_node, temp_tree, val_tree);
10167
 
10168
      append_to_statement_list(set_tree, &stmt_list);
10169
    }
10170
  go_assert(field == NULL_TREE);
10171
 
10172
  return save_expr(stmt_list);
10173
}
10174
 
10175
// Dump ast representation for a call expressin.
10176
 
10177
void
10178
Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10179
{
10180
  this->fn_->dump_expression(ast_dump_context);
10181
  ast_dump_context->ostream() << "(";
10182
  if (args_ != NULL)
10183
    ast_dump_context->dump_expression_list(this->args_);
10184
 
10185
  ast_dump_context->ostream() << ") ";
10186
}
10187
 
10188
// Make a call expression.
10189
 
10190
Call_expression*
10191
Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10192
                      Location location)
10193
{
10194
  return new Call_expression(fn, args, is_varargs, location);
10195
}
10196
 
10197
// A single result from a call which returns multiple results.
10198
 
10199
class Call_result_expression : public Expression
10200
{
10201
 public:
10202
  Call_result_expression(Call_expression* call, unsigned int index)
10203
    : Expression(EXPRESSION_CALL_RESULT, call->location()),
10204
      call_(call), index_(index)
10205
  { }
10206
 
10207
 protected:
10208
  int
10209
  do_traverse(Traverse*);
10210
 
10211
  Type*
10212
  do_type();
10213
 
10214
  void
10215
  do_determine_type(const Type_context*);
10216
 
10217
  void
10218
  do_check_types(Gogo*);
10219
 
10220
  Expression*
10221
  do_copy()
10222
  {
10223
    return new Call_result_expression(this->call_->call_expression(),
10224
                                      this->index_);
10225
  }
10226
 
10227
  bool
10228
  do_must_eval_in_order() const
10229
  { return true; }
10230
 
10231
  tree
10232
  do_get_tree(Translate_context*);
10233
 
10234
  void
10235
  do_dump_expression(Ast_dump_context*) const;
10236
 
10237
 private:
10238
  // The underlying call expression.
10239
  Expression* call_;
10240
  // Which result we want.
10241
  unsigned int index_;
10242
};
10243
 
10244
// Traverse a call result.
10245
 
10246
int
10247
Call_result_expression::do_traverse(Traverse* traverse)
10248
{
10249
  if (traverse->remember_expression(this->call_))
10250
    {
10251
      // We have already traversed the call expression.
10252
      return TRAVERSE_CONTINUE;
10253
    }
10254
  return Expression::traverse(&this->call_, traverse);
10255
}
10256
 
10257
// Get the type.
10258
 
10259
Type*
10260
Call_result_expression::do_type()
10261
{
10262
  if (this->classification() == EXPRESSION_ERROR)
10263
    return Type::make_error_type();
10264
 
10265
  // THIS->CALL_ can be replaced with a temporary reference due to
10266
  // Call_expression::do_must_eval_in_order when there is an error.
10267
  Call_expression* ce = this->call_->call_expression();
10268
  if (ce == NULL)
10269
    {
10270
      this->set_is_error();
10271
      return Type::make_error_type();
10272
    }
10273
  Function_type* fntype = ce->get_function_type();
10274
  if (fntype == NULL)
10275
    {
10276
      if (ce->issue_error())
10277
        {
10278
          if (!ce->fn()->type()->is_error())
10279
            this->report_error(_("expected function"));
10280
        }
10281
      this->set_is_error();
10282
      return Type::make_error_type();
10283
    }
10284
  const Typed_identifier_list* results = fntype->results();
10285
  if (results == NULL || results->size() < 2)
10286
    {
10287
      if (ce->issue_error())
10288
        this->report_error(_("number of results does not match "
10289
                             "number of values"));
10290
      return Type::make_error_type();
10291
    }
10292
  Typed_identifier_list::const_iterator pr = results->begin();
10293
  for (unsigned int i = 0; i < this->index_; ++i)
10294
    {
10295
      if (pr == results->end())
10296
        break;
10297
      ++pr;
10298
    }
10299
  if (pr == results->end())
10300
    {
10301
      if (ce->issue_error())
10302
        this->report_error(_("number of results does not match "
10303
                             "number of values"));
10304
      return Type::make_error_type();
10305
    }
10306
  return pr->type();
10307
}
10308
 
10309
// Check the type.  Just make sure that we trigger the warning in
10310
// do_type.
10311
 
10312
void
10313
Call_result_expression::do_check_types(Gogo*)
10314
{
10315
  this->type();
10316
}
10317
 
10318
// Determine the type.  We have nothing to do here, but the 0 result
10319
// needs to pass down to the caller.
10320
 
10321
void
10322
Call_result_expression::do_determine_type(const Type_context*)
10323
{
10324
  this->call_->determine_type_no_context();
10325
}
10326
 
10327
// Return the tree.  We just refer to the temporary set by the call
10328
// expression.  We don't do this at lowering time because it makes it
10329
// hard to evaluate the call at the right time.
10330
 
10331
tree
10332
Call_result_expression::do_get_tree(Translate_context* context)
10333
{
10334
  Call_expression* ce = this->call_->call_expression();
10335
  go_assert(ce != NULL);
10336
  Temporary_statement* ts = ce->result(this->index_);
10337
  Expression* ref = Expression::make_temporary_reference(ts, this->location());
10338
  return ref->get_tree(context);
10339
}
10340
 
10341
// Dump ast representation for a call result expression.
10342
 
10343
void
10344
Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10345
    const
10346
{
10347
  // FIXME: Wouldn't it be better if the call is assigned to a temporary 
10348
  // (struct) and the fields are referenced instead.
10349
  ast_dump_context->ostream() << this->index_ << "@(";
10350
  ast_dump_context->dump_expression(this->call_);
10351
  ast_dump_context->ostream() << ")";
10352
}
10353
 
10354
// Make a reference to a single result of a call which returns
10355
// multiple results.
10356
 
10357
Expression*
10358
Expression::make_call_result(Call_expression* call, unsigned int index)
10359
{
10360
  return new Call_result_expression(call, index);
10361
}
10362
 
10363
// Class Index_expression.
10364
 
10365
// Traversal.
10366
 
10367
int
10368
Index_expression::do_traverse(Traverse* traverse)
10369
{
10370
  if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10371
      || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10372
      || (this->end_ != NULL
10373
          && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
10374
    return TRAVERSE_EXIT;
10375
  return TRAVERSE_CONTINUE;
10376
}
10377
 
10378
// Lower an index expression.  This converts the generic index
10379
// expression into an array index, a string index, or a map index.
10380
 
10381
Expression*
10382
Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10383
{
10384
  Location location = this->location();
10385
  Expression* left = this->left_;
10386
  Expression* start = this->start_;
10387
  Expression* end = this->end_;
10388
 
10389
  Type* type = left->type();
10390
  if (type->is_error())
10391
    return Expression::make_error(location);
10392
  else if (left->is_type_expression())
10393
    {
10394
      error_at(location, "attempt to index type expression");
10395
      return Expression::make_error(location);
10396
    }
10397
  else if (type->array_type() != NULL)
10398
    return Expression::make_array_index(left, start, end, location);
10399
  else if (type->points_to() != NULL
10400
           && type->points_to()->array_type() != NULL
10401
           && !type->points_to()->is_slice_type())
10402
    {
10403
      Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10404
                                                 location);
10405
      return Expression::make_array_index(deref, start, end, location);
10406
    }
10407
  else if (type->is_string_type())
10408
    return Expression::make_string_index(left, start, end, location);
10409
  else if (type->map_type() != NULL)
10410
    {
10411
      if (end != NULL)
10412
        {
10413
          error_at(location, "invalid slice of map");
10414
          return Expression::make_error(location);
10415
        }
10416
      Map_index_expression* ret = Expression::make_map_index(left, start,
10417
                                                             location);
10418
      if (this->is_lvalue_)
10419
        ret->set_is_lvalue();
10420
      return ret;
10421
    }
10422
  else
10423
    {
10424
      error_at(location,
10425
               "attempt to index object which is not array, string, or map");
10426
      return Expression::make_error(location);
10427
    }
10428
}
10429
 
10430
// Write an indexed expression (expr[expr:expr] or expr[expr]) to a
10431
// dump context
10432
 
10433
void
10434
Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10435
                                        const Expression* expr,
10436
                                        const Expression* start,
10437
                                        const Expression* end)
10438
{
10439
  expr->dump_expression(ast_dump_context);
10440
  ast_dump_context->ostream() << "[";
10441
  start->dump_expression(ast_dump_context);
10442
  if (end != NULL)
10443
    {
10444
      ast_dump_context->ostream() << ":";
10445
      end->dump_expression(ast_dump_context);
10446
    }
10447
  ast_dump_context->ostream() << "]";
10448
}
10449
 
10450
// Dump ast representation for an index expression.
10451
 
10452
void
10453
Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10454
    const
10455
{
10456
  Index_expression::dump_index_expression(ast_dump_context, this->left_,
10457
                                          this->start_, this->end_);
10458
}
10459
 
10460
// Make an index expression.
10461
 
10462
Expression*
10463
Expression::make_index(Expression* left, Expression* start, Expression* end,
10464
                       Location location)
10465
{
10466
  return new Index_expression(left, start, end, location);
10467
}
10468
 
10469
// An array index.  This is used for both indexing and slicing.
10470
 
10471
class Array_index_expression : public Expression
10472
{
10473
 public:
10474
  Array_index_expression(Expression* array, Expression* start,
10475
                         Expression* end, Location location)
10476
    : Expression(EXPRESSION_ARRAY_INDEX, location),
10477
      array_(array), start_(start), end_(end), type_(NULL)
10478
  { }
10479
 
10480
 protected:
10481
  int
10482
  do_traverse(Traverse*);
10483
 
10484
  Type*
10485
  do_type();
10486
 
10487
  void
10488
  do_determine_type(const Type_context*);
10489
 
10490
  void
10491
  do_check_types(Gogo*);
10492
 
10493
  Expression*
10494
  do_copy()
10495
  {
10496
    return Expression::make_array_index(this->array_->copy(),
10497
                                        this->start_->copy(),
10498
                                        (this->end_ == NULL
10499
                                         ? NULL
10500
                                         : this->end_->copy()),
10501
                                        this->location());
10502
  }
10503
 
10504
  bool
10505
  do_must_eval_subexpressions_in_order(int* skip) const
10506
  {
10507
    *skip = 1;
10508
    return true;
10509
  }
10510
 
10511
  bool
10512
  do_is_addressable() const;
10513
 
10514
  void
10515
  do_address_taken(bool escapes)
10516
  { this->array_->address_taken(escapes); }
10517
 
10518
  tree
10519
  do_get_tree(Translate_context*);
10520
 
10521
  void
10522
  do_dump_expression(Ast_dump_context*) const;
10523
 
10524
 private:
10525
  // The array we are getting a value from.
10526
  Expression* array_;
10527
  // The start or only index.
10528
  Expression* start_;
10529
  // The end index of a slice.  This may be NULL for a simple array
10530
  // index, or it may be a nil expression for the length of the array.
10531
  Expression* end_;
10532
  // The type of the expression.
10533
  Type* type_;
10534
};
10535
 
10536
// Array index traversal.
10537
 
10538
int
10539
Array_index_expression::do_traverse(Traverse* traverse)
10540
{
10541
  if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10542
    return TRAVERSE_EXIT;
10543
  if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10544
    return TRAVERSE_EXIT;
10545
  if (this->end_ != NULL)
10546
    {
10547
      if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10548
        return TRAVERSE_EXIT;
10549
    }
10550
  return TRAVERSE_CONTINUE;
10551
}
10552
 
10553
// Return the type of an array index.
10554
 
10555
Type*
10556
Array_index_expression::do_type()
10557
{
10558
  if (this->type_ == NULL)
10559
    {
10560
     Array_type* type = this->array_->type()->array_type();
10561
      if (type == NULL)
10562
        this->type_ = Type::make_error_type();
10563
      else if (this->end_ == NULL)
10564
        this->type_ = type->element_type();
10565
      else if (type->is_slice_type())
10566
        {
10567
          // A slice of a slice has the same type as the original
10568
          // slice.
10569
          this->type_ = this->array_->type()->deref();
10570
        }
10571
      else
10572
        {
10573
          // A slice of an array is a slice.
10574
          this->type_ = Type::make_array_type(type->element_type(), NULL);
10575
        }
10576
    }
10577
  return this->type_;
10578
}
10579
 
10580
// Set the type of an array index.
10581
 
10582
void
10583
Array_index_expression::do_determine_type(const Type_context*)
10584
{
10585
  this->array_->determine_type_no_context();
10586
  this->start_->determine_type_no_context();
10587
  if (this->end_ != NULL)
10588
    this->end_->determine_type_no_context();
10589
}
10590
 
10591
// Check types of an array index.
10592
 
10593
void
10594
Array_index_expression::do_check_types(Gogo*)
10595
{
10596
  if (this->start_->type()->integer_type() == NULL)
10597
    this->report_error(_("index must be integer"));
10598
  if (this->end_ != NULL
10599
      && this->end_->type()->integer_type() == NULL
10600
      && !this->end_->type()->is_error()
10601
      && !this->end_->is_nil_expression()
10602
      && !this->end_->is_error_expression())
10603
    this->report_error(_("slice end must be integer"));
10604
 
10605
  Array_type* array_type = this->array_->type()->array_type();
10606
  if (array_type == NULL)
10607
    {
10608
      go_assert(this->array_->type()->is_error());
10609
      return;
10610
    }
10611
 
10612
  unsigned int int_bits =
10613
    Type::lookup_integer_type("int")->integer_type()->bits();
10614
 
10615
  Type* dummy;
10616
  mpz_t lval;
10617
  mpz_init(lval);
10618
  bool lval_valid = (array_type->length() != NULL
10619
                     && array_type->length()->integer_constant_value(true,
10620
                                                                     lval,
10621
                                                                     &dummy));
10622
  mpz_t ival;
10623
  mpz_init(ival);
10624
  if (this->start_->integer_constant_value(true, ival, &dummy))
10625
    {
10626
      if (mpz_sgn(ival) < 0
10627
          || mpz_sizeinbase(ival, 2) >= int_bits
10628
          || (lval_valid
10629
              && (this->end_ == NULL
10630
                  ? mpz_cmp(ival, lval) >= 0
10631
                  : mpz_cmp(ival, lval) > 0)))
10632
        {
10633
          error_at(this->start_->location(), "array index out of bounds");
10634
          this->set_is_error();
10635
        }
10636
    }
10637
  if (this->end_ != NULL && !this->end_->is_nil_expression())
10638
    {
10639
      if (this->end_->integer_constant_value(true, ival, &dummy))
10640
        {
10641
          if (mpz_sgn(ival) < 0
10642
              || mpz_sizeinbase(ival, 2) >= int_bits
10643
              || (lval_valid && mpz_cmp(ival, lval) > 0))
10644
            {
10645
              error_at(this->end_->location(), "array index out of bounds");
10646
              this->set_is_error();
10647
            }
10648
        }
10649
    }
10650
  mpz_clear(ival);
10651
  mpz_clear(lval);
10652
 
10653
  // A slice of an array requires an addressable array.  A slice of a
10654
  // slice is always possible.
10655
  if (this->end_ != NULL && !array_type->is_slice_type())
10656
    {
10657
      if (!this->array_->is_addressable())
10658
        this->report_error(_("slice of unaddressable value"));
10659
      else
10660
        this->array_->address_taken(true);
10661
    }
10662
}
10663
 
10664
// Return whether this expression is addressable.
10665
 
10666
bool
10667
Array_index_expression::do_is_addressable() const
10668
{
10669
  // A slice expression is not addressable.
10670
  if (this->end_ != NULL)
10671
    return false;
10672
 
10673
  // An index into a slice is addressable.
10674
  if (this->array_->type()->is_slice_type())
10675
    return true;
10676
 
10677
  // An index into an array is addressable if the array is
10678
  // addressable.
10679
  return this->array_->is_addressable();
10680
}
10681
 
10682
// Get a tree for an array index.
10683
 
10684
tree
10685
Array_index_expression::do_get_tree(Translate_context* context)
10686
{
10687
  Gogo* gogo = context->gogo();
10688
  Location loc = this->location();
10689
 
10690
  Array_type* array_type = this->array_->type()->array_type();
10691
  if (array_type == NULL)
10692
    {
10693
      go_assert(this->array_->type()->is_error());
10694
      return error_mark_node;
10695
    }
10696
 
10697
  tree type_tree = type_to_tree(array_type->get_backend(gogo));
10698
  if (type_tree == error_mark_node)
10699
    return error_mark_node;
10700
 
10701
  tree array_tree = this->array_->get_tree(context);
10702
  if (array_tree == error_mark_node)
10703
    return error_mark_node;
10704
 
10705
  if (array_type->length() == NULL && !DECL_P(array_tree))
10706
    array_tree = save_expr(array_tree);
10707
 
10708
  tree length_tree = NULL_TREE;
10709
  if (this->end_ == NULL || this->end_->is_nil_expression())
10710
    {
10711
      length_tree = array_type->length_tree(gogo, array_tree);
10712
      if (length_tree == error_mark_node)
10713
        return error_mark_node;
10714
      length_tree = save_expr(length_tree);
10715
    }
10716
 
10717
  tree capacity_tree = NULL_TREE;
10718
  if (this->end_ != NULL)
10719
    {
10720
      capacity_tree = array_type->capacity_tree(gogo, array_tree);
10721
      if (capacity_tree == error_mark_node)
10722
        return error_mark_node;
10723
      capacity_tree = save_expr(capacity_tree);
10724
    }
10725
 
10726
  tree length_type = (length_tree != NULL_TREE
10727
                      ? TREE_TYPE(length_tree)
10728
                      : TREE_TYPE(capacity_tree));
10729
 
10730
  tree bad_index = boolean_false_node;
10731
 
10732
  tree start_tree = this->start_->get_tree(context);
10733
  if (start_tree == error_mark_node)
10734
    return error_mark_node;
10735
  if (!DECL_P(start_tree))
10736
    start_tree = save_expr(start_tree);
10737
  if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10738
    start_tree = convert_to_integer(length_type, start_tree);
10739
 
10740
  bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10741
                                       loc);
10742
 
10743
  start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10744
  bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10745
                              boolean_type_node, bad_index,
10746
                              fold_build2_loc(loc.gcc_location(),
10747
                                              (this->end_ == NULL
10748
                                               ? GE_EXPR
10749
                                               : GT_EXPR),
10750
                                              boolean_type_node, start_tree,
10751
                                              (this->end_ == NULL
10752
                                               ? length_tree
10753
                                               : capacity_tree)));
10754
 
10755
  int code = (array_type->length() != NULL
10756
              ? (this->end_ == NULL
10757
                 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10758
                 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10759
              : (this->end_ == NULL
10760
                 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10761
                 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10762
  tree crash = Gogo::runtime_error(code, loc);
10763
 
10764
  if (this->end_ == NULL)
10765
    {
10766
      // Simple array indexing.  This has to return an l-value, so
10767
      // wrap the index check into START_TREE.
10768
      start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
10769
                          build3(COND_EXPR, void_type_node,
10770
                                 bad_index, crash, NULL_TREE),
10771
                          start_tree);
10772
      start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
10773
 
10774
      if (array_type->length() != NULL)
10775
        {
10776
          // Fixed array.
10777
          return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
10778
                        start_tree, NULL_TREE, NULL_TREE);
10779
        }
10780
      else
10781
        {
10782
          // Open array.
10783
          tree values = array_type->value_pointer_tree(gogo, array_tree);
10784
          Type* element_type = array_type->element_type();
10785
          Btype* belement_type = element_type->get_backend(gogo);
10786
          tree element_type_tree = type_to_tree(belement_type);
10787
          if (element_type_tree == error_mark_node)
10788
            return error_mark_node;
10789
          tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10790
          tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10791
                                        start_tree, element_size);
10792
          tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10793
                                     TREE_TYPE(values), values, offset);
10794
          return build_fold_indirect_ref(ptr);
10795
        }
10796
    }
10797
 
10798
  // Array slice.
10799
 
10800
  tree end_tree;
10801
  if (this->end_->is_nil_expression())
10802
    end_tree = length_tree;
10803
  else
10804
    {
10805
      end_tree = this->end_->get_tree(context);
10806
      if (end_tree == error_mark_node)
10807
        return error_mark_node;
10808
      if (!DECL_P(end_tree))
10809
        end_tree = save_expr(end_tree);
10810
      if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10811
        end_tree = convert_to_integer(length_type, end_tree);
10812
 
10813
      bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
10814
                                           loc);
10815
 
10816
      end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
10817
 
10818
      tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10819
                                     boolean_type_node,
10820
                                     fold_build2_loc(loc.gcc_location(),
10821
                                                     LT_EXPR, boolean_type_node,
10822
                                                     end_tree, start_tree),
10823
                                     fold_build2_loc(loc.gcc_location(),
10824
                                                     GT_EXPR, boolean_type_node,
10825
                                                     end_tree, capacity_tree));
10826
      bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10827
                                  boolean_type_node, bad_index, bad_end);
10828
    }
10829
 
10830
  Type* element_type = array_type->element_type();
10831
  tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
10832
  if (element_type_tree == error_mark_node)
10833
    return error_mark_node;
10834
  tree element_size = TYPE_SIZE_UNIT(element_type_tree);
10835
 
10836
  tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
10837
                                fold_convert_loc(loc.gcc_location(), sizetype,
10838
                                                 start_tree),
10839
                                element_size);
10840
 
10841
  tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
10842
  if (value_pointer == error_mark_node)
10843
    return error_mark_node;
10844
 
10845
  value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10846
                                  TREE_TYPE(value_pointer),
10847
                                  value_pointer, offset);
10848
 
10849
  tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10850
                                            length_type, end_tree, start_tree);
10851
 
10852
  tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
10853
                                              length_type, capacity_tree,
10854
                                              start_tree);
10855
 
10856
  tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
10857
  go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
10858
 
10859
  VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
10860
 
10861
  constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
10862
  tree field = TYPE_FIELDS(struct_tree);
10863
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
10864
  elt->index = field;
10865
  elt->value = value_pointer;
10866
 
10867
  elt = VEC_quick_push(constructor_elt, init, NULL);
10868
  field = DECL_CHAIN(field);
10869
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
10870
  elt->index = field;
10871
  elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10872
                                result_length_tree);
10873
 
10874
  elt = VEC_quick_push(constructor_elt, init, NULL);
10875
  field = DECL_CHAIN(field);
10876
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
10877
  elt->index = field;
10878
  elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
10879
                                result_capacity_tree);
10880
 
10881
  tree constructor = build_constructor(struct_tree, init);
10882
 
10883
  if (TREE_CONSTANT(value_pointer)
10884
      && TREE_CONSTANT(result_length_tree)
10885
      && TREE_CONSTANT(result_capacity_tree))
10886
    TREE_CONSTANT(constructor) = 1;
10887
 
10888
  return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
10889
                         TREE_TYPE(constructor),
10890
                         build3(COND_EXPR, void_type_node,
10891
                                bad_index, crash, NULL_TREE),
10892
                         constructor);
10893
}
10894
 
10895
// Dump ast representation for an array index expression.
10896
 
10897
void
10898
Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10899
    const
10900
{
10901
  Index_expression::dump_index_expression(ast_dump_context, this->array_,
10902
                                          this->start_, this->end_);
10903
}
10904
 
10905
// Make an array index expression.  END may be NULL.
10906
 
10907
Expression*
10908
Expression::make_array_index(Expression* array, Expression* start,
10909
                             Expression* end, Location location)
10910
{
10911
  return new Array_index_expression(array, start, end, location);
10912
}
10913
 
10914
// A string index.  This is used for both indexing and slicing.
10915
 
10916
class String_index_expression : public Expression
10917
{
10918
 public:
10919
  String_index_expression(Expression* string, Expression* start,
10920
                          Expression* end, Location location)
10921
    : Expression(EXPRESSION_STRING_INDEX, location),
10922
      string_(string), start_(start), end_(end)
10923
  { }
10924
 
10925
 protected:
10926
  int
10927
  do_traverse(Traverse*);
10928
 
10929
  Type*
10930
  do_type();
10931
 
10932
  void
10933
  do_determine_type(const Type_context*);
10934
 
10935
  void
10936
  do_check_types(Gogo*);
10937
 
10938
  Expression*
10939
  do_copy()
10940
  {
10941
    return Expression::make_string_index(this->string_->copy(),
10942
                                         this->start_->copy(),
10943
                                         (this->end_ == NULL
10944
                                          ? NULL
10945
                                          : this->end_->copy()),
10946
                                         this->location());
10947
  }
10948
 
10949
  bool
10950
  do_must_eval_subexpressions_in_order(int* skip) const
10951
  {
10952
    *skip = 1;
10953
    return true;
10954
  }
10955
 
10956
  tree
10957
  do_get_tree(Translate_context*);
10958
 
10959
  void
10960
  do_dump_expression(Ast_dump_context*) const;
10961
 
10962
 private:
10963
  // The string we are getting a value from.
10964
  Expression* string_;
10965
  // The start or only index.
10966
  Expression* start_;
10967
  // The end index of a slice.  This may be NULL for a single index,
10968
  // or it may be a nil expression for the length of the string.
10969
  Expression* end_;
10970
};
10971
 
10972
// String index traversal.
10973
 
10974
int
10975
String_index_expression::do_traverse(Traverse* traverse)
10976
{
10977
  if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10978
    return TRAVERSE_EXIT;
10979
  if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10980
    return TRAVERSE_EXIT;
10981
  if (this->end_ != NULL)
10982
    {
10983
      if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10984
        return TRAVERSE_EXIT;
10985
    }
10986
  return TRAVERSE_CONTINUE;
10987
}
10988
 
10989
// Return the type of a string index.
10990
 
10991
Type*
10992
String_index_expression::do_type()
10993
{
10994
  if (this->end_ == NULL)
10995
    return Type::lookup_integer_type("uint8");
10996
  else
10997
    return this->string_->type();
10998
}
10999
 
11000
// Determine the type of a string index.
11001
 
11002
void
11003
String_index_expression::do_determine_type(const Type_context*)
11004
{
11005
  this->string_->determine_type_no_context();
11006
  this->start_->determine_type_no_context();
11007
  if (this->end_ != NULL)
11008
    this->end_->determine_type_no_context();
11009
}
11010
 
11011
// Check types of a string index.
11012
 
11013
void
11014
String_index_expression::do_check_types(Gogo*)
11015
{
11016
  if (this->start_->type()->integer_type() == NULL)
11017
    this->report_error(_("index must be integer"));
11018
  if (this->end_ != NULL
11019
      && this->end_->type()->integer_type() == NULL
11020
      && !this->end_->is_nil_expression())
11021
    this->report_error(_("slice end must be integer"));
11022
 
11023
  std::string sval;
11024
  bool sval_valid = this->string_->string_constant_value(&sval);
11025
 
11026
  mpz_t ival;
11027
  mpz_init(ival);
11028
  Type* dummy;
11029
  if (this->start_->integer_constant_value(true, ival, &dummy))
11030
    {
11031
      if (mpz_sgn(ival) < 0
11032
          || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
11033
        {
11034
          error_at(this->start_->location(), "string index out of bounds");
11035
          this->set_is_error();
11036
        }
11037
    }
11038
  if (this->end_ != NULL && !this->end_->is_nil_expression())
11039
    {
11040
      if (this->end_->integer_constant_value(true, ival, &dummy))
11041
        {
11042
          if (mpz_sgn(ival) < 0
11043
              || (sval_valid && mpz_cmp_ui(ival, sval.length()) > 0))
11044
            {
11045
              error_at(this->end_->location(), "string index out of bounds");
11046
              this->set_is_error();
11047
            }
11048
        }
11049
    }
11050
  mpz_clear(ival);
11051
}
11052
 
11053
// Get a tree for a string index.
11054
 
11055
tree
11056
String_index_expression::do_get_tree(Translate_context* context)
11057
{
11058
  Location loc = this->location();
11059
 
11060
  tree string_tree = this->string_->get_tree(context);
11061
  if (string_tree == error_mark_node)
11062
    return error_mark_node;
11063
 
11064
  if (this->string_->type()->points_to() != NULL)
11065
    string_tree = build_fold_indirect_ref(string_tree);
11066
  if (!DECL_P(string_tree))
11067
    string_tree = save_expr(string_tree);
11068
  tree string_type = TREE_TYPE(string_tree);
11069
 
11070
  tree length_tree = String_type::length_tree(context->gogo(), string_tree);
11071
  length_tree = save_expr(length_tree);
11072
  tree length_type = TREE_TYPE(length_tree);
11073
 
11074
  tree bad_index = boolean_false_node;
11075
 
11076
  tree start_tree = this->start_->get_tree(context);
11077
  if (start_tree == error_mark_node)
11078
    return error_mark_node;
11079
  if (!DECL_P(start_tree))
11080
    start_tree = save_expr(start_tree);
11081
  if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
11082
    start_tree = convert_to_integer(length_type, start_tree);
11083
 
11084
  bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
11085
                                       loc);
11086
 
11087
  start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
11088
 
11089
  int code = (this->end_ == NULL
11090
              ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11091
              : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11092
  tree crash = Gogo::runtime_error(code, loc);
11093
 
11094
  if (this->end_ == NULL)
11095
    {
11096
      bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
11097
                                  boolean_type_node, bad_index,
11098
                                  fold_build2_loc(loc.gcc_location(), GE_EXPR,
11099
                                                  boolean_type_node,
11100
                                                  start_tree, length_tree));
11101
 
11102
      tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
11103
      tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
11104
                                 TREE_TYPE(bytes_tree),
11105
                                 bytes_tree,
11106
                                 fold_convert_loc(loc.gcc_location(), sizetype,
11107
                                                  start_tree));
11108
      tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
11109
 
11110
      return build2(COMPOUND_EXPR, TREE_TYPE(index),
11111
                    build3(COND_EXPR, void_type_node,
11112
                           bad_index, crash, NULL_TREE),
11113
                    index);
11114
    }
11115
  else
11116
    {
11117
      tree end_tree;
11118
      if (this->end_->is_nil_expression())
11119
        end_tree = build_int_cst(length_type, -1);
11120
      else
11121
        {
11122
          end_tree = this->end_->get_tree(context);
11123
          if (end_tree == error_mark_node)
11124
            return error_mark_node;
11125
          if (!DECL_P(end_tree))
11126
            end_tree = save_expr(end_tree);
11127
          if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
11128
            end_tree = convert_to_integer(length_type, end_tree);
11129
 
11130
          bad_index = Expression::check_bounds(end_tree, length_type,
11131
                                               bad_index, loc);
11132
 
11133
          end_tree = fold_convert_loc(loc.gcc_location(), length_type,
11134
                                      end_tree);
11135
        }
11136
 
11137
      static tree strslice_fndecl;
11138
      tree ret = Gogo::call_builtin(&strslice_fndecl,
11139
                                    loc,
11140
                                    "__go_string_slice",
11141
                                    3,
11142
                                    string_type,
11143
                                    string_type,
11144
                                    string_tree,
11145
                                    length_type,
11146
                                    start_tree,
11147
                                    length_type,
11148
                                    end_tree);
11149
      if (ret == error_mark_node)
11150
        return error_mark_node;
11151
      // This will panic if the bounds are out of range for the
11152
      // string.
11153
      TREE_NOTHROW(strslice_fndecl) = 0;
11154
 
11155
      if (bad_index == boolean_false_node)
11156
        return ret;
11157
      else
11158
        return build2(COMPOUND_EXPR, TREE_TYPE(ret),
11159
                      build3(COND_EXPR, void_type_node,
11160
                             bad_index, crash, NULL_TREE),
11161
                      ret);
11162
    }
11163
}
11164
 
11165
// Dump ast representation for a string index expression.
11166
 
11167
void
11168
String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11169
    const
11170
{
11171
  Index_expression::dump_index_expression(ast_dump_context, this->string_,
11172
                                          this->start_, this->end_);
11173
}
11174
 
11175
// Make a string index expression.  END may be NULL.
11176
 
11177
Expression*
11178
Expression::make_string_index(Expression* string, Expression* start,
11179
                              Expression* end, Location location)
11180
{
11181
  return new String_index_expression(string, start, end, location);
11182
}
11183
 
11184
// Class Map_index.
11185
 
11186
// Get the type of the map.
11187
 
11188
Map_type*
11189
Map_index_expression::get_map_type() const
11190
{
11191
  Map_type* mt = this->map_->type()->deref()->map_type();
11192
  if (mt == NULL)
11193
    go_assert(saw_errors());
11194
  return mt;
11195
}
11196
 
11197
// Map index traversal.
11198
 
11199
int
11200
Map_index_expression::do_traverse(Traverse* traverse)
11201
{
11202
  if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11203
    return TRAVERSE_EXIT;
11204
  return Expression::traverse(&this->index_, traverse);
11205
}
11206
 
11207
// Return the type of a map index.
11208
 
11209
Type*
11210
Map_index_expression::do_type()
11211
{
11212
  Map_type* mt = this->get_map_type();
11213
  if (mt == NULL)
11214
    return Type::make_error_type();
11215
  Type* type = mt->val_type();
11216
  // If this map index is in a tuple assignment, we actually return a
11217
  // pointer to the value type.  Tuple_map_assignment_statement is
11218
  // responsible for handling this correctly.  We need to get the type
11219
  // right in case this gets assigned to a temporary variable.
11220
  if (this->is_in_tuple_assignment_)
11221
    type = Type::make_pointer_type(type);
11222
  return type;
11223
}
11224
 
11225
// Fix the type of a map index.
11226
 
11227
void
11228
Map_index_expression::do_determine_type(const Type_context*)
11229
{
11230
  this->map_->determine_type_no_context();
11231
  Map_type* mt = this->get_map_type();
11232
  Type* key_type = mt == NULL ? NULL : mt->key_type();
11233
  Type_context subcontext(key_type, false);
11234
  this->index_->determine_type(&subcontext);
11235
}
11236
 
11237
// Check types of a map index.
11238
 
11239
void
11240
Map_index_expression::do_check_types(Gogo*)
11241
{
11242
  std::string reason;
11243
  Map_type* mt = this->get_map_type();
11244
  if (mt == NULL)
11245
    return;
11246
  if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11247
    {
11248
      if (reason.empty())
11249
        this->report_error(_("incompatible type for map index"));
11250
      else
11251
        {
11252
          error_at(this->location(), "incompatible type for map index (%s)",
11253
                   reason.c_str());
11254
          this->set_is_error();
11255
        }
11256
    }
11257
}
11258
 
11259
// Get a tree for a map index.
11260
 
11261
tree
11262
Map_index_expression::do_get_tree(Translate_context* context)
11263
{
11264
  Map_type* type = this->get_map_type();
11265
  if (type == NULL)
11266
    return error_mark_node;
11267
 
11268
  tree valptr = this->get_value_pointer(context, this->is_lvalue_);
11269
  if (valptr == error_mark_node)
11270
    return error_mark_node;
11271
  valptr = save_expr(valptr);
11272
 
11273
  tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
11274
 
11275
  if (this->is_lvalue_)
11276
    return build_fold_indirect_ref(valptr);
11277
  else if (this->is_in_tuple_assignment_)
11278
    {
11279
      // Tuple_map_assignment_statement is responsible for using this
11280
      // appropriately.
11281
      return valptr;
11282
    }
11283
  else
11284
    {
11285
      Gogo* gogo = context->gogo();
11286
      Btype* val_btype = type->val_type()->get_backend(gogo);
11287
      Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
11288
      return fold_build3(COND_EXPR, val_type_tree,
11289
                         fold_build2(EQ_EXPR, boolean_type_node, valptr,
11290
                                     fold_convert(TREE_TYPE(valptr),
11291
                                                  null_pointer_node)),
11292
                         expr_to_tree(val_zero),
11293
                         build_fold_indirect_ref(valptr));
11294
    }
11295
}
11296
 
11297
// Get a tree for the map index.  This returns a tree which evaluates
11298
// to a pointer to a value.  The pointer will be NULL if the key is
11299
// not in the map.
11300
 
11301
tree
11302
Map_index_expression::get_value_pointer(Translate_context* context,
11303
                                        bool insert)
11304
{
11305
  Map_type* type = this->get_map_type();
11306
  if (type == NULL)
11307
    return error_mark_node;
11308
 
11309
  tree map_tree = this->map_->get_tree(context);
11310
  tree index_tree = this->index_->get_tree(context);
11311
  index_tree = Expression::convert_for_assignment(context, type->key_type(),
11312
                                                  this->index_->type(),
11313
                                                  index_tree,
11314
                                                  this->location());
11315
  if (map_tree == error_mark_node || index_tree == error_mark_node)
11316
    return error_mark_node;
11317
 
11318
  if (this->map_->type()->points_to() != NULL)
11319
    map_tree = build_fold_indirect_ref(map_tree);
11320
 
11321
  // We need to pass in a pointer to the key, so stuff it into a
11322
  // variable.
11323
  tree tmp;
11324
  tree make_tmp;
11325
  if (current_function_decl != NULL)
11326
    {
11327
      tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
11328
      DECL_IGNORED_P(tmp) = 0;
11329
      DECL_INITIAL(tmp) = index_tree;
11330
      make_tmp = build1(DECL_EXPR, void_type_node, tmp);
11331
      TREE_ADDRESSABLE(tmp) = 1;
11332
    }
11333
  else
11334
    {
11335
      tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11336
                       create_tmp_var_name("M"),
11337
                       TREE_TYPE(index_tree));
11338
      DECL_EXTERNAL(tmp) = 0;
11339
      TREE_PUBLIC(tmp) = 0;
11340
      TREE_STATIC(tmp) = 1;
11341
      DECL_ARTIFICIAL(tmp) = 1;
11342
      if (!TREE_CONSTANT(index_tree))
11343
        make_tmp = fold_build2_loc(this->location().gcc_location(),
11344
                                   INIT_EXPR, void_type_node,
11345
                                   tmp, index_tree);
11346
      else
11347
        {
11348
          TREE_READONLY(tmp) = 1;
11349
          TREE_CONSTANT(tmp) = 1;
11350
          DECL_INITIAL(tmp) = index_tree;
11351
          make_tmp = NULL_TREE;
11352
        }
11353
      rest_of_decl_compilation(tmp, 1, 0);
11354
    }
11355
  tree tmpref =
11356
    fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
11357
                     build_fold_addr_expr_loc(this->location().gcc_location(),
11358
                                              tmp));
11359
 
11360
  static tree map_index_fndecl;
11361
  tree call = Gogo::call_builtin(&map_index_fndecl,
11362
                                 this->location(),
11363
                                 "__go_map_index",
11364
                                 3,
11365
                                 const_ptr_type_node,
11366
                                 TREE_TYPE(map_tree),
11367
                                 map_tree,
11368
                                 const_ptr_type_node,
11369
                                 tmpref,
11370
                                 boolean_type_node,
11371
                                 (insert
11372
                                  ? boolean_true_node
11373
                                  : boolean_false_node));
11374
  if (call == error_mark_node)
11375
    return error_mark_node;
11376
  // This can panic on a map of interface type if the interface holds
11377
  // an uncomparable or unhashable type.
11378
  TREE_NOTHROW(map_index_fndecl) = 0;
11379
 
11380
  Type* val_type = type->val_type();
11381
  tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
11382
  if (val_type_tree == error_mark_node)
11383
    return error_mark_node;
11384
  tree ptr_val_type_tree = build_pointer_type(val_type_tree);
11385
 
11386
  tree ret = fold_convert_loc(this->location().gcc_location(),
11387
                              ptr_val_type_tree, call);
11388
  if (make_tmp != NULL_TREE)
11389
    ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
11390
  return ret;
11391
}
11392
 
11393
// Dump ast representation for a map index expression
11394
 
11395
void
11396
Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11397
    const
11398
{
11399
  Index_expression::dump_index_expression(ast_dump_context,
11400
                                          this->map_, this->index_, NULL);
11401
}
11402
 
11403
// Make a map index expression.
11404
 
11405
Map_index_expression*
11406
Expression::make_map_index(Expression* map, Expression* index,
11407
                           Location location)
11408
{
11409
  return new Map_index_expression(map, index, location);
11410
}
11411
 
11412
// Class Field_reference_expression.
11413
 
11414
// Return the type of a field reference.
11415
 
11416
Type*
11417
Field_reference_expression::do_type()
11418
{
11419
  Type* type = this->expr_->type();
11420
  if (type->is_error())
11421
    return type;
11422
  Struct_type* struct_type = type->struct_type();
11423
  go_assert(struct_type != NULL);
11424
  return struct_type->field(this->field_index_)->type();
11425
}
11426
 
11427
// Check the types for a field reference.
11428
 
11429
void
11430
Field_reference_expression::do_check_types(Gogo*)
11431
{
11432
  Type* type = this->expr_->type();
11433
  if (type->is_error())
11434
    return;
11435
  Struct_type* struct_type = type->struct_type();
11436
  go_assert(struct_type != NULL);
11437
  go_assert(struct_type->field(this->field_index_) != NULL);
11438
}
11439
 
11440
// Get a tree for a field reference.
11441
 
11442
tree
11443
Field_reference_expression::do_get_tree(Translate_context* context)
11444
{
11445
  tree struct_tree = this->expr_->get_tree(context);
11446
  if (struct_tree == error_mark_node
11447
      || TREE_TYPE(struct_tree) == error_mark_node)
11448
    return error_mark_node;
11449
  go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
11450
  tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
11451
  if (field == NULL_TREE)
11452
    {
11453
      // This can happen for a type which refers to itself indirectly
11454
      // and then turns out to be erroneous.
11455
      go_assert(saw_errors());
11456
      return error_mark_node;
11457
    }
11458
  for (unsigned int i = this->field_index_; i > 0; --i)
11459
    {
11460
      field = DECL_CHAIN(field);
11461
      go_assert(field != NULL_TREE);
11462
    }
11463
  if (TREE_TYPE(field) == error_mark_node)
11464
    return error_mark_node;
11465
  return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
11466
                NULL_TREE);
11467
}
11468
 
11469
// Dump ast representation for a field reference expression.
11470
 
11471
void
11472
Field_reference_expression::do_dump_expression(
11473
    Ast_dump_context* ast_dump_context) const
11474
{
11475
  this->expr_->dump_expression(ast_dump_context);
11476
  ast_dump_context->ostream() << "." <<  this->field_index_;
11477
}
11478
 
11479
// Make a reference to a qualified identifier in an expression.
11480
 
11481
Field_reference_expression*
11482
Expression::make_field_reference(Expression* expr, unsigned int field_index,
11483
                                 Location location)
11484
{
11485
  return new Field_reference_expression(expr, field_index, location);
11486
}
11487
 
11488
// Class Interface_field_reference_expression.
11489
 
11490
// Return a tree for the pointer to the function to call.
11491
 
11492
tree
11493
Interface_field_reference_expression::get_function_tree(Translate_context*,
11494
                                                        tree expr)
11495
{
11496
  if (this->expr_->type()->points_to() != NULL)
11497
    expr = build_fold_indirect_ref(expr);
11498
 
11499
  tree expr_type = TREE_TYPE(expr);
11500
  go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
11501
 
11502
  tree field = TYPE_FIELDS(expr_type);
11503
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
11504
 
11505
  tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
11506
  go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
11507
 
11508
  table = build_fold_indirect_ref(table);
11509
  go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
11510
 
11511
  std::string name = Gogo::unpack_hidden_name(this->name_);
11512
  for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
11513
       field != NULL_TREE;
11514
       field = DECL_CHAIN(field))
11515
    {
11516
      if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
11517
        break;
11518
    }
11519
  go_assert(field != NULL_TREE);
11520
 
11521
  return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
11522
}
11523
 
11524
// Return a tree for the first argument to pass to the interface
11525
// function.
11526
 
11527
tree
11528
Interface_field_reference_expression::get_underlying_object_tree(
11529
    Translate_context*,
11530
    tree expr)
11531
{
11532
  if (this->expr_->type()->points_to() != NULL)
11533
    expr = build_fold_indirect_ref(expr);
11534
 
11535
  tree expr_type = TREE_TYPE(expr);
11536
  go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
11537
 
11538
  tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
11539
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
11540
 
11541
  return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
11542
}
11543
 
11544
// Traversal.
11545
 
11546
int
11547
Interface_field_reference_expression::do_traverse(Traverse* traverse)
11548
{
11549
  return Expression::traverse(&this->expr_, traverse);
11550
}
11551
 
11552
// Return the type of an interface field reference.
11553
 
11554
Type*
11555
Interface_field_reference_expression::do_type()
11556
{
11557
  Type* expr_type = this->expr_->type();
11558
 
11559
  Type* points_to = expr_type->points_to();
11560
  if (points_to != NULL)
11561
    expr_type = points_to;
11562
 
11563
  Interface_type* interface_type = expr_type->interface_type();
11564
  if (interface_type == NULL)
11565
    return Type::make_error_type();
11566
 
11567
  const Typed_identifier* method = interface_type->find_method(this->name_);
11568
  if (method == NULL)
11569
    return Type::make_error_type();
11570
 
11571
  return method->type();
11572
}
11573
 
11574
// Determine types.
11575
 
11576
void
11577
Interface_field_reference_expression::do_determine_type(const Type_context*)
11578
{
11579
  this->expr_->determine_type_no_context();
11580
}
11581
 
11582
// Check the types for an interface field reference.
11583
 
11584
void
11585
Interface_field_reference_expression::do_check_types(Gogo*)
11586
{
11587
  Type* type = this->expr_->type();
11588
 
11589
  Type* points_to = type->points_to();
11590
  if (points_to != NULL)
11591
    type = points_to;
11592
 
11593
  Interface_type* interface_type = type->interface_type();
11594
  if (interface_type == NULL)
11595
    {
11596
      if (!type->is_error_type())
11597
        this->report_error(_("expected interface or pointer to interface"));
11598
    }
11599
  else
11600
    {
11601
      const Typed_identifier* method =
11602
        interface_type->find_method(this->name_);
11603
      if (method == NULL)
11604
        {
11605
          error_at(this->location(), "method %qs not in interface",
11606
                   Gogo::message_name(this->name_).c_str());
11607
          this->set_is_error();
11608
        }
11609
    }
11610
}
11611
 
11612
// Get a tree for a reference to a field in an interface.  There is no
11613
// standard tree type representation for this: it's a function
11614
// attached to its first argument, like a Bound_method_expression.
11615
// The only places it may currently be used are in a Call_expression
11616
// or a Go_statement, which will take it apart directly.  So this has
11617
// nothing to do at present.
11618
 
11619
tree
11620
Interface_field_reference_expression::do_get_tree(Translate_context*)
11621
{
11622
  go_unreachable();
11623
}
11624
 
11625
// Dump ast representation for an interface field reference.
11626
 
11627
void
11628
Interface_field_reference_expression::do_dump_expression(
11629
    Ast_dump_context* ast_dump_context) const
11630
{
11631
  this->expr_->dump_expression(ast_dump_context);
11632
  ast_dump_context->ostream() << "." << this->name_;
11633
}
11634
 
11635
// Make a reference to a field in an interface.
11636
 
11637
Expression*
11638
Expression::make_interface_field_reference(Expression* expr,
11639
                                           const std::string& field,
11640
                                           Location location)
11641
{
11642
  return new Interface_field_reference_expression(expr, field, location);
11643
}
11644
 
11645
// A general selector.  This is a Parser_expression for LEFT.NAME.  It
11646
// is lowered after we know the type of the left hand side.
11647
 
11648
class Selector_expression : public Parser_expression
11649
{
11650
 public:
11651
  Selector_expression(Expression* left, const std::string& name,
11652
                      Location location)
11653
    : Parser_expression(EXPRESSION_SELECTOR, location),
11654
      left_(left), name_(name)
11655
  { }
11656
 
11657
 protected:
11658
  int
11659
  do_traverse(Traverse* traverse)
11660
  { return Expression::traverse(&this->left_, traverse); }
11661
 
11662
  Expression*
11663
  do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11664
 
11665
  Expression*
11666
  do_copy()
11667
  {
11668
    return new Selector_expression(this->left_->copy(), this->name_,
11669
                                   this->location());
11670
  }
11671
 
11672
  void
11673
  do_dump_expression(Ast_dump_context* ast_dump_context) const;
11674
 
11675
 private:
11676
  Expression*
11677
  lower_method_expression(Gogo*);
11678
 
11679
  // The expression on the left hand side.
11680
  Expression* left_;
11681
  // The name on the right hand side.
11682
  std::string name_;
11683
};
11684
 
11685
// Lower a selector expression once we know the real type of the left
11686
// hand side.
11687
 
11688
Expression*
11689
Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11690
                              int)
11691
{
11692
  Expression* left = this->left_;
11693
  if (left->is_type_expression())
11694
    return this->lower_method_expression(gogo);
11695
  return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11696
                                    this->location());
11697
}
11698
 
11699
// Lower a method expression T.M or (*T).M.  We turn this into a
11700
// function literal.
11701
 
11702
Expression*
11703
Selector_expression::lower_method_expression(Gogo* gogo)
11704
{
11705
  Location location = this->location();
11706
  Type* type = this->left_->type();
11707
  const std::string& name(this->name_);
11708
 
11709
  bool is_pointer;
11710
  if (type->points_to() == NULL)
11711
    is_pointer = false;
11712
  else
11713
    {
11714
      is_pointer = true;
11715
      type = type->points_to();
11716
    }
11717
  Named_type* nt = type->named_type();
11718
  if (nt == NULL)
11719
    {
11720
      error_at(location,
11721
               ("method expression requires named type or "
11722
                "pointer to named type"));
11723
      return Expression::make_error(location);
11724
    }
11725
 
11726
  bool is_ambiguous;
11727
  Method* method = nt->method_function(name, &is_ambiguous);
11728
  const Typed_identifier* imethod = NULL;
11729
  if (method == NULL && !is_pointer)
11730
    {
11731
      Interface_type* it = nt->interface_type();
11732
      if (it != NULL)
11733
        imethod = it->find_method(name);
11734
    }
11735
 
11736
  if (method == NULL && imethod == NULL)
11737
    {
11738
      if (!is_ambiguous)
11739
        error_at(location, "type %<%s%s%> has no method %<%s%>",
11740
                 is_pointer ? "*" : "",
11741
                 nt->message_name().c_str(),
11742
                 Gogo::message_name(name).c_str());
11743
      else
11744
        error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11745
                 Gogo::message_name(name).c_str(),
11746
                 is_pointer ? "*" : "",
11747
                 nt->message_name().c_str());
11748
      return Expression::make_error(location);
11749
    }
11750
 
11751
  if (method != NULL && !is_pointer && !method->is_value_method())
11752
    {
11753
      error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11754
               nt->message_name().c_str(),
11755
               Gogo::message_name(name).c_str());
11756
      return Expression::make_error(location);
11757
    }
11758
 
11759
  // Build a new function type in which the receiver becomes the first
11760
  // argument.
11761
  Function_type* method_type;
11762
  if (method != NULL)
11763
    {
11764
      method_type = method->type();
11765
      go_assert(method_type->is_method());
11766
    }
11767
  else
11768
    {
11769
      method_type = imethod->type()->function_type();
11770
      go_assert(method_type != NULL && !method_type->is_method());
11771
    }
11772
 
11773
  const char* const receiver_name = "$this";
11774
  Typed_identifier_list* parameters = new Typed_identifier_list();
11775
  parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11776
                                         location));
11777
 
11778
  const Typed_identifier_list* method_parameters = method_type->parameters();
11779
  if (method_parameters != NULL)
11780
    {
11781
      int i = 0;
11782
      for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11783
           p != method_parameters->end();
11784
           ++p, ++i)
11785
        {
11786
          if (!p->name().empty())
11787
            parameters->push_back(*p);
11788
          else
11789
            {
11790
              char buf[20];
11791
              snprintf(buf, sizeof buf, "$param%d", i);
11792
              parameters->push_back(Typed_identifier(buf, p->type(),
11793
                                                     p->location()));
11794
            }
11795
        }
11796
    }
11797
 
11798
  const Typed_identifier_list* method_results = method_type->results();
11799
  Typed_identifier_list* results;
11800
  if (method_results == NULL)
11801
    results = NULL;
11802
  else
11803
    {
11804
      results = new Typed_identifier_list();
11805
      for (Typed_identifier_list::const_iterator p = method_results->begin();
11806
           p != method_results->end();
11807
           ++p)
11808
        results->push_back(*p);
11809
    }
11810
 
11811
  Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11812
                                                   location);
11813
  if (method_type->is_varargs())
11814
    fntype->set_is_varargs();
11815
 
11816
  // We generate methods which always takes a pointer to the receiver
11817
  // as their first argument.  If this is for a pointer type, we can
11818
  // simply reuse the existing function.  We use an internal hack to
11819
  // get the right type.
11820
 
11821
  if (method != NULL && is_pointer)
11822
    {
11823
      Named_object* mno = (method->needs_stub_method()
11824
                           ? method->stub_object()
11825
                           : method->named_object());
11826
      Expression* f = Expression::make_func_reference(mno, NULL, location);
11827
      f = Expression::make_cast(fntype, f, location);
11828
      Type_conversion_expression* tce =
11829
        static_cast<Type_conversion_expression*>(f);
11830
      tce->set_may_convert_function_types();
11831
      return f;
11832
    }
11833
 
11834
  Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11835
                                          location);
11836
 
11837
  Named_object* vno = gogo->lookup(receiver_name, NULL);
11838
  go_assert(vno != NULL);
11839
  Expression* ve = Expression::make_var_reference(vno, location);
11840
  Expression* bm;
11841
  if (method != NULL)
11842
    bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11843
  else
11844
    bm = Expression::make_interface_field_reference(ve, name, location);
11845
 
11846
  // Even though we found the method above, if it has an error type we
11847
  // may see an error here.
11848
  if (bm->is_error_expression())
11849
    {
11850
      gogo->finish_function(location);
11851
      return bm;
11852
    }
11853
 
11854
  Expression_list* args;
11855
  if (parameters->size() <= 1)
11856
    args = NULL;
11857
  else
11858
    {
11859
      args = new Expression_list();
11860
      Typed_identifier_list::const_iterator p = parameters->begin();
11861
      ++p;
11862
      for (; p != parameters->end(); ++p)
11863
        {
11864
          vno = gogo->lookup(p->name(), NULL);
11865
          go_assert(vno != NULL);
11866
          args->push_back(Expression::make_var_reference(vno, location));
11867
        }
11868
    }
11869
 
11870
  gogo->start_block(location);
11871
 
11872
  Call_expression* call = Expression::make_call(bm, args,
11873
                                                method_type->is_varargs(),
11874
                                                location);
11875
 
11876
  size_t count = call->result_count();
11877
  Statement* s;
11878
  if (count == 0)
11879
    s = Statement::make_statement(call, true);
11880
  else
11881
    {
11882
      Expression_list* retvals = new Expression_list();
11883
      if (count <= 1)
11884
        retvals->push_back(call);
11885
      else
11886
        {
11887
          for (size_t i = 0; i < count; ++i)
11888
            retvals->push_back(Expression::make_call_result(call, i));
11889
        }
11890
      s = Statement::make_return_statement(retvals, location);
11891
    }
11892
  gogo->add_statement(s);
11893
 
11894
  Block* b = gogo->finish_block(location);
11895
 
11896
  gogo->add_block(b, location);
11897
 
11898
  // Lower the call in case there are multiple results.
11899
  gogo->lower_block(no, b);
11900
 
11901
  gogo->finish_function(location);
11902
 
11903
  return Expression::make_func_reference(no, NULL, location);
11904
}
11905
 
11906
// Dump the ast for a selector expression.
11907
 
11908
void
11909
Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11910
    const
11911
{
11912
  ast_dump_context->dump_expression(this->left_);
11913
  ast_dump_context->ostream() << ".";
11914
  ast_dump_context->ostream() << this->name_;
11915
}
11916
 
11917
// Make a selector expression.
11918
 
11919
Expression*
11920
Expression::make_selector(Expression* left, const std::string& name,
11921
                          Location location)
11922
{
11923
  return new Selector_expression(left, name, location);
11924
}
11925
 
11926
// Implement the builtin function new.
11927
 
11928
class Allocation_expression : public Expression
11929
{
11930
 public:
11931
  Allocation_expression(Type* type, Location location)
11932
    : Expression(EXPRESSION_ALLOCATION, location),
11933
      type_(type)
11934
  { }
11935
 
11936
 protected:
11937
  int
11938
  do_traverse(Traverse* traverse)
11939
  { return Type::traverse(this->type_, traverse); }
11940
 
11941
  Type*
11942
  do_type()
11943
  { return Type::make_pointer_type(this->type_); }
11944
 
11945
  void
11946
  do_determine_type(const Type_context*)
11947
  { }
11948
 
11949
  Expression*
11950
  do_copy()
11951
  { return new Allocation_expression(this->type_, this->location()); }
11952
 
11953
  tree
11954
  do_get_tree(Translate_context*);
11955
 
11956
  void
11957
  do_dump_expression(Ast_dump_context*) const;
11958
 
11959
 private:
11960
  // The type we are allocating.
11961
  Type* type_;
11962
};
11963
 
11964
// Return a tree for an allocation expression.
11965
 
11966
tree
11967
Allocation_expression::do_get_tree(Translate_context* context)
11968
{
11969
  tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
11970
  if (type_tree == error_mark_node)
11971
    return error_mark_node;
11972
  tree size_tree = TYPE_SIZE_UNIT(type_tree);
11973
  tree space = context->gogo()->allocate_memory(this->type_, size_tree,
11974
                                                this->location());
11975
  if (space == error_mark_node)
11976
    return error_mark_node;
11977
  return fold_convert(build_pointer_type(type_tree), space);
11978
}
11979
 
11980
// Dump ast representation for an allocation expression.
11981
 
11982
void
11983
Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11984
    const
11985
{
11986
  ast_dump_context->ostream() << "new(";
11987
  ast_dump_context->dump_type(this->type_);
11988
  ast_dump_context->ostream() << ")";
11989
}
11990
 
11991
// Make an allocation expression.
11992
 
11993
Expression*
11994
Expression::make_allocation(Type* type, Location location)
11995
{
11996
  return new Allocation_expression(type, location);
11997
}
11998
 
11999
// Construct a struct.
12000
 
12001
class Struct_construction_expression : public Expression
12002
{
12003
 public:
12004
  Struct_construction_expression(Type* type, Expression_list* vals,
12005
                                 Location location)
12006
    : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
12007
      type_(type), vals_(vals)
12008
  { }
12009
 
12010
  // Return whether this is a constant initializer.
12011
  bool
12012
  is_constant_struct() const;
12013
 
12014
 protected:
12015
  int
12016
  do_traverse(Traverse* traverse);
12017
 
12018
  Type*
12019
  do_type()
12020
  { return this->type_; }
12021
 
12022
  void
12023
  do_determine_type(const Type_context*);
12024
 
12025
  void
12026
  do_check_types(Gogo*);
12027
 
12028
  Expression*
12029
  do_copy()
12030
  {
12031
    return new Struct_construction_expression(this->type_, this->vals_->copy(),
12032
                                              this->location());
12033
  }
12034
 
12035
  tree
12036
  do_get_tree(Translate_context*);
12037
 
12038
  void
12039
  do_export(Export*) const;
12040
 
12041
  void
12042
  do_dump_expression(Ast_dump_context*) const;
12043
 
12044
 private:
12045
  // The type of the struct to construct.
12046
  Type* type_;
12047
  // The list of values, in order of the fields in the struct.  A NULL
12048
  // entry means that the field should be zero-initialized.
12049
  Expression_list* vals_;
12050
};
12051
 
12052
// Traversal.
12053
 
12054
int
12055
Struct_construction_expression::do_traverse(Traverse* traverse)
12056
{
12057
  if (this->vals_ != NULL
12058
      && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12059
    return TRAVERSE_EXIT;
12060
  if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12061
    return TRAVERSE_EXIT;
12062
  return TRAVERSE_CONTINUE;
12063
}
12064
 
12065
// Return whether this is a constant initializer.
12066
 
12067
bool
12068
Struct_construction_expression::is_constant_struct() const
12069
{
12070
  if (this->vals_ == NULL)
12071
    return true;
12072
  for (Expression_list::const_iterator pv = this->vals_->begin();
12073
       pv != this->vals_->end();
12074
       ++pv)
12075
    {
12076
      if (*pv != NULL
12077
          && !(*pv)->is_constant()
12078
          && (!(*pv)->is_composite_literal()
12079
              || (*pv)->is_nonconstant_composite_literal()))
12080
        return false;
12081
    }
12082
 
12083
  const Struct_field_list* fields = this->type_->struct_type()->fields();
12084
  for (Struct_field_list::const_iterator pf = fields->begin();
12085
       pf != fields->end();
12086
       ++pf)
12087
    {
12088
      // There are no constant constructors for interfaces.
12089
      if (pf->type()->interface_type() != NULL)
12090
        return false;
12091
    }
12092
 
12093
  return true;
12094
}
12095
 
12096
// Final type determination.
12097
 
12098
void
12099
Struct_construction_expression::do_determine_type(const Type_context*)
12100
{
12101
  if (this->vals_ == NULL)
12102
    return;
12103
  const Struct_field_list* fields = this->type_->struct_type()->fields();
12104
  Expression_list::const_iterator pv = this->vals_->begin();
12105
  for (Struct_field_list::const_iterator pf = fields->begin();
12106
       pf != fields->end();
12107
       ++pf, ++pv)
12108
    {
12109
      if (pv == this->vals_->end())
12110
        return;
12111
      if (*pv != NULL)
12112
        {
12113
          Type_context subcontext(pf->type(), false);
12114
          (*pv)->determine_type(&subcontext);
12115
        }
12116
    }
12117
  // Extra values are an error we will report elsewhere; we still want
12118
  // to determine the type to avoid knockon errors.
12119
  for (; pv != this->vals_->end(); ++pv)
12120
    (*pv)->determine_type_no_context();
12121
}
12122
 
12123
// Check types.
12124
 
12125
void
12126
Struct_construction_expression::do_check_types(Gogo*)
12127
{
12128
  if (this->vals_ == NULL)
12129
    return;
12130
 
12131
  Struct_type* st = this->type_->struct_type();
12132
  if (this->vals_->size() > st->field_count())
12133
    {
12134
      this->report_error(_("too many expressions for struct"));
12135
      return;
12136
    }
12137
 
12138
  const Struct_field_list* fields = st->fields();
12139
  Expression_list::const_iterator pv = this->vals_->begin();
12140
  int i = 0;
12141
  for (Struct_field_list::const_iterator pf = fields->begin();
12142
       pf != fields->end();
12143
       ++pf, ++pv, ++i)
12144
    {
12145
      if (pv == this->vals_->end())
12146
        {
12147
          this->report_error(_("too few expressions for struct"));
12148
          break;
12149
        }
12150
 
12151
      if (*pv == NULL)
12152
        continue;
12153
 
12154
      std::string reason;
12155
      if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12156
        {
12157
          if (reason.empty())
12158
            error_at((*pv)->location(),
12159
                     "incompatible type for field %d in struct construction",
12160
                     i + 1);
12161
          else
12162
            error_at((*pv)->location(),
12163
                     ("incompatible type for field %d in "
12164
                      "struct construction (%s)"),
12165
                     i + 1, reason.c_str());
12166
          this->set_is_error();
12167
        }
12168
    }
12169
  go_assert(pv == this->vals_->end());
12170
}
12171
 
12172
// Return a tree for constructing a struct.
12173
 
12174
tree
12175
Struct_construction_expression::do_get_tree(Translate_context* context)
12176
{
12177
  Gogo* gogo = context->gogo();
12178
 
12179
  if (this->vals_ == NULL)
12180
    {
12181
      Btype* btype = this->type_->get_backend(gogo);
12182
      return expr_to_tree(gogo->backend()->zero_expression(btype));
12183
    }
12184
 
12185
  tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12186
  if (type_tree == error_mark_node)
12187
    return error_mark_node;
12188
  go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12189
 
12190
  bool is_constant = true;
12191
  const Struct_field_list* fields = this->type_->struct_type()->fields();
12192
  VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
12193
                                            fields->size());
12194
  Struct_field_list::const_iterator pf = fields->begin();
12195
  Expression_list::const_iterator pv = this->vals_->begin();
12196
  for (tree field = TYPE_FIELDS(type_tree);
12197
       field != NULL_TREE;
12198
       field = DECL_CHAIN(field), ++pf)
12199
    {
12200
      go_assert(pf != fields->end());
12201
 
12202
      Btype* fbtype = pf->type()->get_backend(gogo);
12203
 
12204
      tree val;
12205
      if (pv == this->vals_->end())
12206
        val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
12207
      else if (*pv == NULL)
12208
        {
12209
          val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
12210
          ++pv;
12211
        }
12212
      else
12213
        {
12214
          val = Expression::convert_for_assignment(context, pf->type(),
12215
                                                   (*pv)->type(),
12216
                                                   (*pv)->get_tree(context),
12217
                                                   this->location());
12218
          ++pv;
12219
        }
12220
 
12221
      if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
12222
        return error_mark_node;
12223
 
12224
      constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
12225
      elt->index = field;
12226
      elt->value = val;
12227
      if (!TREE_CONSTANT(val))
12228
        is_constant = false;
12229
    }
12230
  go_assert(pf == fields->end());
12231
 
12232
  tree ret = build_constructor(type_tree, elts);
12233
  if (is_constant)
12234
    TREE_CONSTANT(ret) = 1;
12235
  return ret;
12236
}
12237
 
12238
// Export a struct construction.
12239
 
12240
void
12241
Struct_construction_expression::do_export(Export* exp) const
12242
{
12243
  exp->write_c_string("convert(");
12244
  exp->write_type(this->type_);
12245
  for (Expression_list::const_iterator pv = this->vals_->begin();
12246
       pv != this->vals_->end();
12247
       ++pv)
12248
    {
12249
      exp->write_c_string(", ");
12250
      if (*pv != NULL)
12251
        (*pv)->export_expression(exp);
12252
    }
12253
  exp->write_c_string(")");
12254
}
12255
 
12256
// Dump ast representation of a struct construction expression.
12257
 
12258
void
12259
Struct_construction_expression::do_dump_expression(
12260
    Ast_dump_context* ast_dump_context) const
12261
{
12262
  ast_dump_context->dump_type(this->type_);
12263
  ast_dump_context->ostream() << "{";
12264
  ast_dump_context->dump_expression_list(this->vals_);
12265
  ast_dump_context->ostream() << "}";
12266
}
12267
 
12268
// Make a struct composite literal.  This used by the thunk code.
12269
 
12270
Expression*
12271
Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12272
                                          Location location)
12273
{
12274
  go_assert(type->struct_type() != NULL);
12275
  return new Struct_construction_expression(type, vals, location);
12276
}
12277
 
12278
// Construct an array.  This class is not used directly; instead we
12279
// use the child classes, Fixed_array_construction_expression and
12280
// Open_array_construction_expression.
12281
 
12282
class Array_construction_expression : public Expression
12283
{
12284
 protected:
12285
  Array_construction_expression(Expression_classification classification,
12286
                                Type* type, Expression_list* vals,
12287
                                Location location)
12288
    : Expression(classification, location),
12289
      type_(type), vals_(vals)
12290
  { }
12291
 
12292
 public:
12293
  // Return whether this is a constant initializer.
12294
  bool
12295
  is_constant_array() const;
12296
 
12297
  // Return the number of elements.
12298
  size_t
12299
  element_count() const
12300
  { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12301
 
12302
protected:
12303
  int
12304
  do_traverse(Traverse* traverse);
12305
 
12306
  Type*
12307
  do_type()
12308
  { return this->type_; }
12309
 
12310
  void
12311
  do_determine_type(const Type_context*);
12312
 
12313
  void
12314
  do_check_types(Gogo*);
12315
 
12316
  void
12317
  do_export(Export*) const;
12318
 
12319
  // The list of values.
12320
  Expression_list*
12321
  vals()
12322
  { return this->vals_; }
12323
 
12324
  // Get a constructor tree for the array values.
12325
  tree
12326
  get_constructor_tree(Translate_context* context, tree type_tree);
12327
 
12328
  void
12329
  do_dump_expression(Ast_dump_context*) const;
12330
 
12331
 private:
12332
  // The type of the array to construct.
12333
  Type* type_;
12334
  // The list of values.
12335
  Expression_list* vals_;
12336
};
12337
 
12338
// Traversal.
12339
 
12340
int
12341
Array_construction_expression::do_traverse(Traverse* traverse)
12342
{
12343
  if (this->vals_ != NULL
12344
      && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12345
    return TRAVERSE_EXIT;
12346
  if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12347
    return TRAVERSE_EXIT;
12348
  return TRAVERSE_CONTINUE;
12349
}
12350
 
12351
// Return whether this is a constant initializer.
12352
 
12353
bool
12354
Array_construction_expression::is_constant_array() const
12355
{
12356
  if (this->vals_ == NULL)
12357
    return true;
12358
 
12359
  // There are no constant constructors for interfaces.
12360
  if (this->type_->array_type()->element_type()->interface_type() != NULL)
12361
    return false;
12362
 
12363
  for (Expression_list::const_iterator pv = this->vals_->begin();
12364
       pv != this->vals_->end();
12365
       ++pv)
12366
    {
12367
      if (*pv != NULL
12368
          && !(*pv)->is_constant()
12369
          && (!(*pv)->is_composite_literal()
12370
              || (*pv)->is_nonconstant_composite_literal()))
12371
        return false;
12372
    }
12373
  return true;
12374
}
12375
 
12376
// Final type determination.
12377
 
12378
void
12379
Array_construction_expression::do_determine_type(const Type_context*)
12380
{
12381
  if (this->vals_ == NULL)
12382
    return;
12383
  Type_context subcontext(this->type_->array_type()->element_type(), false);
12384
  for (Expression_list::const_iterator pv = this->vals_->begin();
12385
       pv != this->vals_->end();
12386
       ++pv)
12387
    {
12388
      if (*pv != NULL)
12389
        (*pv)->determine_type(&subcontext);
12390
    }
12391
}
12392
 
12393
// Check types.
12394
 
12395
void
12396
Array_construction_expression::do_check_types(Gogo*)
12397
{
12398
  if (this->vals_ == NULL)
12399
    return;
12400
 
12401
  Array_type* at = this->type_->array_type();
12402
  int i = 0;
12403
  Type* element_type = at->element_type();
12404
  for (Expression_list::const_iterator pv = this->vals_->begin();
12405
       pv != this->vals_->end();
12406
       ++pv, ++i)
12407
    {
12408
      if (*pv != NULL
12409
          && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12410
        {
12411
          error_at((*pv)->location(),
12412
                   "incompatible type for element %d in composite literal",
12413
                   i + 1);
12414
          this->set_is_error();
12415
        }
12416
    }
12417
 
12418
  Expression* length = at->length();
12419
  if (length != NULL && !length->is_error_expression())
12420
    {
12421
      mpz_t val;
12422
      mpz_init(val);
12423
      Type* type;
12424
      if (at->length()->integer_constant_value(true, val, &type))
12425
        {
12426
          if (this->vals_->size() > mpz_get_ui(val))
12427
            this->report_error(_("too many elements in composite literal"));
12428
        }
12429
      mpz_clear(val);
12430
    }
12431
}
12432
 
12433
// Get a constructor tree for the array values.
12434
 
12435
tree
12436
Array_construction_expression::get_constructor_tree(Translate_context* context,
12437
                                                    tree type_tree)
12438
{
12439
  VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12440
                                              (this->vals_ == NULL
12441
                                               ? 0
12442
                                               : this->vals_->size()));
12443
  Type* element_type = this->type_->array_type()->element_type();
12444
  bool is_constant = true;
12445
  if (this->vals_ != NULL)
12446
    {
12447
      size_t i = 0;
12448
      for (Expression_list::const_iterator pv = this->vals_->begin();
12449
           pv != this->vals_->end();
12450
           ++pv, ++i)
12451
        {
12452
          constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
12453
          elt->index = size_int(i);
12454
          if (*pv == NULL)
12455
            {
12456
              Gogo* gogo = context->gogo();
12457
              Btype* ebtype = element_type->get_backend(gogo);
12458
              Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12459
              elt->value = expr_to_tree(zv);
12460
            }
12461
          else
12462
            {
12463
              tree value_tree = (*pv)->get_tree(context);
12464
              elt->value = Expression::convert_for_assignment(context,
12465
                                                              element_type,
12466
                                                              (*pv)->type(),
12467
                                                              value_tree,
12468
                                                              this->location());
12469
            }
12470
          if (elt->value == error_mark_node)
12471
            return error_mark_node;
12472
          if (!TREE_CONSTANT(elt->value))
12473
            is_constant = false;
12474
        }
12475
    }
12476
 
12477
  tree ret = build_constructor(type_tree, values);
12478
  if (is_constant)
12479
    TREE_CONSTANT(ret) = 1;
12480
  return ret;
12481
}
12482
 
12483
// Export an array construction.
12484
 
12485
void
12486
Array_construction_expression::do_export(Export* exp) const
12487
{
12488
  exp->write_c_string("convert(");
12489
  exp->write_type(this->type_);
12490
  if (this->vals_ != NULL)
12491
    {
12492
      for (Expression_list::const_iterator pv = this->vals_->begin();
12493
           pv != this->vals_->end();
12494
           ++pv)
12495
        {
12496
          exp->write_c_string(", ");
12497
          if (*pv != NULL)
12498
            (*pv)->export_expression(exp);
12499
        }
12500
    }
12501
  exp->write_c_string(")");
12502
}
12503
 
12504
// Dump ast representation of an array construction expressin.
12505
 
12506
void
12507
Array_construction_expression::do_dump_expression(
12508
    Ast_dump_context* ast_dump_context) const
12509
{
12510
  Expression* length = this->type_->array_type() != NULL ?
12511
                         this->type_->array_type()->length() : NULL;
12512
 
12513
  ast_dump_context->ostream() << "[" ;
12514
  if (length != NULL)
12515
    {
12516
      ast_dump_context->dump_expression(length);
12517
    }
12518
  ast_dump_context->ostream() << "]" ;
12519
  ast_dump_context->dump_type(this->type_);
12520
  ast_dump_context->ostream() << "{" ;
12521
  ast_dump_context->dump_expression_list(this->vals_);
12522
  ast_dump_context->ostream() << "}" ;
12523
 
12524
}
12525
 
12526
// Construct a fixed array.
12527
 
12528
class Fixed_array_construction_expression :
12529
  public Array_construction_expression
12530
{
12531
 public:
12532
  Fixed_array_construction_expression(Type* type, Expression_list* vals,
12533
                                      Location location)
12534
    : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12535
                                    type, vals, location)
12536
  {
12537
    go_assert(type->array_type() != NULL
12538
               && type->array_type()->length() != NULL);
12539
  }
12540
 
12541
 protected:
12542
  Expression*
12543
  do_copy()
12544
  {
12545
    return new Fixed_array_construction_expression(this->type(),
12546
                                                   (this->vals() == NULL
12547
                                                    ? NULL
12548
                                                    : this->vals()->copy()),
12549
                                                   this->location());
12550
  }
12551
 
12552
  tree
12553
  do_get_tree(Translate_context*);
12554
 
12555
  void
12556
  do_dump_expression(Ast_dump_context*);
12557
};
12558
 
12559
// Return a tree for constructing a fixed array.
12560
 
12561
tree
12562
Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12563
{
12564
  Type* type = this->type();
12565
  Btype* btype = type->get_backend(context->gogo());
12566
  return this->get_constructor_tree(context, type_to_tree(btype));
12567
}
12568
 
12569
// Dump ast representation of an array construction expressin.
12570
 
12571
void
12572
Fixed_array_construction_expression::do_dump_expression(
12573
    Ast_dump_context* ast_dump_context)
12574
{
12575
 
12576
  ast_dump_context->ostream() << "[";
12577
  ast_dump_context->dump_expression (this->type()->array_type()->length());
12578
  ast_dump_context->ostream() << "]";
12579
  ast_dump_context->dump_type(this->type());
12580
  ast_dump_context->ostream() << "{";
12581
  ast_dump_context->dump_expression_list(this->vals());
12582
  ast_dump_context->ostream() << "}";
12583
 
12584
}
12585
// Construct an open array.
12586
 
12587
class Open_array_construction_expression : public Array_construction_expression
12588
{
12589
 public:
12590
  Open_array_construction_expression(Type* type, Expression_list* vals,
12591
                                     Location location)
12592
    : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
12593
                                    type, vals, location)
12594
  {
12595
    go_assert(type->array_type() != NULL
12596
               && type->array_type()->length() == NULL);
12597
  }
12598
 
12599
 protected:
12600
  // Note that taking the address of an open array literal is invalid.
12601
 
12602
  Expression*
12603
  do_copy()
12604
  {
12605
    return new Open_array_construction_expression(this->type(),
12606
                                                  (this->vals() == NULL
12607
                                                   ? NULL
12608
                                                   : this->vals()->copy()),
12609
                                                  this->location());
12610
  }
12611
 
12612
  tree
12613
  do_get_tree(Translate_context*);
12614
};
12615
 
12616
// Return a tree for constructing an open array.
12617
 
12618
tree
12619
Open_array_construction_expression::do_get_tree(Translate_context* context)
12620
{
12621
  Array_type* array_type = this->type()->array_type();
12622
  if (array_type == NULL)
12623
    {
12624
      go_assert(this->type()->is_error());
12625
      return error_mark_node;
12626
    }
12627
 
12628
  Type* element_type = array_type->element_type();
12629
  Btype* belement_type = element_type->get_backend(context->gogo());
12630
  tree element_type_tree = type_to_tree(belement_type);
12631
  if (element_type_tree == error_mark_node)
12632
    return error_mark_node;
12633
 
12634
  tree values;
12635
  tree length_tree;
12636
  if (this->vals() == NULL || this->vals()->empty())
12637
    {
12638
      // We need to create a unique value.
12639
      tree max = size_int(0);
12640
      tree constructor_type = build_array_type(element_type_tree,
12641
                                               build_index_type(max));
12642
      if (constructor_type == error_mark_node)
12643
        return error_mark_node;
12644
      VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
12645
      constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
12646
      elt->index = size_int(0);
12647
      Gogo* gogo = context->gogo();
12648
      Btype* btype = element_type->get_backend(gogo);
12649
      elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
12650
      values = build_constructor(constructor_type, vec);
12651
      if (TREE_CONSTANT(elt->value))
12652
        TREE_CONSTANT(values) = 1;
12653
      length_tree = size_int(0);
12654
    }
12655
  else
12656
    {
12657
      tree max = size_int(this->vals()->size() - 1);
12658
      tree constructor_type = build_array_type(element_type_tree,
12659
                                               build_index_type(max));
12660
      if (constructor_type == error_mark_node)
12661
        return error_mark_node;
12662
      values = this->get_constructor_tree(context, constructor_type);
12663
      length_tree = size_int(this->vals()->size());
12664
    }
12665
 
12666
  if (values == error_mark_node)
12667
    return error_mark_node;
12668
 
12669
  bool is_constant_initializer = TREE_CONSTANT(values);
12670
 
12671
  // We have to copy the initial values into heap memory if we are in
12672
  // a function or if the values are not constants.  We also have to
12673
  // copy them if they may contain pointers in a non-constant context,
12674
  // as otherwise the garbage collector won't see them.
12675
  bool copy_to_heap = (context->function() != NULL
12676
                       || !is_constant_initializer
12677
                       || (element_type->has_pointer()
12678
                           && !context->is_const()));
12679
 
12680
  if (is_constant_initializer)
12681
    {
12682
      tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
12683
                            create_tmp_var_name("C"), TREE_TYPE(values));
12684
      DECL_EXTERNAL(tmp) = 0;
12685
      TREE_PUBLIC(tmp) = 0;
12686
      TREE_STATIC(tmp) = 1;
12687
      DECL_ARTIFICIAL(tmp) = 1;
12688
      if (copy_to_heap)
12689
        {
12690
          // If we are not copying the value to the heap, we will only
12691
          // initialize the value once, so we can use this directly
12692
          // rather than copying it.  In that case we can't make it
12693
          // read-only, because the program is permitted to change it.
12694
          TREE_READONLY(tmp) = 1;
12695
          TREE_CONSTANT(tmp) = 1;
12696
        }
12697
      DECL_INITIAL(tmp) = values;
12698
      rest_of_decl_compilation(tmp, 1, 0);
12699
      values = tmp;
12700
    }
12701
 
12702
  tree space;
12703
  tree set;
12704
  if (!copy_to_heap)
12705
    {
12706
      // the initializer will only run once.
12707
      space = build_fold_addr_expr(values);
12708
      set = NULL_TREE;
12709
    }
12710
  else
12711
    {
12712
      tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
12713
      space = context->gogo()->allocate_memory(element_type, memsize,
12714
                                               this->location());
12715
      space = save_expr(space);
12716
 
12717
      tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
12718
      tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12719
                                             s);
12720
      TREE_THIS_NOTRAP(ref) = 1;
12721
      set = build2(MODIFY_EXPR, void_type_node, ref, values);
12722
    }
12723
 
12724
  // Build a constructor for the open array.
12725
 
12726
  tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
12727
  if (type_tree == error_mark_node)
12728
    return error_mark_node;
12729
  go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12730
 
12731
  VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
12732
 
12733
  constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
12734
  tree field = TYPE_FIELDS(type_tree);
12735
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
12736
  elt->index = field;
12737
  elt->value = fold_convert(TREE_TYPE(field), space);
12738
 
12739
  elt = VEC_quick_push(constructor_elt, init, NULL);
12740
  field = DECL_CHAIN(field);
12741
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
12742
  elt->index = field;
12743
  elt->value = fold_convert(TREE_TYPE(field), length_tree);
12744
 
12745
  elt = VEC_quick_push(constructor_elt, init, NULL);
12746
  field = DECL_CHAIN(field);
12747
  go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
12748
  elt->index = field;
12749
  elt->value = fold_convert(TREE_TYPE(field), length_tree);
12750
 
12751
  tree constructor = build_constructor(type_tree, init);
12752
  if (constructor == error_mark_node)
12753
    return error_mark_node;
12754
  if (!copy_to_heap)
12755
    TREE_CONSTANT(constructor) = 1;
12756
 
12757
  if (set == NULL_TREE)
12758
    return constructor;
12759
  else
12760
    return build2(COMPOUND_EXPR, type_tree, set, constructor);
12761
}
12762
 
12763
// Make a slice composite literal.  This is used by the type
12764
// descriptor code.
12765
 
12766
Expression*
12767
Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12768
                                         Location location)
12769
{
12770
  go_assert(type->is_slice_type());
12771
  return new Open_array_construction_expression(type, vals, location);
12772
}
12773
 
12774
// Construct a map.
12775
 
12776
class Map_construction_expression : public Expression
12777
{
12778
 public:
12779
  Map_construction_expression(Type* type, Expression_list* vals,
12780
                              Location location)
12781
    : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12782
      type_(type), vals_(vals)
12783
  { go_assert(vals == NULL || vals->size() % 2 == 0); }
12784
 
12785
 protected:
12786
  int
12787
  do_traverse(Traverse* traverse);
12788
 
12789
  Type*
12790
  do_type()
12791
  { return this->type_; }
12792
 
12793
  void
12794
  do_determine_type(const Type_context*);
12795
 
12796
  void
12797
  do_check_types(Gogo*);
12798
 
12799
  Expression*
12800
  do_copy()
12801
  {
12802
    return new Map_construction_expression(this->type_, this->vals_->copy(),
12803
                                           this->location());
12804
  }
12805
 
12806
  tree
12807
  do_get_tree(Translate_context*);
12808
 
12809
  void
12810
  do_export(Export*) const;
12811
 
12812
  void
12813
  do_dump_expression(Ast_dump_context*) const;
12814
 
12815
 private:
12816
  // The type of the map to construct.
12817
  Type* type_;
12818
  // The list of values.
12819
  Expression_list* vals_;
12820
};
12821
 
12822
// Traversal.
12823
 
12824
int
12825
Map_construction_expression::do_traverse(Traverse* traverse)
12826
{
12827
  if (this->vals_ != NULL
12828
      && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12829
    return TRAVERSE_EXIT;
12830
  if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12831
    return TRAVERSE_EXIT;
12832
  return TRAVERSE_CONTINUE;
12833
}
12834
 
12835
// Final type determination.
12836
 
12837
void
12838
Map_construction_expression::do_determine_type(const Type_context*)
12839
{
12840
  if (this->vals_ == NULL)
12841
    return;
12842
 
12843
  Map_type* mt = this->type_->map_type();
12844
  Type_context key_context(mt->key_type(), false);
12845
  Type_context val_context(mt->val_type(), false);
12846
  for (Expression_list::const_iterator pv = this->vals_->begin();
12847
       pv != this->vals_->end();
12848
       ++pv)
12849
    {
12850
      (*pv)->determine_type(&key_context);
12851
      ++pv;
12852
      (*pv)->determine_type(&val_context);
12853
    }
12854
}
12855
 
12856
// Check types.
12857
 
12858
void
12859
Map_construction_expression::do_check_types(Gogo*)
12860
{
12861
  if (this->vals_ == NULL)
12862
    return;
12863
 
12864
  Map_type* mt = this->type_->map_type();
12865
  int i = 0;
12866
  Type* key_type = mt->key_type();
12867
  Type* val_type = mt->val_type();
12868
  for (Expression_list::const_iterator pv = this->vals_->begin();
12869
       pv != this->vals_->end();
12870
       ++pv, ++i)
12871
    {
12872
      if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12873
        {
12874
          error_at((*pv)->location(),
12875
                   "incompatible type for element %d key in map construction",
12876
                   i + 1);
12877
          this->set_is_error();
12878
        }
12879
      ++pv;
12880
      if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12881
        {
12882
          error_at((*pv)->location(),
12883
                   ("incompatible type for element %d value "
12884
                    "in map construction"),
12885
                   i + 1);
12886
          this->set_is_error();
12887
        }
12888
    }
12889
}
12890
 
12891
// Return a tree for constructing a map.
12892
 
12893
tree
12894
Map_construction_expression::do_get_tree(Translate_context* context)
12895
{
12896
  Gogo* gogo = context->gogo();
12897
  Location loc = this->location();
12898
 
12899
  Map_type* mt = this->type_->map_type();
12900
 
12901
  // Build a struct to hold the key and value.
12902
  tree struct_type = make_node(RECORD_TYPE);
12903
 
12904
  Type* key_type = mt->key_type();
12905
  tree id = get_identifier("__key");
12906
  tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12907
  if (key_type_tree == error_mark_node)
12908
    return error_mark_node;
12909
  tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12910
                              key_type_tree);
12911
  DECL_CONTEXT(key_field) = struct_type;
12912
  TYPE_FIELDS(struct_type) = key_field;
12913
 
12914
  Type* val_type = mt->val_type();
12915
  id = get_identifier("__val");
12916
  tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12917
  if (val_type_tree == error_mark_node)
12918
    return error_mark_node;
12919
  tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12920
                              val_type_tree);
12921
  DECL_CONTEXT(val_field) = struct_type;
12922
  DECL_CHAIN(key_field) = val_field;
12923
 
12924
  layout_type(struct_type);
12925
 
12926
  bool is_constant = true;
12927
  size_t i = 0;
12928
  tree valaddr;
12929
  tree make_tmp;
12930
 
12931
  if (this->vals_ == NULL || this->vals_->empty())
12932
    {
12933
      valaddr = null_pointer_node;
12934
      make_tmp = NULL_TREE;
12935
    }
12936
  else
12937
    {
12938
      VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12939
                                                  this->vals_->size() / 2);
12940
 
12941
      for (Expression_list::const_iterator pv = this->vals_->begin();
12942
           pv != this->vals_->end();
12943
           ++pv, ++i)
12944
        {
12945
          bool one_is_constant = true;
12946
 
12947
          VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12948
 
12949
          constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12950
          elt->index = key_field;
12951
          tree val_tree = (*pv)->get_tree(context);
12952
          elt->value = Expression::convert_for_assignment(context, key_type,
12953
                                                          (*pv)->type(),
12954
                                                          val_tree, loc);
12955
          if (elt->value == error_mark_node)
12956
            return error_mark_node;
12957
          if (!TREE_CONSTANT(elt->value))
12958
            one_is_constant = false;
12959
 
12960
          ++pv;
12961
 
12962
          elt = VEC_quick_push(constructor_elt, one, NULL);
12963
          elt->index = val_field;
12964
          val_tree = (*pv)->get_tree(context);
12965
          elt->value = Expression::convert_for_assignment(context, val_type,
12966
                                                          (*pv)->type(),
12967
                                                          val_tree, loc);
12968
          if (elt->value == error_mark_node)
12969
            return error_mark_node;
12970
          if (!TREE_CONSTANT(elt->value))
12971
            one_is_constant = false;
12972
 
12973
          elt = VEC_quick_push(constructor_elt, values, NULL);
12974
          elt->index = size_int(i);
12975
          elt->value = build_constructor(struct_type, one);
12976
          if (one_is_constant)
12977
            TREE_CONSTANT(elt->value) = 1;
12978
          else
12979
            is_constant = false;
12980
        }
12981
 
12982
      tree index_type = build_index_type(size_int(i - 1));
12983
      tree array_type = build_array_type(struct_type, index_type);
12984
      tree init = build_constructor(array_type, values);
12985
      if (is_constant)
12986
        TREE_CONSTANT(init) = 1;
12987
      tree tmp;
12988
      if (current_function_decl != NULL)
12989
        {
12990
          tmp = create_tmp_var(array_type, get_name(array_type));
12991
          DECL_INITIAL(tmp) = init;
12992
          make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
12993
                                     void_type_node, tmp);
12994
          TREE_ADDRESSABLE(tmp) = 1;
12995
        }
12996
      else
12997
        {
12998
          tmp = build_decl(loc.gcc_location(), VAR_DECL,
12999
                           create_tmp_var_name("M"), array_type);
13000
          DECL_EXTERNAL(tmp) = 0;
13001
          TREE_PUBLIC(tmp) = 0;
13002
          TREE_STATIC(tmp) = 1;
13003
          DECL_ARTIFICIAL(tmp) = 1;
13004
          if (!TREE_CONSTANT(init))
13005
            make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
13006
                                       void_type_node, tmp, init);
13007
          else
13008
            {
13009
              TREE_READONLY(tmp) = 1;
13010
              TREE_CONSTANT(tmp) = 1;
13011
              DECL_INITIAL(tmp) = init;
13012
              make_tmp = NULL_TREE;
13013
            }
13014
          rest_of_decl_compilation(tmp, 1, 0);
13015
        }
13016
 
13017
      valaddr = build_fold_addr_expr(tmp);
13018
    }
13019
 
13020
  tree descriptor = mt->map_descriptor_pointer(gogo, loc);
13021
 
13022
  tree type_tree = type_to_tree(this->type_->get_backend(gogo));
13023
  if (type_tree == error_mark_node)
13024
    return error_mark_node;
13025
 
13026
  static tree construct_map_fndecl;
13027
  tree call = Gogo::call_builtin(&construct_map_fndecl,
13028
                                 loc,
13029
                                 "__go_construct_map",
13030
                                 6,
13031
                                 type_tree,
13032
                                 TREE_TYPE(descriptor),
13033
                                 descriptor,
13034
                                 sizetype,
13035
                                 size_int(i),
13036
                                 sizetype,
13037
                                 TYPE_SIZE_UNIT(struct_type),
13038
                                 sizetype,
13039
                                 byte_position(val_field),
13040
                                 sizetype,
13041
                                 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
13042
                                 const_ptr_type_node,
13043
                                 fold_convert(const_ptr_type_node, valaddr));
13044
  if (call == error_mark_node)
13045
    return error_mark_node;
13046
 
13047
  tree ret;
13048
  if (make_tmp == NULL)
13049
    ret = call;
13050
  else
13051
    ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
13052
                          make_tmp, call);
13053
  return ret;
13054
}
13055
 
13056
// Export an array construction.
13057
 
13058
void
13059
Map_construction_expression::do_export(Export* exp) const
13060
{
13061
  exp->write_c_string("convert(");
13062
  exp->write_type(this->type_);
13063
  for (Expression_list::const_iterator pv = this->vals_->begin();
13064
       pv != this->vals_->end();
13065
       ++pv)
13066
    {
13067
      exp->write_c_string(", ");
13068
      (*pv)->export_expression(exp);
13069
    }
13070
  exp->write_c_string(")");
13071
}
13072
 
13073
// Dump ast representation for a map construction expression.
13074
 
13075
void
13076
Map_construction_expression::do_dump_expression(
13077
    Ast_dump_context* ast_dump_context) const
13078
{
13079
  ast_dump_context->ostream() << "{" ;
13080
  ast_dump_context->dump_expression_list(this->vals_, true);
13081
  ast_dump_context->ostream() << "}";
13082
}
13083
 
13084
// A general composite literal.  This is lowered to a type specific
13085
// version.
13086
 
13087
class Composite_literal_expression : public Parser_expression
13088
{
13089
 public:
13090
  Composite_literal_expression(Type* type, int depth, bool has_keys,
13091
                               Expression_list* vals, Location location)
13092
    : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
13093
      type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
13094
  { }
13095
 
13096
 protected:
13097
  int
13098
  do_traverse(Traverse* traverse);
13099
 
13100
  Expression*
13101
  do_lower(Gogo*, Named_object*, Statement_inserter*, int);
13102
 
13103
  Expression*
13104
  do_copy()
13105
  {
13106
    return new Composite_literal_expression(this->type_, this->depth_,
13107
                                            this->has_keys_,
13108
                                            (this->vals_ == NULL
13109
                                             ? NULL
13110
                                             : this->vals_->copy()),
13111
                                            this->location());
13112
  }
13113
 
13114
  void
13115
  do_dump_expression(Ast_dump_context*) const;
13116
 
13117
 private:
13118
  Expression*
13119
  lower_struct(Gogo*, Type*);
13120
 
13121
  Expression*
13122
  lower_array(Type*);
13123
 
13124
  Expression*
13125
  make_array(Type*, Expression_list*);
13126
 
13127
  Expression*
13128
  lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
13129
 
13130
  // The type of the composite literal.
13131
  Type* type_;
13132
  // The depth within a list of composite literals within a composite
13133
  // literal, when the type is omitted.
13134
  int depth_;
13135
  // The values to put in the composite literal.
13136
  Expression_list* vals_;
13137
  // If this is true, then VALS_ is a list of pairs: a key and a
13138
  // value.  In an array initializer, a missing key will be NULL.
13139
  bool has_keys_;
13140
};
13141
 
13142
// Traversal.
13143
 
13144
int
13145
Composite_literal_expression::do_traverse(Traverse* traverse)
13146
{
13147
  if (this->vals_ != NULL
13148
      && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13149
    return TRAVERSE_EXIT;
13150
  return Type::traverse(this->type_, traverse);
13151
}
13152
 
13153
// Lower a generic composite literal into a specific version based on
13154
// the type.
13155
 
13156
Expression*
13157
Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13158
                                       Statement_inserter* inserter, int)
13159
{
13160
  Type* type = this->type_;
13161
 
13162
  for (int depth = this->depth_; depth > 0; --depth)
13163
    {
13164
      if (type->array_type() != NULL)
13165
        type = type->array_type()->element_type();
13166
      else if (type->map_type() != NULL)
13167
        type = type->map_type()->val_type();
13168
      else
13169
        {
13170
          if (!type->is_error())
13171
            error_at(this->location(),
13172
                     ("may only omit types within composite literals "
13173
                      "of slice, array, or map type"));
13174
          return Expression::make_error(this->location());
13175
        }
13176
    }
13177
 
13178
  Type *pt = type->points_to();
13179
  bool is_pointer = false;
13180
  if (pt != NULL)
13181
    {
13182
      is_pointer = true;
13183
      type = pt;
13184
    }
13185
 
13186
  Expression* ret;
13187
  if (type->is_error())
13188
    return Expression::make_error(this->location());
13189
  else if (type->struct_type() != NULL)
13190
    ret = this->lower_struct(gogo, type);
13191
  else if (type->array_type() != NULL)
13192
    ret = this->lower_array(type);
13193
  else if (type->map_type() != NULL)
13194
    ret = this->lower_map(gogo, function, inserter, type);
13195
  else
13196
    {
13197
      error_at(this->location(),
13198
               ("expected struct, slice, array, or map type "
13199
                "for composite literal"));
13200
      return Expression::make_error(this->location());
13201
    }
13202
 
13203
  if (is_pointer)
13204
    ret = Expression::make_heap_composite(ret, this->location());
13205
 
13206
  return ret;
13207
}
13208
 
13209
// Lower a struct composite literal.
13210
 
13211
Expression*
13212
Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13213
{
13214
  Location location = this->location();
13215
  Struct_type* st = type->struct_type();
13216
  if (this->vals_ == NULL || !this->has_keys_)
13217
    {
13218
      if (this->vals_ != NULL
13219
          && !this->vals_->empty()
13220
          && type->named_type() != NULL
13221
          && type->named_type()->named_object()->package() != NULL)
13222
        {
13223
          for (Struct_field_list::const_iterator pf = st->fields()->begin();
13224
               pf != st->fields()->end();
13225
               ++pf)
13226
            {
13227
              if (Gogo::is_hidden_name(pf->field_name()))
13228
                error_at(this->location(),
13229
                         "assignment of unexported field %qs in %qs literal",
13230
                         Gogo::message_name(pf->field_name()).c_str(),
13231
                         type->named_type()->message_name().c_str());
13232
            }
13233
        }
13234
 
13235
      return new Struct_construction_expression(type, this->vals_, location);
13236
    }
13237
 
13238
  size_t field_count = st->field_count();
13239
  std::vector<Expression*> vals(field_count);
13240
  Expression_list::const_iterator p = this->vals_->begin();
13241
  while (p != this->vals_->end())
13242
    {
13243
      Expression* name_expr = *p;
13244
 
13245
      ++p;
13246
      go_assert(p != this->vals_->end());
13247
      Expression* val = *p;
13248
 
13249
      ++p;
13250
 
13251
      if (name_expr == NULL)
13252
        {
13253
          error_at(val->location(), "mixture of field and value initializers");
13254
          return Expression::make_error(location);
13255
        }
13256
 
13257
      bool bad_key = false;
13258
      std::string name;
13259
      const Named_object* no = NULL;
13260
      switch (name_expr->classification())
13261
        {
13262
        case EXPRESSION_UNKNOWN_REFERENCE:
13263
          name = name_expr->unknown_expression()->name();
13264
          break;
13265
 
13266
        case EXPRESSION_CONST_REFERENCE:
13267
          no = static_cast<Const_expression*>(name_expr)->named_object();
13268
          break;
13269
 
13270
        case EXPRESSION_TYPE:
13271
          {
13272
            Type* t = name_expr->type();
13273
            Named_type* nt = t->named_type();
13274
            if (nt == NULL)
13275
              bad_key = true;
13276
            else
13277
              no = nt->named_object();
13278
          }
13279
          break;
13280
 
13281
        case EXPRESSION_VAR_REFERENCE:
13282
          no = name_expr->var_expression()->named_object();
13283
          break;
13284
 
13285
        case EXPRESSION_FUNC_REFERENCE:
13286
          no = name_expr->func_expression()->named_object();
13287
          break;
13288
 
13289
        case EXPRESSION_UNARY:
13290
          // If there is a local variable around with the same name as
13291
          // the field, and this occurs in the closure, then the
13292
          // parser may turn the field reference into an indirection
13293
          // through the closure.  FIXME: This is a mess.
13294
          {
13295
            bad_key = true;
13296
            Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13297
            if (ue->op() == OPERATOR_MULT)
13298
              {
13299
                Field_reference_expression* fre =
13300
                  ue->operand()->field_reference_expression();
13301
                if (fre != NULL)
13302
                  {
13303
                    Struct_type* st =
13304
                      fre->expr()->type()->deref()->struct_type();
13305
                    if (st != NULL)
13306
                      {
13307
                        const Struct_field* sf = st->field(fre->field_index());
13308
                        name = sf->field_name();
13309
 
13310
                        // See below.  FIXME.
13311
                        if (!Gogo::is_hidden_name(name)
13312
                            && name[0] >= 'a'
13313
                            && name[0] <= 'z')
13314
                          {
13315
                            if (gogo->lookup_global(name.c_str()) != NULL)
13316
                              name = gogo->pack_hidden_name(name, false);
13317
                          }
13318
 
13319
                        char buf[20];
13320
                        snprintf(buf, sizeof buf, "%u", fre->field_index());
13321
                        size_t buflen = strlen(buf);
13322
                        if (name.compare(name.length() - buflen, buflen, buf)
13323
                            == 0)
13324
                          {
13325
                            name = name.substr(0, name.length() - buflen);
13326
                            bad_key = false;
13327
                          }
13328
                      }
13329
                  }
13330
              }
13331
          }
13332
          break;
13333
 
13334
        default:
13335
          bad_key = true;
13336
          break;
13337
        }
13338
      if (bad_key)
13339
        {
13340
          error_at(name_expr->location(), "expected struct field name");
13341
          return Expression::make_error(location);
13342
        }
13343
 
13344
      if (no != NULL)
13345
        {
13346
          name = no->name();
13347
 
13348
          // A predefined name won't be packed.  If it starts with a
13349
          // lower case letter we need to check for that case, because
13350
          // the field name will be packed.  FIXME.
13351
          if (!Gogo::is_hidden_name(name)
13352
              && name[0] >= 'a'
13353
              && name[0] <= 'z')
13354
            {
13355
              Named_object* gno = gogo->lookup_global(name.c_str());
13356
              if (gno == no)
13357
                name = gogo->pack_hidden_name(name, false);
13358
            }
13359
        }
13360
 
13361
      unsigned int index;
13362
      const Struct_field* sf = st->find_local_field(name, &index);
13363
      if (sf == NULL)
13364
        {
13365
          error_at(name_expr->location(), "unknown field %qs in %qs",
13366
                   Gogo::message_name(name).c_str(),
13367
                   (type->named_type() != NULL
13368
                    ? type->named_type()->message_name().c_str()
13369
                    : "unnamed struct"));
13370
          return Expression::make_error(location);
13371
        }
13372
      if (vals[index] != NULL)
13373
        {
13374
          error_at(name_expr->location(),
13375
                   "duplicate value for field %qs in %qs",
13376
                   Gogo::message_name(name).c_str(),
13377
                   (type->named_type() != NULL
13378
                    ? type->named_type()->message_name().c_str()
13379
                    : "unnamed struct"));
13380
          return Expression::make_error(location);
13381
        }
13382
 
13383
      if (type->named_type() != NULL
13384
          && type->named_type()->named_object()->package() != NULL
13385
          && Gogo::is_hidden_name(sf->field_name()))
13386
        error_at(name_expr->location(),
13387
                 "assignment of unexported field %qs in %qs literal",
13388
                 Gogo::message_name(sf->field_name()).c_str(),
13389
                 type->named_type()->message_name().c_str());
13390
 
13391
      vals[index] = val;
13392
    }
13393
 
13394
  Expression_list* list = new Expression_list;
13395
  list->reserve(field_count);
13396
  for (size_t i = 0; i < field_count; ++i)
13397
    list->push_back(vals[i]);
13398
 
13399
  return new Struct_construction_expression(type, list, location);
13400
}
13401
 
13402
// Lower an array composite literal.
13403
 
13404
Expression*
13405
Composite_literal_expression::lower_array(Type* type)
13406
{
13407
  Location location = this->location();
13408
  if (this->vals_ == NULL || !this->has_keys_)
13409
    return this->make_array(type, this->vals_);
13410
 
13411
  std::vector<Expression*> vals;
13412
  vals.reserve(this->vals_->size());
13413
  unsigned long index = 0;
13414
  Expression_list::const_iterator p = this->vals_->begin();
13415
  while (p != this->vals_->end())
13416
    {
13417
      Expression* index_expr = *p;
13418
 
13419
      ++p;
13420
      go_assert(p != this->vals_->end());
13421
      Expression* val = *p;
13422
 
13423
      ++p;
13424
 
13425
      if (index_expr != NULL)
13426
        {
13427
          mpz_t ival;
13428
          mpz_init(ival);
13429
 
13430
          Type* dummy;
13431
          if (!index_expr->integer_constant_value(true, ival, &dummy))
13432
            {
13433
              mpz_clear(ival);
13434
              error_at(index_expr->location(),
13435
                       "index expression is not integer constant");
13436
              return Expression::make_error(location);
13437
            }
13438
 
13439
          if (mpz_sgn(ival) < 0)
13440
            {
13441
              mpz_clear(ival);
13442
              error_at(index_expr->location(), "index expression is negative");
13443
              return Expression::make_error(location);
13444
            }
13445
 
13446
          index = mpz_get_ui(ival);
13447
          if (mpz_cmp_ui(ival, index) != 0)
13448
            {
13449
              mpz_clear(ival);
13450
              error_at(index_expr->location(), "index value overflow");
13451
              return Expression::make_error(location);
13452
            }
13453
 
13454
          Named_type* ntype = Type::lookup_integer_type("int");
13455
          Integer_type* inttype = ntype->integer_type();
13456
          mpz_t max;
13457
          mpz_init_set_ui(max, 1);
13458
          mpz_mul_2exp(max, max, inttype->bits() - 1);
13459
          bool ok = mpz_cmp(ival, max) < 0;
13460
          mpz_clear(max);
13461
          if (!ok)
13462
            {
13463
              mpz_clear(ival);
13464
              error_at(index_expr->location(), "index value overflow");
13465
              return Expression::make_error(location);
13466
            }
13467
 
13468
          mpz_clear(ival);
13469
 
13470
          // FIXME: Our representation isn't very good; this avoids
13471
          // thrashing.
13472
          if (index > 0x1000000)
13473
            {
13474
              error_at(index_expr->location(), "index too large for compiler");
13475
              return Expression::make_error(location);
13476
            }
13477
        }
13478
 
13479
      if (index == vals.size())
13480
        vals.push_back(val);
13481
      else
13482
        {
13483
          if (index > vals.size())
13484
            {
13485
              vals.reserve(index + 32);
13486
              vals.resize(index + 1, static_cast<Expression*>(NULL));
13487
            }
13488
          if (vals[index] != NULL)
13489
            {
13490
              error_at((index_expr != NULL
13491
                        ? index_expr->location()
13492
                        : val->location()),
13493
                       "duplicate value for index %lu",
13494
                       index);
13495
              return Expression::make_error(location);
13496
            }
13497
          vals[index] = val;
13498
        }
13499
 
13500
      ++index;
13501
    }
13502
 
13503
  size_t size = vals.size();
13504
  Expression_list* list = new Expression_list;
13505
  list->reserve(size);
13506
  for (size_t i = 0; i < size; ++i)
13507
    list->push_back(vals[i]);
13508
 
13509
  return this->make_array(type, list);
13510
}
13511
 
13512
// Actually build the array composite literal. This handles
13513
// [...]{...}.
13514
 
13515
Expression*
13516
Composite_literal_expression::make_array(Type* type, Expression_list* vals)
13517
{
13518
  Location location = this->location();
13519
  Array_type* at = type->array_type();
13520
  if (at->length() != NULL && at->length()->is_nil_expression())
13521
    {
13522
      size_t size = vals == NULL ? 0 : vals->size();
13523
      mpz_t vlen;
13524
      mpz_init_set_ui(vlen, size);
13525
      Expression* elen = Expression::make_integer(&vlen, NULL, location);
13526
      mpz_clear(vlen);
13527
      at = Type::make_array_type(at->element_type(), elen);
13528
      type = at;
13529
    }
13530
  if (at->length() != NULL)
13531
    return new Fixed_array_construction_expression(type, vals, location);
13532
  else
13533
    return new Open_array_construction_expression(type, vals, location);
13534
}
13535
 
13536
// Lower a map composite literal.
13537
 
13538
Expression*
13539
Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13540
                                        Statement_inserter* inserter,
13541
                                        Type* type)
13542
{
13543
  Location location = this->location();
13544
  if (this->vals_ != NULL)
13545
    {
13546
      if (!this->has_keys_)
13547
        {
13548
          error_at(location, "map composite literal must have keys");
13549
          return Expression::make_error(location);
13550
        }
13551
 
13552
      for (Expression_list::iterator p = this->vals_->begin();
13553
           p != this->vals_->end();
13554
           p += 2)
13555
        {
13556
          if (*p == NULL)
13557
            {
13558
              ++p;
13559
              error_at((*p)->location(),
13560
                       "map composite literal must have keys for every value");
13561
              return Expression::make_error(location);
13562
            }
13563
          // Make sure we have lowered the key; it may not have been
13564
          // lowered in order to handle keys for struct composite
13565
          // literals.  Lower it now to get the right error message.
13566
          if ((*p)->unknown_expression() != NULL)
13567
            {
13568
              (*p)->unknown_expression()->clear_is_composite_literal_key();
13569
              gogo->lower_expression(function, inserter, &*p);
13570
              go_assert((*p)->is_error_expression());
13571
              return Expression::make_error(location);
13572
            }
13573
        }
13574
    }
13575
 
13576
  return new Map_construction_expression(type, this->vals_, location);
13577
}
13578
 
13579
// Dump ast representation for a composite literal expression.
13580
 
13581
void
13582
Composite_literal_expression::do_dump_expression(
13583
                               Ast_dump_context* ast_dump_context) const
13584
{
13585
  ast_dump_context->ostream() << "composite(";
13586
  ast_dump_context->dump_type(this->type_);
13587
  ast_dump_context->ostream() << ", {";
13588
  ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13589
  ast_dump_context->ostream() << "})";
13590
}
13591
 
13592
// Make a composite literal expression.
13593
 
13594
Expression*
13595
Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13596
                                   Expression_list* vals,
13597
                                   Location location)
13598
{
13599
  return new Composite_literal_expression(type, depth, has_keys, vals,
13600
                                          location);
13601
}
13602
 
13603
// Return whether this expression is a composite literal.
13604
 
13605
bool
13606
Expression::is_composite_literal() const
13607
{
13608
  switch (this->classification_)
13609
    {
13610
    case EXPRESSION_COMPOSITE_LITERAL:
13611
    case EXPRESSION_STRUCT_CONSTRUCTION:
13612
    case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13613
    case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
13614
    case EXPRESSION_MAP_CONSTRUCTION:
13615
      return true;
13616
    default:
13617
      return false;
13618
    }
13619
}
13620
 
13621
// Return whether this expression is a composite literal which is not
13622
// constant.
13623
 
13624
bool
13625
Expression::is_nonconstant_composite_literal() const
13626
{
13627
  switch (this->classification_)
13628
    {
13629
    case EXPRESSION_STRUCT_CONSTRUCTION:
13630
      {
13631
        const Struct_construction_expression *psce =
13632
          static_cast<const Struct_construction_expression*>(this);
13633
        return !psce->is_constant_struct();
13634
      }
13635
    case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13636
      {
13637
        const Fixed_array_construction_expression *pace =
13638
          static_cast<const Fixed_array_construction_expression*>(this);
13639
        return !pace->is_constant_array();
13640
      }
13641
    case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
13642
      {
13643
        const Open_array_construction_expression *pace =
13644
          static_cast<const Open_array_construction_expression*>(this);
13645
        return !pace->is_constant_array();
13646
      }
13647
    case EXPRESSION_MAP_CONSTRUCTION:
13648
      return true;
13649
    default:
13650
      return false;
13651
    }
13652
}
13653
 
13654
// Return true if this is a reference to a local variable.
13655
 
13656
bool
13657
Expression::is_local_variable() const
13658
{
13659
  const Var_expression* ve = this->var_expression();
13660
  if (ve == NULL)
13661
    return false;
13662
  const Named_object* no = ve->named_object();
13663
  return (no->is_result_variable()
13664
          || (no->is_variable() && !no->var_value()->is_global()));
13665
}
13666
 
13667
// Class Type_guard_expression.
13668
 
13669
// Traversal.
13670
 
13671
int
13672
Type_guard_expression::do_traverse(Traverse* traverse)
13673
{
13674
  if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13675
      || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13676
    return TRAVERSE_EXIT;
13677
  return TRAVERSE_CONTINUE;
13678
}
13679
 
13680
// Check types of a type guard expression.  The expression must have
13681
// an interface type, but the actual type conversion is checked at run
13682
// time.
13683
 
13684
void
13685
Type_guard_expression::do_check_types(Gogo*)
13686
{
13687
  // 6g permits using a type guard with unsafe.pointer; we are
13688
  // compatible.
13689
  Type* expr_type = this->expr_->type();
13690
  if (expr_type->is_unsafe_pointer_type())
13691
    {
13692
      if (this->type_->points_to() == NULL
13693
          && (this->type_->integer_type() == NULL
13694
              || (this->type_->forwarded()
13695
                  != Type::lookup_integer_type("uintptr"))))
13696
        this->report_error(_("invalid unsafe.Pointer conversion"));
13697
    }
13698
  else if (this->type_->is_unsafe_pointer_type())
13699
    {
13700
      if (expr_type->points_to() == NULL
13701
          && (expr_type->integer_type() == NULL
13702
              || (expr_type->forwarded()
13703
                  != Type::lookup_integer_type("uintptr"))))
13704
        this->report_error(_("invalid unsafe.Pointer conversion"));
13705
    }
13706
  else if (expr_type->interface_type() == NULL)
13707
    {
13708
      if (!expr_type->is_error() && !this->type_->is_error())
13709
        this->report_error(_("type assertion only valid for interface types"));
13710
      this->set_is_error();
13711
    }
13712
  else if (this->type_->interface_type() == NULL)
13713
    {
13714
      std::string reason;
13715
      if (!expr_type->interface_type()->implements_interface(this->type_,
13716
                                                             &reason))
13717
        {
13718
          if (!this->type_->is_error())
13719
            {
13720
              if (reason.empty())
13721
                this->report_error(_("impossible type assertion: "
13722
                                     "type does not implement interface"));
13723
              else
13724
                error_at(this->location(),
13725
                         ("impossible type assertion: "
13726
                          "type does not implement interface (%s)"),
13727
                         reason.c_str());
13728
            }
13729
          this->set_is_error();
13730
        }
13731
    }
13732
}
13733
 
13734
// Return a tree for a type guard expression.
13735
 
13736
tree
13737
Type_guard_expression::do_get_tree(Translate_context* context)
13738
{
13739
  Gogo* gogo = context->gogo();
13740
  tree expr_tree = this->expr_->get_tree(context);
13741
  if (expr_tree == error_mark_node)
13742
    return error_mark_node;
13743
  Type* expr_type = this->expr_->type();
13744
  if ((this->type_->is_unsafe_pointer_type()
13745
       && (expr_type->points_to() != NULL
13746
           || expr_type->integer_type() != NULL))
13747
      || (expr_type->is_unsafe_pointer_type()
13748
          && this->type_->points_to() != NULL))
13749
    return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
13750
                              expr_tree);
13751
  else if (expr_type->is_unsafe_pointer_type()
13752
           && this->type_->integer_type() != NULL)
13753
    return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
13754
                              expr_tree);
13755
  else if (this->type_->interface_type() != NULL)
13756
    return Expression::convert_interface_to_interface(context, this->type_,
13757
                                                      this->expr_->type(),
13758
                                                      expr_tree, true,
13759
                                                      this->location());
13760
  else
13761
    return Expression::convert_for_assignment(context, this->type_,
13762
                                              this->expr_->type(), expr_tree,
13763
                                              this->location());
13764
}
13765
 
13766
// Dump ast representation for a type guard expression.
13767
 
13768
void
13769
Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13770
    const
13771
{
13772
  this->expr_->dump_expression(ast_dump_context);
13773
  ast_dump_context->ostream() <<  ".";
13774
  ast_dump_context->dump_type(this->type_);
13775
}
13776
 
13777
// Make a type guard expression.
13778
 
13779
Expression*
13780
Expression::make_type_guard(Expression* expr, Type* type,
13781
                            Location location)
13782
{
13783
  return new Type_guard_expression(expr, type, location);
13784
}
13785
 
13786
// Class Heap_composite_expression.
13787
 
13788
// When you take the address of a composite literal, it is allocated
13789
// on the heap.  This class implements that.
13790
 
13791
class Heap_composite_expression : public Expression
13792
{
13793
 public:
13794
  Heap_composite_expression(Expression* expr, Location location)
13795
    : Expression(EXPRESSION_HEAP_COMPOSITE, location),
13796
      expr_(expr)
13797
  { }
13798
 
13799
 protected:
13800
  int
13801
  do_traverse(Traverse* traverse)
13802
  { return Expression::traverse(&this->expr_, traverse); }
13803
 
13804
  Type*
13805
  do_type()
13806
  { return Type::make_pointer_type(this->expr_->type()); }
13807
 
13808
  void
13809
  do_determine_type(const Type_context*)
13810
  { this->expr_->determine_type_no_context(); }
13811
 
13812
  Expression*
13813
  do_copy()
13814
  {
13815
    return Expression::make_heap_composite(this->expr_->copy(),
13816
                                           this->location());
13817
  }
13818
 
13819
  tree
13820
  do_get_tree(Translate_context*);
13821
 
13822
  // We only export global objects, and the parser does not generate
13823
  // this in global scope.
13824
  void
13825
  do_export(Export*) const
13826
  { go_unreachable(); }
13827
 
13828
  void
13829
  do_dump_expression(Ast_dump_context*) const;
13830
 
13831
 private:
13832
  // The composite literal which is being put on the heap.
13833
  Expression* expr_;
13834
};
13835
 
13836
// Return a tree which allocates a composite literal on the heap.
13837
 
13838
tree
13839
Heap_composite_expression::do_get_tree(Translate_context* context)
13840
{
13841
  tree expr_tree = this->expr_->get_tree(context);
13842
  if (expr_tree == error_mark_node)
13843
    return error_mark_node;
13844
  tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13845
  go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13846
  tree space = context->gogo()->allocate_memory(this->expr_->type(),
13847
                                                expr_size, this->location());
13848
  space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13849
  space = save_expr(space);
13850
  tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13851
                                         space);
13852
  TREE_THIS_NOTRAP(ref) = 1;
13853
  tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13854
                    build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13855
                    space);
13856
  SET_EXPR_LOCATION(ret, this->location().gcc_location());
13857
  return ret;
13858
}
13859
 
13860
// Dump ast representation for a heap composite expression.
13861
 
13862
void
13863
Heap_composite_expression::do_dump_expression(
13864
    Ast_dump_context* ast_dump_context) const
13865
{
13866
  ast_dump_context->ostream() << "&(";
13867
  ast_dump_context->dump_expression(this->expr_);
13868
  ast_dump_context->ostream() << ")";
13869
}
13870
 
13871
// Allocate a composite literal on the heap.
13872
 
13873
Expression*
13874
Expression::make_heap_composite(Expression* expr, Location location)
13875
{
13876
  return new Heap_composite_expression(expr, location);
13877
}
13878
 
13879
// Class Receive_expression.
13880
 
13881
// Return the type of a receive expression.
13882
 
13883
Type*
13884
Receive_expression::do_type()
13885
{
13886
  Channel_type* channel_type = this->channel_->type()->channel_type();
13887
  if (channel_type == NULL)
13888
    return Type::make_error_type();
13889
  return channel_type->element_type();
13890
}
13891
 
13892
// Check types for a receive expression.
13893
 
13894
void
13895
Receive_expression::do_check_types(Gogo*)
13896
{
13897
  Type* type = this->channel_->type();
13898
  if (type->is_error())
13899
    {
13900
      this->set_is_error();
13901
      return;
13902
    }
13903
  if (type->channel_type() == NULL)
13904
    {
13905
      this->report_error(_("expected channel"));
13906
      return;
13907
    }
13908
  if (!type->channel_type()->may_receive())
13909
    {
13910
      this->report_error(_("invalid receive on send-only channel"));
13911
      return;
13912
    }
13913
}
13914
 
13915
// Get a tree for a receive expression.
13916
 
13917
tree
13918
Receive_expression::do_get_tree(Translate_context* context)
13919
{
13920
  Location loc = this->location();
13921
 
13922
  Channel_type* channel_type = this->channel_->type()->channel_type();
13923
  if (channel_type == NULL)
13924
    {
13925
      go_assert(this->channel_->type()->is_error());
13926
      return error_mark_node;
13927
    }
13928
 
13929
  Expression* td = Expression::make_type_descriptor(channel_type, loc);
13930
  tree td_tree = td->get_tree(context);
13931
 
13932
  Type* element_type = channel_type->element_type();
13933
  Btype* element_type_btype = element_type->get_backend(context->gogo());
13934
  tree element_type_tree = type_to_tree(element_type_btype);
13935
 
13936
  tree channel = this->channel_->get_tree(context);
13937
  if (element_type_tree == error_mark_node || channel == error_mark_node)
13938
    return error_mark_node;
13939
 
13940
  return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13941
}
13942
 
13943
// Dump ast representation for a receive expression.
13944
 
13945
void
13946
Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13947
{
13948
  ast_dump_context->ostream() << " <- " ;
13949
  ast_dump_context->dump_expression(channel_);
13950
}
13951
 
13952
// Make a receive expression.
13953
 
13954
Receive_expression*
13955
Expression::make_receive(Expression* channel, Location location)
13956
{
13957
  return new Receive_expression(channel, location);
13958
}
13959
 
13960
// An expression which evaluates to a pointer to the type descriptor
13961
// of a type.
13962
 
13963
class Type_descriptor_expression : public Expression
13964
{
13965
 public:
13966
  Type_descriptor_expression(Type* type, Location location)
13967
    : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13968
      type_(type)
13969
  { }
13970
 
13971
 protected:
13972
  Type*
13973
  do_type()
13974
  { return Type::make_type_descriptor_ptr_type(); }
13975
 
13976
  void
13977
  do_determine_type(const Type_context*)
13978
  { }
13979
 
13980
  Expression*
13981
  do_copy()
13982
  { return this; }
13983
 
13984
  tree
13985
  do_get_tree(Translate_context* context)
13986
  {
13987
    return this->type_->type_descriptor_pointer(context->gogo(),
13988
                                                this->location());
13989
  }
13990
 
13991
  void
13992
  do_dump_expression(Ast_dump_context*) const;
13993
 
13994
 private:
13995
  // The type for which this is the descriptor.
13996
  Type* type_;
13997
};
13998
 
13999
// Dump ast representation for a type descriptor expression.
14000
 
14001
void
14002
Type_descriptor_expression::do_dump_expression(
14003
    Ast_dump_context* ast_dump_context) const
14004
{
14005
  ast_dump_context->dump_type(this->type_);
14006
}
14007
 
14008
// Make a type descriptor expression.
14009
 
14010
Expression*
14011
Expression::make_type_descriptor(Type* type, Location location)
14012
{
14013
  return new Type_descriptor_expression(type, location);
14014
}
14015
 
14016
// An expression which evaluates to some characteristic of a type.
14017
// This is only used to initialize fields of a type descriptor.  Using
14018
// a new expression class is slightly inefficient but gives us a good
14019
// separation between the frontend and the middle-end with regard to
14020
// how types are laid out.
14021
 
14022
class Type_info_expression : public Expression
14023
{
14024
 public:
14025
  Type_info_expression(Type* type, Type_info type_info)
14026
    : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14027
      type_(type), type_info_(type_info)
14028
  { }
14029
 
14030
 protected:
14031
  Type*
14032
  do_type();
14033
 
14034
  void
14035
  do_determine_type(const Type_context*)
14036
  { }
14037
 
14038
  Expression*
14039
  do_copy()
14040
  { return this; }
14041
 
14042
  tree
14043
  do_get_tree(Translate_context* context);
14044
 
14045
  void
14046
  do_dump_expression(Ast_dump_context*) const;
14047
 
14048
 private:
14049
  // The type for which we are getting information.
14050
  Type* type_;
14051
  // What information we want.
14052
  Type_info type_info_;
14053
};
14054
 
14055
// The type is chosen to match what the type descriptor struct
14056
// expects.
14057
 
14058
Type*
14059
Type_info_expression::do_type()
14060
{
14061
  switch (this->type_info_)
14062
    {
14063
    case TYPE_INFO_SIZE:
14064
      return Type::lookup_integer_type("uintptr");
14065
    case TYPE_INFO_ALIGNMENT:
14066
    case TYPE_INFO_FIELD_ALIGNMENT:
14067
      return Type::lookup_integer_type("uint8");
14068
    default:
14069
      go_unreachable();
14070
    }
14071
}
14072
 
14073
// Return type information in GENERIC.
14074
 
14075
tree
14076
Type_info_expression::do_get_tree(Translate_context* context)
14077
{
14078
  Btype* btype = this->type_->get_backend(context->gogo());
14079
  Gogo* gogo = context->gogo();
14080
  size_t val;
14081
  switch (this->type_info_)
14082
    {
14083
    case TYPE_INFO_SIZE:
14084
      val = gogo->backend()->type_size(btype);
14085
      break;
14086
    case TYPE_INFO_ALIGNMENT:
14087
      val = gogo->backend()->type_alignment(btype);
14088
      break;
14089
    case TYPE_INFO_FIELD_ALIGNMENT:
14090
      val = gogo->backend()->type_field_alignment(btype);
14091
      break;
14092
    default:
14093
      go_unreachable();
14094
    }
14095
  tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14096
  go_assert(val_type_tree != error_mark_node);
14097
  return build_int_cstu(val_type_tree, val);
14098
}
14099
 
14100
// Dump ast representation for a type info expression.
14101
 
14102
void
14103
Type_info_expression::do_dump_expression(
14104
    Ast_dump_context* ast_dump_context) const
14105
{
14106
  ast_dump_context->ostream() << "typeinfo(";
14107
  ast_dump_context->dump_type(this->type_);
14108
  ast_dump_context->ostream() << ",";
14109
  ast_dump_context->ostream() <<
14110
    (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14111
    : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14112
    : this->type_info_ == TYPE_INFO_SIZE ? "size "
14113
    : "unknown");
14114
  ast_dump_context->ostream() << ")";
14115
}
14116
 
14117
// Make a type info expression.
14118
 
14119
Expression*
14120
Expression::make_type_info(Type* type, Type_info type_info)
14121
{
14122
  return new Type_info_expression(type, type_info);
14123
}
14124
 
14125
// An expression which evaluates to the offset of a field within a
14126
// struct.  This, like Type_info_expression, q.v., is only used to
14127
// initialize fields of a type descriptor.
14128
 
14129
class Struct_field_offset_expression : public Expression
14130
{
14131
 public:
14132
  Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14133
    : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14134
                 Linemap::predeclared_location()),
14135
      type_(type), field_(field)
14136
  { }
14137
 
14138
 protected:
14139
  Type*
14140
  do_type()
14141
  { return Type::lookup_integer_type("uintptr"); }
14142
 
14143
  void
14144
  do_determine_type(const Type_context*)
14145
  { }
14146
 
14147
  Expression*
14148
  do_copy()
14149
  { return this; }
14150
 
14151
  tree
14152
  do_get_tree(Translate_context* context);
14153
 
14154
  void
14155
  do_dump_expression(Ast_dump_context*) const;
14156
 
14157
 private:
14158
  // The type of the struct.
14159
  Struct_type* type_;
14160
  // The field.
14161
  const Struct_field* field_;
14162
};
14163
 
14164
// Return a struct field offset in GENERIC.
14165
 
14166
tree
14167
Struct_field_offset_expression::do_get_tree(Translate_context* context)
14168
{
14169
  tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
14170
  if (type_tree == error_mark_node)
14171
    return error_mark_node;
14172
 
14173
  tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
14174
  go_assert(val_type_tree != error_mark_node);
14175
 
14176
  const Struct_field_list* fields = this->type_->fields();
14177
  tree struct_field_tree = TYPE_FIELDS(type_tree);
14178
  Struct_field_list::const_iterator p;
14179
  for (p = fields->begin();
14180
       p != fields->end();
14181
       ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14182
    {
14183
      go_assert(struct_field_tree != NULL_TREE);
14184
      if (&*p == this->field_)
14185
        break;
14186
    }
14187
  go_assert(&*p == this->field_);
14188
 
14189
  return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14190
                          byte_position(struct_field_tree));
14191
}
14192
 
14193
// Dump ast representation for a struct field offset expression.
14194
 
14195
void
14196
Struct_field_offset_expression::do_dump_expression(
14197
    Ast_dump_context* ast_dump_context) const
14198
{
14199
  ast_dump_context->ostream() <<  "unsafe.Offsetof(";
14200
  ast_dump_context->dump_type(this->type_);
14201
  ast_dump_context->ostream() << '.';
14202
  ast_dump_context->ostream() <<
14203
    Gogo::message_name(this->field_->field_name());
14204
  ast_dump_context->ostream() << ")";
14205
}
14206
 
14207
// Make an expression for a struct field offset.
14208
 
14209
Expression*
14210
Expression::make_struct_field_offset(Struct_type* type,
14211
                                     const Struct_field* field)
14212
{
14213
  return new Struct_field_offset_expression(type, field);
14214
}
14215
 
14216
// An expression which evaluates to a pointer to the map descriptor of
14217
// a map type.
14218
 
14219
class Map_descriptor_expression : public Expression
14220
{
14221
 public:
14222
  Map_descriptor_expression(Map_type* type, Location location)
14223
    : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14224
      type_(type)
14225
  { }
14226
 
14227
 protected:
14228
  Type*
14229
  do_type()
14230
  { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14231
 
14232
  void
14233
  do_determine_type(const Type_context*)
14234
  { }
14235
 
14236
  Expression*
14237
  do_copy()
14238
  { return this; }
14239
 
14240
  tree
14241
  do_get_tree(Translate_context* context)
14242
  {
14243
    return this->type_->map_descriptor_pointer(context->gogo(),
14244
                                               this->location());
14245
  }
14246
 
14247
  void
14248
  do_dump_expression(Ast_dump_context*) const;
14249
 
14250
 private:
14251
  // The type for which this is the descriptor.
14252
  Map_type* type_;
14253
};
14254
 
14255
// Dump ast representation for a map descriptor expression.
14256
 
14257
void
14258
Map_descriptor_expression::do_dump_expression(
14259
    Ast_dump_context* ast_dump_context) const
14260
{
14261
  ast_dump_context->ostream() << "map_descriptor(";
14262
  ast_dump_context->dump_type(this->type_);
14263
  ast_dump_context->ostream() << ")";
14264
}
14265
 
14266
// Make a map descriptor expression.
14267
 
14268
Expression*
14269
Expression::make_map_descriptor(Map_type* type, Location location)
14270
{
14271
  return new Map_descriptor_expression(type, location);
14272
}
14273
 
14274
// An expression which evaluates to the address of an unnamed label.
14275
 
14276
class Label_addr_expression : public Expression
14277
{
14278
 public:
14279
  Label_addr_expression(Label* label, Location location)
14280
    : Expression(EXPRESSION_LABEL_ADDR, location),
14281
      label_(label)
14282
  { }
14283
 
14284
 protected:
14285
  Type*
14286
  do_type()
14287
  { return Type::make_pointer_type(Type::make_void_type()); }
14288
 
14289
  void
14290
  do_determine_type(const Type_context*)
14291
  { }
14292
 
14293
  Expression*
14294
  do_copy()
14295
  { return new Label_addr_expression(this->label_, this->location()); }
14296
 
14297
  tree
14298
  do_get_tree(Translate_context* context)
14299
  {
14300
    return expr_to_tree(this->label_->get_addr(context, this->location()));
14301
  }
14302
 
14303
  void
14304
  do_dump_expression(Ast_dump_context* ast_dump_context) const
14305
  { ast_dump_context->ostream() << this->label_->name(); }
14306
 
14307
 private:
14308
  // The label whose address we are taking.
14309
  Label* label_;
14310
};
14311
 
14312
// Make an expression for the address of an unnamed label.
14313
 
14314
Expression*
14315
Expression::make_label_addr(Label* label, Location location)
14316
{
14317
  return new Label_addr_expression(label, location);
14318
}
14319
 
14320
// Import an expression.  This comes at the end in order to see the
14321
// various class definitions.
14322
 
14323
Expression*
14324
Expression::import_expression(Import* imp)
14325
{
14326
  int c = imp->peek_char();
14327
  if (imp->match_c_string("- ")
14328
      || imp->match_c_string("! ")
14329
      || imp->match_c_string("^ "))
14330
    return Unary_expression::do_import(imp);
14331
  else if (c == '(')
14332
    return Binary_expression::do_import(imp);
14333
  else if (imp->match_c_string("true")
14334
           || imp->match_c_string("false"))
14335
    return Boolean_expression::do_import(imp);
14336
  else if (c == '"')
14337
    return String_expression::do_import(imp);
14338
  else if (c == '-' || (c >= '0' && c <= '9'))
14339
    {
14340
      // This handles integers, floats and complex constants.
14341
      return Integer_expression::do_import(imp);
14342
    }
14343
  else if (imp->match_c_string("nil"))
14344
    return Nil_expression::do_import(imp);
14345
  else if (imp->match_c_string("convert"))
14346
    return Type_conversion_expression::do_import(imp);
14347
  else
14348
    {
14349
      error_at(imp->location(), "import error: expected expression");
14350
      return Expression::make_error(imp->location());
14351
    }
14352
}
14353
 
14354
// Class Expression_list.
14355
 
14356
// Traverse the list.
14357
 
14358
int
14359
Expression_list::traverse(Traverse* traverse)
14360
{
14361
  for (Expression_list::iterator p = this->begin();
14362
       p != this->end();
14363
       ++p)
14364
    {
14365
      if (*p != NULL)
14366
        {
14367
          if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14368
            return TRAVERSE_EXIT;
14369
        }
14370
    }
14371
  return TRAVERSE_CONTINUE;
14372
}
14373
 
14374
// Copy the list.
14375
 
14376
Expression_list*
14377
Expression_list::copy()
14378
{
14379
  Expression_list* ret = new Expression_list();
14380
  for (Expression_list::iterator p = this->begin();
14381
       p != this->end();
14382
       ++p)
14383
    {
14384
      if (*p == NULL)
14385
        ret->push_back(NULL);
14386
      else
14387
        ret->push_back((*p)->copy());
14388
    }
14389
  return ret;
14390
}
14391
 
14392
// Return whether an expression list has an error expression.
14393
 
14394
bool
14395
Expression_list::contains_error() const
14396
{
14397
  for (Expression_list::const_iterator p = this->begin();
14398
       p != this->end();
14399
       ++p)
14400
    if (*p != NULL && (*p)->is_error_expression())
14401
      return true;
14402
  return false;
14403
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.